本文整理汇总了Python中pyndn.util.common.Common.getNowMilliseconds方法的典型用法代码示例。如果您正苦于以下问题:Python Common.getNowMilliseconds方法的具体用法?Python Common.getNowMilliseconds怎么用?Python Common.getNowMilliseconds使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类pyndn.util.common.Common
的用法示例。
在下文中一共展示了Common.getNowMilliseconds方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: processEvents
# 需要导入模块: from pyndn.util.common import Common [as 别名]
# 或者: from pyndn.util.common.Common import getNowMilliseconds [as 别名]
def processEvents(self):
"""
Process any packets to receive and call callbacks such as onData,
onInterest or onTimeout. This returns immediately if there is no data to
receive. This blocks while calling the callbacks. You should repeatedly
call this from an event loop, with calls to sleep as needed so that the
loop doesn't use 100% of the CPU. Since processEvents modifies the pending
interest table, your application should make sure that it calls
processEvents in the same thread as expressInterest (which also modifies
the pending interest table).
:raises: This may raise an exception for reading data or in the callback
for processing the data. If you call this from an main event loop,
you may want to catch and log/disregard all exceptions.
"""
self._transport.processEvents()
# Check for PIT entry timeouts. Go backwards through the list so we can
# erase entries.
nowMilliseconds = Common.getNowMilliseconds()
i = len(self._pendingInterestTable) - 1
while i >= 0:
if self._pendingInterestTable[i].isTimedOut(nowMilliseconds):
# Save the PendingInterest and remove it from the PIT. Then
# call the callback.
pendingInterest = self._pendingInterestTable[i]
self._pendingInterestTable.pop(i)
pendingInterest.callTimeout()
# Refresh now since the timeout callback might have delayed.
nowMilliseconds = Common.getNowMilliseconds()
i -= 1
示例2: test_self_signed_cert_validity
# 需要导入模块: from pyndn.util.common import Common [as 别名]
# 或者: from pyndn.util.common.Common import getNowMilliseconds [as 别名]
def test_self_signed_cert_validity(self):
certificate = (self._fixture.addIdentity
(Name("/Security/V2/TestKeyChain/SelfSignedCertValidity"))
.getDefaultKey().getDefaultCertificate())
self.assertTrue(certificate.isValid())
# Check 10 years from now.
self.assertTrue(certificate.isValid
(Common.getNowMilliseconds() + 10 * 365 * 24 * 3600 * 1000.0))
# Check that notAfter is later than 10 years from now.
self.assertTrue(certificate.getValidityPeriod().getNotAfter() >
Common.getNowMilliseconds() + 10 * 365 * 24 * 3600 * 1000.0)
示例3: addSubCertificate
# 需要导入模块: from pyndn.util.common import Common [as 别名]
# 或者: from pyndn.util.common.Common import getNowMilliseconds [as 别名]
def addSubCertificate(self, subIdentityName, issuer, params = None):
"""
Issue a certificate for subIdentityName signed by issuer. If the
identity does not exist, it is created. A new key is generated as the
default key for the identity. A default certificate for the key is
signed by the issuer using its default certificate.
"""
if params == None:
params = KeyChain.getDefaultKeyParams()
subIdentity = self.addIdentity(subIdentityName, params)
request = subIdentity.getDefaultKey().getDefaultCertificate()
request.setName(request.getKeyName().append("parent").appendVersion(1))
certificateParams = SigningInfo(issuer)
# Validity period of 20 years.
now = Common.getNowMilliseconds()
certificateParams.setValidityPeriod(
ValidityPeriod(now, now + 20 * 365 * 24 * 3600 * 1000.0))
# Skip the AdditionalDescription.
self._keyChain.sign(request, certificateParams)
self._keyChain.setDefaultCertificate(subIdentity.getDefaultKey(), request)
return subIdentity
示例4: addCertificate
# 需要导入模块: from pyndn.util.common import Common [as 别名]
# 或者: from pyndn.util.common.Common import getNowMilliseconds [as 别名]
def addCertificate(self, key, issuerId):
"""
Add a self-signed certificate made from the key and issuer ID.
:param PibKey key: The key for the certificate.
:param str issuerId: The issuer ID name component for the certificate
name.
:return: The new certificate.
:rtype: CertificateV2
"""
certificateName = Name(key.getName())
certificateName.append(issuerId).appendVersion(3)
certificate = CertificateV2()
certificate.setName(certificateName)
# Set the MetaInfo.
certificate.getMetaInfo().setType(ContentType.KEY)
# One hour.
certificate.getMetaInfo().setFreshnessPeriod(3600 * 1000.0)
# Set the content.
certificate.setContent(key.getPublicKey())
params = SigningInfo(key)
# Validity period of 10 days.
now = Common.getNowMilliseconds()
params.setValidityPeriod(
ValidityPeriod(now, now + 10 * 24 * 3600 * 1000.0))
self._keyChain.sign(certificate, params)
return certificate
示例5: processEvents
# 需要导入模块: from pyndn.util.common import Common [as 别名]
# 或者: from pyndn.util.common.Common import getNowMilliseconds [as 别名]
def processEvents(self):
"""
Process any packets to receive and call callbacks such as onData,
onInterest or onTimeout. This returns immediately if there is no data to
receive. This blocks while calling the callbacks. You should repeatedly
call this from an event loop, with calls to sleep as needed so that the
loop doesn't use 100% of the CPU. Since processEvents modifies the pending
interest table, your application should make sure that it calls
processEvents in the same thread as expressInterest (which also modifies
the pending interest table).
:raises: This may raise an exception for reading data or in the callback
for processing the data. If you call this from an main event loop,
you may want to catch and log/disregard all exceptions.
"""
self._transport.processEvents()
# Check for delayed calls. Since callLater does a sorted insert into
# _delayedCallTable, the check for timeouts is quick and does not
# require searching the entire table. If callLater is overridden to use
# a different mechanism, then processEvents is not needed to check for
# delayed calls.
now = Common.getNowMilliseconds()
# _delayedCallTable is sorted on _callTime, so we only need to process
# the timed-out entries at the front, then quit.
while (len(self._delayedCallTable) > 0 and
self._delayedCallTable[0].getCallTime() <= now):
delayedCall = self._delayedCallTable[0]
del self._delayedCallTable[0]
delayedCall.callCallback()
示例6: _updateTimestampForKey
# 需要导入模块: from pyndn.util.common import Common [as 别名]
# 或者: from pyndn.util.common.Common import getNowMilliseconds [as 别名]
def _updateTimestampForKey(self, keyName, timestamp):
"""
Trim the table size down if necessary, and insert/update the latest
interest signing timestamp for the key.
Any key which has not been used within the TTL period is purged. If the
table is still too large, the oldest key is purged.
:param Name keyName: The name of the public key used to sign the interest.
:paramt int timestamp: The timestamp extracted from the interest name.
"""
self._keyTimestamps[keyName.toUri()] = timestamp
if len(self._keyTimestamps) >= self._maxTrackedKeys:
now = Common.getNowMilliseconds()
oldestTimestamp = now
oldestKey = None
trackedKeys = self._keyTimestamps.keys()
for keyUri in trackedKeys:
ts = self._keyTimestamps[keyUri]
if now - ts > self._keyTimestampTtl:
del self._keyTimestamps[keyUri]
elif ts < oldestTimestamp:
oldestTimestamp = ts
oldestKey = keyUri
if len(self._keyTimestamps) > self._maxTrackedKeys:
# have not removed enough
del self._keyTimestamps[oldestKey]
示例7: _refresh
# 需要导入模块: from pyndn.util.common import Common [as 别名]
# 或者: from pyndn.util.common.Common import getNowMilliseconds [as 别名]
def _refresh(self):
"""
Remove all outdated certificate entries.
"""
# _nowOffsetMilliseconds is only used for testing.
now = Common.getNowMilliseconds() + self._nowOffsetMilliseconds
if now < self._nextRefreshTime:
return
# We recompute _nextRefreshTime.
nextRefreshTime = sys.float_info.max
# Go backwards through the list so we can erase entries.
i = len(self._certificatesByNameKeys) - 1
while i >= 0:
entry = self._certificatesByName[self._certificatesByNameKeys[i]]
if entry._removalTime <= now:
del self._certificatesByName[self._certificatesByNameKeys[i]]
self._certificatesByNameKeys.pop(i)
else:
nextRefreshTime = min(nextRefreshTime, entry._removalTime)
i -= 1
self._nextRefreshTime = nextRefreshTime
示例8: getNewKeyName
# 需要导入模块: from pyndn.util.common import Common [as 别名]
# 或者: from pyndn.util.common.Common import getNowMilliseconds [as 别名]
def getNewKeyName(self, identityName, useKsk):
"""
Generate a name for a new key belonging to the identity.
:param Name identityName: The identity name.
:param bool useKsk: If True, generate a KSK name, otherwise a DSK name.
:return: The generated key name.
:rtype: Name
"""
timestamp = math.floor(Common.getNowMilliseconds() / 1000.0)
while timestamp <= self._lastTimestamp:
# Make the timestamp unique.
timestamp += 1
self._lastTimestamp = timestamp
nowString = repr(timestamp).replace(".0", "")
if useKsk:
keyIdStr = "ksk-" + nowString
else:
keyIdStr = "dsk-" + nowString
keyName = Name(identityName).append(keyIdStr)
if self.doesKeyExist(keyName):
raise SecurityException("Key name already exists")
return keyName
示例9: __init__
# 需要导入模块: from pyndn.util.common import Common [as 别名]
# 或者: from pyndn.util.common.Common import getNowMilliseconds [as 别名]
def __init__(self, data):
super(MemoryContentCache._StaleTimeContent, self).__init__(data)
# Set up staleTimeMilliseconds which is The time when the content
# becomse stale in milliseconds according to
# Common.getNowMilliseconds().
self._staleTimeMilliseconds = (Common.getNowMilliseconds() +
data.getMetaInfo().getFreshnessPeriod())
示例10: _contentCacheAdd
# 需要导入模块: from pyndn.util.common import Common [as 别名]
# 或者: from pyndn.util.common.Common import getNowMilliseconds [as 别名]
def _contentCacheAdd(self, data):
"""
Add the data packet to the _contentCache. Remove timed-out entries
from _pendingInterestTable. If the data packet satisfies any pending
interest, then send the data packet to the pending interest's transport
and remove from the _pendingInterestTable.
:param Data data: The data packet to add.
"""
self._contentCache.add(data)
# Remove timed-out interests and check if the data packet matches any
# pending interest.
# Go backwards through the list so we can erase entries.
nowMilliseconds = Common.getNowMilliseconds()
for i in range(len(self._pendingInterestTable) - 1, -1, -1):
pendingInterest = self._pendingInterestTable[i]
if pendingInterest.isTimedOut(nowMilliseconds):
self._pendingInterestTable.pop(i)
continue
if pendingInterest.getInterest().matchesName(data.getName()):
try:
# Send to the same transport from the original call to onInterest.
# wireEncode returns the cached encoding if available.
pendingInterest.getTransport().send(data.wireEncode().toBuffer())
except Exception as ex:
logging.getLogger(__name__).error(
"Error in transport.send: %s", str(ex))
return
# The pending interest is satisfied, so remove it.
self._pendingInterestTable.pop(i)
示例11: _interestTimestampIsFresh
# 需要导入模块: from pyndn.util.common import Common [as 别名]
# 或者: from pyndn.util.common.Common import getNowMilliseconds [as 别名]
def _interestTimestampIsFresh(self, keyName, timestamp, failureReason):
"""
Determine whether the timestamp from the interest is newer than the last use
of this key, or within the grace interval on first use.
:param Name keyName: The name of the public key used to sign the interest.
:paramt int timestamp: The timestamp extracted from the interest name.
:param Array<str> failureReason: If verification fails, set
failureReason[0] to the failure reason string.
"""
try:
lastTimestamp = self._keyTimestamps[keyName.toUri()]
except KeyError:
now = Common.getNowMilliseconds()
notBefore = now - self._keyGraceInterval
notAfter = now + self._keyGraceInterval
if not (timestamp > notBefore and timestamp < notAfter):
return False
failureReason[0] = (
"The command interest timestamp is not within the first use grace period of " +
str(self._keyGraceInterval) + " milliseconds.")
else:
return True
else:
if timestamp <= lastTimestamp:
failureReason[0] = (
"The command interest timestamp is not newer than the previous timestamp")
return False
else:
return True
示例12: _generateCertificateForKey
# 需要导入模块: from pyndn.util.common import Common [as 别名]
# 或者: from pyndn.util.common.Common import getNowMilliseconds [as 别名]
def _generateCertificateForKey(self, keyName):
# Let any raised SecurityExceptions bubble up.
publicKeyBits = self._identityStorage.getKey(keyName)
publicKey = PublicKey(publicKeyBits)
timestamp = Common.getNowMilliseconds()
# TODO: Specify where the 'KEY' component is inserted
# to delegate responsibility for cert delivery.
# cf: http://redmine.named-data.net/issues/1659
certificateName = keyName.getPrefix(-1).append('KEY').append(keyName.get(-1))
certificateName.append("ID-CERT").appendVersion(int(timestamp))
certificate = IdentityCertificate()
certificate.setName(certificateName)
certificate.setNotBefore(timestamp)
certificate.setNotAfter((timestamp + 2*365*24*3600*1000)) # about 2 years.
certificate.setPublicKeyInfo(publicKey)
# ndnsec likes to put the key name in a subject description.
sd = CertificateSubjectDescription("2.5.4.41", keyName.toUri())
certificate.addSubjectDescription(sd)
certificate.encode()
return certificate
示例13: addDirectory
# 需要导入模块: from pyndn.util.common import Common [as 别名]
# 或者: from pyndn.util.common.Common import getNowMilliseconds [as 别名]
def addDirectory(self, directoryName, refreshPeriod):
allFiles = [f for f in os.listdir(directoryName)
if os.path.isfile(os.path.join(directoryName, f))]
certificateNames = []
for f in allFiles:
if self._isSecurityV1:
try:
fullPath = os.path.join(directoryName, f)
cert = self.loadIdentityCertificateFromFile(fullPath)
except Exception:
pass # allow files that are not certificates
else:
# Cut off the timestamp so it matches KeyLocator Name format.
certUri = cert.getName()[:-1].toUri()
self._certificateCache.insertCertificate(cert)
certificateNames.append(certUri)
else:
try:
fullPath = os.path.join(directoryName, f)
cert = self.loadCertificateV2FromFile(fullPath)
except Exception:
pass # allow files that are not certificates
else:
# Get the key name since this is in the KeyLocator.
certUri = CertificateV2.extractKeyNameFromCertName(
cert.getName()).toUri()
self._certificateCacheV2.insert(cert)
certificateNames.append(certUri)
self._refreshDirectories[directoryName] = {
'certificates': certificateNames,
'nextRefresh': Common.getNowMilliseconds() + refreshPeriod,
'refreshPeriod':refreshPeriod }
示例14: refreshAnchors
# 需要导入模块: from pyndn.util.common import Common [as 别名]
# 或者: from pyndn.util.common.Common import getNowMilliseconds [as 别名]
def refreshAnchors(self):
refreshTime = Common.getNowMilliseconds()
for directory, info in self._refreshDirectories.items():
nextRefreshTime = info['nextRefresh']
if nextRefreshTime <= refreshTime:
certificateList = info['certificates'][:]
# delete the certificates associated with this directory if possible
# then re-import
# IdentityStorage subclasses may not support deletion
# should we be deleting
for c in certificateList:
try:
if self._isSecurityV1:
self._certificateCache.deleteCertificate(Name(c))
else:
# The name in the CertificateCacheV2 contains the
# but the name in the certificateList does not, so
# find the certificate based on the prefix first.
foundCertificate = self._certificateCacheV2.find(Name(c))
if foundCertificate != None:
self._certificateCacheV2.deleteCertificate(
foundCertificate.getName())
except KeyError:
# was already removed? not supported?
pass
self.addDirectory(directory, info['refreshPeriod'])
示例15: processInterest
# 需要导入模块: from pyndn.util.common import Common [as 别名]
# 或者: from pyndn.util.common.Common import getNowMilliseconds [as 别名]
def processInterest(interest, onData, onTimeout, onNetworkNack):
try:
# Create another key for the same identity and sign it properly.
parentKey = self._fixture._keyChain.createKey(
self._fixture._subIdentity)
requestedKey = self._fixture._subIdentity.getKey(interest.getName())
# Copy the Name.
certificateName = Name(requestedKey.getName())
certificateName.append("looper").appendVersion(1)
certificate = CertificateV2()
certificate.setName(certificateName)
# Set the MetaInfo.
certificate.getMetaInfo().setType(ContentType.KEY)
# Set the freshness period to one hour.
certificate.getMetaInfo().setFreshnessPeriod(3600 * 1000.0)
# Set the content.
certificate.setContent(requestedKey.getPublicKey())
# Set SigningInfo.
params = SigningInfo(parentKey)
# Validity period from 10 days before to 10 days after now.
now = Common.getNowMilliseconds()
params.setValidityPeriod(ValidityPeriod(
now - 10 * 24 * 3600 * 1000.0, now + 10 * 24 * 3600 * 1000.0))
self._fixture._keyChain.sign(certificate, params)
onData(interest, certificate)
except Exception as ex:
self.fail("Error in InfiniteCertificateChain: " + repr(ex))