util

package
v0.0.0-...-3b800f5 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Feb 9, 2018 License: Apache-2.0 Imports: 37 Imported by: 0

Documentation

Index

Constants

View Source
const (
	// Pending job is wait to running
	Pending = JobState(0)
	// Running job is running
	Running = JobState(1)
	// Cancelling job is cancelling
	Cancelling = JobState(2)
	// Cancelled job is cancelled
	Cancelled = JobState(3)
	// Finished job is complete
	Finished = JobState(4)
	// Failed job is failed when execute
	Failed = JobState(5)
)
View Source
const MaxInt = int(MaxUint >> 1)
View Source
const MaxUint = ^uint(0)

https://stackoverflow.com/questions/6878590/the-maximum-value-for-an-int-type-in-go

View Source
const MinInt = -MaxInt - 1
View Source
const MinUint = 0

Variables

View Source
var (
	// ErrDisposed is returned when an operation is performed on a disposed
	// queue.
	ErrDisposed = errors.New(`queue: disposed`)

	// ErrTimeout is returned when an applicable queue operation times out.
	ErrTimeout = errors.New(`queue: poll timed out`)

	// ErrEmptyQueue is returned when an non-applicable queue operation was called
	// due to the queue's empty item state
	ErrEmptyQueue = errors.New(`queue: empty queue`)
)
View Source
var (
	// ErrJobCancelled error job cancelled
	ErrJobCancelled = errors.New("Job cancelled")
)

Functions

func BytesToUint64

func BytesToUint64(b []byte) (uint64, error)

BytesToUint64 bytes -> uint64

func DefaultTimeoutWheel

func DefaultTimeoutWheel() *goetty.TimeoutWheel

DefaultTimeoutWheel returns default timeout wheel

func DiskStats

func DiskStats(path string) (*disk.UsageStat, error)

DiskStats returns the disk usage stats

func ExecuteInParallel

func ExecuteInParallel(q *Queue, fn func(interface{}))

ExecuteInParallel will (in parallel) call the provided function with each item in the queue until the queue is exhausted. When the queue is exhausted execution is complete and all goroutines will be killed. This means that the queue will be disposed so cannot be used again.

func FileMarshal

func FileMarshal(fp string, v interface{}) (err error)

FileMarshal marshals the given object to file.

func FileMmap

func FileMmap(f *os.File) (data []byte, err error)

FileMmap mmaps the given file. https://medium.com/@arpith/adventures-with-mmap-463b33405223

func FileMunmap

func FileMunmap(data []byte) (err error)

FileMunmap unmaps the given file.

func FileUnmarshal

func FileUnmarshal(fp string, v interface{}) (err error)

FileUnmarshal unmarshals the given file to object.

func Float32ToSortableUint64

func Float32ToSortableUint64(valS string) (val uint64, err error)

Float32ToSortableUint64 converts a float32 string to sortable uint64.

Refers to: github.com/apache/lucene-solr/lucene/core/src/java/org/apache/lucene/util/NumericUtils.java,

public static int floatToSortableInt(float value);
public static long doubleToSortableLong(double value);

https://en.wikipedia.org/wiki/Single-precision_floating-point_format https://en.wikipedia.org/wiki/Double-precision_floating-point_format

func Float64ToSortableUint64

func Float64ToSortableUint64(valS string) (val uint64, err error)

Float64ToSortableUint64 converts a float64 string to sortable uint64.

func FormatFloat64ToBytes

func FormatFloat64ToBytes(v float64) []byte

FormatFloat64ToBytes float64 -> string

func FormatInt64ToBytes

func FormatInt64ToBytes(v int64) []byte

FormatInt64ToBytes int64 -> string

func GZIP

func GZIP(path string) error

GZIP compress a path to a gzip file

func GetIntValue

func GetIntValue(value, defaultValue int) int

GetIntValue get int value if value if 0 reutrn default value

func GetStringValue

func GetStringValue(value, defaultValue string) string

GetStringValue get string value if value if "" reutrn default value

func GetUint64Value

func GetUint64Value(value, defaultValue uint64) uint64

GetUint64Value get uint64 value if value if 0 reutrn default value

func InitMetric

func InitMetric(runner *Runner, cfg *MetricCfg)

InitMetric init the metric

func MustMarshal

func MustMarshal(target Marashal) []byte

MustMarshal if marsh failed, will panic

func MustMarshalTo

func MustMarshalTo(target Marashal, data []byte) int

MustMarshalTo if marsh failed, will panic

