1 /*
2  * Copyright (C) 2018 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 package com.android.tradefed.suite.checker;
17 
18 import com.android.ddmlib.Log.LogLevel;
19 import com.android.tradefed.device.DeviceNotAvailableException;
20 import com.android.tradefed.device.ITestDevice;
21 import com.android.tradefed.log.LogUtil.CLog;
22 import com.android.tradefed.suite.checker.StatusCheckerResult.CheckStatus;
23 import com.android.tradefed.util.TimeUtil;
24 
25 import java.util.Date;
26 
27 /** Status checker to ensure that the device and host time are kept in sync. */
28 public class TimeStatusChecker implements ISystemStatusChecker {
29 
30     private boolean mFailing = false;
31 
32     @Override
postExecutionCheck(ITestDevice device)33     public StatusCheckerResult postExecutionCheck(ITestDevice device)
34             throws DeviceNotAvailableException {
35         long difference = device.getDeviceTimeOffset(new Date());
36         if (difference > 5000L) {
37             String message =
38                     String.format(
39                             "Found a difference of '%s' between the host and device clock, "
40                                     + "resetting the device time.",
41                             TimeUtil.formatElapsedTime(difference));
42             CLog.w(message);
43             device.logOnDevice(
44                     "Tradefed.TimeStatusChecker",
45                     LogLevel.VERBOSE,
46                     "Module Checker is about to reset the time.");
47             device.setDate(new Date());
48             if (mFailing) {
49                 // Avoid capturing more bugreport if the issue continues to happen, only the first
50                 // module will capture it.
51                 CLog.w("TimeStatusChecker is still failing on %s", device.getSerialNumber());
52                 return new StatusCheckerResult(CheckStatus.SUCCESS);
53             }
54             StatusCheckerResult result = new StatusCheckerResult(CheckStatus.FAILED);
55             result.setErrorMessage(message);
56             mFailing = true;
57             return result;
58         }
59         mFailing = false;
60         return new StatusCheckerResult(CheckStatus.SUCCESS);
61     }
62 }
63