예제 #1
0
파일: fissile.go 프로젝트: hpcloud/fissile
// 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
}
예제 #2
0
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())))
						}
					}
				}
			}
		}
	}
}
예제 #3
0
func testFiles(t *testing.T, files []string, loader *Loader) {
	var passing, total, schemaErrors int
	for _, file := range files {
		f, err := os.Open(file)
		if err != nil {
			t.Fatalf("Failed to open %q: %s", file, err)
		}
		v, err := json.Parse(f)
		f.Close()
		if err != nil {
			t.Fatalf("Failed to parse %q: %s", file, err)
		}

		tests, ok := v.(*json.Array)
		if !ok {
			t.Fatalf("Content of %q is not an array: %T", file, v)
		}
		for i, tt := range tests.Value {
			test, ok := tt.(*json.Object)
			if !ok {
				t.Fatalf("Test %d in %q is not an object", i, file)
			}
			t.Logf(color.BlueString("=====> Testing %s, case %d: %s", file, i, test.Find("description")))
			schema := test.Find("schema")
			err := ValidateDraft04Schema(schema)
			if err != nil {
				t.Errorf(color.RedString("schema does not pass validation: %s", err))
				schemaErrors++
			}
			v, _ := NewValidator(schema, loader) // not checking the error since schema is already validated
			cases := test.Find("tests").(*json.Array)
			for _, c := range cases.Value {
				total++
				case_ := c.(*json.Object)
				valid := case_.Find("valid").(*json.Bool).Value
				err := v.Validate(case_.Find("data"))
				switch {
				case err == nil && valid:
					passing++
					t.Logf("%s %s", color.GreenString("PASSED"), case_.Find("description"))
				case err != nil && !valid:
					passing++
					t.Logf("%s %s: %s", color.GreenString("PASSED"), case_.Find("description"), err)
				case err != nil && valid:
					t.Errorf("%s %s: %s", color.RedString("FAILED"), case_.Find("description"), err)
				case err == nil && !valid:
					t.Errorf("%s %s", color.RedString("FAILED"), case_.Find("description"))
				}
			}
		}
	}
	t.Logf("Passing %d out of %d tests (%g%%)", passing, total, float64(passing)/float64(total)*100)
	if schemaErrors > 0 {
		t.Logf("%d schemas failed validation", schemaErrors)
	}
}
예제 #4
0
파일: fissile.go 프로젝트: hpcloud/fissile
// 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
}
예제 #5
0
파일: serve.go 프로젝트: kulikov/serve
func main() {
	manifestFile := kingpin.Flag("manifest", "Path to manifest.yml file.").Default("manifest.yml").String()
	plugin := kingpin.Arg("plugin", "Plugin name for run.").String()
	vars := *kingpin.Flag("var", "key=value pairs with manifest vars.").StringMap()
	dryRun := kingpin.Flag("dry-run", "Show manifest section only").Bool()
	noColor := kingpin.Flag("no-color", "Disable colored output").Bool()
	pluginData := kingpin.Flag("plugin-data", "Data for plugin").String()

	kingpin.Version(version)
	kingpin.Parse()

	var plugins []manifest.PluginData
	var err error
	var manifestData *manifest.Manifest

	color.NoColor = *noColor

	if *pluginData != "" {
		manifestData = manifest.LoadJSON(*pluginData)
	} else {
		manifestData = manifest.Load(*manifestFile, vars)
	}

	if *plugin == "" && *dryRun {
		fmt.Printf("%s\n%s\n%s\n",
			color.GreenString(">>> manifest:"),
			manifestData.String(),
			color.GreenString("<<< manifest: OK\n"))
		return
	}

	if *pluginData != "" {
		plugins = []manifest.PluginData{manifestData.GetPluginWithData(*plugin)}
	} else {
		plugins, err = manifestData.FindPlugins(*plugin)
	}

	if err != nil {
		log.Fatalln(color.RedString("Error find plugins for '%s': %v", *plugin, err))
	}

	for _, pair := range plugins {
		log.Printf("%s\n%s\n\n", color.GreenString(">>> %s:", pair.PluginName), color.CyanString("%s", pair.Data))

		if !*dryRun {
			if err := pair.Plugin.Run(pair.Data); err != nil {
				fmt.Println("")
				log.Fatalln(color.RedString("Error on run plugin `%s`: %v", pair.PluginName, err))
			} else {
				log.Println(color.GreenString("<<< %s: OK", pair.PluginName))
			}
		}
	}
}
예제 #6
0
func (channel *Channel) NickListString(v *gocui.View) {
	sort.Sort(NickSorter(channel.Users))

	fmt.Fprintf(v, "\n%s", color.GreenString("== NICK LIST START\n"))

	for i, u := range channel.Users {
		if i == len(channel.Users)-1 {
			fmt.Fprintf(v, "%s%s", u.Mode, u.Nick)
		} else {
			fmt.Fprintf(v, "%s%s, ", u.Mode, u.Nick)
		}
	}

	fmt.Fprintf(v, "\n%s", color.GreenString("== NICK LIST END\n\n"))
}
예제 #7
0
파일: packages.go 프로젝트: abutre/bunch
func checkOutdatedPackages(b *BunchFile) error {
	err := setVendorEnv()
	if err != nil {
		return errors.Trace(err)
	}

	for _, pack := range b.Packages {
		if pack.IsSelf {
			continue
		}

		fmt.Printf("package %s ... ", pack.Repo)

		err := fetchPackage(pack.Repo)
		if err != nil {
			return errors.Trace(err)
		}

		needsUpdate, recency, err := checkPackageRecency(pack)
		if err != nil {
			return errors.Trace(err)
		}

		if !needsUpdate {
			if recency.UpstreamDiffCount == 0 {
				fmt.Printf("\rpackage %s ... %s\n", pack.Repo, color.GreenString("up to date"))
			} else {
				if pack.LockedVersion == "" {
					fmt.Printf("\rpackage %s ... %s by %s, current is %6s, latest is %6s\n", pack.Repo, color.YellowString("behind upstream"), commitsPlural(recency.UpstreamDiffCount), gitShort(recency.InstalledCommit), gitShort(recency.LatestUpstreamCommit))
				} else {
					fmt.Printf("\rpackage %s ... %s by %s, current is %6s, latest is %6s\n", pack.Repo, color.YellowString("locked, but behind upstream"), commitsPlural(recency.UpstreamDiffCount), gitShort(recency.InstalledCommit), gitShort(recency.LatestUpstreamCommit))
				}
			}
		} else {
			if recency.InstalledDiffCount == 0 {
				fmt.Printf("\rpackage %s ... %s\n", pack.Repo, color.GreenString("up to date"))
			} else {
				if pack.LockedVersion == "" {
					fmt.Printf("\rpackage %s ... %s by %s, current is %6s, latest is %6s\n", pack.Repo, color.RedString("outdated"), commitsPlural(recency.InstalledDiffCount), gitShort(recency.InstalledCommit), gitShort(recency.LatestCommit))
				} else {
					fmt.Printf("\rpackage %s ... %s by %s, current is %6s, latest is %6s\n", pack.Repo, color.YellowString("locked, but outdated"), commitsPlural(recency.InstalledDiffCount), gitShort(recency.InstalledCommit), gitShort(recency.LatestCommit))
				}
			}
		}
	}

	return nil
}
예제 #8
0
func main() {
	l := termlog.NewLog()
	testpatt(l)

	g := l.Group()
	g.Say("This is a group...")
	testpatt(g)
	g.Done()

	g = l.Group()
	g.Say("Here are some composed colours...")
	g.Say(
		"%s %s %s",
		color.RedString("red"),
		color.GreenString("green"),
		color.BlueString("blue"),
	)
	g.Done()

	l.Enable("demo")
	g = l.Group()
	g.SayAs("disabled", "These don't show...")
	g.SayAs("demo", "Some named log entries...")
	g.SayAs("demo", "This is a test")
	g.SayAs("disabled", "This is a test")
	g.Done()

	g = l.Group()
	g.Say("Disabled colour output...")
	l.NoColor()
	testpatt(g)
	g.Done()
}
예제 #9
0
파일: pb_test.go 프로젝트: dzyk/dcoin-go
func Test_Format(t *testing.T) {
	bar := New(5000).Format(strings.Join([]string{
		color.GreenString("["),
		color.New(color.BgGreen).SprintFunc()("o"),
		color.New(color.BgHiGreen).SprintFunc()("o"),
		color.New(color.BgRed).SprintFunc()("o"),
		color.GreenString("]"),
	}, "\x00"))
	w := colorable.NewColorableStdout()
	bar.Callback = func(out string) {
		w.Write([]byte(out))
	}
	bar.Add(2000)
	bar.Finish()
	bar.Finish()
}
예제 #10
0
파일: fissile.go 프로젝트: hpcloud/fissile
// 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
}
예제 #11
0
func resetPasswordCommand(c CommandLine) error {
	newPassword := c.Args().First()

	password := models.Password(newPassword)
	if password.IsWeak() {
		return fmt.Errorf("New password is too short")
	}

	userQuery := models.GetUserByIdQuery{Id: AdminUserId}

	if err := bus.Dispatch(&userQuery); err != nil {
		return fmt.Errorf("Could not read user from database. Error: %v", err)
	}

	passwordHashed := util.EncodePassword(newPassword, userQuery.Result.Salt)

	cmd := models.ChangeUserPasswordCommand{
		UserId:      AdminUserId,
		NewPassword: passwordHashed,
	}

	if err := bus.Dispatch(&cmd); err != nil {
		return fmt.Errorf("Failed to update user password")
	}

	logger.Infof("\n")
	logger.Infof("Admin password changed successfully %s", color.GreenString("✔"))

	return nil
}
예제 #12
0
파일: formats.go 프로젝트: sgoertzen/pvi
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)
	}
}
예제 #13
0
파일: fissile.go 프로젝트: hpcloud/fissile
func (f *Fissile) reportHashDiffs(hashDiffs *HashDiffs) {
	if len(hashDiffs.DeletedKeys) > 0 {
		f.UI.Println(color.RedString("Dropped keys:"))
		sort.Strings(hashDiffs.DeletedKeys)
		for _, v := range hashDiffs.DeletedKeys {
			f.UI.Printf("  %s\n", v)
		}
	}
	if len(hashDiffs.AddedKeys) > 0 {
		f.UI.Println(color.GreenString("Added keys:"))
		sort.Strings(hashDiffs.AddedKeys)
		for _, v := range hashDiffs.AddedKeys {
			f.UI.Printf("  %s\n", v)
		}
	}
	if len(hashDiffs.ChangedValues) > 0 {
		f.UI.Println(color.BlueString("Changed values:"))
		sortedKeys := make([]string, len(hashDiffs.ChangedValues))
		i := 0
		for k := range hashDiffs.ChangedValues {
			sortedKeys[i] = k
			i++
		}
		sort.Strings(sortedKeys)
		for _, k := range sortedKeys {
			v := hashDiffs.ChangedValues[k]
			f.UI.Printf("  %s: %s => %s\n", k, v[0], v[1])
		}
	}
}
예제 #14
0
func okColor(format string, args ...interface{}) string {
	if *flag_color {
		return color.GreenString(format, args...)
	} else {
		return fmt.Sprintf(format, args...)
	}
}
예제 #15
0
파일: responselogger.go 프로젝트: npk/devd
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)
}
예제 #16
0
파일: protocol.go 프로젝트: javajax/degdb
func (s *Server) handleHandshake(conn *Conn, msg *protocol.Message) {
	handshake := msg.GetHandshake()
	conn.Peer = handshake.GetSender()

	s.peersLock.RLock()
	peer := s.Peers[conn.Peer.Id]
	s.peersLock.RUnlock()

	if peer != nil {
		s.Printf("Ignoring duplicate peer %s.", conn.PrettyID())
		if err := conn.Close(); err != nil && err != io.EOF {
			s.Printf("ERR closing connection %s", err)
		}
		return
	}

	s.peersLock.Lock()
	s.Peers[conn.Peer.Id] = conn
	s.peersLock.Unlock()

	s.Print(color.GreenString("New peer %s", conn.PrettyID()))
	if !handshake.Response {
		if err := s.sendHandshake(conn, true); err != nil {
			s.Printf("ERR sendHandshake %s", err)
		}
	} else {
		if err := s.sendPeerRequest(conn); err != nil {
			s.Printf("ERR sendPeerRequest %s", err)
		}
	}
	go s.connHeartbeat(conn)
}
예제 #17
0
func (this *Options) Echo() {
	output := color.CyanString("replacing:   ")
	output += color.GreenString("%s\n", this.From)
	output += color.CyanString("with:        ")
	output += color.GreenString("%s\n", this.To)
	output += color.CyanString("in files:    ")
	output += color.GreenString("%s\n", this.File)
	output += color.CyanString("starting in: ")
	output += color.GreenString("%s\n", this.Dir)

	if this.Ignore != "" {
		output += color.CyanString("ignoring:    ")
		output += color.GreenString("%s\n", this.Ignore)
	}

	fmt.Print(output)
}
예제 #18
0
파일: main.go 프로젝트: osamingo/git-fire
func isPushed(remote string, err error) {

	if err == nil {
		fmt.Printf("\t%s: %s\n", remote, color.GreenString("OK"))
		return
	}

	fmt.Printf("\t%s: %s\n", remote, color.RedString("NG"))
}
예제 #19
0
파일: mssh.go 프로젝트: colebrumley/mssh-go
func (s *StdOutLogger) Success(message string, content string) {
	var str string
	if runtime.GOOS == "windows" {
		str = fmt.Sprintf("%s %s", s.okPrefix, message)
	} else {
		str = fmt.Sprintf("%s", color.GreenString("%s %s", s.okPrefix, message))
	}
	fmt.Printf("%s\n%s\n", str, content)
}
예제 #20
0
func (a Samidare) Do() error {
	fmt.Fprintf(color.Output, "TestName : %s \n", color.GreenString("%s", a.Name))

	for idx, testCase := range a.GetTestCases() {
		fmt.Fprintf(color.Output, "TestCaseName: [%d] %s\n", idx+1, color.GreenString("%s", testCase.Name))

		req, err := testCase.Request.BuildRequest()
		if err != nil {
			fmt.Fprintf(color.Output, "%s\n", color.RedString("%s", err.Error()))
			continue
		}
		resp, err := a.client.Do(req)
		if err != nil {
			fmt.Fprintf(color.Output, "%s\n", color.RedString("%s", err.Error()))
			continue
		}

		if resp.StatusCode != testCase.Response.Status {
			fmt.Fprintf(color.Output, "NG status: %s\n", color.RedString("%d != %d", resp.StatusCode, testCase.Response.Status))
		} else {
			fmt.Fprintf(color.Output, "OK status: %s\n", color.BlueString("%d == %d", resp.StatusCode, testCase.Response.Status))
		}

		for k, v := range testCase.Response.Headers {
			if resp.Header[k][0] != fmt.Sprintf("%v", v) {
				fmt.Fprintf(color.Output, "OK %s: %s\n", k, color.RedString("%v != %v", resp.Header[k][0], v))
			} else {
				fmt.Fprintf(color.Output, "OK %s: %s\n", k, color.BlueString("%v == %v", resp.Header[k][0], v))
			}
		}

		data, err := ioutil.ReadAll(resp.Body)
		defer resp.Body.Close()
		if err != nil {
			log.Println(err)
		} else {
			// TODO: Option
			//			fmt.Println(string(data))
			_ = data
		}
	}

	return nil
}
예제 #21
0
func (c container) updateCache(hash string, body string, backendURL string, async bool) (string, error) {
	var response string
	var err error

	if c.lockUpdate(hash) == false {
		if async == true {
			log.Debug(fmt.Sprintf("%s %s", hash, color.RedString("LOCKED")))
			return response, err
		}
	}

	redisConn := c.pool.Get()
	defer redisConn.Close()

	log.Debug("%s %s", hash, color.BlueString("UPDATE"))

	httpClient := http.Client{Timeout: time.Duration(600 * time.Second)}
	resp, httperror := httpClient.Post(backendURL, "application/JSON", strings.NewReader(body))

	if httperror == nil {
		if resp.StatusCode != 200 {
			log.Error(fmt.Sprintf("Backend error code: %v ", resp.StatusCode))
			return response, err
		}

		requestBody, err := ioutil.ReadAll(resp.Body)
		if err != nil {
			log.Error(fmt.Sprintf("body read failed: %s : %s", hash, err.Error()))
		}

		response = string(requestBody)
		if response != "" {
			_, err = redisConn.Do("SET", hash, string(requestBody))
			if err != nil {
				log.Error(fmt.Sprintf("key set failed: %s : %s", hash, err.Error()))
				return response, err
			}
			log.Debug(fmt.Sprintf("%s %s", hash, color.GreenString("SET")))
			_, err = redisConn.Do("EXPIRE", hash, config.expire)
			if err != nil {
				log.Error(fmt.Sprintf("key expire set failed: %s : %s", hash, err.Error()))
				return response, err
			}
		} else {
			log.Error("Empty backend response")
			fmt.Println(resp)
		}

	} else {
		log.Error(fmt.Sprintf("Backend request failure: %s", httperror.Error()))
	}

	c.unlockUpdate(hash)

	return response, err
}
예제 #22
0
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)
	}
}
예제 #23
0
파일: logo.go 프로젝트: mephux/komanda-cli
func (e *LogoCmd) Exec(args []string) error {

	Server.Exec(client.StatusChannel, func(g *gocui.Gui, v *gocui.View, s *client.Server) error {
		fmt.Fprintln(v, color.CyanString(ui.Logo))
		fmt.Fprintln(v, color.GreenString(ui.VersionLine))
		return nil
	})

	return nil
}
예제 #24
0
파일: fissile.go 프로젝트: hpcloud/fissile
// 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
}
예제 #25
0
파일: fissile.go 프로젝트: hpcloud/fissile
// 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
}
예제 #26
0
파일: fissile.go 프로젝트: hpcloud/fissile
// 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
}
예제 #27
0
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}
}
예제 #28
0
파일: main.go 프로젝트: nowk/gowatch
func init() {
	flag.Usage = func() {
		fmt.Printf("%s options\n%s\n", os.Args[0], strings.Join([]string{
			color.GreenString("  -args") + "=\"\": arguments to pass to the underlying app",
			color.GreenString("  -debug") + "=false: enabled debug print statements",
			color.GreenString("  -ignore") + "=\".git/*,node_modules/*\": comma delimited paths to ignore in the file watcher",
			color.GreenString("  -lint") + "=true: run go lint on reload",
			color.GreenString("  -onerror") + "=true: If the app should restart if a lint/test/build/non-zero exit code occurs",
			color.GreenString("  -onexit") + "=true: If the app sould restart on exit, regardless of exit code",
			color.GreenString("  -test") + "=true: run go test on reload",
			color.GreenString("  -wait") + "=2s: # seconds to wait before restarting",
		}, "\n"))
	}
}
예제 #29
0
// Check for fairness on a built SSA
func Check(info *ssabuilder.SSAInfo) {
	if cgRoot := info.CallGraph(); cgRoot != nil {
		fa := NewFairnessAnalysis()
		fa.info = info
		fa.logger = log.New(logwriter.New(os.Stdout, true, true), "fairness: ", log.LstdFlags)
		cgRoot.Traverse(fa)
		if fa.unsafe <= 0 {
			fa.logger.Printf(color.GreenString("Result: %d/%d is likely unsafe", fa.unsafe, fa.total))
		} else {
			fa.logger.Printf(color.RedString("Result: %d/%d is likely unsafe", fa.unsafe, fa.total))
		}
	}
}
예제 #30
0
// 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
}