github.com/brownsys/tracing-framework-go@v0.0.0-20161210174012-0542a62412fe/xtrace/client/local.go (about)

     1  package client
     2  
     3  import (
     4  	"crypto/rand"
     5  	"encoding/binary"
     6  	"fmt"
     7  
     8  	"github.com/brownsys/tracing-framework-go/local"
     9  )
    10  
    11  var token local.Token
    12  
    13  type localStorage struct {
    14  	taskID  int64
    15  	eventID int64
    16  }
    17  
    18  func init() {
    19  	token = local.Register(&localStorage{
    20  		taskID:  randInt64(),
    21  		eventID: randInt64(),
    22  	}, local.Callbacks{
    23  		func(l interface{}) interface{} {
    24  			// deep copy l
    25  			n := *(l.(*localStorage))
    26  			return &n
    27  		},
    28  	})
    29  }
    30  
    31  func getLocal() *localStorage {
    32  	return local.GetLocal(token).(*localStorage)
    33  }
    34  
    35  // SetEventID sets the current goroutine's X-Trace Event ID.
    36  // This should be used when propagating Event IDs over RPC
    37  // calls or other channels.
    38  //
    39  // WARNING: This will overwrite any previous Event ID,
    40  // so call with caution.
    41  func SetEventID(eventID int64) {
    42  	getLocal().eventID = eventID
    43  }
    44  
    45  // SetTaskID sets the current goroutine's X-Trace Task ID.
    46  // This should be used when propagating Task IDs over RPC
    47  // calls or other channels.
    48  //
    49  // WARNING: This will overwrite any previous Task ID,
    50  // so call with caution.
    51  func SetTaskID(taskID int64) {
    52  	getLocal().taskID = taskID
    53  }
    54  
    55  // GetEventID gets the current goroutine's X-Trace Event ID.
    56  // Note that if one has not been set yet, GetEventID will
    57  // return 0. This should be used when propagating Event IDs
    58  // over RPC calls or other channels.
    59  func GetEventID() (eventID int64) {
    60  	return getLocal().eventID
    61  }
    62  
    63  // GetTaskID gets the current goroutine's X-Trace Task ID.
    64  // Note that if one has not been set yet, GetTaskID will
    65  // return 0. This should be used when propagating Task IDs
    66  // over RPC calls or other channels.
    67  func GetTaskID() (taskID int64) {
    68  	return getLocal().taskID
    69  }
    70  
    71  func newEvent() (parent, event int64) {
    72  	parent = GetEventID()
    73  	event = randInt64()
    74  	SetEventID(event)
    75  	return parent, event
    76  }
    77  
    78  func randInt64() int64 {
    79  	var b [8]byte
    80  	_, err := rand.Read(b[:])
    81  	if err != nil {
    82  		panic(fmt.Errorf("could not read random bytes: %v", err))
    83  	}
    84  	// shift to guarantee high bit is 0 and thus
    85  	// int64 version is non-negative
    86  	return int64(binary.BigEndian.Uint64(b[:]) >> 1)
    87  }