Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

RUMM-1744 Copy Kronos code to SDK #701

Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 0 additions & 1 deletion Cartfile
Original file line number Diff line number Diff line change
@@ -1,2 +1 @@
github "lyft/Kronos" ~> 4.2
github "microsoft/plcrashreporter" ~> 1.10.1
1 change: 0 additions & 1 deletion Cartfile.resolved
Original file line number Diff line number Diff line change
@@ -1,2 +1 @@
github "lyft/Kronos" "4.2.1"
github "microsoft/plcrashreporter" "1.10.1"
86 changes: 76 additions & 10 deletions Datadog/Datadog.xcodeproj/project.pbxproj

Large diffs are not rendered by default.

1 change: 0 additions & 1 deletion DatadogSDK.podspec
Original file line number Diff line number Diff line change
Expand Up @@ -25,5 +25,4 @@ Pod::Spec.new do |s|
s.public_header_files = ["Datadog/TargetSupport/Datadog/Datadog.h",
"Sources/_Datadog_Private/include/*.h"]

s.dependency 'Kronos', '~> 4.2'
end
1 change: 0 additions & 1 deletion DatadogSDK.podspec.src
Original file line number Diff line number Diff line change
Expand Up @@ -25,5 +25,4 @@ Pod::Spec.new do |s|
s.public_header_files = ["Datadog/TargetSupport/Datadog/Datadog.h",
"Sources/_Datadog_Private/include/*.h"]

