func (j roleBuildJob) Run() { select { case <-j.abort: j.resultsCh <- nil return default: } roleImageName := GetRoleDevImageName(j.repository, j.role, j.role.GetRoleDevVersion()) if !j.force { if hasImage, err := j.dockerManager.HasImage(roleImageName); err != nil { j.resultsCh <- err return } else if hasImage { j.ui.Printf("Skipping build of role image %s because it exists\n", color.YellowString(j.role.Name)) j.resultsCh <- nil return } } if j.builder.metricsPath != "" { seriesName := fmt.Sprintf("create-role-images::%s", roleImageName) stampy.Stamp(j.builder.metricsPath, "fissile", seriesName, "start") defer stampy.Stamp(j.builder.metricsPath, "fissile", seriesName, "done") } j.ui.Printf("Creating Dockerfile for role %s ...\n", color.YellowString(j.role.Name)) dockerfileDir, err := j.builder.CreateDockerfileDir(j.role, j.baseImageName) if err != nil { j.resultsCh <- fmt.Errorf("Error creating Dockerfile and/or assets for role %s: %s", j.role.Name, err.Error()) return } if j.noBuild { j.ui.Printf("Skipping build of role image %s because of flag\n", color.YellowString(j.role.Name)) j.resultsCh <- nil return } if !strings.HasSuffix(dockerfileDir, string(os.PathSeparator)) { dockerfileDir = fmt.Sprintf("%s%c", dockerfileDir, os.PathSeparator) } j.ui.Printf("Building docker image of %s in %s ...\n", color.YellowString(j.role.Name), color.YellowString(dockerfileDir)) log := new(bytes.Buffer) stdoutWriter := docker.NewFormattingWriter( log, docker.ColoredBuildStringFunc(roleImageName), ) err = j.dockerManager.BuildImage(dockerfileDir, roleImageName, stdoutWriter) if err != nil { log.WriteTo(j.ui) j.resultsCh <- fmt.Errorf("Error building image: %s", err.Error()) return } j.resultsCh <- nil }
// ShowBaseImage will show details about the base BOSH images func (f *Fissile) ShowBaseImage(repository string) error { dockerManager, err := docker.NewImageManager() if err != nil { return fmt.Errorf("Error connecting to docker: %s", err.Error()) } comp, err := compilator.NewCompilator(dockerManager, "", "", repository, compilation.UbuntuBase, f.Version, false, f.UI) if err != nil { return fmt.Errorf("Error creating a new compilator: %s", err.Error()) } image, err := dockerManager.FindImage(comp.BaseImageName()) if err != nil { return fmt.Errorf("Error looking up base image %s: %s", comp.BaseImageName(), err.Error()) } f.UI.Printf("\nCompilation Layer: %s\n", color.GreenString(comp.BaseImageName())) f.UI.Printf("ID: %s\n", color.GreenString(image.ID)) f.UI.Printf("Virtual Size: %sMB\n", color.YellowString("%.2f", float64(image.VirtualSize)/(1024*1024))) baseImageName := builder.GetBaseImageName(repository, f.Version) image, err = dockerManager.FindImage(baseImageName) f.UI.Printf("\nStemcell Layer: %s\n", color.GreenString(baseImageName)) f.UI.Printf("ID: %s\n", color.GreenString(image.ID)) f.UI.Printf("Virtual Size: %sMB\n", color.YellowString("%.2f", float64(image.VirtualSize)/(1024*1024))) return nil }
func printProject(project *Project, depth int, buffer *bytes.Buffer, noColor bool, showpath bool) { color.NoColor = noColor buffer.WriteString(strings.Repeat(" ", depth)) buffer.WriteString(color.GreenString(project.ArtifactID)) buffer.WriteString(" (") buffer.WriteString(project.Version) buffer.WriteString(")") if project.MismatchParentVersion != "" { buffer.WriteString(color.YellowString(" Warning: looking for parent version: ")) buffer.WriteString(project.MismatchParentVersion) } else if project.MissingParent != "" { buffer.WriteString(color.YellowString(" Warning: parent not found: ")) buffer.WriteString(project.MissingParent) } if showpath { buffer.WriteString(color.CyanString(" " + project.FullPath)) } buffer.WriteString("\n") sort.Sort(project.Children) for _, child := range project.Children { printProject(child, depth+1, buffer, noColor, showpath) } }
func (c container) cacheHandler(w http.ResponseWriter, r *http.Request) { if r.Method == "POST" { var cacheStatus string var urlComponents = []string{ "http://", config.backend, r.URL.Path, } backendURL := strings.Join(urlComponents, "") body, _ := ioutil.ReadAll(r.Body) identifier := []byte(fmt.Sprintf("%s%s", body, r.URL.Path)) sum := md5.Sum(identifier) hash := hex.EncodeToString(sum[:16]) redisConn := c.pool.Get() defer redisConn.Close() repl, err := redisConn.Do("GET", hash) if err != nil { log.Error(err.Error()) return } if repl == nil { log.Debug(fmt.Sprintf("%s %s", hash, color.YellowString("MISS"))) w.Header().Set("X-postcache", "MISS") response, cacheError := c.updateCache(hash, string(body), backendURL, false) if cacheError != nil { log.Error(cacheError.Error()) } w.Write([]byte(response)) } else { ttlrepl, ttlerr := redisConn.Do("TTL", hash) if ttlerr != nil { log.Error("key is gone? maybe the TTL expired before we got here.") } else { if ttlrepl.(int64) < int64((config.expire - config.freshness)) { cacheStatus = color.YellowString("STALE") go c.updateCache(hash, string(body), backendURL, true) } else { cacheStatus = color.CyanString("HIT") } } log.Debug(fmt.Sprintf("%s %s ", hash, cacheStatus)) w.Header().Set("X-postcache", cacheStatus) w.Write(repl.([]byte)) } } else { w.Header().Set("X-postcache", "CANT-CACHE") proxy := &httputil.ReverseProxy{ Director: func(req *http.Request) { req.URL.Scheme = "http" req.URL.Host = config.backend }, } proxy.ServeHTTP(w, r) } }
// GenerateBaseDockerImage generates a base docker image to be used as a FROM for role images func (f *Fissile) GenerateBaseDockerImage(targetPath, baseImage, metricsPath string, noBuild bool, repository string) error { if metricsPath != "" { stampy.Stamp(metricsPath, "fissile", "create-role-base", "start") defer stampy.Stamp(metricsPath, "fissile", "create-role-base", "done") } dockerManager, err := docker.NewImageManager() if err != nil { return fmt.Errorf("Error connecting to docker: %s", err.Error()) } baseImageName := builder.GetBaseImageName(repository, f.Version) image, err := dockerManager.FindImage(baseImageName) if err == docker.ErrImageNotFound { f.UI.Println("Image doesn't exist, it will be created ...") } else if err != nil { return fmt.Errorf("Error looking up image: %s", err.Error()) } else { f.UI.Println(color.GreenString( "Base role image %s with ID %s already exists. Doing nothing.", color.YellowString(baseImageName), color.YellowString(image.ID), )) return nil } if !strings.HasSuffix(targetPath, string(os.PathSeparator)) { targetPath = fmt.Sprintf("%s%c", targetPath, os.PathSeparator) } baseImageBuilder := builder.NewBaseImageBuilder(baseImage) if noBuild { f.UI.Println("Skipping image build because of flag.") return nil } f.UI.Println("Building base docker image ...") log := new(bytes.Buffer) stdoutWriter := docker.NewFormattingWriter( log, docker.ColoredBuildStringFunc(baseImageName), ) tarPopulator := baseImageBuilder.NewDockerPopulator() err = dockerManager.BuildImageFromCallback(baseImageName, stdoutWriter, tarPopulator) if err != nil { log.WriteTo(f.UI) return fmt.Errorf("Error building base image: %s", err) } f.UI.Println(color.GreenString("Done.")) return nil }
func SupervisorCommand() cli.Command { return cli.Command{ Name: "supervisor", SkipFlagParsing: true, Action: func(c *cli.Context) error { var cmd *exec.Cmd = nil go func() { backoff.Retry(func() error { log.Println(color.GreenString("supervisor: Starting %v", c.Args())) cmd = exec.Command(c.Args().First(), c.Args().Tail()...) cmd.Stdout = os.Stdout cmd.Stderr = os.Stderr if err := cmd.Start(); err != nil { log.Println(color.RedString("supervisor: Error on process staring %v", err)) return err } err := cmd.Wait() if err != nil { log.Println(color.RedString("supervisor: Command exit with error: %v", err)) } else { log.Println(color.YellowString("supervisor: Command completed.")) os.Exit(0) } return err }, backoff.NewConstantBackOff(time.Second*3)) }() // Handle shutdown signals and kill child process ch := make(chan os.Signal) signal.Notify(ch, syscall.SIGINT, syscall.SIGTERM, syscall.SIGKILL) log.Println("supervisor: receive signal", <-ch) if cmd != nil { log.Println("supervisor: send SIGTERM to subprocess") cmd.Process.Signal(syscall.SIGTERM) res, err := cmd.Process.Wait() log.Println("supervisor: subprocess stopped with", res, err) } log.Println(color.YellowString("supervisor: Stopped.")) os.Exit(143) return nil }, } }
// GeneratePackagesRoleImage builds the docker image for the packages layer // where all packages are included func (f *Fissile) GeneratePackagesRoleImage(repository string, roleManifest *model.RoleManifest, noBuild, force bool, packagesImageBuilder *builder.PackagesImageBuilder) error { if len(f.releases) == 0 { return fmt.Errorf("Releases not loaded") } dockerManager, err := docker.NewImageManager() if err != nil { return fmt.Errorf("Error connecting to docker: %s", err.Error()) } packagesLayerImageName := packagesImageBuilder.GetRolePackageImageName(roleManifest) if !force { if hasImage, err := dockerManager.HasImage(packagesLayerImageName); err == nil && hasImage { f.UI.Printf("Packages layer %s already exists. Skipping ...\n", color.YellowString(packagesLayerImageName)) return nil } } baseImageName := builder.GetBaseImageName(repository, f.Version) if hasImage, err := dockerManager.HasImage(baseImageName); err != nil { return fmt.Errorf("Error getting base image: %s", err) } else if !hasImage { return fmt.Errorf("Failed to find role base %s, did you build it first?", baseImageName) } if noBuild { f.UI.Println("Skipping packages layer docker image build because of --no-build flag.") return nil } f.UI.Printf("Building packages layer docker image %s ...\n", color.YellowString(packagesLayerImageName)) log := new(bytes.Buffer) stdoutWriter := docker.NewFormattingWriter( log, docker.ColoredBuildStringFunc(packagesLayerImageName), ) tarPopulator := packagesImageBuilder.NewDockerPopulator(roleManifest, force) err = dockerManager.BuildImageFromCallback(packagesLayerImageName, stdoutWriter, tarPopulator) if err != nil { log.WriteTo(f.UI) return fmt.Errorf("Error building packages layer docker image: %s", err.Error()) } f.UI.Println(color.GreenString("Done.")) return nil }
func (rl *ResponseLogWriter) logCode(code int, status string) { var codestr string switch { case code >= 200 && code < 300: codestr = color.GreenString("%d %s", code, status) case code >= 300 && code < 400: codestr = color.BlueString("%d %s", code, status) case code >= 400 && code < 500: codestr = color.YellowString("%d %s", code, status) case code >= 500 && code < 600: codestr = color.RedString("%d %s", code, status) default: codestr = fmt.Sprintf("%d %s", code, status) } cl := rl.Header().Get("content-length") if cl != "" { cli, err := strconv.Atoi(cl) if err != nil { cl = "invalid content length header" } else { cl = fmt.Sprintf("%s", humanize.Bytes(uint64(cli))) } } rl.Log.Say("<- %s %s", codestr, cl) }
// CreateBaseCompilationImage will recompile the base BOSH image for a release func (f *Fissile) CreateBaseCompilationImage(baseImageName, repository, metricsPath string, keepContainer bool) error { if metricsPath != "" { stampy.Stamp(metricsPath, "fissile", "create-compilation-image", "start") defer stampy.Stamp(metricsPath, "fissile", "create-compilation-image", "done") } dockerManager, err := docker.NewImageManager() if err != nil { return fmt.Errorf("Error connecting to docker: %s", err.Error()) } baseImage, err := dockerManager.FindImage(baseImageName) if err != nil { return fmt.Errorf("Error looking up base image %s: %s", baseImageName, err) } f.UI.Println(color.GreenString("Base image with ID %s found", color.YellowString(baseImage.ID))) comp, err := compilator.NewCompilator(dockerManager, "", "", repository, compilation.UbuntuBase, f.Version, keepContainer, f.UI) if err != nil { return fmt.Errorf("Error creating a new compilator: %s", err.Error()) } if _, err := comp.CreateCompilationBase(baseImageName); err != nil { return fmt.Errorf("Error creating compilation base image: %s", err.Error()) } return nil }
func TestErrorPrinter_Printing(t *testing.T) { saveExitFunction := exitFunction defer func() { exitFunction = saveExitFunction }() exitCode := -1 exitFunction = func(code int) { exitCode = codeUnsupportedOSError } in, out := &bytes.Buffer{}, &bytes.Buffer{} ui := New(in, out, nil) printer := NewErrorPrinter(ui) err1 := UnsupportedOSError("windows") err2 := fmt.Errorf("Generic error") printer.PrintAndExit(err1) exp := color.RedString("Error (%d): Unsupported OS: windows", codeUnsupportedOSError) if got := strings.TrimSpace(out.String()); got != exp { t.Error("wrong error message:", got) } if exitCode != codeUnsupportedOSError { t.Error("wrong exit code:", exitCode) } out.Reset() printer.PrintWarning(err2) exp = color.YellowString("Warning (%d): Generic error", CodeUnknownError) if got := strings.TrimSpace(out.String()); got != exp { t.Error("wrong error message:", got) } }
func (m Manifest) FindPlugins(plugin string) ([]PluginData, error) { tree := m.tree.Path(plugin) result := make([]PluginData, 0) if tree.Data() == nil { return nil, fmt.Errorf("Plugin `%s` not found in manifest!", plugin) } if _, ok := tree.Data().([]interface{}); ok { arr, _ := tree.Children() for _, item := range arr { if _, ok := item.Data().(string); ok { result = append(result, makePluginPair(plugin, item)) } else if res, err := item.ChildrenMap(); err == nil { if len(res) == 1 { for subplugin, data := range res { result = append(result, makePluginPair(plugin+"."+subplugin, data)) break } } else { result = append(result, makePluginPair(plugin, item)) } } } } else if PluginRegestry.Has(plugin) { result = append(result, makePluginPair(plugin, tree)) } else { log.Println(color.YellowString("Plugins for `%s` section not specified, skip...", plugin)) } return result, nil }
func dump(w http.ResponseWriter, r *http.Request) { var jsonData interface{} defer r.Body.Close() r.Header.Set("Host", r.Host) for _, header := range sortHeaderKeys(r.Header) { fmt.Printf("%s %s: %s\n", color.YellowString("[H]"), header, r.Header.Get(header)) } body, err := ioutil.ReadAll(r.Body) if err != nil { fmt.Printf("error: unable to read request body: %s", err) return } if getContentType(r) == "application/json" { if err := json.Unmarshal(body, &jsonData); err != nil { fmt.Printf("%s error: request Content-Type is application/json, but unable to process JSON %s\n", color.RedString("[!]"), err) fmt.Printf("%s %s\n", color.CyanString("[B]"), body) } else { jf := prettyjson.NewFormatter() j, _ := jf.Format(body) fmt.Printf("%s %s\n", color.CyanString("[B]"), j) } } else { fmt.Printf("%s %s\n", color.CyanString("[B]"), body) } }
func getSearchOpt() (SearchType, FilterType) { var ( search SearchType = SearchBySubject filter FilterType = SearchFilterAll ) for { color.White("Please select search range:\n") for k := SearchFilterAll; k <= SearchConference; k++ { fmt.Fprintf(color.Output, "\t %s: %s\n", color.CyanString("%d", k), searchFilterHints[k]) } fmt.Fprintf(color.Output, "$ %s", color.YellowString("select: ")) s := getInputString() if len(s) > 0 { selected, err := strconv.ParseInt(s, 16, 32) if err != nil || selected < int64(SearchFilterAll) || selected > int64(SearchConference) { color.Red("Invalid selection\n") continue } filter = FilterType(selected) } break } return search, filter }
// WarnHandler captures Sass warnings and redirects to stdout func WarnHandler(v interface{}, csv libsass.SassValue, rsv *libsass.SassValue) error { var s string libsass.Unmarshal(csv, &s) fmt.Println(color.YellowString("WARNING: " + s)) r, _ := libsass.Marshal("") *rsv = r return nil }
func (f *Fissile) listPropertiesForHuman() { // Human readable output. for _, release := range f.releases { f.UI.Println(color.GreenString("Dev release %s (%s)", color.YellowString(release.Name), color.MagentaString(release.Version))) for _, job := range release.Jobs { f.UI.Printf("%s (%s): %s\n", color.YellowString(job.Name), color.WhiteString(job.Version), job.Description) for _, property := range job.Properties { f.UI.Printf("\t%s: %v\n", color.YellowString(property.Name), property.Default) } } } }
func (fa *FairnessAnalysis) Visit(fn *ssa.Function) { visitedBlk := make(map[*ssa.BasicBlock]bool) fa.logger.Printf("Visiting: %s", fn.String()) for _, blk := range fn.Blocks { if _, visited := visitedBlk[blk]; !visited { visitedBlk[blk] = true fa.logger.Printf(" block %d %s", blk.Index, blk.Comment) // First consider blocks with loop initialisation blocks. if blk.Comment == "rangeindex.loop" { fa.total++ fa.logger.Println(color.GreenString("✓ range loops are fair")) } else if blk.Comment == "rangechan.loop" { fa.total++ hasClose := false for _, ch := range fa.info.FindChan(blk.Instrs[0].(*ssa.UnOp).X) { if ch.Type == ssabuilder.ChanClose { fa.logger.Println(color.GreenString("✓ found corresponding close() - channel range likely fair")) hasClose = true } } if !hasClose { fa.logger.Println(color.RedString("❌ range over channel w/o close() likely unfair (%s)", fa.info.FSet.Position(blk.Instrs[0].Pos()))) fa.unsafe++ } } else if blk.Comment == "for.loop" { fa.total++ if fa.isLikelyUnsafe(blk) { fa.logger.Println(color.RedString("❌ for.loop maybe bad")) fa.unsafe++ } else { fa.logger.Println(color.GreenString("✓ for.loop is ok")) } } else { // Normal blocks (or loops without initialisation blocks). if len(blk.Instrs) > 1 { if ifInst, ok := blk.Instrs[len(blk.Instrs)-1].(*ssa.If); ok { _, thenVisited := visitedBlk[ifInst.Block().Succs[0]] _, elseVisited := visitedBlk[ifInst.Block().Succs[1]] if thenVisited || elseVisited { // there is a loop! fa.total++ if !fa.isCondFair(ifInst.Cond) { fa.logger.Println(color.YellowString("Warning: recurring block condition probably unfair")) fa.unsafe++ } else { fa.logger.Println(color.GreenString("✓ recurring block is ok")) } } } else if jInst, ok := blk.Instrs[len(blk.Instrs)-1].(*ssa.Jump); ok { if _, visited := visitedBlk[jInst.Block().Succs[0]]; visited { fa.total++ fa.unsafe++ fa.logger.Println(color.RedString("❌ infinite loop or recurring block, probably bad (%s)", fa.info.FSet.Position(blk.Instrs[0].Pos()))) } } } } } } }
func DeletePluginData(plugin string, packageName string, consulAddress string) error { log.Println(color.YellowString("Delete %s for %s package in consul", plugin, packageName)) consulApi, err := ConsulClient(consulAddress) if err != nil { return err } return DelConsulKv(consulApi, "services/data/"+packageName+"/"+plugin) }
func (app *App) Interactive() { rl, err := readline.NewEx(&readline.Config{ Prompt: color.BlueString("say » "), HistoryFile: app.Config.HistoryFile, }) if err != nil { log.Fatal(err) } defer rl.Close() app.Log.SetOutput(rl.Stderr()) log.SetOutput(rl.Stderr()) color.Output = ansicolor.NewAnsiColorWriter(rl.Stderr()) pings := make(map[string]time.Time) // Subscribe to all replies and print them to stdout app.Client.Subscribe("", "self", func(msg sarif.Message) { text := msg.Text if text == "" { text = msg.Action + " from " + msg.Source } if msg.IsAction("err") { text = color.RedString(text) } if sent, ok := pings[msg.CorrId]; ok { text += color.YellowString("[%.1fms]", time.Since(sent).Seconds()*1e3) } log.Println(color.GreenString(" « ") + strings.Replace(text, "\n", "\n ", -1)) }) // Interactive mode sends all lines from stdin. for { line, err := rl.Readline() if err != nil { if err == io.EOF { return } log.Fatal(err) } if len(line) == 0 { continue } // Publish natural message msg := sarif.Message{ Id: sarif.GenerateId(), Action: "natural/handle", Text: line, } if *profile { pings[msg.Id] = time.Now() } app.Client.Publish(msg) } }
// CleanCache inspects the compilation cache and removes all packages // which are not referenced (anymore). func (f *Fissile) CleanCache(targetPath string) error { // 1. Collect list of packages referenced by the releases. A // variant of the code in ListPackages, we keep only the // hashes. if len(f.releases) == 0 { return fmt.Errorf("Releases not loaded") } referenced := make(map[string]int) for _, release := range f.releases { for _, pkg := range release.Packages { referenced[pkg.Version] = 1 } } /// 2. Scan local compilation cache, compare to referenced, /// remove anything not found. f.UI.Printf("Cleaning up %s\n", color.MagentaString(targetPath)) cached, err := filepath.Glob(targetPath + "/*") if err != nil { return err } removed := 0 for _, cache := range cached { key := filepath.Base(cache) if _, ok := referenced[key]; ok { continue } f.UI.Printf("- Removing %s\n", color.YellowString(key)) if err := os.RemoveAll(cache); err != nil { return err } removed++ } if removed == 0 { f.UI.Println("Nothing found to remove") return nil } plural := "" if removed > 1 { plural = "s" } f.UI.Printf("Removed %s package%s\n", color.MagentaString(fmt.Sprintf("%d", removed)), plural) return nil }
func highlightWords(message, keyword string) string { words := []string{} for _, word := range strings.Fields(keyword) { words = append(words, regexp.QuoteMeta(word)) } pattern := regexp.MustCompile(strings.Join(words, "|")) return pattern.ReplaceAllStringFunc(message, func(s string) string { return color.YellowString(s) }) }
// ListJobs will list all jobs within a list of dev releases func (f *Fissile) ListJobs() error { if len(f.releases) == 0 { return fmt.Errorf("Releases not loaded") } for _, release := range f.releases { f.UI.Println(color.GreenString("Dev release %s (%s)", color.YellowString(release.Name), color.MagentaString(release.Version))) for _, job := range release.Jobs { f.UI.Printf("%s (%s): %s\n", color.YellowString(job.Name), color.WhiteString(job.Version), job.Description) } f.UI.Printf( "There are %s jobs present.\n\n", color.GreenString("%d", len(release.Jobs)), ) } return nil }
// ListPackages will list all BOSH packages within a list of dev releases func (f *Fissile) ListPackages() error { if len(f.releases) == 0 { return fmt.Errorf("Releases not loaded") } for _, release := range f.releases { f.UI.Println(color.GreenString("Dev release %s (%s)", color.YellowString(release.Name), color.MagentaString(release.Version))) for _, pkg := range release.Packages { f.UI.Printf("%s (%s)\n", color.YellowString(pkg.Name), color.WhiteString(pkg.Version)) } f.UI.Printf( "There are %s packages present.\n\n", color.GreenString("%d", len(release.Packages)), ) } return nil }
// ListRoleImages lists all dev role images func (f *Fissile) ListRoleImages(repository string, rolesManifestPath string, existingOnDocker, withVirtualSize bool) error { if withVirtualSize && !existingOnDocker { return fmt.Errorf("Cannot list image virtual sizes if not matching image names with docker") } if len(f.releases) == 0 { return fmt.Errorf("Releases not loaded") } var dockerManager *docker.ImageManager var err error if existingOnDocker { dockerManager, err = docker.NewImageManager() if err != nil { return fmt.Errorf("Error connecting to docker: %s", err.Error()) } } rolesManifest, err := model.LoadRoleManifest(rolesManifestPath, f.releases) if err != nil { return fmt.Errorf("Error loading roles manifest: %s", err.Error()) } for _, role := range rolesManifest.Roles { imageName := builder.GetRoleDevImageName(repository, role, role.GetRoleDevVersion()) if !existingOnDocker { f.UI.Println(imageName) continue } image, err := dockerManager.FindImage(imageName) if err == docker.ErrImageNotFound { continue } else if err != nil { return fmt.Errorf("Error looking up image: %s", err.Error()) } if withVirtualSize { f.UI.Printf( "%s (%sMB)\n", color.GreenString(imageName), color.YellowString("%.2f", float64(image.VirtualSize)/(1024*1024)), ) } else { f.UI.Println(imageName) } } return nil }
func (e *Entry) Row() []string { y, m, d := e.Time.Date() date := color.BlueString("%d/%d/%d", m, d, y) ip := color.RedString("%s", e.Ip) attempts := color.GreenString("%d", e.Attempts) user := color.YellowString("%s", e.User) auth := color.WhiteString("%s", e.AuthType) proto := color.CyanString("%s", e.Protocol) port := e.Port server := e.Server return []string{date, ip, attempts, user, auth, proto, port, server} }
// isCondFair returns true if an if condition (bool expression) is constant. func (fa *FairnessAnalysis) isCondFair(cond ssa.Value) bool { switch cond := cond.(type) { case *ssa.Const: fa.logger.Println(color.YellowString("Warning: loop condition is constant")) return false case *ssa.BinOp: // <, <=, !=, == if _, xConst := cond.X.(*ssa.Const); xConst { if _, yConst := cond.Y.(*ssa.Const); yConst { fa.logger.Println(color.YellowString("Warning: loop condition is constant")) return false } else { fa.logger.Println(color.YellowString("Try to trace back on Y")) } } else { fa.logger.Println(color.YellowString("Try to trace back on X")) } case *ssa.UnOp: if _, con := cond.X.(*ssa.Const); con { fa.logger.Println(color.YellowString("Warning: loop condition is constant")) return false } case *ssa.Call: fa.logger.Println(color.YellowString("Warning:%s: condition is function call --> unsure", fa.info.FSet.Position(cond.Pos()).String())) return false } return true // Assume fair by default }
// Logo with color func Logo() string { var logo string logo += "\n\n" logo += color.GreenString(" ██╗ ██╗ ██████╗ ███╗ ███╗ █████╗ ███╗ ██╗██████╗ █████╗\n") logo += color.MagentaString(" ██║ ██╔╝██╔═══██╗████╗ ████║██╔══██╗████╗ ██║██╔══██╗██╔══██╗\n") logo += color.YellowString(" █████╔╝ ██║ ██║██╔████╔██║███████║██╔██╗ ██║██║ ██║███████║\n") logo += color.CyanString(" ██╔═██╗ ██║ ██║██║╚██╔╝██║██╔══██║██║╚██╗██║██║ ██║██╔══██║\n") logo += color.BlueString(" ██║ ██╗╚██████╔╝██║ ╚═╝ ██║██║ ██║██║ ╚████║██████╔╝██║ ██║\n") logo += color.RedString(" ╚═╝ ╚═╝ ╚═════╝ ╚═╝ ╚═╝╚═╝ ╚═╝╚═╝ ╚═══╝╚═════╝ ╚═╝ ╚═╝") return logo }
// isLikelyUnsafe checks if a given "for.loop" block has non-static index and // non-static loop condition. func (fa *FairnessAnalysis) isLikelyUnsafe(blk *ssa.BasicBlock) bool { for _, instr := range blk.Instrs { switch instr := instr.(type) { case *ssa.DebugRef: case *ssa.If: // Last instruction of block if !fa.isCondFair(instr.Cond) { fa.logger.Println(color.YellowString("Warning: loop condition probably unfair")) return true // Definitely unsafe } } } // Reaching here mean the exit cond is not func call or constant if fa.isIndexStatic(blk) { // If index is static or unchanged (i.e. while loop), that means // 1. The exit condition is NOT index // 2. The exit condition dependent on 'outside' variable // TODO(nickng): check that if-condition is used in body fa.logger.Println(color.YellowString("Warning: cannot find loop index")) return true // Assume unsafe } return false }
func blockUntilSignal() { sigs := make(chan os.Signal, 1) done := make(chan bool, 1) signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM) go func() { <-sigs done <- true }() <-done log.Println(color.YellowString("Received signal to quit.")) }
// // print a set of articles // func printArticles(page int, articles []Article) { fmt.Fprintf(color.Output, "\n-----------------------------------------------------------(%s)--\n", color.MagentaString("page:%d", page)) for id, entry := range articles { source := entry.Information.SourceName if len(source) == 0 { source = "N/A" } fmt.Fprintf(color.Output, "%s: %s (%s)\n", color.CyanString("%02d", id+1), color.WhiteString(entry.Information.Title), color.YellowString("%s", source)) } fmt.Fprintf(color.Output, "-----------------------------------------------------------(%s)--\n\n", color.MagentaString("page%d", page)) }
func printOutput(outs []byte, commandError bool) { if len(outs) > 0 { var output string if commandError { output = color.RedString("%s", string(outs)) } else { output = color.YellowString("%s", string(outs)) } fmt.Println(output) } }