func MustUnmarshal

func MustUnmarshal(target Unmarshal, data []byte)

MustUnmarshal if unmarshal failed, will panic

func NoConvert

func NoConvert(key []byte, do func([]byte) metapb.Cell) metapb.Cell

NoConvert no converter

func ParseUrls

func ParseUrls(s string) ([]url.URL, error)

ParseUrls parse a string into multiple urls.

func ReplaceFpExt

func ReplaceFpExt(fp string, newExt string) string

func SliceToString

func SliceToString(b []byte) (s string)

SliceToString slice to string with out data copy

func StrFloat64

func StrFloat64(v []byte) (float64, error)

StrFloat64 str -> float64

func StrInt64

func StrInt64(v []byte) (int64, error)

StrInt64 str -> int64

func StringToSlice

func StringToSlice(s string) (b []byte)

StringToSlice string to slice with out data copy

func Uint64Convert

func Uint64Convert(key []byte, do func([]byte) metapb.Cell) metapb.Cell

Uint64Convert returns the hash crc64 result value, must use `ReleaseConvertBytes` to release

func Uint64ToBytes

func Uint64ToBytes(v uint64) []byte

Uint64ToBytes uint64 -> bytes

func UnGZIP

func UnGZIP(file string, dest string) error

UnGZIP ungip file

Types

type CellItem

type CellItem struct {
	// contains filtered or unexported fields
}

CellItem is the cell btree item

func (*CellItem) Contains

func (r *CellItem) Contains(key []byte) bool

Contains returns the item contains the key

func (*CellItem) Less

func (r *CellItem) Less(other btree.Item) bool

Less returns true if the cell start key is greater than the other. So we will sort the cell with start key reversely.

type CellTree

type CellTree struct {
	sync.RWMutex
	// contains filtered or unexported fields
}

CellTree is the btree for cell

func NewCellTree

func NewCellTree() *CellTree

NewCellTree returns a default cell btree

func (*CellTree) Ascend

func (t *CellTree) Ascend(fn func(cell *metapb.Cell) bool)

Ascend asc iterator the tree until fn returns false

func (*CellTree) AscendRange

func (t *CellTree) AscendRange(start, end []byte, fn func(cell *metapb.Cell) bool)

AscendRange asc iterator the tree in the range [start, end) until fn returns false

func (*CellTree) NextCell

func (t *CellTree) NextCell(start []byte) *metapb.Cell

NextCell return the next bigger key range cell

func (*CellTree) Remove

func (t *CellTree) Remove(cell metapb.Cell) bool

Remove removes a cell if the cell is in the tree. It will do nothing if it cannot find the cell or the found cell is not the same with the cell.

func (*CellTree) Search

func (t *CellTree) Search(key []byte) metapb.Cell

Search returns a cell that contains the key.

func (*CellTree) Update

func (t *CellTree) Update(cell metapb.Cell)

Update updates the tree with the cell. It finds and deletes all the overlapped cells first, and then insert the cell.

type Item

type Item interface {
	// Compare returns a int that can be used to determine
	// ordering in the priority queue.  Assuming the queue
	// is in ascending order, this should return > logic.
	// Return 1 to indicate this object is greater than the
	// the other logic, 0 to indicate equality, and -1 to indicate
	// less than other.
	Compare(other Item) int
}

Item is an item that can be added to the priority queue.

type Job

type Job struct {
	sync.RWMutex
	// contains filtered or unexported fields
}

Job is do for something with state

func (*Job) Cancel

func (job *Job) Cancel()

Cancel cancel the job

func (*Job) GetResult

func (job *Job) GetResult() interface{}

GetResult returns job result

func (*Job) IsCancelled

func (job *Job) IsCancelled() bool

IsCancelled returns true if job state is Cancelled

func (*Job) IsCancelling

func (job *Job) IsCancelling() bool

IsCancelling returns true if job state is Cancelling

func (*Job) IsComplete

func (job *Job) IsComplete() bool

IsComplete return true means the job is complete.

func (*Job) IsFailed

func (job *Job) IsFailed() bool

IsFailed returns true if job state is Failed

func (*Job) IsFinished

func (job *Job) IsFinished() bool

IsFinished returns true if job state is Finished

func (*Job) IsNotComplete

func (job *Job) IsNotComplete() bool

IsNotComplete return true means the job is not complete.

func (*Job) IsPending

func (job *Job) IsPending() bool

IsPending returns true if job state is Pending

func (*Job) IsRunning

