github.com/insionng/yougam@v0.0.0-20170714101924-2bc18d833463/libraries/pingcap/tidb/store/tikv/oracle/oracles/pd.go (about)

     1  // Copyright 2016 PingCAP, Inc.
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //     http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // See the License for the specific language governing permissions and
    12  // limitations under the License.
    13  
    14  package oracles
    15  
    16  import (
    17  	"time"
    18  
    19  	"github.com/insionng/yougam/libraries/juju/errors"
    20  	"github.com/insionng/yougam/libraries/ngaut/log"
    21  	"github.com/insionng/yougam/libraries/pingcap/pd/pd-client"
    22  	"github.com/insionng/yougam/libraries/pingcap/tidb/store/tikv/oracle"
    23  )
    24  
    25  var _ oracle.Oracle = &pdOracle{}
    26  
    27  const slowDist = 30 * time.Millisecond
    28  
    29  // pdOracle is an Oracle that uses a placement driver client as source.
    30  type pdOracle struct {
    31  	c pd.Client
    32  }
    33  
    34  // NewPdOracle create an Oracle that uses a pd client source.
    35  // Refer https://yougam/libraries/pingcap/pd/blob/master/pd-client/client.go for more details.
    36  func NewPdOracle(pdClient pd.Client) oracle.Oracle {
    37  	return &pdOracle{
    38  		c: pdClient,
    39  	}
    40  }
    41  
    42  // IsExpired returns whether lockTs+TTL is expired, both are ms.
    43  func (t *pdOracle) IsExpired(lockTs, TTL uint64) (bool, error) {
    44  	physical, _, err := t.c.GetTS()
    45  	if err != nil {
    46  		return false, errors.Trace(err)
    47  	}
    48  	return uint64(physical) >= (lockTs>>epochShiftBits)+TTL, nil
    49  }
    50  
    51  // GetTimestamp gets a new increasing time.
    52  func (t *pdOracle) GetTimestamp() (uint64, error) {
    53  	now := time.Now()
    54  	physical, logical, err := t.c.GetTS()
    55  	if err != nil {
    56  		return 0, errors.Trace(err)
    57  	}
    58  	dist := time.Since(now)
    59  	if dist > slowDist {
    60  		log.Warnf("get timestamp too slow: %s", dist)
    61  	}
    62  	return uint64((physical << epochShiftBits) + logical), nil
    63  }