// GetToken wraps the incoming username into a TokenStruct, serializes the result to json // and generates a Fernet token based on the resulting string func GetToken(username string) string { // If the configuration has changed, re-load the keys if confVersion != util.GetConfig().Version { loadMintKey() } claims := jwt.StandardClaims{ Issuer: "FoxAuthn", Subject: username, IssuedAt: time.Now().Unix(), ExpiresAt: time.Now().Add(time.Duration(util.GetConfig().Authn.TokenTTL) * time.Second).Unix(), } log.WithFields(log.Fields{ "claims": claims, }).Debug("Going to sign with these claims") token := jwt.NewWithClaims(jwt.SigningMethodRS384, claims) ss, err := token.SignedString(GetKey()) if err != nil { log.WithFields(log.Fields{ "path": mint.From, }).Panic("Failed to create signed token: ", err) } return ss }
func newRepo(name string, simpleDocker SimpleDocker.SimpleDocker) (Repo, error) { log.WithFields(log.Fields{ "name": name, }).Info("Creating new repo") r := Repo{ Name: name, SimpleDocker: simpleDocker, } startTime := time.Now() repoName := fmt.Sprintf("ihsw/%s", name) if err := r.pullImage(repoName); err != nil { log.WithFields(log.Fields{ "name": name, "err": err.Error(), "repoName": repoName, }).Warn("Could not pull image") return Repo{}, err } log.WithFields(log.Fields{ "name": name, "duration": fmt.Sprintf("%v", time.Now().Sub(startTime)), }).Info("Repo create success") return r, nil }
func main() { var ( accessToken = kingpin.Flag("access-token", "GitHub access token").Required().PlaceHolder("TOKEN").String() owner = kingpin.Flag("owner", "GitHub repository owner whose pull requests will be operated upon").Required().PlaceHolder("OWNER").String() repository = kingpin.Flag("repository", "GitHub repository name whose pull requests will be operated upon").Required().PlaceHolder("REPO").String() label = kingpin.Flag("label", "Name of a label used on the pull request to indicate that it has automatically been closed").PlaceHolder("LABEL").String() comment = kingpin.Flag("comment", "Content of comment, which will be created when pull request is closed").PlaceHolder("TEXT").Default("Pull request was automatically closed").String() days = kingpin.Flag("days", "Integer number of days. If at least this number of days elapses after a pull request has been created without any new comment or commits being posted it will be closed and an explanatory comment will be posted").Required().PlaceHolder("LABEL").Int() ) kingpin.UsageTemplate(kingpin.CompactUsageTemplate) kingpin.CommandLine.Help = "Tool to auto-close old GitHub pull requests that were forgotten by their committer" kingpin.Parse() p := NewPullRequestCloser(*accessToken) pullRequests, err := p.findPullRequests(*owner, *repository, *days) if err != nil { log.WithFields(log.Fields{"error": err}).Fatal("Failed to find pull requests") } for _, pullRequest := range pullRequests { log.WithFields(log.Fields{"pull_request": *pullRequest.HTMLURL}).Info("Closing pull request") err = p.closePullRequest(*owner, *repository, pullRequest, *comment, *label) if err != nil { log.WithFields(log.Fields{"error": err, "pull_request": *pullRequest.HTMLURL}).Warn("Failed to close pull request") } } }
// Start the link with the specified toxics func (link *ToxicLink) Start(name string, source io.Reader, dest io.WriteCloser) { go func() { bytes, err := io.Copy(link.input, source) if err != nil { logrus.WithFields(logrus.Fields{ "name": link.proxy.Name, "upstream": link.proxy.Upstream, "bytes": bytes, "err": err, }).Warn("Source terminated") } link.input.Close() }() for i, toxic := range link.toxics.chain { go link.stubs[i].Run(toxic) } go func() { bytes, err := io.Copy(dest, link.output) if err != nil { logrus.WithFields(logrus.Fields{ "name": link.proxy.Name, "upstream": link.proxy.Upstream, "bytes": bytes, "err": err, }).Warn("Destination terminated") } dest.Close() link.toxics.RemoveLink(name) link.proxy.RemoveConnection(name) }() }
func generateTempSocketPath(dir, prefix string) (string, error) { // Use TempFile to allocate a uniquely named file in either the specified // dir or the default temp dir. It is then removed so that the unix socket // can be created with that name. // TODO: Decide on permissions if dir != "" { if err := os.MkdirAll(dir, os.ModePerm); err != nil { log.WithFields(log.Fields{ "directory": dir, "perm": os.ModePerm, "error": err, }).Error("failed to create directory for socket") return "", err } } f, err := ioutil.TempFile(dir, prefix) if err != nil { log.WithFields(log.Fields{ "error": err, }).Error("failed to create temp file for response socket") return "", err } _ = f.Close() _ = os.Remove(f.Name()) return fmt.Sprintf("%s.sock", f.Name()), nil }
func (f *forwarder) connect() { if f.c != nil { return } rate := time.Tick(200 * time.Millisecond) for { var c net.Conn var err error if f.Config.TlsConfig != nil { c, err = tls.Dial("tcp", f.Config.ForwardDest, f.Config.TlsConfig) } else { c, err = net.DialTimeout("tcp", f.Config.ForwardDest, f.Config.ForwardDestConnectTimeout) } if err != nil { f.cErrors.Inc(1) log.WithFields(log.Fields{"id": f.ID, "message": err}).Error("Forwarder Connection Error") f.disconnect() } else { f.cSuccesses.Inc(1) log.WithFields(log.Fields{"id": f.ID, "remote_addr": c.RemoteAddr().String()}).Info("Forwarder Connection Success") f.c = c return } <-rate } }
// loadMintKeyByName loads a key by filename and stores it in the struct // The function is threadsafe and panics if the key file is invalid func LoadMintKeyByName(filename string) { keyPath := util.GetPaths([]string{filename})[0] b, err := ioutil.ReadFile(keyPath) if err != nil { log.WithFields(log.Fields{ "path": keyPath, }).Panic("Failed to load mint key: ", err) } k, err := jwt.ParseRSAPrivateKeyFromPEM(b) if err != nil { log.WithFields(log.Fields{ "path": keyPath, }).Panic("Failed to parse mint key: ", err) } log.WithFields(log.Fields{ "path": keyPath, }).Debugf("Successfully loaded mint key from %s", keyPath) // Store only after we are sure loading was good mint.Lock() defer mint.Unlock() mint.Key = k mint.From = keyPath }
func (peer *Peer) handleRouteRefresh(e *FsmMsg) []*table.Path { m := e.MsgData.(*bgp.BGPMessage) rr := m.Body.(*bgp.BGPRouteRefresh) rf := bgp.AfiSafiToRouteFamily(rr.AFI, rr.SAFI) if _, ok := peer.fsm.rfMap[rf]; !ok { log.WithFields(log.Fields{ "Topic": "Peer", "Key": peer.ID(), "Data": rf, }).Warn("Route family isn't supported") return nil } if _, ok := peer.fsm.capMap[bgp.BGP_CAP_ROUTE_REFRESH]; !ok { log.WithFields(log.Fields{ "Topic": "Peer", "Key": peer.ID(), }).Warn("ROUTE_REFRESH received but the capability wasn't advertised") return nil } rfList := []bgp.RouteFamily{rf} peer.adjRibOut.Drop(rfList) accepted, filtered := peer.getBestFromLocal(rfList) peer.adjRibOut.Update(accepted) for _, path := range filtered { path.IsWithdraw = true accepted = append(accepted, path) } return accepted }
func makeHeloChecker(sendLimiter *rerate.Limiter, spamLimiter *rerate.Limiter) func(smtpd.Peer, string) error { return func(peer smtpd.Peer, heloName string) error { if err := sendLimiter.Inc(heloName); err != nil { log.WithFields(log.Fields{ "heloName": heloName, "error": err, }).Warn("Can't increment send") } if exc, _ := sendLimiter.Exceeded(heloName); exc { log.WithFields(log.Fields{ "rateLimit": "send", "peer": peer, }).Warn("rateLimit exceeded") return smtpd.Error{Code: 451, Message: "Rate Limit exceeded"} } if exc, _ := spamLimiter.Exceeded(heloName); exc { log.WithFields(log.Fields{ "rateLimit": "spam", "peer": peer, }).Warn("rateLimit exceeded") return smtpd.Error{Code: 451, Message: "Rate Limit exceeded"} } return nil } }
// ValidateDeletePeer is the validation function for DeletePeer to invoke the rpc // server call func ValidateDeletePeer(remoteAddress string, id string) (*PeerGenericResp, error) { args := &PeerDeleteReq{ID: id} rpcConn, e := grpc.Dial(remoteAddress, grpc.WithInsecure()) if e != nil { log.WithFields(log.Fields{ "error": e, "remote": remoteAddress, }).Error("failed to grpc.Dial remote") rsp := &PeerGenericResp{ OpRet: -1, OpError: e.Error(), } return rsp, e } defer rpcConn.Close() client := NewPeerServiceClient(rpcConn) rsp, e := client.ValidateDelete(netctx.TODO(), args) if e != nil { log.WithFields(log.Fields{ "error": e, "rpc": "PeerService.ValidateDelete", "remote": remoteAddress, }).Error("failed RPC call") rsp := &PeerGenericResp{ OpRet: -1, OpError: e.Error(), } return rsp, e } return rsp, nil }
// ConfigureRemoteETCD will reconfigure etcd server on remote node to either // join or remove itself from an etcd cluster. func ConfigureRemoteETCD(remoteAddress string, args *EtcdConfigReq) (*PeerGenericResp, error) { rpcConn, e := grpc.Dial(remoteAddress, grpc.WithInsecure()) if e != nil { log.WithFields(log.Fields{ "error": e, "remote": remoteAddress, }).Error("failed to grpc.Dial remote") rsp := &PeerGenericResp{ OpRet: -1, OpError: e.Error(), } return rsp, e } defer rpcConn.Close() client := NewPeerServiceClient(rpcConn) rsp, e := client.ExportAndStoreETCDConfig(netctx.TODO(), args) if e != nil { log.WithFields(log.Fields{ "error": e, "rpc": "PeerService.ExportAndStoreETCDConfig", "remote": remoteAddress, }).Error("failed RPC call") rsp := &PeerGenericResp{ OpRet: -1, OpError: e.Error(), } return rsp, e } return rsp, nil }
// Serve starts DNS server func (dns *DNS) Serve(net string) (err error) { log.WithFields(log.Fields{ "service": "dns", "net": net, }).Info("Serve over ", net) dns.Server = &mdns.Server{ Addr: fmt.Sprintf("%s:%d", dns.Config.DNS.IP, dns.Config.DNS.Port), Net: net, } mdns.HandleFunc(".", dns.HandleRequest) err = dns.Server.ListenAndServe() if err != nil { log.WithFields(log.Fields{ "service": "dns", "addr": dns.Config.DNS.IP, "port": dns.Config.DNS.Port, "net": net, "error": err, }).Error("Can't start server") } defer dns.Server.Shutdown() log.WithFields(log.Fields{ "service": "dns", }).Info("[dns] Shutdown...") return }
func configGet(c *cli.Context) { arg := c.Args().Get(0) if arg == "" { return } cfg, err := config.LoadConfig() if err != nil { log.WithFields(log.Fields{"err": err}).Fatal("config get: failed to load config") } val, err := cfg.Get(arg) if err != nil { log.WithFields(log.Fields{"cfg": cfg, "key": arg, "val": val, "err": err}).Fatal("config get: failed to retrieve value") } printYaml := false switch val.(type) { case []interface{}: printYaml = true case map[interface{}]interface{}: printYaml = true } if printYaml { bytes, err := yaml.Marshal(val) if err != nil { log.Fatal(err) } fmt.Println(string(bytes)) } else { fmt.Println(val) } }
func main() { err := jq.Init() if err != nil { log.Fatal(err) } log.WithFields(log.Fields{ "version": jq.Version, "path": jq.Path, }).Info("initialized jq") conf, err := config.Load() if err != nil { log.Fatal(err) } log.WithFields(log.Fields{ "host": conf.Host, "port": conf.Port, }).Infof("Starting server at %s:%s", conf.Host, conf.Port) srv := server.New(conf) err = srv.Start() if err != nil { log.WithError(err).Fatal("error starting sever") } }
func startInterruptHandling(modules ...coreModule) { c := make(chan os.Signal, 1) signal.Notify(c, os.Interrupt, os.Kill, syscall.SIGTERM) //Let's block until someone tells us to quit go func() { sig := <-c log.WithFields( log.Fields{ "block": "main", "_module": "snapd", }).Info("shutting down modules") for _, m := range modules { log.WithFields( log.Fields{ "block": "main", "_module": "snapd", "snap-module": m.Name(), }).Info("stopping module") m.Stop() } log.WithFields( log.Fields{ "block": "main", "_module": "snapd", "signal": sig.String(), }).Info("exiting on signal") os.Exit(0) }() }
// Stream streams data from a URL to a destination writer. func Stream(dest io.Writer, addr *url.URL) error { if dest == nil { err := errors.New("missing dest") log.WithFields(log.Fields{ "error": err, }).Error(err) return err } if addr == nil { err := errors.New("missing addr") log.WithFields(log.Fields{ "error": err, }).Error(err) return err } switch addr.Scheme { case "unix": return streamUnix(dest, addr) case "http", "https": return streamHTTP(dest, addr) default: err := errors.New("unknown url type") log.WithFields(log.Fields{ "error": err, "type": addr.Scheme, "addr": addr, }).Error("cannot stream from url") return err } }
func (d *Daemon) Run(oneShot bool, noop bool) int { d.oneShot = oneShot d.noop = noop if err := d.Setup(); err != nil { log.WithFields(log.Fields{"err": err.Error()}).Error("Error in initial setup") return 1 } if !d.RouteTableManager.InstanceIsRouter(d.Instance) { log.WithFields(log.Fields{"instance_id": d.Instance}).Error("I am not a router (do not have src/destination checking disabled)") return 1 } d.quitChan = make(chan bool, 1) err := d.RunRouteTables() if err != nil { log.WithFields(log.Fields{"err": err.Error()}).Error("Error in initial route table run") return 1 } d.loopQuitChan = make(chan bool, 1) d.loopTimerChan = make(chan bool, 1) if oneShot { d.quitChan <- true } else { d.runHealthChecks() defer d.stopHealthChecks() d.RunSleepLoop() } <-d.quitChan d.loopQuitChan <- true return 0 }
func (pfs *physicalFS) ChangeDirectory(path string) error { var tmpDir string if pfs.homeRealDirectory == pfs.currentRealDirectory && path == ".." { return nil } if path[0] == '/' { // absolute path, join with homeDirectory tmpDir = filepath.Join(pfs.homeRealDirectory, path) } else { // relative path, join with currentDirectory tmpDir = filepath.Join(pfs.currentRealDirectory, path) } log.WithFields(log.Fields{"physicalFS": pfs, "tmpDir": tmpDir}).Debug("localFS::physicalFS::ChangeDirectory before testing tmpDir") // check existence and availability stat, err := os.Stat(tmpDir) if err != nil { log.WithFields(log.Fields{"physicalFS": pfs, "tmpDir": tmpDir}).Info("localFS::physicalFS::ChangeDirectory requested invalid directory") return err } if !stat.IsDir() { log.WithFields(log.Fields{"physicalFS": pfs, "tmpDir": tmpDir}).Info("localFS::physicalFS::ChangeDirectory requested entry is not a directory") return fmt.Errorf("%s requested entry is not a directory", path) } pfs.currentRealDirectory = tmpDir log.WithFields(log.Fields{"physicalFS": pfs}).Debug("localFS::physicalFS::ChangeDirectory before finish") return nil }
// NewPrimary creates a new API router. func NewPrimary(cluster cluster.Cluster, tlsConfig *tls.Config, status StatusHandler, enableCors bool) *mux.Router { // Register the API events handler in the cluster. eventsHandler := newEventsHandler() cluster.RegisterEventHandler(eventsHandler) context := &context{ cluster: cluster, eventsHandler: eventsHandler, statusHandler: status, tlsConfig: tlsConfig, } r := mux.NewRouter() for method, mappings := range routes { for route, fct := range mappings { log.WithFields(log.Fields{"method": method, "route": route}).Debug("Registering HTTP route") localRoute := route localFct := fct wrap := func(w http.ResponseWriter, r *http.Request) { log.WithFields(log.Fields{"method": r.Method, "uri": r.RequestURI}).Debug("HTTP request received") if enableCors { writeCorsHeaders(w, r) } localFct(context, w, r) } localMethod := method r.Path("/v{version:[0-9.]+}" + localRoute).Methods(localMethod).HandlerFunc(wrap) r.Path(localRoute).Methods(localMethod).HandlerFunc(wrap) } } return r }
func (mc *metricCatalog) AddLoadedMetricType(lp *loadedPlugin, mt core.Metric) error { if err := validateMetricNamespace(mt.Namespace()); err != nil { log.WithFields(log.Fields{ "_module": "control", "_file": "metrics.go,", "_block": "add-loaded-metric-type", "error": fmt.Errorf("Metric namespace %s is invalid", mt.Namespace()), }).Error("error adding loaded metric type") return err } if lp.ConfigPolicy == nil { err := errors.New("Config policy is nil") log.WithFields(log.Fields{ "_module": "control", "_file": "metrics.go,", "_block": "add-loaded-metric-type", "error": err, }).Error("error adding loaded metric type") return err } newMt := metricType{ Plugin: lp, namespace: mt.Namespace(), version: mt.Version(), lastAdvertisedTime: mt.LastAdvertisedTime(), tags: mt.Tags(), policy: lp.ConfigPolicy.Get(mt.Namespace().Strings()), description: mt.Description(), unit: mt.Unit(), } mc.Add(&newMt) return nil }
func makeMailHandler(mandrillAPI *gochimp.MandrillAPI, sendLimiter *rerate.Limiter, spamLimiter *rerate.Limiter) func(smtpd.Peer, smtpd.Envelope) error { return func(peer smtpd.Peer, env smtpd.Envelope) error { // Validate data before sending them if _, err := mail.ReadMessage(bytes.NewReader(env.Data)); err != nil { return err } response, err := mandrillAPI.MessageSendRaw(string(env.Data), env.Recipients, gochimp.Recipient{Email: env.Sender}, false) if err != nil { log.WithFields(log.Fields{ "peer": peer, "error": err, }).Info("Error sending message") return smtpd.Error{Code: 451, Message: "Error with Remote API"} } if response[0].Status == "rejected" && response[0].RejectedReason == "spam" { log.WithFields(log.Fields{ "peer": peer, "RejectedReason": response[0].RejectedReason, }).Info("Message filtered as SPAM") if err := spamLimiter.Inc(peer.HeloName); err != nil { log.WithFields(log.Fields{ "heloName": peer.HeloName, "error": err, }).Warn("Can't increment send") } return smtpd.Error{Code: 451, Message: "Spam filtered, increment rate limit"} } return nil } }
// refreshLoop periodically triggers engine refresh. func (e *Engine) refreshLoop() { for { var err error // Wait for the delayer or quit if we get stopped. select { case <-e.refreshDelayer.Wait(): case <-e.stopCh: return } if !e.IsHealthy() { if err = e.updateSpecs(); err != nil { log.WithFields(log.Fields{"name": e.Name, "id": e.ID}).Errorf("Update engine specs failed: %v", err) continue } e.client.StopAllMonitorEvents() e.client.StartMonitorEvents(e.handler, nil) } err = e.RefreshContainers(false) if err == nil { // Do not check error as older daemon don't support this call e.RefreshVolumes() e.RefreshNetworks() e.RefreshImages() log.WithFields(log.Fields{"id": e.ID, "name": e.Name}).Debugf("Engine update succeeded") } else { log.WithFields(log.Fields{"id": e.ID, "name": e.Name}).Debugf("Engine refresh failed") } } }
func httpError(w http.ResponseWriter, err error) { if err == nil || w == nil { logrus.WithFields(logrus.Fields{"error": err, "writer": w}).Error("unexpected HTTP error handling") return } statusCode := http.StatusInternalServerError // FIXME: this is brittle and should not be necessary. // If we need to differentiate between different possible error types, we should // create appropriate error types with clearly defined meaning. errStr := strings.ToLower(err.Error()) for keyword, status := range map[string]int{ "not found": http.StatusNotFound, "no such": http.StatusNotFound, "bad parameter": http.StatusBadRequest, "conflict": http.StatusConflict, "impossible": http.StatusNotAcceptable, "wrong login/password": http.StatusUnauthorized, "hasn't been activated": http.StatusForbidden, } { if strings.Contains(errStr, keyword) { statusCode = status break } } logrus.WithFields(logrus.Fields{"statusCode": statusCode, "err": err}).Error("HTTP Error") http.Error(w, err.Error(), statusCode) }
func (d *Daemon) Start() error { log.Info("Starting lifecycled daemon") if d.InstanceID != "" { log.WithFields(log.Fields{"instance_id": d.InstanceID}).Info("Filtering messages by instance id") } else { log.Warn("Not filtering by instance id") } ch := make(chan Message) go func() { for m := range ch { if m.Transition == "" { continue } if d.InstanceID != "" && d.InstanceID != m.InstanceID { log.WithFields(log.Fields{"instanceid": m.InstanceID}).Debug("Skipping filtered message based on instance id") continue } d.handleMessage(m) } }() log.WithFields(log.Fields{"queue": d.Queue}).Info("Listening for events") return d.Queue.Receive(ch, d.ReceiveOpts) }
func init() { event.On(event.EntityQuery, func(args ...interface{}) { e := args[0].(*Entity) universeId := args[1].(uint) comp := &ItemSlot{} if err := comp.QueryEntityUniverse(e.Id, universeId); err != nil { logrus.WithFields(logrus.Fields{ "Entity": e.Id, "Universe": universeId, }).Error("save.ItemSlot(entity): " + err.Error()) return } e.AddComponent(comp) if item, err := GetItem(comp.Item); item != nil { e.Image = item.Image } else if err != nil { logrus.WithFields(logrus.Fields{ "Entity": e.Id, "Universe": universeId, "Item": comp.Item, }).Error("save.ItemSlot(item): " + err.Error()) } }) }
// process an inbound connection func (s *Server) handleInboundConnection(c net.Conn) { log.WithFields(log.Fields{ "pkg": "nntp-server", "addr": c.RemoteAddr(), }).Debug("handling inbound connection") var nc Conn nc = newInboundConn(s, c) err := nc.Negotiate(true) if err == nil { // do they want to stream? if nc.WantsStreaming() { // yeeeeeh let's stream var chnl chan ArticleEntry chnl, err = nc.StartStreaming() // for inbound we will recv messages go s.recvInboundStream(chnl) nc.StreamAndQuit() log.WithFields(log.Fields{ "pkg": "nntp-server", "addr": c.RemoteAddr(), }).Info("streaming finished") return } else { // handle non streaming commands nc.ProcessInbound(s) } } else { log.WithFields(log.Fields{ "pkg": "nntp-server", "addr": c.RemoteAddr(), }).Warn("failed to negotiate with inbound connection", err) c.Close() } }
// GetResponseBody calls stubo func (c *Client) GetResponseBody(uri string) ([]byte, error) { // logging get Response body log.WithFields(log.Fields{ "uri": uri, }).Info("Getting response body") resp, err := c.HTTPClient.Get(uri) if err != nil { // logging get error log.WithFields(log.Fields{ "error": err.Error(), "uri": uri, }).Warn("Failed to get response from Stubo!") return []byte(""), err } defer resp.Body.Close() // reading resposne body body, err := ioutil.ReadAll(resp.Body) if err != nil { // logging read error log.WithFields(log.Fields{ "error": err.Error(), "uri": uri, }).Warn("Failed to read response from Stubo!") return []byte(""), err } return body, nil }
// // Look up the length of the Certificate, reporting errors if the certificate is // shorter than the minimum certificate size or if the reported length doesn't // match the provided data. // func (certificate Certificate) Length() (length int, err error) { cert_len := len(certificate) _, err = certificate.Type() if err != nil { return } length = Integer(certificate[1:CERT_MIN_SIZE]) inferred_len := length + CERT_MIN_SIZE if inferred_len > cert_len { log.WithFields(log.Fields{ "at": "(Certificate) Length", "certificate_bytes_length": cert_len, "certificate_length_field": length, "expected_bytes_length": inferred_len, "reason": "data shorter than specified", }).Warn("certificate format warning") err = errors.New("certificate parsing warning: certificate data is shorter than specified by length") } else if cert_len > inferred_len { log.WithFields(log.Fields{ "at": "(Certificate) Length", "certificate_bytes_length": cert_len, "certificate_length_field": length, "expected_bytes_length": inferred_len, "reason": "data longer than expected", }).Warn("certificate format warning") err = errors.New("certificate parsing warning: certificate contains data beyond length") } return }
// TrackRequest tracks a request. This does not need to be called after using // ProxyUnix. func (t *Tracker) TrackRequest(req *Request, timeout time.Duration) error { t.requestsLock.Lock() defer t.requestsLock.Unlock() if t.status == statusStarted { if _, ok := t.requests[req.ID]; ok { err := errors.New("request id already traacked") log.WithFields(log.Fields{ "request": req, "error": err, }).Error(err) return err } t.waitgroup.Add(1) t.requests[req.ID] = req t.setRequestTimeout(req, timeout) return nil } err := errors.New("failed to track request in unstarted tracker") log.WithFields(log.Fields{ "request": req, "trackerStatus": t.status, "error": err, }).Error(err) return err }
func (p *testProcess) finish() error { if p.writer != nil { if err := p.writer.Flush(); err != nil { log.WithFields(log.Fields{ "error": err, "func": "bufio.Writer.Flush", "name": p.name, "path": p.path, }).Error("Could not flush buffer") return err } if err := p.file.Close(); err != nil { log.WithFields(log.Fields{ "error": err, "func": "os.File.Close", "name": p.name, "path": p.path, }).Error("Could not close log file") return err } } if err := p.cmd.Process.Signal(os.Kill); err != nil { log.WithFields(log.Fields{ "error": err, "func": "exec.Cmd.Process.Signal", "name": p.name, }).Error("Could not kill process") return err } _ = p.cmd.Wait() return nil }