func (job *Job) IsRunning() bool

IsRunning returns true if job state is Running

func (*Job) SetResult

func (job *Job) SetResult(result interface{})

SetResult set result

type JobState

type JobState int

JobState is the job state

type KVTree

type KVTree struct {
	sync.RWMutex
	// contains filtered or unexported fields
}

KVTree kv btree

func NewKVTree

func NewKVTree() *KVTree

NewKVTree return a kv btree

func (*KVTree) Delete

func (kv *KVTree) Delete(key []byte) bool

Delete deletes a key, return false if not the key is not exists

func (*KVTree) Get

func (kv *KVTree) Get(key []byte) []byte

Get get value, return nil if not the key is not exists

func (*KVTree) Put

func (kv *KVTree) Put(key, value []byte)

Put puts a key, value to the tree

func (*KVTree) RangeDelete

func (kv *KVTree) RangeDelete(start, end []byte)

RangeDelete deletes key in [start, end)

func (*KVTree) Scan

func (kv *KVTree) Scan(start, end []byte, handler func(key, value []byte) (bool, error)) error

Scan scans in [start, end]

func (*KVTree) Seek

func (kv *KVTree) Seek(key []byte) ([]byte, []byte)

Seek returns the next key and value which key >= spec key

type Limiter

type Limiter struct {
	// contains filtered or unexported fields
}

Limiter limiter implemention by token

func NewLimiter

func NewLimiter(max uint64) *Limiter

NewLimiter return a limiter with max

func (*Limiter) Release

func (l *Limiter) Release()

Release release token

func (*Limiter) Wait

func (l *Limiter) Wait(ctx context.Context) error

Wait wait until get the token

type Marashal

type Marashal interface {
	Size() int
	Marshal() ([]byte, error)
	MarshalTo(data []byte) (int, error)
}

Marashal marashal interface

type MetricCfg

type MetricCfg struct {
	Job          string
	Instance     string
	Address      string
	DurationSync time.Duration
}

MetricCfg is the metric configuration.

func NewMetricCfg

func NewMetricCfg(job, instance, address string, durationSync time.Duration) *MetricCfg

NewMetricCfg returns metric cfg

type OffsetQueue

type OffsetQueue struct {
	sync.Mutex
	// contains filtered or unexported fields
}

OffsetQueue is a queue for sync.

func NewOffsetQueue

func NewOffsetQueue() *OffsetQueue

NewOffsetQueue returns a offset queue

func (*OffsetQueue) Add

func (q *OffsetQueue) Add(item interface{}) uint64

Add add a item to the queue

func (*OffsetQueue) Get

func (q *OffsetQueue) Get(offset uint64) ([]interface{}, uint64)

Get returns all the items after the offset, and remove all items before this offset

func (*OffsetQueue) GetMaxOffset

func (q *OffsetQueue) GetMaxOffset() uint64

GetMaxOffset returns the max offset in the queue

type OrderedArray

type OrderedArray struct {
	// contains filtered or unexported fields
}

OrderedArray is similar to size limited array except that it's to solve "get M smallest ones among N(N>M) items".

func NewOrderedArray

func NewOrderedArray(capacity int) (oa *OrderedArray, err error)

NewOrderedArray is the constructor for an ordered array. capacity is size limit of queue. capacity shall > 0.

func (*OrderedArray) Finalize

func (oa *OrderedArray) Finalize() (items []Item)

Finalize retrieves all items from and clear the array. items is sorted in ascending order.

func (*OrderedArray) Len

func (oa *OrderedArray) Len() int

Len returns a number indicating how many items are in the array.

func (*OrderedArray) Put

func (oa *OrderedArray) Put(items ...Item)

Put adds items to the queue.

type PriorityQueue

type PriorityQueue struct {
	// contains filtered or unexported fields
}

PriorityQueue is similar to queue except that it takes items that implement the Item interface and adds them to the queue in priority order.

func NewPriorityQueue

func NewPriorityQueue(capHint int) *PriorityQueue

NewPriorityQueue is the constructor for a priority queue.

func (*PriorityQueue) BulkGet

func (pq *PriorityQueue) BulkGet(number int) (items []Item)

BulkGet retrieves items from the queue. len(items) will be max(0, min(number, len(pq.items))) items is sorted in ascending order.

func (*PriorityQueue) Empty

func (pq *PriorityQueue) Empty() bool

Empty returns a bool indicating if there are any items left in the queue.

func (*PriorityQueue) Get

