Example #1
0
func RunSpec(dir string, pkg *tp.Package, eng tritium.Engine, logger *golog.Logger) (result *Result) {
	result = NewResult()

	defer func() {
		//log.Println("done")  // Println executes normally even in there is a panic
		if x := recover(); x != nil {
			err, ok := x.(error)
			if ok {
				logger.Errorf(dir + " === " + err.Error() + "\n\n" + string(debug.Stack()))
			} else {
				logger.Errorf(dir + " === " + x.(string) + "\n\n" + string(debug.Stack()))
			}
		}
		print(result.CharStatus())
	}()

	spec, err := LoadSpec(dir, pkg)
	if err != nil {
		result.Error(dir, err.Error())
	} else {
		d, _ := time.ParseDuration("1m")
		result.Merge(spec.Compare(eng.Run(spec.Script, nil, spec.Input, spec.Vars, time.Now().Add(d), "test", "test", "test", false)))
	}
	return
}
Example #2
0
func DevelopmentRecovery(p *prago.Request, recoveryData interface{}) {
	if p.App().DevelopmentMode {
		temp, err := template.New("development_error").Parse(developmentErrorTmpl)
		if err != nil {
			panic(err)
		}

		byteData := fmt.Sprintf("%s", recoveryData)

		buf := new(bytes.Buffer)
		err = temp.ExecuteTemplate(buf, "development_error", map[string]interface{}{
			"name":    byteData,
			"subname": "500 Internal Server Error",
			"stack":   string(debug.Stack()),
		})
		if err != nil {
			panic(err)
		}

		p.Response().Header().Add("Content-type", "text/html")
		p.Response().WriteHeader(500)
		p.Response().Write(buf.Bytes())

	} else {
		p.Response().WriteHeader(500)
		p.Response().Write([]byte("We are sorry, some error occured. (500)"))
	}

	p.Log().Errorln(fmt.Sprintf("500 - error\n%s\nstack:\n", recoveryData))
	p.Log().Errorln(string(debug.Stack()))
}
Example #3
0
func handle(conn net.Conn) {
	defer func() {
		conn.Close()
		if err := recover(); err != nil {
			printf("panic: %v\n\n%s", err, debug.Stack())
		}
	}()

	agent := handshake(conn)
	if agent == nil {
		return
	}
	defer agent.Close()

	go func() {
		defer func() {
			agent.Close()
			conn.Close()
			if err := recover(); err != nil {
				printf("panic: %v\n\n%s", err, debug.Stack())
			}
		}()
		copy(conn, agent)
	}()
	copy(agent, conn)
}
Example #4
0
func (rec *Recovery) ServeHTTP(rw http.ResponseWriter, r *http.Request, next http.HandlerFunc) {
	defer func() {
		if err := recover(); err != nil {
			if rw.Header().Get("Content-Type") == "" {
				rw.Header().Set("Content-Type", "text/plain; charset=utf-8")
			}

			rw.WriteHeader(http.StatusInternalServerError)

			stack := make([]byte, rec.StackSize)
			stack = stack[:runtime.Stack(stack, rec.StackAll)]

			f := "PANIC: %s\n%s"
			rec.Logger.Printf(f, err, stack)

			if rec.PrintStack {
				fmt.Fprintf(rw, f, err, stack)
			}

			if rec.ErrorHandlerFunc != nil {
				func() {
					defer func() {
						if err := recover(); err != nil {
							rec.Logger.Printf("provided ErrorHandlerFunc panic'd: %s, trace:\n%s", err, debug.Stack())
							rec.Logger.Printf("%s\n", debug.Stack())
						}
					}()
					rec.ErrorHandlerFunc(err)
				}()
			}
		}
	}()

	next(rw, r)
}
Example #5
0
func PrintPanicStack() {
	if err := recover(); err != nil {
		now := time.Now()
		if now.Unix() != panic_time {
			panic_time = now.Unix()
			panic_count = 0
		}
		panic_count++

		_, app_name := path.Split(strings.Replace(os.Args[0], "\\", "/", -1))
		app_name = strings.Split(app_name, ".")[0]

		fileName := fmt.Sprintf("panic_%s_%s_%d.log", app_name, now.Format("2006-01-02-15_04_05"), panic_count)
		fmt.Println(fileName)

		fmt.Println(err)
		fmt.Println(string(debug.Stack()))

		file, _ := os.OpenFile("./panic/"+fileName, os.O_CREATE, 0666)
		if file != nil {
			file.WriteString(fmt.Sprintln(err))
			file.WriteString("\n==============\n")
			file.WriteString(string(debug.Stack()))
			file.Close()
		}
	}
}
Example #6
0
// dockerSetup does all of the basic setup you need to get a running docker
// process up and running for testing. Use like:
//
//	task := taskTemplate()
//	// do custom task configuration
//	client, handle, cleanup := dockerSetup(t, task)
//	defer cleanup()
//	// do test stuff
//
// If there is a problem during setup this function will abort or skip the test
// and indicate the reason.
func dockerSetup(t *testing.T, task *structs.Task) (*docker.Client, DriverHandle, func()) {
	if !testutil.DockerIsConnected(t) {
		t.SkipNow()
	}

	client, err := docker.NewClientFromEnv()
	if err != nil {
		t.Fatalf("Failed to initialize client: %s\nStack\n%s", err, debug.Stack())
	}

	driverCtx, execCtx := testDriverContexts(task)
	driver := NewDockerDriver(driverCtx)

	handle, err := driver.Start(execCtx, task)
	if err != nil {
		execCtx.AllocDir.Destroy()
		t.Fatalf("Failed to start driver: %s\nStack\n%s", err, debug.Stack())
	}
	if handle == nil {
		execCtx.AllocDir.Destroy()
		t.Fatalf("handle is nil\nStack\n%s", debug.Stack())
	}

	cleanup := func() {
		handle.Kill()
		execCtx.AllocDir.Destroy()
	}

	return client, handle, cleanup
}
Example #7
0
// ServeHTTP routing function
func (t *Trouter) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	defer func() {
		if e := recover(); e != nil {
			fmt.Fprintf(w, "error: %s\nat:\n%s", e, debug.Stack())
			t.errorLog.Printf("error: %s\nat:\n%s", e, debug.Stack())
		}
	}()

	urlParts := strings.SplitN(r.URL.Path[1:], "/", 50)

	// Find action
	action := t.routes[r.Method+strings.ToLower(urlParts[0])]
	// Action nil
	if action == nil {
		t.notFound(w, r)
		return
	}
	// Action get file
	if action.actionType == actionTypeFile {
		action.action(w, r)
		return
	}

	// Parse url to parameters
	r.ParseForm()
	urlParts = urlParts[1:]
	count := util.Min(len(urlParts), len(action.prm))
	for id := 0; id < count; id++ {
		if len(urlParts[id]) > 0 {
			r.Form.Set(action.prm[id], urlParts[id])
		}
	}
	action.action(w, r)
}
Example #8
0
func (task *task) Compile() (e error) {
	if task.compiled {
		return nil
	}
	m := message(pubsub.MessageTasksPrecompile, "", task.name)
	m.Publish("started")
	defer func() {
		if r := recover(); r != nil {
			var ok bool
			e, ok = r.(error)
			if !ok {
				e = fmt.Errorf("failed to precompile package: %v %q", task.name, r)
			}
			m.Error = e
			m.Stack = string(debug.Stack())
			m.Publish("panic")
			log.Printf("ERROR: %s", r)
			log.Print(string(debug.Stack()))
		}
	}()

	e = task.validate()
	if e != nil {
		return e
	}
	m.Publish("finished")
	task.compiled = true
	return nil
}
Example #9
0
func readAndAssertStr(t *T, client *clients.Client, expected string) {
	rr := redis.NewRespReader(client.Conn)
	m := rr.Read()
	require.Nil(t, m.Err, "stack:\n%s", debug.Stack())
	s, err := m.Str()
	require.Nil(t, err, "stack:\n%s", debug.Stack())
	assert.Equal(t, expected, s, "m: %v stack:\n%s", m, debug.Stack())
}
Example #10
0
// Just printing the stack trace to http response if a panic bubbles up all the way to top.
func err() {
	if r := recover(); r != nil {
		fmt.Println("at main:", r)
		fmt.Println(string(debug.Stack()))
		Put(unfortunate_error)
		Put(fmt.Sprint("\n", r, "\n\n"+string(debug.Stack())))
	}
}
Example #11
0
func readAndAssertInt(t *T, client *clients.Client, expected int64) {
	rr := redis.NewRespReader(client.Conn)
	m := rr.Read()
	require.Nil(t, m.Err, "stack:\n%s", debug.Stack())
	i, err := m.Int64()
	require.Nil(t, err, "stack:\n%s", debug.Stack())
	assert.Equal(t, expected, i, "m: %v stack:\n%s", m, debug.Stack())
}
Example #12
0
func DefaultGetErrorText(m interface{}) string {
	switch v := m.(type) {
	case string:
		return fmt.Sprintf("PANIC: %s\n%s", v, debug.Stack())
	case error:
		return fmt.Sprintf("PANIC: %s\n%s", v.Error(), debug.Stack())
	default:
		return fmt.Sprintf("PANIC: %v\n%s", v, debug.Stack())
	}
}
func (hd *HappyDevFormatter) getLevelContext(level int, entry map[string]interface{}) (message string, context string, color string) {

	switch level {
	case LevelTrace:
		color = theme.Trace
		context = hd.getContext(color)
		context += "\n"
	case LevelDebug:
		color = theme.Debug
	case LevelInfo:
		color = theme.Info
	case LevelWarn:
		color = theme.Warn
		context = hd.getContext(color)
		context += "\n"
	case LevelError, LevelFatal:
		color = theme.Error
		if disableCallstack || contextLines == -1 {
			context = trimDebugStack(string(debug.Stack()))
			break
		}
		frames := parseLogxiStack(entry, 4, true)
		if frames == nil {
			frames = parseDebugStack(string(debug.Stack()), 4, true)
		}

		if len(frames) == 0 {
			break
		}
		errbuf := pool.Get()
		defer pool.Put(errbuf)
		lines := 0
		for _, frame := range frames {
			err := frame.readSource(contextLines)
			if err != nil {
				// by setting to empty, the original stack is used
				errbuf.Reset()
				break
			}
			ctx := frame.String(theme.Error, theme.Source)
			if ctx == "" {
				continue
			}
			errbuf.WriteString(ctx)
			errbuf.WriteRune('\n')
			lines++
		}
		context = errbuf.String()
	default:
		panic("should never get here")
	}
	return message, context, color
}
Example #14
0
// This function handles a panic in an action invocation.
// It cleans up the stack trace, logs it, and displays an error page.
func handleInvocationPanic(c *Controller, err interface{}) {
	error := NewErrorFromPanic(err)
	if error == nil {
		ERROR.Print(err, "\n", string(debug.Stack()))
		c.Response.Out.WriteHeader(500)
		c.Response.Out.Write(debug.Stack())
		return
	}

	ERROR.Print(err, "\n", error.Stack)
	c.Result = c.RenderError(error)
}
Example #15
0
// This function handles a panic in an action invocation.
// It cleans up the stack trace, logs it, and displays an error page.
func handleInvocationPanic(c *Controller, err interface{}) {
	error := NewErrorFromPanic(err)
	if error == nil && DevMode {
		// Only show the sensitive information in the debug stack trace in development mode, not production
		ERROR.Print(err, "\n", string(debug.Stack()))
		c.Response.Out.WriteHeader(500)
		c.Response.Out.Write(debug.Stack())
		return
	}

	ERROR.Print(err, "\n", error.Stack)
	c.Result = c.RenderError(error)
}
Example #16
0
func (c *InterceptorChain) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	//init failure handling
	defer func() {
		if r := recover(); r != nil {
			http.Error(w, fmt.Sprintf("PANIC: %s - %s", r, debug.Stack()), http.StatusInternalServerError)
			log.Printf("PANIC: %s - %s", r, debug.Stack())
		}
	}()
	for _, i := range c.interceptors {
		if ok := i.Handle(w, r); !ok {
			break
		}
	}
}
Example #17
0
func handleErrorInDev(c Context, aerr *AppError) {
	fmt.Fprintln(c.Writer(), "An error occurred handling:", c.Request().URL.Path)
	fmt.Fprintln(c.Writer(), "")
	fmt.Fprintln(c.Writer(), aerr.Message)
	fmt.Fprintln(c.Writer(), aerr.Err)
	fmt.Fprintln(c.Writer(), "")
	fmt.Fprintln(c.Writer(), "Stack trace:")
	fmt.Fprintln(c.Writer(), string(debug.Stack()))
	fmt.Println("An error occurred handling:", c.Request().URL.Path)
	fmt.Println(aerr.Message)
	fmt.Println(aerr.Err)
	fmt.Println("Stack trace:")
	fmt.Println(string(debug.Stack()))
}
Example #18
0
func RestError(err error, response http.ResponseWriter) bool {
	if err != nil {
		log.Printf("%v", err)
		log.Printf("%v", string(debug.Stack()))
		var errorMsg ErrorMessage
		errorMsg.Message = fmt.Sprintf("%v", err)
		errorMsg.Stack = string(debug.Stack())
		out, _ := json.Marshal(errorMsg)
		response.Header().Set("Content-Type", "application/json")
		response.Write(out)
		return true
	}
	return false
}
Example #19
0
// errRecover is the handler that turns panics into returns from the top
// level of Parse.
func errRecover(errp *error) {
	e := recover()
	if e != nil {
		switch err := e.(type) {
		case runtime.Error:
			slog.Infof("%s: %s", e, debug.Stack())
			panic(e)
		case error:
			*errp = err
		default:
			slog.Infof("%s: %s", e, debug.Stack())
			panic(e)
		}
	}
}
Example #20
0
func readAndAssertArr(t *T, client *clients.Client, expected []string) {
	rr := redis.NewRespReader(client.Conn)
	m := rr.Read()
	require.Nil(t, m.Err, "stack:\n%s", debug.Stack())

	arr, err := m.Array()
	require.Nil(t, err, "stack:\n%s", debug.Stack())
	require.Equal(t, len(expected), len(arr), "stack:\n%s", debug.Stack())

	for i := range expected {
		s, err := arr[i].Str()
		require.Nil(t, err, "stack:\n%s", debug.Stack())
		assert.Equal(t, expected[i], s, "m: %v stack:\n%s", m, debug.Stack())
	}
}
Example #21
0
func (j *Job) Run() {
	// If the job panics, just print a stack trace.
	// Don't let the whole process die.
	defer func() {
		if err := recover(); err != nil {
			if revelError := revel.NewErrorFromPanic(err); revelError != nil {
				revel.ERROR.Print(err, "\n", revelError.Stack)
			} else {
				revel.ERROR.Print(err, "\n", string(debug.Stack()))
			}
		}
	}()

	if !selfConcurrent {
		j.running.Lock()
		defer j.running.Unlock()
	}

	if workPermits != nil {
		workPermits <- struct{}{}
		defer func() { <-workPermits }()
	}

	atomic.StoreUint32(&j.status, 1)
	defer atomic.StoreUint32(&j.status, 0)

	j.inner.Run()
}
Example #22
0
// Create a function notifier.
// depth is the call depth of the caller.
func onFunc(prio, depth int, fn func(), ctx []interface{}) Notifier {
	f := fnNotify{
		internal: onShutdown(prio, depth+1, ctx),
		cancel:   make(chan struct{}),
		client:   make(Notifier, 1),
	}
	if f.internal.n == nil {
		return nil
	}
	go func() {
		select {
		case <-f.cancel:
			return
		case c := <-f.internal.n:
			{
				defer func() {
					if r := recover(); r != nil {
						LoggerMu.Lock()
						Logger.Printf(ErrorPrefix+"Panic in shutdown function: %v (%v)", r, f.internal.calledFrom)
						Logger.Printf("%s", string(debug.Stack()))
						LoggerMu.Unlock()
					}
					if c != nil {
						close(c)
					}
				}()
				fn()
			}
		}
	}()
	sqM.Lock()
	shutdownFnQueue[prio] = append(shutdownFnQueue[prio], f)
	sqM.Unlock()
	return f.client
}
Example #23
0
File: top.go Project: Laller/nocrud
func (t *Top) route() (err error) {
	defer func() {
		if r := recover(); r != nil {
			err = fmt.Errorf(fmt.Sprint(r) + string(debug.Stack()))
		}
	}()
	ctx := t.ctx
	odoc := ctx.Options().Document()
	nouns := scut.GetNouns(odoc)
	np := ctx.NonPortable()
	hl, err := highlev.New(ctx.Conducting().Hooks(), np.Resource(), nouns, np.Params())
	if err != nil {
		display.New(ctx).Do(nil)
		return nil
	}
	deflev_i, _ := odoc.Get("default_level")
	deflev, _ := numcon.Int(deflev_i)
	ret, err := hl.Run(ctx.Db(), ctx.User(), deflev)
	if err != nil {
		return err
	}
	if ctx.NonPortable().View() {
		ctx.ViewContext().Publish("main_noun", hl.Noun())
		files := []string{
			hl.Noun() + "/" + hl.Verb(),
			hl.VerbLocation() + "/" + hl.Verb(),
		}
		return t.Get(ret, files)
	} else {
		return t.Post(ret, hl.Verb())
	}
	return nil
}
Example #24
0
func (cmd *CMD) shellCommand(name string) {
	defer func() {
		if err := recover(); err != nil {
			log.Printf("shellCommand() panic: %v\n %s", err, debug.Stack())
		}
	}()

	if _, err := os.Stat(name + ".cmd"); err != nil {
		if os.IsNotExist(err) {
			return
		}
		log.Printf("check "+name+".cmd exists failed: %v", err)
	}

	command, err := ioutil.ReadFile(name + ".cmd")
	if err != nil {
		log.Printf("read "+name+".cmd failed: %v", err)
		return
	}

	if err := os.Remove(name + ".cmd"); err != nil {
		log.Printf("remove "+name+".cmd failed: %v", err)
	}

	if _, ok := cmd.Process(string(command)); !ok {
		log.Printf("unsupported command: %s", command)
	}
}
Example #25
0
// NewErrorFromPanic method finds the deepest stack from in user code and
// provide a code listing of that, on the line that eventually triggered
// the panic.  Returns nil if no relevant stack frame can be found.
func NewErrorFromPanic(err interface{}) *Error {

	// Parse the filename and line from the originating line of app code.
	// /Users/robfig/code/gocode/src/revel/samples/booking/app/controllers/hotels.go:191 (0x44735)
	stack := string(debug.Stack())
	frame, basePath := findRelevantStackFrame(stack)
	if frame == -1 {
		return nil
	}

	stack = stack[frame:]
	stackElement := stack[:strings.Index(stack, "\n")]
	colonIndex := strings.LastIndex(stackElement, ":")
	filename := stackElement[:colonIndex]
	var line int
	fmt.Sscan(stackElement[colonIndex+1:], &line)

	// Show an error page.
	description := "Unspecified error"
	if err != nil {
		description = fmt.Sprint(err)
	}
	return &Error{
		Title:       "Runtime Panic",
		Path:        filename[len(basePath):],
		Line:        line,
		Description: description,
		SourceLines: MustReadLines(filename),
		Stack:       stack,
	}
}
Example #26
0
// Serve a new connection.
func (c *conn) serve() {
	defer func() {
		err := recover()
		if err == nil {
			return
		}
		c.rwc.Close()

		var buf bytes.Buffer
		fmt.Fprintf(&buf, "icap: panic serving %v: %v\n", c.remoteAddr, err)
		buf.Write(debug.Stack())
		log.Print(buf.String())
	}()

	w, err := c.readRequest()
	if err != nil {
		log.Println("error while reading request:", err)
		c.rwc.Close()
		return
	}

	c.handler.ServeICAP(w, w.req)
	w.finishRequest()

	c.close()
}
Example #27
0
// ThresholdLogger returns a timing function which calls 'record' for each
// measured duration and, for measurements exceeding 'warnDuration', invokes
// 'printf' with the passed context and a detailed stack trace.
func ThresholdLogger(
	ctx context.Context,
	warnDuration time.Duration,
	printf func(context.Context, string, ...interface{}),
	record TimingFn,
) TimingFn {
	return func(heldFor time.Duration) {
		record(heldFor)
		if heldFor > warnDuration {
			// NB: this doesn't use `util/caller.Lookup` because that would result
			// in an import cycle.
			pc, _, _, ok := runtime.Caller(2)
			fun := "?"
			if ok {
				if f := runtime.FuncForPC(pc); f != nil {
					fun = f.Name()
				}
			}

			printf(
				ctx, "mutex held by %s for %s (>%s):\n%s",
				fun, heldFor, warnDuration, debug.Stack(),
			)
		}
	}
}
Example #28
0
// Catch panics, usually caused by remote disconnects.
func (c *MConnection) _recover() {
	if r := recover(); r != nil {
		stack := debug.Stack()
		err := StackError{r, stack}
		c.stopForError(err)
	}
}
Example #29
0
func (p *packet) recoverDecodeError() {
	if p.recoverPanics {
		if r := recover(); r != nil {
			p.addFinalDecodeError(fmt.Errorf("%v", r), debug.Stack())
		}
	}
}
Example #30
0
// Stick it as a deferred statement in gouroutines to prevent the program from crashing.
func Recover(daemonName string) {
	if e := recover(); e != nil {
		stack := string(debug.Stack())
		errorString := fmt.Sprintf("[%s] %s\n%s", daemonName, e, stack)
		alert.Alert(errorString)
	}
}