s.dependency 'Kronos', '~> 4.2'
end
2 changes: 1 addition & 1 deletion LICENSE-3rdparty.csv
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
Component,Origin,License,Copyright
import,io.opentracing,MIT,Copyright 2018 LightStep
import,com.Lyft.Kronos,Apache-2.0,Copyright (C) 2016 Lyft Inc.
import,com.Lyft.Kronos,Apache-2.0,Copyright (C) 2016 Lyft Inc. and MobileNativeFoundation
import,PLCrashReporter,MIT,Copyright Microsoft Corporation
import (tools),https://github.com/jpsim/SourceKitten,MIT,Copyright (c) 2014 JP Simard
import (tools),https://github.com/apple/swift-argument-parser,Apache-2.0,(c) 2020 Apple Inc. and the Swift project authors
Expand Down
2 changes: 0 additions & 2 deletions Package.swift
Original file line number Diff line number Diff line change
Expand Up @@ -35,15 +35,13 @@ let package = Package(
),
],
dependencies: [
.package(name: "Kronos", url: "https://github.com/lyft/Kronos.git", from: "4.2.1"),
.package(name: "PLCrashReporter", url: "https://github.com/microsoft/plcrashreporter.git", from: "1.10.0"),
],
targets: [
.target(
name: "Datadog",
dependencies: [
"_Datadog_Private",
.product(name: "Kronos", package: "Kronos"),
],
swiftSettings: [.define("SPM_BUILD")]
),
Expand Down
5 changes: 2 additions & 3 deletions Sources/Datadog/Core/System/Time/ServerDateProvider.swift
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@
*/

import Foundation
import Kronos

/// Abstract the monotonic clock synchronized with the server using NTP.
internal protocol ServerDateProvider {
Expand All @@ -28,7 +27,7 @@ internal class NTPServerDateProvider: ServerDateProvider {
}

func synchronize(with pool: String, completion: @escaping (TimeInterval?) -> Void) {
Clock.sync(
KronosClock.sync(
from: pool,
first: { [weak self] _, offset in
self?.publisher.publishAsync(offset)
Expand All @@ -50,6 +49,6 @@ internal class NTPServerDateProvider: ServerDateProvider {

// `Kronos.sync` first loads the previous state from the `UserDefaults` if any.
// We can invoke `Clock.now` to retrieve the stored offset.
publisher.publishAsync(Clock.now?.timeIntervalSinceNow)
publisher.publishAsync(KronosClock.now?.timeIntervalSinceNow)
}
}
114 changes: 114 additions & 0 deletions Sources/Datadog/Kronos/KronosClock.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,114 @@
/*
* Unless explicitly stated otherwise all files in this repository are licensed under the Apache License Version 2.0.
* This product includes software developed at Datadog (https://www.datadoghq.com/).
* Copyright 2019-2020 Datadog, Inc.
*
* This file includes software developed by MobileNativeFoundation, https://mobilenativefoundation.org and altered by Datadog.
* Use of this source code is governed by Apache License 2.0 license: https://github.com/MobileNativeFoundation/Kronos/blob/main/LICENSE
*/

import Foundation

/// Struct that has time + related metadata
internal typealias KronosAnnotatedTime = (
/// Time that is being annotated
date: Date,

/// Amount of time that has passed since the last NTP sync; in other words, the NTP response age.
timeSinceLastNtpSync: TimeInterval
)

/// High level implementation for clock synchronization using NTP. All returned dates use the most accurate
/// synchronization and it's not affected by clock changes. The NTP synchronization implementation has sub-
/// second accuracy but given that Darwin doesn't support microseconds on bootTime, dates don't have sub-
/// second accuracy.
///
/// Example usage:
///
/// ```swift
/// KronosClock.sync { date, offset in
/// print(date)
/// }
/// // (... later on ...)
/// print(KronosClock.now)
/// ```
internal struct KronosClock {
private static var stableTime: KronosTimeFreeze? {
didSet {
self.storage.stableTime = self.stableTime
}
}

/// Determines where the most current stable time is stored. Use TimeStoragePolicy.appGroup to share
/// between your app and an extension.
static var storage = KronosTimeStorage(storagePolicy: .standard)

/// The most accurate timestamp that we have so far (nil if no synchronization was done yet)
static var timestamp: TimeInterval? {
return self.stableTime?.adjustedTimestamp
}

/// The most accurate date that we have so far (nil if no synchronization was done yet)
static var now: Date? {
return self.annotatedNow?.date
}

/// Same as `now` except with analytic metadata about the time
static var annotatedNow: KronosAnnotatedTime? {
guard let stableTime = self.stableTime else {
return nil
}

return KronosAnnotatedTime(
date: Date(timeIntervalSince1970: stableTime.adjustedTimestamp),
timeSinceLastNtpSync: stableTime.timeSinceLastNtpSync
)
}

/// Syncs the clock using NTP. Note that the full synchronization could take a few seconds. The given
/// closure will be called with the first valid NTP response which accuracy should be good enough for the
/// initial clock adjustment but it might not be the most accurate representation. After calling the
/// closure this method will continue syncing with multiple servers and multiple passes.
///
/// - parameter pool: NTP pool that will be resolved into multiple NTP servers that will be used for
/// the synchronization.
/// - parameter samples: The number of samples to be acquired from each server (default 4).
/// - parameter completion: A closure that will be called after _all_ the NTP calls are finished.
/// - parameter first: A closure that will be called after the first valid date is calculated.
static func sync(
from pool: String = "time.apple.com",
samples: Int = 4,
first: ((Date, TimeInterval) -> Void)? = nil,
completion: ((Date?, TimeInterval?) -> Void)? = nil
) {
self.loadFromDefaults()

KronosNTPClient().query(pool: pool, numberOfSamples: samples) { offset, done, total in
if let offset = offset {
self.stableTime = KronosTimeFreeze(offset: offset)

if done == 1, let now = self.now {
first?(now, offset)
}
}

if done == total {
completion?(self.now, offset)
}
}
}

/// Resets all state of the monotonic clock. Note that you won't be able to access `now` until you `sync`
/// again.
static func reset() {
self.stableTime = nil
}

private static func loadFromDefaults() {
guard let previousStableTime = self.storage.stableTime else {
self.stableTime = nil
return
}
self.stableTime = previousStableTime
}
}
101 changes: 101 additions & 0 deletions Sources/Datadog/Kronos/KronosDNSResolver.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
/*
* Unless explicitly stated otherwise all files in this repository are licensed under the Apache License Version 2.0.
* This product includes software developed at Datadog (https://www.datadoghq.com/).
* Copyright 2019-2020 Datadog, Inc.
*
* This file includes software developed by MobileNativeFoundation, https://mobilenativefoundation.org and altered by Datadog.
* Use of this source code is governed by Apache License 2.0 license: https://github.com/MobileNativeFoundation/Kronos/blob/main/LICENSE
*/

import Foundation

private let kCopyNoOperation = unsafeBitCast(0, to: CFAllocatorCopyDescriptionCallBack.self)
private let kDefaultTimeout = 8.0

internal final class KronosDNSResolver {
private var completion: (([KronosInternetAddress]) -> Void)?
private var timer: Timer?

private init() {}

/// Performs DNS lookups and calls the given completion with the answers that are returned from the name
/// server(s) that were queried.
///
/// - parameter host: The host to be looked up.
/// - parameter timeout: The connection timeout.
/// - parameter completion: A completion block that will be called both on failure and success with a list
/// of IPs.
static func resolve(
host: String,
timeout: TimeInterval = kDefaultTimeout,
completion: @escaping ([KronosInternetAddress]) -> Void
) {
let callback: CFHostClientCallBack = { host, _, _, info in
guard let info = info else {
return
}
let retainedSelf = Unmanaged<KronosDNSResolver>.fromOpaque(info)
let resolver = retainedSelf.takeUnretainedValue()
resolver.timer?.invalidate()
resolver.timer = nil

var resolved: DarwinBoolean = false
guard let addresses = CFHostGetAddressing(host, &resolved), resolved.boolValue else {
resolver.completion?([])
retainedSelf.release()
return
}

let IPs = (addresses.takeUnretainedValue() as NSArray)
.compactMap { $0 as? NSData }
.compactMap(KronosInternetAddress.init)

resolver.completion?(IPs)
retainedSelf.release()
}

let resolver = KronosDNSResolver()
resolver.completion = completion

let retainedClosure = Unmanaged.passRetained(resolver).toOpaque()
var clientContext = CFHostClientContext(
version: 0,
info: UnsafeMutableRawPointer(retainedClosure),
retain: nil,
release: nil,
copyDescription: kCopyNoOperation
)

let hostReference = CFHostCreateWithName(kCFAllocatorDefault, host as CFString).takeUnretainedValue()
resolver.timer = Timer.scheduledTimer(
timeInterval: timeout,
target: resolver,
selector: #selector(KronosDNSResolver.onTimeout),
userInfo: hostReference,
repeats: false
)

CFHostSetClient(hostReference, callback, &clientContext)
CFHostScheduleWithRunLoop(hostReference, CFRunLoopGetMain(), CFRunLoopMode.commonModes.rawValue)
CFHostStartInfoResolution(hostReference, .addresses, nil)
}

@objc
private func onTimeout() {
defer {
self.completion?([])

// Manually release the previously retained self.
Unmanaged.passUnretained(self).release()
}

guard let userInfo = self.timer?.userInfo else {
return
}

let hostReference = unsafeBitCast(userInfo as AnyObject, to: CFHost.self)
CFHostCancelInfoResolution(hostReference, .addresses)
CFHostUnscheduleFromRunLoop(hostReference, CFRunLoopGetMain(), CFRunLoopMode.commonModes.rawValue)
CFHostSetClient(hostReference, nil, nil)
}
}
99 changes: 99 additions & 0 deletions Sources/Datadog/Kronos/KronosData+Bytes.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
/*
* Unless explicitly stated otherwise all files in this repository are licensed under the Apache License Version 2.0.
* This product includes software developed at Datadog (https://www.datadoghq.com/).
* Copyright 2019-2020 Datadog, Inc.
*
* This file includes software developed by MobileNativeFoundation, https://mobilenativefoundation.org and altered by Datadog.
* Use of this source code is governed by Apache License 2.0 license: https://github.com/MobileNativeFoundation/Kronos/blob/main/LICENSE
*/

import Foundation

extension Data {
/// Creates an Data instance based on a hex string (example: "ffff" would be <FF FF>).
///
/// - parameter hex: The hex string without any spaces; should only have [0-9A-Fa-f].
init?(hex: String) {
if hex.count % 2 != 0 {
return nil
}

let hexArray = Array(hex)
var bytes: [UInt8] = []

for index in stride(from: 0, to: hexArray.count, by: 2) {
guard let byte = UInt8("\(hexArray[index])\(hexArray[index + 1])", radix: 16) else {
return nil
}

bytes.append(byte)
}

self.init(bytes: bytes, count: bytes.count)
}

/// Gets one byte from the given index.
///
/// - parameter index: The index of the byte to be retrieved. Note that this should never be >= length.
///
/// - returns: The byte located at position `index`.
func getByte(at index: Int) -> Int8 {
let data: Int8 = self.subdata(in: index ..< (index + 1)).withUnsafeBytes { rawPointer in
rawPointer.bindMemory(to: Int8.self).baseAddress!.pointee // swiftlint:disable:this force_unwrapping
}

return data
}

/// Gets an unsigned int (32 bits => 4 bytes) from the given index.
///
/// - parameter index: The index of the uint to be retrieved. Note that this should never be >= length -
/// 3.
///
/// - returns: The unsigned int located at position `index`.
func getUnsignedInteger(at index: Int, bigEndian: Bool = true) -> UInt32 {
let data: UInt32 = self.subdata(in: index ..< (index + 4)).withUnsafeBytes { rawPointer in
rawPointer.bindMemory(to: UInt32.self).baseAddress!.pointee // swiftlint:disable:this force_unwrapping
}

return bigEndian ? data.bigEndian : data.littleEndian
}

/// Gets an unsigned long integer (64 bits => 8 bytes) from the given index.
///
/// - parameter index: The index of the ulong to be retrieved. Note that this should never be >= length -
/// 7.
///
/// - returns: The unsigned long integer located at position `index`.
func getUnsignedLong(at index: Int, bigEndian: Bool = true) -> UInt64 {
let data: UInt64 = self.subdata(in: index ..< (index + 8)).withUnsafeBytes { rawPointer in
rawPointer.bindMemory(to: UInt64.self).baseAddress!.pointee // swiftlint:disable:this force_unwrapping
}

return bigEndian ? data.bigEndian : data.littleEndian
}

/// Appends the given byte (8 bits) into the receiver Data.
///
/// - parameter data: The byte to be appended.
mutating func append(byte data: Int8) {
var data = data
self.append(Data(bytes: &data, count: MemoryLayout<Int8>.size))
}

/// Appends the given unsigned integer (32 bits; 4 bytes) into the receiver Data.
///
/// - parameter data: The unsigned integer to be appended.
mutating func append(unsignedInteger data: UInt32, bigEndian: Bool = true) {
var data = bigEndian ? data.bigEndian : data.littleEndian
self.append(Data(bytes: &data, count: MemoryLayout<UInt32>.size))
}

/// Appends the given unsigned long (64 bits; 8 bytes) into the receiver Data.
///
/// - parameter data: The unsigned long to be appended.
mutating func append(unsignedLong data: UInt64, bigEndian: Bool = true) {
var data = bigEndian ? data.bigEndian : data.littleEndian
self.append(Data(bytes: &data, count: MemoryLayout<UInt64>.size))
}
}
Loading