func (pq *PriorityQueue) Get() (item Item)

Get retrieves an item from the queue if non-empty, othewise returns nil

func (*PriorityQueue) Len

func (pq *PriorityQueue) Len() int

Len returns a number indicating how many items are in the queue.

func (*PriorityQueue) Peek

func (pq *PriorityQueue) Peek() Item

Peek will look at the next item without removing it from the queue.

func (*PriorityQueue) Put

func (pq *PriorityQueue) Put(items ...Item)

Put adds items to the queue.

type Queue

type Queue struct {
	// contains filtered or unexported fields
}

Queue is the struct responsible for tracking the state of the queue.

func New

func New(hint int64) *Queue

New is a constructor for a new threadsafe queue.

func (*Queue) Dispose

func (q *Queue) Dispose() []interface{}

Dispose will dispose of this queue and returns the items disposed. Any subsequent calls to Get or Put will return an error.

func (*Queue) Disposed

func (q *Queue) Disposed() bool

Disposed returns a bool indicating if this queue has had disposed called on it.

func (*Queue) Empty

func (q *Queue) Empty() bool

Empty returns a bool indicating if this bool is empty.

func (*Queue) Get

func (q *Queue) Get(number int64, items []interface{}) (int64, error)

Get retrieves items from the queue. If there are some items in the queue, get will return a number UP TO the number passed in as a parameter. If no items are in the queue, this method will pause until items are added to the queue.

func (*Queue) Len

func (q *Queue) Len() int64

Len returns the number of items in this queue.

func (*Queue) Peek

func (q *Queue) Peek() (interface{}, error)

Peek returns a the first item in the queue by value without modifying the queue.

func (*Queue) Poll

func (q *Queue) Poll(number int64, items []interface{}, timeout time.Duration) (int64, error)

Poll retrieves items from the queue. If there are some items in the queue, Poll will return a number UP TO the number passed in as a parameter. If no items are in the queue, this method will pause until items are added to the queue or the provided timeout is reached. A non-positive timeout will block until items are added. If a timeout occurs, ErrTimeout is returned.

func (*Queue) Put

func (q *Queue) Put(items ...interface{}) error

Put will add the specified items to the queue.

func (*Queue) PutOrUpdate

func (q *Queue) PutOrUpdate(cmp func(interface{}, interface{}) bool, item interface{}) error

PutOrUpdate will add the specified item to the queue, update it if exists

type Runner

type Runner struct {
	sync.RWMutex
	// contains filtered or unexported fields
}

Runner TODO

func NewRunner

func NewRunner() *Runner

NewRunner returns a task runner

func (*Runner) AddNamedWorker

func (s *Runner) AddNamedWorker(name string) (uint64, error)

AddNamedWorker add a named worker, the named worker has uniq queue, so jobs are linear execution

func (*Runner) IsNamedWorkerBusy

func (s *Runner) IsNamedWorkerBusy(worker string) bool

IsNamedWorkerBusy returns true if named queue is not empty

func (*Runner) RunCancelableTask

func (s *Runner) RunCancelableTask(task func(context.Context)) (uint64, error)

RunCancelableTask run a task that can be cancelled Example:

err := s.RunCancelableTask(func(ctx context.Context) {
	select {
	case <-ctx.Done():
	// cancelled
	case <-time.After(time.Second):
		// do something
	}
})
if err != nil {
	// hanle error
	return
}

func (*Runner) RunJob

func (s *Runner) RunJob(desc string, task func() error) error

RunJob run a job

func (*Runner) RunJobWithNamedWorker

func (s *Runner) RunJobWithNamedWorker(desc, worker string, task func() error) error

RunJobWithNamedWorker run a job in a named worker

func (*Runner) RunJobWithNamedWorkerWithCB

func (s *Runner) RunJobWithNamedWorkerWithCB(desc, worker string, task func() error, cb func(*Job)) error

RunJobWithNamedWorkerWithCB run a job in a named worker

func (*Runner) RunTask

func (s *Runner) RunTask(task func()) error

RunTask runs a task in new goroutine

func (*Runner) Stop

func (s *Runner) Stop() error

Stop stop all task RunTask will failure with an error Wait complete for the tasks that already in execute Cancel the tasks that is not start

func (*Runner) StopCancelableTask

func (s *Runner) StopCancelableTask(id uint64) error

StopCancelableTask stop cancelable spec task

type Unmarshal

type Unmarshal interface {
	Unmarshal([]byte) error
}

Unmarshal unmarashal interface

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL