func TestUpdatedMsg(t *testing.T) { testsOld := []map[string]model.MeasurementsProperty{ {"fping": {true, []string{""}, 60}, "tcpping": {true, []string{""}, 60}, "tcpconn": {true, []string{""}, 60}}, {"fping": {false, []string{""}, 60}, "tcpping": {false, []string{""}, 60}, "tcpconn": {false, []string{""}, 60}}, {"fping": {true, []string{""}, 60}, "tcpping": {false, []string{""}, 60}, "tcpconn": {true, []string{""}, 60}}, {"fping": {true, []string{""}, 60}, "tcpping": {false, []string{""}, 60}, "tcpconn": {false, []string{""}, 60}}, {"fping": {false, []string{""}, 60}, "tcpping": {true, []string{""}, 60}, "tcpconn": {false, []string{""}, 60}}, {"fping": {false, []string{""}, 60}, "tcpping": {true, []string{""}, 60}, "tcpconn": {true, []string{""}, 60}}, nil, } testsUpdated := []map[string]model.MeasurementsProperty{ {"fping": {false, []string{""}, 60}, "tcpping": {false, []string{""}, 60}, "tcpconn": {false, []string{""}, 60}}, {"fping": {true, []string{""}, 60}, "tcpping": {true, []string{""}, 60}, "tcpconn": {true, []string{""}, 60}}, {"fping": {false, []string{""}, 60}, "tcpping": {false, []string{""}, 60}, "tcpconn": {true, []string{""}, 60}}, {"fping": {false, []string{""}, 60}, "tcpping": {false, []string{""}, 60}, "tcpconn": {true, []string{""}, 60}}, {"fping": {false, []string{""}, 60}, "tcpping": {true, []string{""}, 60}, "tcpconn": {false, []string{""}, 60}}, nil, {"fping": {true, []string{""}, 60}, "tcpping": {true, []string{""}, 60}, "tcpconn": {false, []string{""}, 60}}, } expecteds := []string{ "<fping Disabled> <tcpping Disabled> <tcpconn Disabled> ", "<fping Enabled> <tcpping Enabled> <tcpconn Enabled> ", "<fping Disabled> ", "<fping Disabled> <tcpconn Enabled> ", "", "<tcpping Disabled> <tcpconn Disabled> ", "<fping Enabled> <tcpping Enabled> ", } for i, _ := range testsOld { o := testsOld[i] u := testsUpdated[i] msg := updatedMsg(o, u) msgSlice := strings.SplitAfter(msg, "> ") msgMap := make(map[string]bool) for _, m := range msgSlice { if m == "" { continue } msgMap[m] = true } expectedSlice := strings.SplitAfter(expecteds[i], "> ") expectedMap := make(map[string]bool) for _, m := range expectedSlice { if m == "" { continue } expectedMap[m] = true } if !reflect.DeepEqual(expectedMap, msgMap) { t.Error(expectedMap, msgMap) } t.Log(msg) } }
func main() { obytes, _ := ioutil.ReadFile(os.Args[1]) nbytes, _ := ioutil.ReadFile(os.Args[2]) o := strings.SplitAfter(string(obytes), "\n", -1) n := strings.SplitAfter(string(nbytes), "\n", -1) fmt.Println(patience.Diff(o, n)) }
// Flush the spans for a request in zipkin format func Flush(t gotocol.TraceContextType, trace []*spannotype) { var zip zipkinspan var ctx string n := -1 sort.Sort(ByCtx(trace)) for _, a := range trace { //fmt.Println(*a) if ctx != a.Ctx { // new span if ctx != "" { // not the first WriteZip(zip) file.WriteString(",") zip.Annotations = nil } n++ zip.Traceid = fmt.Sprintf("%016d", t) // pad id's to 16 characters to keep zipkin happy zip.Name = a.Imp s := strings.SplitAfter(a.Ctx, "s") // tXpYsZ -> [tXpYs, Z] p := strings.TrimSuffix(strings.SplitAfter(s[0], "p")[1], "s") // tXpYs -> [tXp, Ys] -> Ys -> Y zip.Id = "000000000000000"[0:(16-len(s[1]))] + s[1] // pad id's to 16 characters to keep zipkin happy if p != "0" { zip.ParentId = "000000000000000"[0:(16-len(p))] + p // pad id's to 16 characters to keep zipkin happy } ctx = a.Ctx } var ann zipkinannotation ann.Endpoint.Servicename = a.Host ann.Endpoint.Ipv4 = dhcp.Lookup(a.Host) ann.Endpoint.Port = 8080 ann.Timestamp = a.Timestamp / 1000 // convert from UnixNano to Microseconds ann.Value = a.Value zip.Annotations = append(zip.Annotations, ann) } WriteZip(zip) }
func createRedirectServer(t *testing.T) *httptest.Server { ts := createTestServer(func(w http.ResponseWriter, r *http.Request) { t.Logf("Method: %v", r.Method) t.Logf("Path: %v", r.URL.Path) if r.Method == GET { if strings.HasPrefix(r.URL.Path, "/redirect-host-check-") { cntStr := strings.SplitAfter(r.URL.Path, "-")[3] cnt, _ := strconv.Atoi(cntStr) if cnt != 7 { // Testing hard stop via logical if cnt >= 5 { http.Redirect(w, r, "http://httpbin.org/get", http.StatusTemporaryRedirect) } else { http.Redirect(w, r, fmt.Sprintf("/redirect-host-check-%d", (cnt+1)), http.StatusTemporaryRedirect) } } } else if strings.HasPrefix(r.URL.Path, "/redirect-") { cntStr := strings.SplitAfter(r.URL.Path, "-")[1] cnt, _ := strconv.Atoi(cntStr) http.Redirect(w, r, fmt.Sprintf("/redirect-%d", (cnt+1)), http.StatusTemporaryRedirect) } } }) return ts }
func FindNamespace(host string) (string, error) { //Attempt to access the host website resp, err := http.Get(host) if err == nil { bytes, err := ioutil.ReadAll(resp.Body) if err == nil { //Successfully accessed the website! body := string(bytes) //Parse body looking for "v23.namespace.root=" //If found, return number after that //Else keep looking if strings.Contains(body, "v23.namespace.root=") { //formatting return string namespaces := strings.SplitAfter(body, "v23.namespace.root=") for i := 1; i < len(namespaces); i += 2 { namespaceWithJunk := namespaces[i] namespace := strings.SplitAfter(namespaceWithJunk, "\n")[0] cleanNamespace := strings.TrimSpace(namespace) if cleanNamespace != "" { return cleanNamespace, nil } } } } } //no instance of "v23.namespace.root=" is found return "", errors.New("No namespace found") }
func (d *FileDiff) Fprint(f io.Writer) (e os.Error) { switch d.Change { case plumbing.Added: fmt.Fprintln(f, color.String("Added "+d.Name, color.Meta)) case plumbing.Deleted: fmt.Fprintln(f,color.String("Deleted "+d.Name, color.Meta)) case plumbing.Modified: if d.OldMode != d.NewMode { fmt.Fprintln(f,d) } oldf, newf, e := d.OldNewStrings() if e != nil { debug.Printf("Had trouble reading file and old %s: %s\n", d.Name, e.String()) return } if newf == oldf { debug.Println("File "+d.Name+" is unchanged.") return } newer := strings.SplitAfter(newf,"\n",-1) older := strings.SplitAfter(oldf,"\n",-1) mychunks := patience.Diff(older, newer) lastline := 0 debug.Printf("File %s has %d chunks changed\n",d.Name,len(mychunks)) if len(mychunks) == 0 { debug.Println("File "+d.Name+" mysteriously looks unchanged.") return } if mychunks[0].Line-4 > lastline { lastline = mychunks[0].Line - 4 } fmt.Fprintf(f,color.String("¤¤¤ %s %d ¤¤¤\n", color.Meta),d.Name,lastline+1) for _,ch := range mychunks { if ch.Line > lastline + 6 { for i:=lastline; i<lastline+3; i++ { fmt.Fprint(f," ",newer[i]) } fmt.Fprintf(f,color.String("¤¤¤ %s %d ¤¤¤\n", color.Meta), d.Name,ch.Line-4+1) for i:=ch.Line-4; i<ch.Line-1; i++ { fmt.Fprint(f," ",newer[i]) } } else { for i:=lastline; i<ch.Line-1; i++ { fmt.Fprint(f," ",newer[i]) } } fmt.Fprint(f,ch) lastline = ch.Line - 1 + len(ch.New) } for i:=lastline; i<len(newer) && i < lastline+3;i++ { fmt.Fprint(f," ",newer[i]) } default: fmt.Fprintln(f,d) } return }
func getIpAddress() string { out, err := exec.Command("ifconfig", "eth0").Output() if err != nil { log.Fatal(err) } lines := strings.SplitAfter(string(out), "\n") addresses := strings.SplitAfter(lines[1], ":") address := strings.SplitAfter(addresses[1], " ") return strings.TrimSpace(address[0]) }
// Returns similar tracks func GetSimilarTracks(track *Track, collections Collections) (similarTracks SimilarTracks, err error) { var chans = []chan CommandResult{} for i := 0; i < len(collections); i++ { ch := make(chan CommandResult) RunCommand(fmt.Sprintf("musly -p \"%s\" -k20 -c \"%s\"", track.Pathname, collections[i].Pathname), ch) chans = append(chans, ch) } var crs = []CommandResult{} for i := 0; i < len(chans); i++ { mr := <-chans[i] crs = append(crs, mr) } var stdouts bytes.Buffer for i := 0; i < len(crs); i++ { stdouts.WriteString(crs[i].Stdout + "\n") } occuriences := map[string]float64{} similaritySum := map[string]float64{} scanner := bufio.NewScanner(strings.NewReader(stdouts.String())) for scanner.Scan() { line := scanner.Text() if strings.HasPrefix(line, "track-id") == false { continue } pathname := strings.Replace(strings.SplitAfter(line, "track-origin: ")[1], "/collection", "", 1) similarity, _ := strconv.ParseFloat(strings.Split(strings.SplitAfter(line, "track-similarity: ")[1], ", ")[0], 64) similaritySum[pathname] += similarity occuriences[pathname]++ } similarTracks = SimilarTracks{} for pathname, similarity := range similaritySum { similarity, _ = strconv.ParseFloat(fmt.Sprintf("%.4f", 100-(similarity/occuriences[pathname]*100)), 64) similarTracks = append(similarTracks, SimilarTrack{NewTrack(pathname), similarity}) } sort.Sort(similarTracks) return }
// loadTokens imports auth keys from rootkey.csv (AWS keyset) func loadTokens(key *Keys) bool { if tokens, err := ioutil.ReadFile("rootkey.csv"); err == nil { temp := strings.Split(string(tokens), "\n") if len(temp) == 2 { key.AccessKey = strings.SplitAfter(temp[0], "=")[1] key.SecretKey = strings.SplitAfter(temp[1], "=")[1] return true } } log.Println("Error loading tokens from rootkey.csv") return false }
//Stats gets the cpu and memory usage of a process func (cp *ChildProcess) Stats() (map[string]string, error) { stats, err := exec.Command("ps", "-p", strconv.Itoa(cp.PID), "-o", "%cpu,%mem").Output() if err != nil { return map[string]string{}, err } statsStr := strings.Trim(strings.SplitAfter(string(stats), "\n")[1], " ") l := strings.SplitAfter(statsStr, " ") return map[string]string{ "cpu": l[0], "mem": strings.Replace(l[2], "\n", "", -1), }, nil }
func (s Patch) String() (out string) { out = s.Header for _, f := range s.File { if len(out) > 0 { out += "\n" } // out += string(f.Verb) + " " + f.Src if f.OldMode != 0 && f.NewMode != 0 { out += "\n" + fmt.Sprint(f.OldMode) + " -> " + fmt.Sprint(f.NewMode) } if f.OldMode != 0 && f.NewMode == 0 { // The file has been removed! out += color.String("\nRemoved "+ f.Src, color.Meta) continue } switch d := f.Diff.(type) { default: if f.Diff == patch.NoDiff { // There is nothing here to see... } else { out += fmt.Sprintf("\nunexpected type %T", f.Diff) // %T prints type } case patch.TextDiff: for _, chunk := range d { older := strings.SplitAfter(string(chunk.Old), "\n",-1) newer := strings.SplitAfter(string(chunk.New), "\n",-1) lastline:=chunk.Line mychunks := patience.DiffFromLine(chunk.Line, older, newer) fmt.Println(color.String("¤¤¤¤¤¤ "+f.Src+string(chunk.Line)+" ¤¤¤¤¤¤", color.Meta)) for _,ch := range mychunks { if ch.Line > lastline + 6 { for i:=lastline+1; i<lastline+4; i++ { fmt.Print(" ",newer[i-chunk.Line]) } fmt.Println(color.String("¤¤¤¤¤¤ "+f.Src+string(chunk.Line-3)+" ¤¤¤¤¤¤", color.Meta)) for i:=ch.Line-3; i<ch.Line; i++ { fmt.Print(" ",newer[i-chunk.Line]) } } else { for i:=lastline; i<ch.Line; i++ { fmt.Print(" ",newer[i-chunk.Line]) } } fmt.Print(ch) lastline = ch.Line + len(ch.New) } for i:=lastline-chunk.Line; i<len(newer);i++ { fmt.Print(" ",newer[i]) } } } } return }
// extension of strings.SplitAfter to split string multiple times using multiple // split strings func splitAfterMultiple(x string, s []string) []string { if len(s) == 0 { return []string{} } r := strings.SplitAfter(x, s[0]) for _, sx := range s[1:] { t := make([]string, 0, len(r)) for _, ry := range r { t = append(t, strings.SplitAfter(ry, sx)...) } r = t } return r }
func (v *Vdc) FindVAppByID(vappid string) (VApp, error) { // Horrible hack to fetch a vapp with its id. // urn:vcloud:vapp:00000000-0000-0000-0000-000000000000 err := v.Refresh() if err != nil { return VApp{}, fmt.Errorf("error refreshing vdc: %s", err) } urnslice := strings.SplitAfter(vappid, ":") urnid := urnslice[len(urnslice)-1] for _, resents := range v.Vdc.ResourceEntities { for _, resent := range resents.ResourceEntity { hrefslice := strings.SplitAfter(resent.HREF, "/") hrefslice = strings.SplitAfter(hrefslice[len(hrefslice)-1], "-") res := strings.Join(hrefslice[1:], "") if res == urnid && resent.Type == "application/vnd.vmware.vcloud.vApp+xml" { u, err := url.ParseRequestURI(resent.HREF) if err != nil { return VApp{}, fmt.Errorf("error decoding vdc response: %s", err) } // Querying the VApp req := v.c.NewRequest(map[string]string{}, "GET", *u, nil) resp, err := checkResp(v.c.Http.Do(req)) if err != nil { return VApp{}, fmt.Errorf("error retrieving vApp: %s", err) } newvapp := NewVApp(v.c) if err = decodeBody(resp, newvapp.VApp); err != nil { return VApp{}, fmt.Errorf("error decoding vApp response: %s", err) } return *newvapp, nil } } } return VApp{}, fmt.Errorf("can't find vApp") }
func getOathToken(userID string, userCode string) { fmt.Println("Getting the OAuthToken") //CHANGE FROM LOCALHOST requestString := "https://foursquare.com/oauth2/access_token?client_id=5ATHFEOTK5EU23DGQXCJ4XHYF1OWTBDIIV2CHXBAYQN0X5IO&client_secret=F1SZ1YRLHF4RURVU40QTC5NCB4Y3AHPM4MMIXHFDCRZZD4R0&grant_type=authorization_code&redirect_uri=https://localhost/afterlanding.html&code=" + userCode fmt.Println(requestString) response, err := http.Get(requestString) if response.StatusCode != 200 { fmt.Println("error") body, _ := ioutil.ReadAll(response.Body) fmt.Println("Body: ", string(body)) return } check(err) body, _ := ioutil.ReadAll(response.Body) fmt.Println("Body: ", string(body)) strings := strings.SplitAfter(string(body), ":") fmt.Println("Strings after Split: ", strings) session, err := mgo.Dial("localhost") check(err) defer session.Close() session.SetMode(mgo.Monotonic, true) c := session.DB("test").C("foursqare") toInsert := foursquareInformation{userID, strings[1], make([]string, 0), make([]string, 0)} c.Insert(&toInsert) //I presume we would here go get the user's data }
func bootstrapFixImports(text, srcFile string) string { lines := strings.SplitAfter(text, "\n") inBlock := false for i, line := range lines { if strings.HasPrefix(line, "import (") { inBlock = true continue } if inBlock && strings.HasPrefix(line, ")") { inBlock = false continue } if strings.HasPrefix(line, `import "`) || strings.HasPrefix(line, `import . "`) || inBlock && (strings.HasPrefix(line, "\t\"") || strings.HasPrefix(line, "\t. \"")) { line = strings.Replace(line, `"cmd/`, `"bootstrap/cmd/`, -1) for _, dir := range bootstrapDirs { if strings.HasPrefix(dir, "cmd/") { continue } line = strings.Replace(line, `"`+dir+`"`, `"bootstrap/`+dir+`"`, -1) } lines[i] = line } } lines[0] = "// Do not edit. Bootstrap copy of " + srcFile + "\n\n//line " + srcFile + ":1\n" + lines[0] return strings.Join(lines, "") }
// runs in a goroutine (Raid.Conduct) func (p Plane) launchAndReport(urlInvariant string, logCh chan map[string]interface{}, squadronID string) { results, err := p.Launch(logCh) if err != nil { logCh <- map[string]interface{}{ "error": err, "severity": "ERROR", } } for weaponID, result := range results { var path string parts := strings.SplitAfter(result.Path, urlInvariant) if len(parts) >= 2 { path = parts[1] } else { path = result.Path } stats := map[string]interface{}{ "plane": p.Name, "weapon_id": weaponID, "squadron_id": squadronID, "method": result.Verb, "path": path, "response_time": result.Duration * time.Millisecond, "status_code": result.StatusCode, } logCh <- stats } }
func (s ConsoleServer) Start() { // here is where I would specify the console interface if I actually planned on using the // from the command line. For now it will just expect a command to look like `./calhoun // -ui=cli upload file=/path/to/file` url := s.Args[0] filepath := strings.SplitAfter(s.Args[1], "=")[1] // file=/path/to/file, so I need everything after the = var file multipart.File switch url { case "upload": file, err := os.Open(filepath) defer file.Close() if err != nil { log.Fatal("error reading photo upload: ", err) } default: log.Fatal("invalid command: `", url, "`") } route := s.routeWithPath(url) baseHandler := s.App.LookupHandler(route.Action) calhounHandler := route.ApplyMiddlewareToBase(baseHandler) request := CalhounRequest{UploadFile: &file} calhounHandler(os.Stdout, &request) }
// Get the value at a path. func (c *Client) GetPath(path *Path) (*KVResult, error) { resp, err := c.doRequest("GET", path.trailingGetURI(), nil, nil) if err != nil { return nil, err } defer resp.Body.Close() if resp.StatusCode != 200 { return nil, newError(resp) } // TODO: Check for a content-length header so we can pre-allocate buffer // space. buf := bytes.NewBuffer(nil) if _, err := buf.ReadFrom(resp.Body); err != nil { return nil, err } if path.Ref == "" { path.Ref = strings.SplitAfter(resp.Header.Get("Content-Location"), "/")[5] } return &KVResult{Path: *path, RawValue: buf.Bytes()}, nil }
func (ss *setSecurityDefinitions) Parse(lines []string) error { if len(lines) == 0 || (len(lines) == 1 && len(lines[0]) == 0) { return nil } var result []map[string][]string for _, line := range lines { kv := strings.SplitN(line, ":", 2) var scopes []string var key string if len(kv) > 1 { scs := strings.Split(kv[1], ",") for _, scope := range scs { tr := strings.TrimSpace(scope) if tr != "" { tr = strings.SplitAfter(tr, " ")[0] scopes = append(scopes, strings.TrimSpace(tr)) } } key = strings.TrimSpace(kv[0]) result = append(result, map[string][]string{key: scopes}) } } ss.set(result) return nil }
// IO.readlines(filename) // [RString] func RIO_readlines(vm *GobiesVM, env *ThreadEnv, receiver Object, v []Object) Object { vm.transactionEnd(env) filename := v[0].(*RObject).val.str content, _ := ioutil.ReadFile(filename) str := string(content[:]) items := []Object{} dummy_obj := []Object{nil} lines := strings.SplitAfter(str, "\n") for _, line := range lines { dummy_obj[0] = line rstr := RString_new(vm, nil, receiver, dummy_obj) items = append(items, rstr) } obj := RArray_new(vm, nil, receiver, items) // Begin empty transaction vm.transactionBegin(env, []Instruction{}) return obj }
// handleFilelist reads the file given and handles each non-blank line as a command line for gocog. func handleFilelist(name string, opts *processor.Options) ([]*processor.Processor, error) { if opts.Verbose { log.Printf("Processing filelist '%s'", name) } b, err := ioutil.ReadFile(name) if err != nil { return nil, err } lines := strings.SplitAfter(string(b), "\n") procs := make([]*processor.Processor, 0, len(lines)) for i, line := range lines { if len(line) == 0 { continue } args, err := shellquote.Split(line) if err != nil { return nil, fmt.Errorf("Error parsing command line in filelist '%s' line %d", name, i+1) } p, err := handleCommandLine(args, *opts) if err != nil { return nil, err } procs = append(procs, p...) } return procs, nil }
func Parse(content string) template.HTML { mode := 0 code, out := "", "" content = strings.Replace(content, "\r", "", -1) lines := strings.SplitAfter(content, "\n") lines[len(lines)-1] = lines[len(lines)-1] + "\n" for _, line := range lines { p := new(Parsed) p.parse(line) if mode == 1 { if p.tag == 'F' { mode = 0 out += parseCode(code) out += p.render() continue } code += line continue } if p.tag == 'F' { mode = 1 } out += p.render() } return template.HTML(out) }
func (u *UserMetaData) SaveUserMetaData() RD.ReturnData { returnData := RD.ReturnData{} dbSession := Connection.GetDBSession() dbSession.SetMode(mgo.Monotonic, true) dataBase := strings.SplitAfter(os.Getenv("MONGOHQ_URL"), "/") c := dbSession.DB(dataBase[3]).C("jove") u.Id = bson.NewObjectId() u.Created_on = time.Now() err := c.Insert(u) if err != nil { log.Print(err.Error()) returnData.ErrorMsg = err.Error() returnData.Success = false returnData.Status = "422" } else { returnData.Success = true jsonData, _ := json.Marshal(&u) returnData.JsonData = jsonData returnData.Status = "201" } return returnData }
func mapIncoming(inputString string) map[string]string { dataMap := map[string]string{} // We only want data which exist after the 'Current Values:' String input := strings.SplitAfter(string(inputString), "Current values:")[1] // This output is terribly formatted. Let's start by finding actual lines // by separating on the newline characters (0x0a) r, err := regexp.Compile(`\x0A(?:.+:)(.+)`) if err != nil { panic(err) } rows := r.FindAllStringSubmatch(input, -1) // Now we have a number of rows, with a variable key followed by some whitespace // followed by its value. Let's parse that into the final key/value pairs for i := 0; i < len(rows); i++ { r, err = regexp.Compile(`(.+)\s+(.+)`) data := r.FindAllStringSubmatch(rows[i][1], -1) for j := 0; j < len(data); j++ { dataMap[strings.TrimSpace(data[j][1])] = strings.TrimSpace(data[j][2]) } } return dataMap }
func GetUserById(userId string) string { var response string dbSession := Connection.GetDBSession() dbSession.SetMode(mgo.Monotonic, true) dataBase := strings.SplitAfter(os.Getenv("MONGOHQ_URL"), "/") c := dbSession.DB(dataBase[3]).C("jove") result := UserMetaData{} err := c.Find(bson.M{"_id": bson.ObjectIdHex(userId)}).One(&result) if err != nil { log.Println(err) response = err.Error() // returnData.ErrorMsg = err.Error() // returnData.Status = "400" // returnData.Success = false } else { log.Println(result) // returnData.ErrorMsg = "All is well" // returnData.Status = "200" // returnData.Success = true response, _ := json.Marshal(result) log.Println(response) // returnData.JsonData = jsonRes } return response }
// cpu使用率,多cpu的情况,第一个是平均值 func (a *Agent) Pcpu() ([]Pcpu, error) { var pcpus []Pcpu all, err := exec.Command("/usr/bin/mpstat", "-P", "ALL").Output() if err != nil { a.Log.Println("/usr/bin/mpstat -P ALL", err) return nil, err } s := strings.SplitAfter(string(all), "\n") for i := 3; i <= numcpu+3; i++ { var cpu = s[i] cur := strings.Fields(cpu) /* *ID := cur[1] *us,ni,sy := cur[2],cur[3],cur[4] *wa,hi,si := cur[5],cur[6],cur[7] *st,idle := cur[8],cur[10] */ us, _ := strconv.ParseFloat(cur[2], 64) sy, _ := strconv.ParseFloat(cur[4], 64) wa, _ := strconv.ParseFloat(cur[5], 64) idle, _ := strconv.ParseFloat(cur[10], 64) pcpus = append(pcpus, Pcpu{cur[1], us, sy, wa, idle}) } return pcpus, nil }
func (c *Collector) virtualFunctions(nic *NIC) ([]*NIC, error) { out, err := c.Run(fmt.Sprintf("path=$(find /sys/devices -name \"%s\" );ls -d $path/virtf* 2>/dev/null", nic.PCIAddr)) if err != nil { return nil, err } var list []*NIC for _, line := range strings.SplitAfter(out, "\n") { entry, _ := c.Run("readlink -f " + strings.TrimSpace(line)) if err != nil { return nil, err } s := strings.Split(entry, "/") vf := new(NIC) vf.Name = "N/A" vf.Vendor = nic.Vendor vf.Model = "Ethernet Controller Virtual Function" vf.Desc = nic.Vendor + " " + vf.Model vf.Type = NicTypePhysVF vf.NUMANode = nic.NUMANode vf.PCIAddr = s[len(s)-1] vf.Driver = nic.Driver list = append(list, vf) } return list, nil }
// NewNetflow returns a netflow object listening on port Netflow.Port func NewNetflow() (*Netflow, int, error) { log.Debugln("NewNetflow") nf := &Netflow{ writers: make(map[string]chan *Packet), } conn, err := net.ListenUDP("udp", &net.UDPAddr{}) if err != nil { return nil, -1, err } nf.conn = conn addr := nf.conn.LocalAddr() f := strings.SplitAfter(addr.String(), ":") if len(f) < 2 { return nil, -1, fmt.Errorf("invalid LocalAddr %v", addr) } p, err := strconv.Atoi(f[len(f)-1]) if err != nil { return nil, -1, err } go nf.reader() nf.port = p return nf, p, nil }
func getEntrypointFromSpecs(path string) string { pSpec := getConfigSpec(path) if pSpec == nil { return "" } spec := *pSpec prefixDir := "" entryPoint := spec.Process.Args if entryPoint == nil { return "/bin/sh" } if !filepath.IsAbs(entryPoint[0]) { if spec.Process.Cwd == "" { prefixDir = "/" } else { prefixDir = spec.Process.Cwd } } entryPoint[0] = prefixDir + entryPoint[0] var res []string res = strings.SplitAfter(entryPoint[0], "/") if len(res) <= 2 { entryPoint[0] = "/bin" + entryPoint[0] } return entryPoint[0] }
func PortIsListenedOn(t *testing.T, addr_expect string) bool { // Equivalent to: $(netstat -nuptl| grep <ip:port> | grep LISTEN). // Input addr_expect: is of the form "tcp://127.0.0.1:1777" // and we discard everyting before the // to get ip:port. out, err := exec.Command("netstat", "-nuptl").Output() if err != nil { t.Fatal(err) } lines := strings.Split(string(out), "\n") needle := strings.SplitAfter(addr_expect, "//")[1] //e.g. needle := "127.0.0.1:1776" t.Logf("using netstat -nuptl to look for %v LISTEN line.\n", needle) found := false for _, haystack := range lines { if strings.Contains(haystack, needle) && strings.Contains(haystack, "LISTEN") { found = true t.Logf("'netstat -nuptl | grep %v | grep LISTEN' found: %v", needle, haystack) break } } return found }