Clean up logging

pull/27/head
Niels Andriesse 6 years ago
parent c040ea1e5e
commit 39c497f13d

@ -332,13 +332,13 @@ static NSTimeInterval launchStartedAt;
if ([serverURLDescription hasSuffix:@"/"]) { if ([serverURLDescription hasSuffix:@"/"]) {
serverURLDescription = [serverURLDescription substringToIndex:serverURLDescription.length - 1]; serverURLDescription = [serverURLDescription substringToIndex:serverURLDescription.length - 1];
} }
OWSLogInfo(@"[Loki] Started server at %@.", serverURLDescription); NSLog(@"[Loki] Started server at %@.", serverURLDescription);
break; break;
} }
} }
if (!self.lokiP2PServer.isRunning) { if (!self.lokiP2PServer.isRunning) {
OWSLogWarn(@"[Loki] Failed to start P2P server."); NSLog(@"[Loki] Failed to start P2P server.");
} }
return YES; return YES;
@ -1416,7 +1416,7 @@ static NSTimeInterval launchStartedAt;
- (void)handleNewMessagesReceived:(NSNotification *)notification - (void)handleNewMessagesReceived:(NSNotification *)notification
{ {
NSArray *messages = (NSArray *)notification.userInfo[@"messages"]; NSArray *messages = (NSArray *)notification.userInfo[@"messages"];
OWSLogInfo(@"[Loki] Received %lu messages through long polling.", messages.count); NSLog(@"[Loki] Received %lu messages through long polling.", messages.count);
for (SSKProtoEnvelope *envelope in messages) { for (SSKProtoEnvelope *envelope in messages) {
NSData *envelopeData = envelope.serializedDataIgnoringErrors; NSData *envelopeData = envelope.serializedDataIgnoringErrors;

@ -147,7 +147,7 @@ public class SessionResetOperation: OWSOperation, DurableOperation {
message.save(with: transaction) message.save(with: transaction)
// Loki: We have initiated a session reset // Loki: We have initiated a session reset
Logger.debug("[Loki] Session reset initiated.") print("[Loki] Session reset initiated.")
self.contactThread.sessionResetState = .initiated self.contactThread.sessionResetState = .initiated
self.contactThread.save(with: transaction) self.contactThread.save(with: transaction)
} }

@ -25,7 +25,7 @@ private extension GCDWebServerDataRequest {
let object = try JSONSerialization.jsonObject(with: data, options: .allowFragments) let object = try JSONSerialization.jsonObject(with: data, options: .allowFragments)
return object as? JSON return object as? JSON
} catch let error { } catch let error {
Logger.debug("[Loki] Failed to serialize JSON: \(error).") print("[Loki] Failed to serialize JSON: \(error).")
} }
return nil return nil

@ -36,7 +36,7 @@ public class CreatePreKeysOperation: OWSOperation {
self.primaryStorage.storeSignedPreKey(signedPreKeyRecord.id, signedPreKeyRecord: signedPreKeyRecord) self.primaryStorage.storeSignedPreKey(signedPreKeyRecord.id, signedPreKeyRecord: signedPreKeyRecord)
self.primaryStorage.setCurrentSignedPrekeyId(signedPreKeyRecord.id) self.primaryStorage.setCurrentSignedPrekeyId(signedPreKeyRecord.id)
Logger.debug("[Loki] Create pre keys operation done.") print("[Loki] Create pre keys operation done.")
self.reportSuccess() self.reportSuccess()
/* Loki: Original code /* Loki: Original code

@ -52,7 +52,7 @@ public class RefreshPreKeysOperation: OWSOperation {
TSPreKeyManager.clearPreKeyUpdateFailureCount() TSPreKeyManager.clearPreKeyUpdateFailureCount()
TSPreKeyManager.clearSignedPreKeyRecords() TSPreKeyManager.clearSignedPreKeyRecords()
Logger.debug("[Loki] Pre key refresh operation done.") print("[Loki] Pre key refresh operation done.")
self.reportSuccess() self.reportSuccess()
} }

@ -37,7 +37,7 @@ public class RotateSignedPreKeyOperation: OWSOperation {
TSPreKeyManager.clearPreKeyUpdateFailureCount() TSPreKeyManager.clearPreKeyUpdateFailureCount()
TSPreKeyManager.clearSignedPreKeyRecords() TSPreKeyManager.clearSignedPreKeyRecords()
Logger.debug("[Loki] Rotate signed pre key operation done.") print("[Loki] Rotate signed pre key operation done.")
self.reportSuccess() self.reportSuccess()
} }

@ -768,7 +768,7 @@ ConversationColorName const kConversationColorName_Default = ConversationColorNa
- (void)saveFriendRequestStatus:(LKThreadFriendRequestStatus)friendRequestStatus withTransaction:(YapDatabaseReadWriteTransaction *_Nullable)transaction - (void)saveFriendRequestStatus:(LKThreadFriendRequestStatus)friendRequestStatus withTransaction:(YapDatabaseReadWriteTransaction *_Nullable)transaction
{ {
self.friendRequestStatus = friendRequestStatus; self.friendRequestStatus = friendRequestStatus;
OWSLogInfo(@"[Loki] Setting thread friend request status to %@.", self.friendRequestStatusDescription); NSLog(@"[Loki] Setting thread friend request status to %@.", self.friendRequestStatusDescription);
void (^postNotification)() = ^() { void (^postNotification)() = ^() {
[NSNotificationCenter.defaultCenter postNotificationName:NSNotification.threadFriendRequestStatusChanged object:self.uniqueId]; [NSNotificationCenter.defaultCenter postNotificationName:NSNotification.threadFriendRequestStatusChanged object:self.uniqueId];
}; };

@ -15,7 +15,7 @@ public extension LokiAPI {
isLongPolling = true isLongPolling = true
shouldStopPolling = false shouldStopPolling = false
Logger.info("[Loki] Started long polling.") print("[Loki] Started long polling.")
longPoll() longPoll()
} }
@ -27,7 +27,7 @@ public extension LokiAPI {
usedSnodes.removeAll() usedSnodes.removeAll()
cancelAllPromises() cancelAllPromises()
Logger.info("[Loki] Stopped long polling.") print("[Loki] Stopped long polling.")
} }
/// The long polling loop /// The long polling loop

@ -78,7 +78,7 @@ public extension LokiAPI {
// MARK: Parsing // MARK: Parsing
private static func parseTargets(from rawResponse: Any) -> [LokiAPITarget] { private static func parseTargets(from rawResponse: Any) -> [LokiAPITarget] {
guard let json = rawResponse as? JSON, let rawSnodes = json["snodes"] as? [JSON] else { guard let json = rawResponse as? JSON, let rawSnodes = json["snodes"] as? [JSON] else {
Logger.warn("[Loki] Failed to parse targets from: \(rawResponse).") print("[Loki] Failed to parse targets from: \(rawResponse).")
return [] return []
} }
return rawSnodes.flatMap { rawSnode in return rawSnodes.flatMap { rawSnode in
@ -97,10 +97,10 @@ internal extension Promise {
switch error.statusCode { switch error.statusCode {
case 0: case 0:
// The snode is unreachable; usually a problem with LokiNet // The snode is unreachable; usually a problem with LokiNet
Logger.warn("[Loki] Couldn't reach snode at: \(target.address):\(target.port).") print("[Loki] Couldn't reach snode at: \(target.address):\(target.port).")
case 421: case 421:
// The snode isn't associated with the given public key anymore // The snode isn't associated with the given public key anymore
Logger.warn("[Loki] Invalidating swarm for: \(hexEncodedPublicKey).") print("[Loki] Invalidating swarm for: \(hexEncodedPublicKey).")
LokiAPI.dropIfNeeded(target, hexEncodedPublicKey: hexEncodedPublicKey) LokiAPI.dropIfNeeded(target, hexEncodedPublicKey: hexEncodedPublicKey)
default: break default: break
} }

@ -9,6 +9,7 @@ public final class LokiAPI : NSObject {
// MARK: Settings // MARK: Settings
private static let version = "v1" private static let version = "v1"
private static let maxRetryCount: UInt = 3 private static let maxRetryCount: UInt = 3
private static let defaultTimeout: TimeInterval = 20
private static let longPollingTimeout: TimeInterval = 40 private static let longPollingTimeout: TimeInterval = 40
public static let defaultMessageTTL: UInt64 = 24 * 60 * 60 * 1000 public static let defaultMessageTTL: UInt64 = 24 * 60 * 60 * 1000
@ -40,7 +41,10 @@ public final class LokiAPI : NSObject {
let url = URL(string: "\(target.address):\(target.port)/\(version)/storage_rpc")! let url = URL(string: "\(target.address):\(target.port)/\(version)/storage_rpc")!
let request = TSRequest(url: url, method: "POST", parameters: [ "method" : method.rawValue, "params" : parameters ]) let request = TSRequest(url: url, method: "POST", parameters: [ "method" : method.rawValue, "params" : parameters ])
if let headers = headers { request.allHTTPHeaderFields = headers } if let headers = headers { request.allHTTPHeaderFields = headers }
if let timeout = timeout { request.timeoutInterval = timeout } if let timeout = timeout { request.timeoutInterval = timeout ?? defaultTimeout }
let headers = request.allHTTPHeaderFields ?? [:]
let headersDescription = headers.isEmpty ? "no custom headers specified" : headers.description
print("[Loki] Invoking \(method.rawValue) on \(url) with \(parameters) (\(headersDescription)).")
return TSNetworkManager.shared().makePromise(request: request).map { $0.responseObject } return TSNetworkManager.shared().makePromise(request: request).map { $0.responseObject }
.handlingSwarmSpecificErrorsIfNeeded(for: target, associatedWith: hexEncodedPublicKey).recoveringNetworkErrorsIfNeeded() .handlingSwarmSpecificErrorsIfNeeded(for: target, associatedWith: hexEncodedPublicKey).recoveringNetworkErrorsIfNeeded()
} }
@ -82,7 +86,7 @@ public final class LokiAPI : NSObject {
}.recover { error -> Promise<Set<RawResponsePromise>> in }.recover { error -> Promise<Set<RawResponsePromise>> in
LokiP2PAPI.markOffline(destination) LokiP2PAPI.markOffline(destination)
if lokiMessage.isPing { if lokiMessage.isPing {
Logger.warn("[Loki] Failed to ping \(destination); marking contact as offline.") print("[Loki] Failed to ping \(destination); marking contact as offline.")
if let error = error as? NSError { if let error = error as? NSError {
error.isRetryable = false error.isRetryable = false
throw error throw error
@ -119,7 +123,7 @@ public final class LokiAPI : NSObject {
if let lastMessage = rawMessages.last, let hashValue = lastMessage["hash"] as? String, let expirationDate = lastMessage["expiration"] as? Int { if let lastMessage = rawMessages.last, let hashValue = lastMessage["hash"] as? String, let expirationDate = lastMessage["expiration"] as? Int {
setLastMessageHashValue(for: target, hashValue: hashValue, expirationDate: UInt64(expirationDate)) setLastMessageHashValue(for: target, hashValue: hashValue, expirationDate: UInt64(expirationDate))
} else if (!rawMessages.isEmpty) { } else if (!rawMessages.isEmpty) {
Logger.warn("[Loki] Failed to update last message hash value from: \(rawMessages).") print("[Loki] Failed to update last message hash value from: \(rawMessages).")
} }
} }
@ -127,7 +131,7 @@ public final class LokiAPI : NSObject {
var receivedMessageHashValues = getReceivedMessageHashValues() ?? [] var receivedMessageHashValues = getReceivedMessageHashValues() ?? []
return rawMessages.filter { rawMessage in return rawMessages.filter { rawMessage in
guard let hashValue = rawMessage["hash"] as? String else { guard let hashValue = rawMessage["hash"] as? String else {
Logger.warn("[Loki] Missing hash value for message: \(rawMessage).") print("[Loki] Missing hash value for message: \(rawMessage).")
return false return false
} }
let isDuplicate = receivedMessageHashValues.contains(hashValue) let isDuplicate = receivedMessageHashValues.contains(hashValue)
@ -140,11 +144,11 @@ public final class LokiAPI : NSObject {
private static func parseProtoEnvelopes(from rawMessages: [JSON]) -> [SSKProtoEnvelope] { private static func parseProtoEnvelopes(from rawMessages: [JSON]) -> [SSKProtoEnvelope] {
return rawMessages.compactMap { rawMessage in return rawMessages.compactMap { rawMessage in
guard let base64EncodedData = rawMessage["data"] as? String, let data = Data(base64Encoded: base64EncodedData) else { guard let base64EncodedData = rawMessage["data"] as? String, let data = Data(base64Encoded: base64EncodedData) else {
Logger.warn("[Loki] Failed to decode data for message: \(rawMessage).") print("[Loki] Failed to decode data for message: \(rawMessage).")
return nil return nil
} }
guard let envelope = try? LokiMessageWrapper.unwrap(data: data) else { guard let envelope = try? LokiMessageWrapper.unwrap(data: data) else {
Logger.warn("[Loki] Failed to unwrap data for message: \(rawMessage).") print("[Loki] Failed to unwrap data for message: \(rawMessage).")
return nil return nil
} }
return envelope return envelope

@ -29,4 +29,7 @@ internal final class LokiAPITarget : NSObject, NSCoding {
coder.encode(address, forKey: "address") coder.encode(address, forKey: "address")
coder.encode(port, forKey: "port") coder.encode(port, forKey: "port")
} }
// MARK: Description
override var description: String { return "\(address):\(port)" }
} }

@ -39,7 +39,7 @@ public struct LokiMessage {
let isPing = signalMessage.isPing let isPing = signalMessage.isPing
return LokiMessage(destination: destination, data: data, ttl: ttl, isPing: isPing) return LokiMessage(destination: destination, data: data, ttl: ttl, isPing: isPing)
} catch let error { } catch let error {
Logger.debug("[Loki] Failed to convert Signal message to Loki message: \(signalMessage).") print("[Loki] Failed to convert Signal message to Loki message: \(signalMessage).")
return nil return nil
} }
} }

@ -48,12 +48,12 @@ public class LokiP2PAPI : NSObject {
} }
guard let thread = contactThread else { guard let thread = contactThread else {
Logger.warn("[Loki] Failed to fetch thread when attempting to ping: \(pubKey).") print("[Loki] Failed to fetch thread when attempting to ping: \(pubKey).")
return return
} }
guard let message = createLokiAddressMessage(for: thread, isPing: true) else { guard let message = createLokiAddressMessage(for: thread, isPing: true) else {
Logger.warn("[Loki] Failed to build ping message for \(pubKey).") print("[Loki] Failed to build ping message for \(pubKey).")
return return
} }
@ -75,11 +75,11 @@ public class LokiP2PAPI : NSObject {
public static func handleReceivedMessage(base64EncodedData: String) { public static func handleReceivedMessage(base64EncodedData: String) {
guard let data = Data(base64Encoded: base64EncodedData) else { guard let data = Data(base64Encoded: base64EncodedData) else {
Logger.warn("[Loki] Failed to decode data for P2P message.") print("[Loki] Failed to decode data for P2P message.")
return return
} }
guard let envelope = try? LokiMessageWrapper.unwrap(data: data) else { guard let envelope = try? LokiMessageWrapper.unwrap(data: data) else {
Logger.warn("[Loki] Failed to unwrap data for P2P message.") print("[Loki] Failed to unwrap data for P2P message.")
return return
} }
// We need to set the P2P field on the envelope // We need to set the P2P field on the envelope
@ -91,7 +91,7 @@ public class LokiP2PAPI : NSObject {
let envelopeData = try newEnvelope.serializedData() let envelopeData = try newEnvelope.serializedData()
messageReceiver.handleReceivedEnvelopeData(envelopeData) messageReceiver.handleReceivedEnvelopeData(envelopeData)
} catch let error { } catch let error {
Logger.warn("[Loki] Something went wrong during proto conversion: \(error).") print("[Loki] Something went wrong during proto conversion: \(error).")
} }
} }
@ -198,7 +198,7 @@ public class LokiP2PAPI : NSObject {
AssertIsOnMainThread() AssertIsOnMainThread()
guard let message = onlineBroadcastMessage(forThread: thread) else { guard let message = onlineBroadcastMessage(forThread: thread) else {
Logger.warn("[Loki] P2P address not set.") print("[Loki] P2P address not set.")
return return
} }
@ -222,7 +222,7 @@ public class LokiP2PAPI : NSObject {
private static func createLokiAddressMessage(for thread: TSThread, isPing: Bool) -> LokiAddressMessage? { private static func createLokiAddressMessage(for thread: TSThread, isPing: Bool) -> LokiAddressMessage? {
guard let ourAddress = ourP2PAddress else { guard let ourAddress = ourP2PAddress else {
Logger.warn("[Loki] P2P address not set.") print("[Loki] P2P address not set.")
return nil return nil
} }

@ -62,7 +62,7 @@
@try { @try {
return [self throws_loadPreKey:preKeyId]; return [self throws_loadPreKey:preKeyId];
} @catch (NSException *exception) { } @catch (NSException *exception) {
OWSLogWarn(@"[Loki] New prekey generated for %@.", pubKey); NSLog(@"[Loki] New prekey generated for %@.", pubKey);
return [self generateAndStorePreKeyForContact:pubKey]; return [self generateAndStorePreKeyForContact:pubKey];
} }
} }

@ -140,7 +140,7 @@ public final class FriendRequestExpirationJob : NSObject {
private func timerDidFire(isMainTimer: Bool) { private func timerDidFire(isMainTimer: Bool) {
guard CurrentAppContext().isMainAppAndActive else { guard CurrentAppContext().isMainAppAndActive else {
let infoString = isMainTimer ? "Main timer fired while main app is inactive." : "Ignoring fallback timer for app which is not main and active." let infoString = isMainTimer ? "Main timer fired while main app is inactive." : "Ignoring fallback timer for app which is not main and active."
Logger.info("[Loki] Friend request expiration job running: \(infoString).") print("[Loki] Friend request expiration job running: \(infoString).")
return return
} }

@ -40,7 +40,7 @@ public enum LokiMessageWrapper {
} }
return try builder.build() return try builder.build()
} catch let error { } catch let error {
Logger.warn("[Loki] Failed to wrap message in envelope: \(error).") print("[Loki] Failed to wrap message in envelope: \(error).")
throw WrappingError.failedToWrapMessageInEnvelope throw WrappingError.failedToWrapMessageInEnvelope
} }
} }
@ -53,7 +53,7 @@ public enum LokiMessageWrapper {
messageBuilder.setRequest(try requestBuilder.build()) messageBuilder.setRequest(try requestBuilder.build())
return try messageBuilder.build() return try messageBuilder.build()
} catch let error { } catch let error {
Logger.warn("[Loki] Failed to wrap envelope in web socket message: \(error).") print("[Loki] Failed to wrap envelope in web socket message: \(error).")
throw WrappingError.failedToWrapEnvelopeInWebSocketMessage throw WrappingError.failedToWrapEnvelopeInWebSocketMessage
} }
} }
@ -65,7 +65,7 @@ public enum LokiMessageWrapper {
let envelope = webSocketMessage.request!.body! let envelope = webSocketMessage.request!.body!
return try SSKProtoEnvelope.parseData(envelope) return try SSKProtoEnvelope.parseData(envelope)
} catch let error { } catch let error {
Logger.warn("[Loki] Failed to unwrap data: \(error).") print("[Loki] Failed to unwrap data: \(error).")
throw WrappingError.failedToUnwrapData throw WrappingError.failedToUnwrapData
} }
} }

@ -445,7 +445,7 @@ static const NSUInteger OWSMessageSchemaVersion = 4;
- (void)saveFriendRequestStatus:(LKMessageFriendRequestStatus)friendRequestStatus withTransaction:(YapDatabaseReadWriteTransaction *_Nullable)transaction - (void)saveFriendRequestStatus:(LKMessageFriendRequestStatus)friendRequestStatus withTransaction:(YapDatabaseReadWriteTransaction *_Nullable)transaction
{ {
self.friendRequestStatus = friendRequestStatus; self.friendRequestStatus = friendRequestStatus;
OWSLogInfo(@"[Loki] Setting message friend request status to %@.", self.friendRequestStatusDescription); NSLog(@"[Loki] Setting message friend request status to %@.", self.friendRequestStatusDescription);
void (^postNotification)() = ^() { void (^postNotification)() = ^() {
[NSNotificationCenter.defaultCenter postNotificationName:NSNotification.messageFriendRequestStatusChanged object:self.uniqueId]; [NSNotificationCenter.defaultCenter postNotificationName:NSNotification.messageFriendRequestStatusChanged object:self.uniqueId];
}; };

@ -1032,7 +1032,7 @@ NS_ASSUME_NONNULL_BEGIN
LKEphemeralMessage *emptyMessage = [[LKEphemeralMessage alloc] initInThread:thread]; LKEphemeralMessage *emptyMessage = [[LKEphemeralMessage alloc] initInThread:thread];
[self.messageSenderJobQueue addMessage:emptyMessage transaction:transaction]; [self.messageSenderJobQueue addMessage:emptyMessage transaction:transaction];
OWSLogDebug(@"[Loki] Session reset received from %@.", envelope.source); NSLog(@"[Loki] Session reset received from %@.", envelope.source);
/* Loki: Original code /* Loki: Original code
* ================ * ================
@ -1737,7 +1737,7 @@ NS_ASSUME_NONNULL_BEGIN
TSContactThread *_Nullable thread = [TSContactThread getThreadWithContactId:pubKey transaction:transaction]; TSContactThread *_Nullable thread = [TSContactThread getThreadWithContactId:pubKey transaction:transaction];
if (!thread) { if (!thread) {
OWSLogDebug(@"[Loki] A new session was adopted but we failed to get the thread for %@.", pubKey); NSLog(@"[Loki] A new session was adopted but we failed to get the thread for %@.", pubKey);
return; return;
} }

@ -27,7 +27,7 @@ typedef NS_ENUM(NSInteger, TSWhisperMessageType) {
// Production // Production
#define textSecureWebSocketAPI @"wss://textsecure-service.whispersystems.org/v1/websocket/" #define textSecureWebSocketAPI @"wss://textsecure-service.whispersystems.org/v1/websocket/"
#define textSecureServerURL @"http://13.236.173.190" // TODO: Temporary #define textSecureServerURL @"https://textsecure-service.whispersystems.org/"
#define textSecureCDNServerURL @"https://cdn.signal.org" #define textSecureCDNServerURL @"https://cdn.signal.org"
// Use same reflector for service and CDN // Use same reflector for service and CDN
#define textSecureServiceReflectorHost @"europe-west1-signal-cdn-reflector.cloudfunctions.net" #define textSecureServiceReflectorHost @"europe-west1-signal-cdn-reflector.cloudfunctions.net"

Loading…
Cancel
Save