Exemple #1
0
func getFromCache(repo string) (checksResp, error) {
	// try and fetch from boltdb
	db, err := bolt.Open(DBPath, 0600, &bolt.Options{Timeout: 1 * time.Second})
	if err != nil {
		return checksResp{}, fmt.Errorf("failed to open bolt database during GET: %v", err)
	}
	defer db.Close()

	resp := checksResp{}
	err = db.View(func(tx *bolt.Tx) error {
		b := tx.Bucket([]byte(RepoBucket))
		if b == nil {
			return errors.New("No repo bucket")
		}
		cached := b.Get([]byte(repo))
		if cached == nil {
			return fmt.Errorf("%q not found in cache", repo)
		}

		err = json.Unmarshal(cached, &resp)
		if err != nil {
			return fmt.Errorf("failed to parse JSON for %q in cache", repo)
		}
		return nil
	})

	if err != nil {
		return resp, err
	}

	resp.LastRefresh = resp.LastRefresh.UTC()
	resp.HumanizedLastRefresh = humanize.Time(resp.LastRefresh.UTC())

	return resp, nil
}
Exemple #2
0
func main() {
	var simple = flag.Bool("simple", false, "Use simple (debugging) output format")

	flag.Usage = func() {
		fmt.Fprintf(os.Stderr, "usage: %s [options]  <VPN ID>\n", path.Base(os.Args[0]))
		flag.PrintDefaults()
	}

	flag.Parse()
	if flag.NArg() != 1 {
		flag.Usage()
		os.Exit(1)
	}

	client, err := clcv2.NewCLIClient()
	if err != nil {
		exit.Fatal(err.Error())
	}

	vpn, err := client.GetVPN(flag.Arg(0))
	if err != nil {
		exit.Fatalf("failed to query VPN %s: %s", flag.Arg(0), err)
	}

	if *simple {
		pretty.Println(vpn)
	} else {
		table := tablewriter.NewWriter(os.Stdout)
		table.SetAutoFormatHeaders(false)
		table.SetAlignment(tablewriter.ALIGN_LEFT)
		table.SetAutoWrapText(false)

		//		table.SetHeader([]string{"CLC => Remote", "CLC Nets",			"Remote", "Remote Nets", "ID", "Last Change",		})

		modifiedStr := humanize.Time(vpn.ChangeInfo.ModifiedDate)
		// The ModifiedBy field can be an email address, or an API Key (hex string)
		if _, err := hex.DecodeString(vpn.ChangeInfo.ModifiedBy); err == nil {
			modifiedStr += " via API Key"
		} else {
			modifiedStr += ", by " + vpn.ChangeInfo.ModifiedBy
		}

		table.Append([]string{fmt.Sprintf("%s subnets:", vpn.Local.LocationAlias), strings.Join(vpn.Local.Subnets, ", ")})
		table.Append([]string{fmt.Sprintf("%s endpoint:", vpn.Local.LocationAlias), vpn.Local.Address})
		table.Append([]string{fmt.Sprintf("%s endpoint:", vpn.Remote.SiteName), vpn.Remote.Address})
		table.Append([]string{fmt.Sprintf("%s subnets:", vpn.Remote.SiteName), strings.Join(vpn.Remote.Subnets, ", ")})
		table.Append([]string{"IKE configuration:", fmt.Sprintf("%s, %s/%s, Key: %q, NAT traversal: %t, Lifetime: %s",
			vpn.IKE.DiffieHellmanGroup,
			vpn.IKE.Encryption, vpn.IKE.Hashing, vpn.IKE.PreSharedKey,
			vpn.IKE.NatTraversal,
			time.Duration(vpn.IKE.Lifetime)*time.Second)})
		table.Append([]string{"IPsec configuration:", fmt.Sprintf("%s, %s/%s, %s, Lifetime: %s",
			vpn.IPsec.Pfs, vpn.IPsec.Encryption, vpn.IPsec.Hashing,
			strings.ToUpper(vpn.IPsec.Protocol), time.Duration(vpn.IPsec.Lifetime)*time.Second)})
		table.Append([]string{"Last change:", modifiedStr})

		table.Render()
	}
}
Exemple #3
0
func homeHandler(w http.ResponseWriter, r *http.Request) {
	data.Title = "Home"
	data.Posts = make([]Post, 5)
	for k, v := range posts[:5] {
		data.Posts[k] = *v
		data.Posts[k].PrettyDate = humanize.Time(v.Date)
	}
	fmt.Fprint(w, mustache.RenderFileInLayout("templates/home.html.mustache", "templates/layout.html.mustache", data))
}
Exemple #4
0
func (a arriba) prettyPrintChannelStandup(cstandup channelStandup) string {
	text := "¡Ándale! ¡Ándale! here's the standup status :tada:\n"
	for _, userID := range cstandup.getKeysByTimestamp() {
		standupMsg := cstandup[userID]
		humanTime := humanize.Time(standupMsg.ts)
		userName := a.getUserName(userID)
		text += fmt.Sprintf("*%s*: %s _(%s)_\n", userName, standupMsg.text, humanTime)
	}
	return text
}
Exemple #5
0
func printStats() {
	statTimer := time.NewTicker(30 * time.Second)
	for {
		<-statTimer.C
		var memstats runtime.MemStats
		runtime.ReadMemStats(&memstats)
		log.Printf("stats [up since: %s]\n", humanize.Time(timeStarted))
		log.Printf(" - CPUTemp=%.02f deg C, MemStats.Alloc=%s, MemStats.Sys=%s, totalNetworkMessagesSent=%s\n", globalStatus.CPUTemp, humanize.Bytes(uint64(memstats.Alloc)), humanize.Bytes(uint64(memstats.Sys)), humanize.Comma(int64(totalNetworkMessagesSent)))
		log.Printf(" - UAT/min %s/%s [maxSS=%.02f%%], ES/min %s/%s\n", humanize.Comma(int64(globalStatus.UAT_messages_last_minute)), humanize.Comma(int64(globalStatus.UAT_messages_max)), float64(maxSignalStrength)/10.0, humanize.Comma(int64(globalStatus.ES_messages_last_minute)), humanize.Comma(int64(globalStatus.ES_messages_max)))
		log.Printf(" - Total traffic targets tracked=%s, last GPS fix: %s, GPS solution type: %d, NACp: %d, est accuracy %.02f m\n", humanize.Comma(int64(len(seenTraffic))), humanize.Time(mySituation.LastFixLocalTime), mySituation.quality, mySituation.NACp, mySituation.Accuracy)
	}
}
Exemple #6
0
func main() {
	var simple = flag.Bool("simple", false, "Use simple (debugging) output format")
	flag.Parse()

	client, err := clcv2.NewCLIClient()
	if err != nil {
		exit.Fatal(err.Error())
	}

	vpns, err := client.GetVPNs()
	if err != nil {
		exit.Fatalf("failed to list VPNs: %s", err)
	}

	if len(vpns) == 0 {
		fmt.Printf("No VPNs registered for account %s.\n", client.AccountAlias)
	} else if *simple {
		pretty.Println(vpns)
	} else {
		table := tablewriter.NewWriter(os.Stdout)
		table.SetAutoFormatHeaders(false)
		table.SetAlignment(tablewriter.ALIGN_LEFT)
		table.SetAutoWrapText(true)

		table.SetHeader([]string{"CLC => Remote", "CLC Nets",
			"Remote", "Remote Nets", "ID", "Last Change",
		})

		for _, v := range vpns {
			modifiedStr := humanize.Time(v.ChangeInfo.ModifiedDate)
			// The ModifiedBy field can be an email address, or an API Key (hex string)
			if _, err := hex.DecodeString(v.ChangeInfo.ModifiedBy); err == nil {
				modifiedStr += " via API Key"
			} else if len(v.ChangeInfo.ModifiedBy) > 6 {
				modifiedStr += " by " + v.ChangeInfo.ModifiedBy[:6]
			} else {
				modifiedStr += " by " + v.ChangeInfo.ModifiedBy
			}

			table.Append([]string{
				fmt.Sprintf("%s => %-15s", v.Local.LocationAlias, v.Remote.Address),
				strings.Join(v.Local.Subnets, ", "),
				v.Remote.SiteName,
				strings.Join(v.Remote.Subnets, ", "),
				v.ID,
				modifiedStr,
			})
		}
		table.Render()
	}
}
Exemple #7
0
func (a arriba) prettyPrintChannelStandup(cstandup channelStandup) string {
	text := "¡Ándale! ¡Ándale! here's the standup status :tada:\n"
	for _, userID := range cstandup.getKeysByTimestamp() {
		standupMsg := cstandup[userID]
		humanTime := humanize.Time(standupMsg.ts)
		userName := a.getUserName(userID)
		// Inject zero-width unicode character in username to avoid notifying users
		if len(userName) > 1 {
			userName = string(userName[0]) + "\ufeff" + string(userName[1:])
		}
		text += fmt.Sprintf("*%s*: %s _(%s)_\n", userName, standupMsg.text, humanTime)
	}
	return text
}
Exemple #8
0
func (p PgpUI) OutputSignatureSuccess(_ context.Context, arg keybase1.OutputSignatureSuccessArg) error {
	signedAt := keybase1.FromTime(arg.SignedAt)
	un := ColorString("bold", arg.Username)
	output := func(fmtString string, args ...interface{}) {
		s := fmt.Sprintf(fmtString, args...)
		s = ColorString("green", s)
		p.w.Write([]byte(s))
	}

	if signedAt.IsZero() {
		output("Signature verified. Signed by %s.\n", un)
	} else {
		output("Signature verified. Signed by %s %s (%s).\n", un, humanize.Time(signedAt), signedAt)
	}
	output("PGP Fingerprint: %s.\n", arg.Fingerprint)
	return nil
}
Exemple #9
0
// InitSystem register's dice commands on module load
func InitSystem(mod *modules.Module) {
	owner := &modules.OwnerPermission{}
	mod.AddResponse(quitreg, func(r *modules.Response) {
		r.Respond("okey, " + r.Nick + "! Goodbye everypony!")
		syscall.Kill(syscall.Getpid(), syscall.SIGINT)
	}, owner)
	mod.AddResponse(restartreg, func(r *modules.Response) {
		r.Respond("okey, " + r.Nick + "! Reebooot!")
		syscall.Kill(syscall.Getpid(), syscall.SIGUSR2)
	}, owner)
	mod.AddResponse(joinpartreg, func(r *modules.Response) {
		if r.Matches[1] == "join" {
			if len(r.Matches)-1 >= 3 && r.Matches[3] != "" {
				r.Server.Join("#" + r.Matches[3])
				r.Respond("okey, " + r.Nick + "! let'z join " + "#" + r.Matches[3])
			} else {
				r.Mention("tell me where to join!")
			}
		} else if r.Matches[1] == "part" {
			if len(r.Matches)-1 >= 3 && r.Matches[3] != "" {
				r.Respond("okey, " + r.Nick + "! let'z leave " + "#" + r.Matches[3])
				r.Server.Part("#" + r.Matches[3])
			} else if r.Channel != "" {
				r.Respond("okey, " + r.Nick + " leaving from here!")
				r.Server.Part(r.Channel)
			} else {
				r.Mention("tell me from what to leave!")
			}
		}

	}, owner)
	mod.AddResponse(nickreg, func(r *modules.Response) {
		r.Server.Nick(r.Matches[1])
		r.Respond("okey, " + r.Nick + "! Let'z talk as another pony!")
	}, owner)

	mod.AddResponse(statsreg, func(r *modules.Response) {
		mem := &runtime.MemStats{}
		runtime.ReadMemStats(mem)
		r.Respond("PID: " + strconv.Itoa(syscall.Getpid()) + ", last (re)start: " + human.Time(startTime) + ", sys memory: " + human.Bytes(mem.Sys))
	}, owner)
}
Exemple #10
0
func (c *CmdDecrypt) explainDecryptionFailure(info *keybase1.SaltpackEncryptedMessageInfo) {
	if info == nil {
		return
	}
	out := c.G().UI.GetTerminalUI().ErrorWriter()
	prnt := func(s string, args ...interface{}) {
		fmt.Fprintf(out, s, args...)
	}
	if len(info.Devices) > 0 {
		prnt("Decryption failed; try one of these devices instead:\n")
		for _, d := range info.Devices {
			t := keybase1.FromTime(d.CTime)
			prnt("  * %s (%s); provisioned %s (%s)\n", ColorString("bold", d.Name), d.Type,
				humanize.Time(t), t.Format("2006-01-02 15:04:05 MST"))
		}
		if info.NumAnonReceivers > 0 {
			prnt("Additionally, there were %d hidden receivers for this message\n", info.NumAnonReceivers)
		}
	} else if info.NumAnonReceivers > 0 {
		prnt("Decryption failed; it was encrypted for %d hidden receivers, which may or may not you\n", info.NumAnonReceivers)
	} else {
		prnt("Decryption failed; message wasn't encrypted for any of your known keys\n")
	}
}
Exemple #11
0
func HumanizeTime(then int64) string {
	return humanize.Time(time.Unix(then, 0))
}
Exemple #12
0
// Show condensed details of multiple servers
// @client:    authenticated CLCv2 Client
// @servnames: server names
func showServers(client *clcv2.CLIClient, servnames ...string) {
	var truncate = func(s string, maxlen int) string {
		if len(s) >= maxlen {
			s = s[:maxlen]
		}
		return s
	}

	table := tablewriter.NewWriter(os.Stdout)
	table.SetAutoFormatHeaders(false)
	table.SetAlignment(tablewriter.ALIGN_LEFT)
	table.SetAutoWrapText(true)

	table.SetHeader([]string{
		"Name", "Group", "Description", "OS",
		"IP", "CPU", "Mem", "Storage",
		"Status", "Last Change",
	})

	for _, servname := range servnames {
		server, err := client.GetServer(servname)
		if err != nil {
			fmt.Fprintf(os.Stderr, "Failed to list details of server %q: %s", servname, err)
			continue
		}

		grp, err := client.GetGroup(server.GroupId)
		if err != nil {
			exit.Fatalf("failed to resolve %s group UUID: %s", servname, err)
		}

		IPs := []string{}
		for _, ip := range server.Details.IpAddresses {
			if ip.Public != "" {
				IPs = append(IPs, ip.Public)
			}
			if ip.Internal != "" {
				IPs = append(IPs, ip.Internal)
			}
		}

		status := server.Details.PowerState
		if server.Details.InMaintenanceMode {
			status = "MAINTENANCE"
		} else if server.Status != "active" {
			status = server.Status
		}

		desc := server.Description
		if server.IsTemplate {
			desc = "TPL: " + desc
		}

		modifiedStr := humanize.Time(server.ChangeInfo.ModifiedDate)
		/* The ModifiedBy field can be an email address, or an API Key (hex string) */
		if _, err := hex.DecodeString(server.ChangeInfo.ModifiedBy); err == nil {
			modifiedStr += " via API Key"
		} else {
			modifiedStr += " by " + truncate(server.ChangeInfo.ModifiedBy, 6)
		}

		// Append a tilde (~) to indicate it has snapshots
		serverName := server.Name
		if len(server.Details.Snapshots) > 0 {
			serverName += "~"
		}

		table.Append([]string{
			serverName, grp.Name, truncate(desc, 30), truncate(server.OsType, 15),
			strings.Join(IPs, " "),
			fmt.Sprint(server.Details.Cpu), fmt.Sprintf("%d G", server.Details.MemoryMb/1024),
			fmt.Sprintf("%d G", server.Details.StorageGb),
			status, modifiedStr,
		})
	}
	table.Render()
}
Exemple #13
0
func (fi FileInfo) representTimeDetailed() string {
	return humanize.Time(fi.f.ModTime()) + " (" + fi.f.ModTime().String() + ")"
}
Exemple #14
0
func newChecksResp(repo string, forceRefresh bool) (checksResp, error) {
	if !forceRefresh {
		resp, err := getFromCache(repo)
		if err != nil {
			// just log the error and continue
			log.Println(err)
		} else {
			resp.Grade = grade(resp.Average * 100) // grade is not stored for some repos, yet
			return resp, nil
		}
	}

	// fetch the repo and grade it
	err := goGet(repo, "")
	if err != nil {
		return checksResp{}, fmt.Errorf("could not clone repo: %v", err)
	}

	dir := dirName(repo)
	filenames, err := check.GoFiles(dir)
	if err != nil {
		return checksResp{}, fmt.Errorf("could not get filenames: %v", err)
	}
	if len(filenames) == 0 {
		return checksResp{}, fmt.Errorf("no .go files found")
	}
	checks := []check.Check{
		check.GoFmt{Dir: dir, Filenames: filenames},
		check.GoVet{Dir: dir, Filenames: filenames},
		check.GoLint{Dir: dir, Filenames: filenames},
		check.GoCyclo{Dir: dir, Filenames: filenames},
		check.License{Dir: dir, Filenames: []string{}},
		check.Misspell{Dir: dir, Filenames: filenames},
		check.IneffAssign{Dir: dir, Filenames: filenames},
		check.ErrCheck{Dir: dir, Filenames: filenames},
	}

	ch := make(chan score)
	for _, c := range checks {
		go func(c check.Check) {
			p, summaries, err := c.Percentage()
			if err != nil {
				log.Printf("ERROR: (%s) %v", c.Name(), err)
			}
			s := score{
				Name:          c.Name(),
				Description:   c.Description(),
				FileSummaries: summaries,
				Weight:        c.Weight(),
				Percentage:    p,
			}
			ch <- s
		}(c)
	}

	resp := checksResp{
		Repo:                 repo,
		Files:                len(filenames),
		LastRefresh:          time.Now().UTC(),
		HumanizedLastRefresh: humanize.Time(time.Now().UTC()),
	}

	var total float64
	var totalWeight float64
	var issues = make(map[string]bool)
	for i := 0; i < len(checks); i++ {
		s := <-ch
		resp.Checks = append(resp.Checks, s)
		total += s.Percentage * s.Weight
		totalWeight += s.Weight
		for _, fs := range s.FileSummaries {
			issues[fs.Filename] = true
		}
	}
	total /= totalWeight

	sort.Sort(ByWeight(resp.Checks))
	resp.Average = total
	resp.Issues = len(issues)
	resp.Grade = grade(total * 100)

	return resp, nil
}
Exemple #15
0
func (fi FileInfo) representTime() string {
	return humanize.Time(fi.f.ModTime())
}
Exemple #16
0
func printStats() {
	statTimer := time.NewTicker(30 * time.Second)
	for {
		<-statTimer.C
		var memstats runtime.MemStats
		runtime.ReadMemStats(&memstats)
		log.Printf("stats [started: %s]\n", humanize.RelTime(time.Time{}, stratuxClock.Time, "ago", "from now"))
		log.Printf(" - CPUTemp=%.02f deg C, MemStats.Alloc=%s, MemStats.Sys=%s, totalNetworkMessagesSent=%s\n", globalStatus.CPUTemp, humanize.Bytes(uint64(memstats.Alloc)), humanize.Bytes(uint64(memstats.Sys)), humanize.Comma(int64(totalNetworkMessagesSent)))
		log.Printf(" - UAT/min %s/%s [maxSS=%.02f%%], ES/min %s/%s\n, Total traffic targets tracked=%s", humanize.Comma(int64(globalStatus.UAT_messages_last_minute)), humanize.Comma(int64(globalStatus.UAT_messages_max)), float64(maxSignalStrength)/10.0, humanize.Comma(int64(globalStatus.ES_messages_last_minute)), humanize.Comma(int64(globalStatus.ES_messages_max)), humanize.Comma(int64(len(seenTraffic))))
		if globalSettings.GPS_Enabled {
			log.Printf(" - Last GPS fix: %s, GPS solution type: %d using %d satellites (%d/%d seen/tracked), NACp: %d, est accuracy %.02f m\n", humanize.Time(mySituation.LastFixLocalTime), mySituation.quality, mySituation.Satellites, mySituation.SatellitesSeen, mySituation.SatellitesTracked, mySituation.NACp, mySituation.Accuracy)
			log.Printf(" - GPS vertical velocity: %.02f ft/sec; GPS vertical accuracy: %v m\n", mySituation.GPSVertVel, mySituation.AccuracyVert)
		}
	}
}
Exemple #17
0
// Show details of a single server
// @client:    authenticated CLCv2 Client
// @servname:  server name
func showServer(client *clcv2.CLIClient, servname string) {
	server, err := client.GetServer(servname)
	if err != nil {
		exit.Fatalf("failed to list details of server %q: %s", servname, err)
	}

	grp, err := client.GetGroup(server.GroupId)
	if err != nil {
		exit.Fatalf("failed to resolve group UUID: %s", err)
	}

	/* First public, then private */
	IPs := []string{}
	for _, ip := range server.Details.IpAddresses {
		if ip.Public != "" {
			IPs = append(IPs, ip.Public)
		}
	}
	for _, ip := range server.Details.IpAddresses {
		if ip.Internal != "" {
			IPs = append(IPs, ip.Internal)
		}
	}

	table := tablewriter.NewWriter(os.Stdout)
	table.SetAutoFormatHeaders(false)
	table.SetAlignment(tablewriter.ALIGN_LEFT)
	table.SetAutoWrapText(true)

	// CPU, Memory, IP and Power status are not filled in until the server reaches 'active' state.
	if server.Status == "active" {
		table.SetHeader([]string{
			"Name", "Group", "Description", "OS",
			"CPU", "Mem", "IP", "Power",
			"Last Change",
		})

	} else {
		table.SetHeader([]string{
			"Name", "Group", "Description", "OS",
			"Status",
			"Owner", "Last Change",
		})
	}

	modifiedStr := humanize.Time(server.ChangeInfo.ModifiedDate)
	/* The ModifiedBy field can be an email address, or an API Key (hex string) */
	if _, err := hex.DecodeString(server.ChangeInfo.ModifiedBy); err == nil {
		modifiedStr += " via API Key"
	} else if len(server.ChangeInfo.ModifiedBy) > 6 {
		modifiedStr += " by " + server.ChangeInfo.ModifiedBy[:6]
	} else {
		modifiedStr += " by " + server.ChangeInfo.ModifiedBy
	}

	if server.Status == "active" {
		table.Append([]string{
			server.Name, grp.Name, server.Description, server.OsType,
			fmt.Sprint(server.Details.Cpu), fmt.Sprintf("%d G", server.Details.MemoryMb/1024), strings.Join(IPs, " "), server.Details.PowerState,
			modifiedStr,
		})
	} else {
		table.Append([]string{
			server.Name, grp.Name, server.Description, server.OsType,
			server.Status,
			server.ChangeInfo.CreatedBy, modifiedStr,
		})
	}
	table.Render()

	// Disks
	if len(server.Details.Disks) > 0 {
		fmt.Printf("\nDisks of %s (total storage: %d GB)\n", server.Name, server.Details.StorageGb)
		table = tablewriter.NewWriter(os.Stdout)
		table.SetAutoFormatHeaders(false)
		table.SetAlignment(tablewriter.ALIGN_RIGHT)
		table.SetAutoWrapText(true)

		table.SetHeader([]string{"Disk ID", "Disk Size/GB", "Paths"})
		for _, d := range server.Details.Disks {
			table.Append([]string{d.Id, fmt.Sprint(d.SizeGB), strings.Join(d.PartitionPaths, ", ")})
		}
		table.Render()
	}

	// Partitions
	if len(server.Details.Partitions) > 0 {
		fmt.Printf("\nPartitions of %s:\n", server.Name)
		table = tablewriter.NewWriter(os.Stdout)
		table.SetAutoFormatHeaders(false)
		table.SetAlignment(tablewriter.ALIGN_RIGHT)
		table.SetAutoWrapText(true)

		table.SetHeader([]string{"Partition Path", "Partition Size/GB"})
		for _, p := range server.Details.Partitions {
			table.Append([]string{p.Path, fmt.Sprintf("%.1f", p.SizeGB)})
		}
		table.Render()
	}

	// Snapshots
	if len(server.Details.Snapshots) > 0 {
		fmt.Println()

		table = tablewriter.NewWriter(os.Stdout)
		table.SetAutoFormatHeaders(false)
		table.SetAlignment(tablewriter.ALIGN_CENTRE)
		table.SetAutoWrapText(true)

		table.SetHeader([]string{fmt.Sprintf("Snapshots of %s", server.Name)})
		for _, s := range server.Details.Snapshots {
			table.Append([]string{s.Name})
		}
		table.Render()
	}
}