Skip to content

Commit

Permalink
Merge pull request #565 from AzureAD/jinjia/apiEvents
Browse files Browse the repository at this point in the history
Integrate the telemetry events
  • Loading branch information
heidijinxujia authored Sep 5, 2019
2 parents 6fa9ccd + 1b5eb34 commit 19bf142
Show file tree
Hide file tree
Showing 22 changed files with 340 additions and 208 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,9 @@

import com.microsoft.identity.common.adal.internal.PowerManagerWrapper;
import com.microsoft.identity.common.adal.internal.UsageStatsManagerWrapper;
import com.microsoft.identity.common.internal.telemetry.Telemetry;
import com.microsoft.identity.common.internal.telemetry.TelemetryEventStrings;
import com.microsoft.identity.common.internal.telemetry.events.BaseEvent;

/**
* Default connection service check network connectivity.
Expand Down Expand Up @@ -60,7 +63,9 @@ public boolean isConnectionAvailable() {
ConnectivityManager connectivityManager = (ConnectivityManager) mConnectionContext
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = connectivityManager.getActiveNetworkInfo();
return activeNetwork != null && activeNetwork.isConnectedOrConnecting() && !isNetworkDisabledFromOptimizations();
final boolean isConnectionAvailable = activeNetwork != null && activeNetwork.isConnectedOrConnecting() && !isNetworkDisabledFromOptimizations();
Telemetry.emit((BaseEvent) new BaseEvent().put(TelemetryEventStrings.Key.NETWORK_CONNECTION, String.valueOf(isConnectionAvailable)));
return isConnectionAvailable;
}

/**
Expand All @@ -74,15 +79,18 @@ public boolean isNetworkDisabledFromOptimizations() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
final UsageStatsManagerWrapper usageStatsManagerWrapper = UsageStatsManagerWrapper.getInstance();
if (usageStatsManagerWrapper.isAppInactive(mConnectionContext)) {
Telemetry.emit((BaseEvent) new BaseEvent().put(TelemetryEventStrings.Key.POWER_OPTIMIZATION, String.valueOf(true)));
return true;
}

final PowerManagerWrapper powerManagerWrapper = PowerManagerWrapper.getInstance();
if (powerManagerWrapper.isDeviceIdleMode(mConnectionContext) && !powerManagerWrapper.isIgnoringBatteryOptimizations(mConnectionContext)) {
Telemetry.emit((BaseEvent) new BaseEvent().put(TelemetryEventStrings.Key.POWER_OPTIMIZATION, String.valueOf(true)));
return true;
}
}

Telemetry.emit((BaseEvent) new BaseEvent().put(TelemetryEventStrings.Key.POWER_OPTIMIZATION, String.valueOf(false)));
return false;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,10 @@
import com.microsoft.identity.common.internal.providers.oauth2.OAuth2Strategy;
import com.microsoft.identity.common.internal.providers.oauth2.OAuth2TokenCache;
import com.microsoft.identity.common.internal.providers.oauth2.TokenResponse;
import com.microsoft.identity.common.internal.telemetry.Telemetry;
import com.microsoft.identity.common.internal.telemetry.TelemetryEventStrings;
import com.microsoft.identity.common.internal.telemetry.events.CacheEndEvent;
import com.microsoft.identity.common.internal.telemetry.events.CacheStartEvent;

import java.util.ArrayList;
import java.util.Arrays;
Expand Down Expand Up @@ -491,6 +495,8 @@ public ICacheRecord save(@NonNull final AccountRecord accountToSave,
public ICacheRecord load(@NonNull final String clientId,
@Nullable final String target,
@NonNull final AccountRecord account) {
Telemetry.emit(new CacheStartEvent());

final boolean isMultiResourceCapable = MicrosoftAccount.AUTHORITY_TYPE_V1_V2.equals(
account.getAuthorityType()
);
Expand Down Expand Up @@ -546,6 +552,7 @@ public ICacheRecord load(@NonNull final String clientId,
result.setIdToken(idTokens.isEmpty() ? null : (IdTokenRecord) idTokens.get(0));
result.setV1IdToken(v1IdTokens.isEmpty() ? null : (IdTokenRecord) v1IdTokens.get(0));

Telemetry.emit(new CacheEndEvent().putCacheRecordStatus(result));
return result;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,8 @@
import com.microsoft.identity.common.internal.result.AcquireTokenResult;
import com.microsoft.identity.common.internal.result.LocalAuthenticationResult;
import com.microsoft.identity.common.internal.telemetry.CliTelemInfo;
import com.microsoft.identity.common.internal.telemetry.Telemetry;
import com.microsoft.identity.common.internal.telemetry.events.CacheEndEvent;

import java.io.IOException;
import java.util.Arrays;
Expand Down Expand Up @@ -233,6 +235,8 @@ protected void renewAccessToken(@NonNull final AcquireTokenSilentOperationParame
authenticationResult.setRefreshTokenAge(cliTelemInfo.getRefreshTokenAge());
}

Telemetry.emit(new CacheEndEvent().putSpeInfo(tokenResult.getCliTelemInfo().getSpeRing()));

// Set the AuthenticationResult on the final result object
acquireTokenSilentResult.setLocalAuthenticationResult(authenticationResult);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@ public static class SerializedNames {
private String mClientId;

/**
* A designated {@link CredentialType} represnted as a String.
* A designated {@link CredentialType} represented as a String.
*/
@SerializedName(CREDENTIAL_TYPE)
private String mCredentialType;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,9 @@
// THE SOFTWARE.
package com.microsoft.identity.common.internal.net;

import com.microsoft.identity.common.internal.telemetry.Telemetry;
import com.microsoft.identity.common.internal.telemetry.events.HttpEndEvent;
import com.microsoft.identity.common.internal.telemetry.events.HttpStartEvent;
import com.microsoft.identity.common.internal.util.StringUtil;

import java.io.BufferedReader;
Expand All @@ -38,6 +41,8 @@
import java.util.Map;
import java.util.Set;

import static com.microsoft.identity.common.adal.internal.AuthenticationConstants.AAD.CLIENT_REQUEST_ID;

/**
* Internal class for handling http request.
*/
Expand Down Expand Up @@ -114,9 +119,19 @@ private HttpRequest(final URL requestUrl, final Map<String, String> requestHeade
public static HttpResponse sendPost(final URL requestUrl, final Map<String, String> requestHeaders,
final byte[] requestContent, final String requestContentType)
throws IOException {
Telemetry.emit(
new HttpStartEvent()
.putMethod(REQUEST_METHOD_POST)
.putPath(requestUrl)
.putRequestIdHeader(requestHeaders.get(CLIENT_REQUEST_ID))
);

final HttpRequest httpRequest = new HttpRequest(requestUrl, requestHeaders, REQUEST_METHOD_POST,
requestContent, requestContentType);
return httpRequest.send();
final HttpResponse response = httpRequest.send();
Telemetry.emit(new HttpEndEvent().putStatusCode(response.getStatusCode()));

return response;
}

/**
Expand All @@ -129,9 +144,21 @@ public static HttpResponse sendPost(final URL requestUrl, final Map<String, Stri
*/
public static HttpResponse sendGet(final URL requestUrl, final Map<String, String> requestHeaders)
throws IOException {
Telemetry.emit(
new HttpStartEvent()
.putMethod(REQUEST_METHOD_GET)
.putPath(requestUrl)
.putRequestIdHeader(requestHeaders.get(CLIENT_REQUEST_ID))
);

final HttpRequest httpRequest = new HttpRequest(requestUrl, requestHeaders, REQUEST_METHOD_GET);
final HttpResponse response = httpRequest.send();

return httpRequest.send();
Telemetry.emit(
new HttpEndEvent()
.putStatusCode(response.getStatusCode())
);
return response;
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,9 @@
import com.microsoft.identity.common.internal.controllers.ApiDispatcher;
import com.microsoft.identity.common.internal.logging.DiagnosticContext;
import com.microsoft.identity.common.internal.logging.Logger;
import com.microsoft.identity.common.internal.telemetry.Telemetry;
import com.microsoft.identity.common.internal.telemetry.events.UiEndEvent;
import com.microsoft.identity.common.internal.telemetry.events.UiStartEvent;
import com.microsoft.identity.common.internal.ui.AuthorizationAgent;
import com.microsoft.identity.common.internal.ui.webview.AzureActiveDirectoryWebViewClient;
import com.microsoft.identity.common.internal.ui.webview.challengehandlers.IAuthorizationCompletionCallback;
Expand Down Expand Up @@ -84,6 +87,7 @@ public final class AuthorizationActivity extends Activity {
@Override
public void onReceive(Context context, Intent intent) {
Logger.info(TAG, "Received Authorization flow cancel request from SDK");
Telemetry.emit(new UiEndEvent().isUserCancelled());
sendResult(AuthenticationConstants.UIResponse.BROWSER_CODE_SDK_CANCEL, new Intent());
finish();
}
Expand Down Expand Up @@ -178,6 +182,7 @@ private HashMap<String, String> getRequestHeaders(final Bundle state) {
protected void onCreate(final Bundle savedInstanceState) {
final String methodName = "#onCreate";
super.onCreate(savedInstanceState);

setContentView(R.layout.common_activity_authentication);

// Register Broadcast receiver to cancel the auth request
Expand All @@ -193,6 +198,7 @@ protected void onCreate(final Bundle savedInstanceState) {
Logger.verbose(TAG + methodName, "Extract state from the saved bundle.");
extractState(savedInstanceState);
}
Telemetry.emit(new UiStartEvent().putUserAgent(mAuthorizationAgent));

if (mAuthorizationAgent == AuthorizationAgent.WEBVIEW) {
AzureActiveDirectoryWebViewClient webViewClient = new AzureActiveDirectoryWebViewClient(this, new AuthorizationCompletionCallback(), mRedirectUri);
Expand Down Expand Up @@ -285,6 +291,7 @@ protected void onStop() {
Logger.info(TAG + methodName,
"Activity is destroyed before Auth request is completed, sending request cancel"
);
Telemetry.emit(new UiEndEvent().isUserCancelled());
sendResult(AuthenticationConstants.UIResponse.BROWSER_CODE_SDK_CANCEL, new Intent());
}
super.onStop();
Expand All @@ -298,6 +305,7 @@ protected void onDestroy() {
Logger.info(TAG + methodName,
"Activity is destroyed before Auth request is completed, sending request cancel"
);
Telemetry.emit(new UiEndEvent().isUserCancelled());
sendResult(AuthenticationConstants.UIResponse.BROWSER_CODE_SDK_CANCEL, new Intent());
}
unregisterReceiver(mCancelRequestReceiver);
Expand Down Expand Up @@ -326,11 +334,14 @@ private void completeAuthorization() {
sendResult(AuthenticationConstants.UIResponse.BROKER_REQUEST_RESUME, resultIntent);
} else if (!StringUtil.isEmpty(resultIntent.getStringExtra(AuthorizationStrategy.AUTHORIZATION_FINAL_URL))) {
sendResult(AuthenticationConstants.UIResponse.BROWSER_CODE_COMPLETE, resultIntent);
Telemetry.emit(new UiEndEvent().isUiComplete());
} else if (!StringUtil.isEmpty(resultIntent.getStringExtra(AuthenticationConstants.Browser.RESPONSE_ERROR_SUBCODE))
&& resultIntent.getStringExtra(AuthenticationConstants.Browser.RESPONSE_ERROR_SUBCODE).equalsIgnoreCase("cancel")) {
//when the user click the "cancel" button in the UI, server will send the the redirect uri with "cancel" error sub-code and redirects back to the calling app
Telemetry.emit(new UiEndEvent().isUserCancelled());
sendResult(AuthenticationConstants.UIResponse.BROWSER_CODE_SDK_CANCEL, resultIntent);
} else {
Telemetry.emit(new UiEndEvent().isUiCancelled());
sendResult(AuthenticationConstants.UIResponse.BROWSER_CODE_ERROR, resultIntent);
}

Expand All @@ -342,6 +353,7 @@ private void cancelAuthorization() {
final Intent resultIntent = new Intent();
resultIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
sendResult(AuthenticationConstants.UIResponse.BROWSER_CODE_CANCEL, resultIntent);
Telemetry.emit(new UiEndEvent().isUserCancelled());
finish();
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,7 @@ public synchronized static Telemetry getInstance() {
return sTelemetryInstance;
}

TelemetryContext getTelemetryContext() {
public TelemetryContext getTelemetryContext() {
return mTelemetryContext;
}

Expand Down Expand Up @@ -239,6 +239,7 @@ public void flush(@NonNull final String correlationId) {
finalRawMap.add(applyPiiOiiRule(mTelemetryContext.getProperties()));

for (ITelemetryObserver observer : mObservers) {
//You can add more obersers by implementing the ITelemetryDefaultObserver interface.
if (observer instanceof ITelemetryAggregatedObserver) {
new TelemetryAggregationAdapter((ITelemetryAggregatedObserver)observer).process(finalRawMap);
} else if (observer instanceof ITelemetryDefaultObserver) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,9 +26,15 @@
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Build;
import android.provider.Settings;

import androidx.annotation.NonNull;

import com.microsoft.identity.common.adal.internal.util.StringExtensions;
import com.microsoft.identity.common.internal.logging.Logger;

import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;
import java.util.TimeZone;
import java.util.concurrent.ConcurrentHashMap;

Expand All @@ -53,7 +59,7 @@ public class TelemetryContext extends Properties {
static synchronized TelemetryContext create(final Context context) {
final TelemetryContext telemetryContext = new TelemetryContext(new ConcurrentHashMap<String, String>());
telemetryContext.addApplicationInfo(context);
telemetryContext.addDeviceInfo();
telemetryContext.addDeviceInfo(context);
telemetryContext.addOsInfo();
telemetryContext.put(Device.TIMEZONE, TimeZone.getDefault().getID());
return telemetryContext;
Expand All @@ -63,7 +69,7 @@ void addApplicationInfo(@NonNull final Context context) {
try {
final PackageManager packageManager = context.getPackageManager();
final PackageInfo packageInfo = packageManager.getPackageInfo(context.getPackageName(), 0);
put(App.NAME, packageInfo.applicationInfo.loadLabel(packageManager).toString());
put(App.NAME, packageInfo.applicationInfo.packageName);
put(App.VERSION, packageInfo.versionName);
put(App.BUILD, String.valueOf(packageInfo.versionCode));
} catch (final PackageManager.NameNotFoundException e) {
Expand All @@ -72,10 +78,23 @@ void addApplicationInfo(@NonNull final Context context) {
}
}

void addDeviceInfo() {
void addDeviceInfo(@NonNull final Context context) {
put(Device.MANUFACTURER, Build.MANUFACTURER);
put(Device.MODEL, Build.MODEL);
put(Device.NAME, Build.DEVICE);
try {
put(
Device.ID,
StringExtensions.createHash(
Settings.Secure.getString(
context.getContentResolver(),
Settings.Secure.ANDROID_ID
)
)
);
} catch (final NoSuchAlgorithmException | UnsupportedEncodingException exception) {
Logger.warn(TAG, "Unable to get the device id.");
}
}

void addOsInfo() {
Expand All @@ -86,4 +105,12 @@ void addOsInfo() {
put(Os.SECURITY_PATCH, Build.VERSION.SECURITY_PATCH);
}
}

public void isNetworkDisabledFromOptimizations(final boolean isDozed) {
put(Key.POWER_OPTIMIZATION, String.valueOf(isDozed));
}

public void isNetworkConnected(final boolean isConnected) {
put(Key.NETWORK_CONNECTION, String.valueOf(isConnected));
}
}
Loading

0 comments on commit 19bf142

Please sign in to comment.