startop: Move compiled trace file installation after activity checking (bugfix).

Test: pytest run_app_with_prefetch_test.py
Test: python run_app_with_prefetch.py -p com.android.settings  -i input -d -r fadvise

Bug: 135286022
Change-Id: I06040bb10bfd8edf3f520576c4aed5a28587b142
diff --git a/startop/scripts/app_startup/lib/adb_utils.py b/startop/scripts/app_startup/lib/adb_utils.py
index 00e2e99..761dc2e 100644
--- a/startop/scripts/app_startup/lib/adb_utils.py
+++ b/startop/scripts/app_startup/lib/adb_utils.py
@@ -18,6 +18,7 @@
 
 import os
 import sys
+import time
 
 sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(
   os.path.abspath(__file__)))))
@@ -54,10 +55,13 @@
   cmd_utils.run_shell_command('adb wait-for-device')
 
 def pkill(procname: str):
-  """Kills a process in device by its package name."""
+  """Kills a process on device specified by the substring pattern in procname"""
   _, pids = cmd_utils.run_shell_command('adb shell ps | grep "{}" | '
                                         'awk \'{{print $2;}}\''.
                                           format(procname))
 
   for pid in pids.split('\n'):
-    cmd_utils.run_adb_shell_command('kill {}'.format(pid))
+    pid = pid.strip()
+    if pid:
+      passed,_ = cmd_utils.run_adb_shell_command('kill {}'.format(pid))
+      time.sleep(1)
diff --git a/startop/scripts/app_startup/run_app_with_prefetch.py b/startop/scripts/app_startup/run_app_with_prefetch.py
index 41cbb2a..df9f1f3 100644
--- a/startop/scripts/app_startup/run_app_with_prefetch.py
+++ b/startop/scripts/app_startup/run_app_with_prefetch.py
@@ -31,7 +31,6 @@
 import sys
 import time
 from typing import List, Tuple
-from pathlib import Path
 
 # local imports
 import lib.adb_utils as adb_utils
@@ -103,7 +102,17 @@
     print_utils.error_print('--input not specified!')
     return False
 
-  # Install necessary trace file.
+  if not opts.activity:
+    _, opts.activity = cmd_utils.run_shell_func(IORAP_COMMON_BASH_SCRIPT,
+                                                'get_activity_name',
+                                                [opts.package])
+
+  if not opts.activity:
+    print_utils.error_print('Activity name could not be found, '
+                              'invalid package name?!')
+    return False
+
+  # Install necessary trace file. This must be after the activity checking.
   if needs_trace_file:
     passed = iorapd_utils.iorapd_compiler_install_trace_file(
       opts.package, opts.activity, opts.input)
@@ -113,18 +122,6 @@
                                 format(opts.package, opts.activity))
       return False
 
-  if opts.activity is not None:
-    return True
-
-  _, opts.activity = cmd_utils.run_shell_func(IORAP_COMMON_BASH_SCRIPT,
-                                              'get_activity_name',
-                                              [opts.package])
-
-  if not opts.activity:
-    print_utils.error_print('Activity name could not be found, '
-                              'invalid package name?!')
-    return False
-
   return True
 
 def set_up_adb_env():
@@ -223,6 +220,9 @@
   print_utils.debug_print('=====             START              =====')
   print_utils.debug_print('==========================================')
 
+  # Kill any existing process of this app
+  adb_utils.pkill(package)
+
   if readahead != 'warm':
     print_utils.debug_print('Drop caches for non-warm start.')
     # Drop all caches to get cold starts.
diff --git a/startop/scripts/app_startup/run_app_with_prefetch_test.py b/startop/scripts/app_startup/run_app_with_prefetch_test.py
index 32c3911..a33d5d0 100644
--- a/startop/scripts/app_startup/run_app_with_prefetch_test.py
+++ b/startop/scripts/app_startup/run_app_with_prefetch_test.py
@@ -200,7 +200,7 @@
 
 def _mocked_run_shell_command(*args, **kwargs):
   if args[0] == 'adb shell "date -u +\'%Y-%m-%d %H:%M:%S.%N\'"':
-    return (True, "123:123")
+    return (True, "2019-07-02 23:20:06.972674825")
   elif args[0] == 'adb shell ps | grep "music" | awk \'{print $2;}\'':
     return (True, '9999')
   else:
@@ -217,7 +217,9 @@
             simulate=False,
             debug=False)
 
-    calls = [call('adb shell "date -u +\'%Y-%m-%d %H:%M:%S.%N\'"'),
+    calls = [call('adb shell ps | grep "music" | awk \'{print $2;}\''),
+             call('adb shell "kill 9999"'),
+             call('adb shell "date -u +\'%Y-%m-%d %H:%M:%S.%N\'"'),
              call(
                'timeout {timeout} "{DIR}/launch_application" "{package}" "{activity}" | '
                '"{DIR}/parse_metrics" --package {package} --activity {activity} '
@@ -226,7 +228,7 @@
                          DIR=run.DIR,
                          package='music',
                          activity='MainActivity',
-                         timestamp='123:123')),
+                         timestamp='2019-07-02 23:20:06.972674825')),
              call('adb shell ps | grep "music" | awk \'{print $2;}\''),
              call('adb shell "kill 9999"')]
     mock_run_shell_command.assert_has_calls(calls)
@@ -242,9 +244,11 @@
             simulate=False,
             debug=False)
 
-    calls = [call('adb shell "echo 3 > /proc/sys/vm/drop_caches"'),
+    calls = [call('adb shell ps | grep "music" | awk \'{print $2;}\''),
+             call('adb shell "kill 9999"'),
+             call('adb shell "echo 3 > /proc/sys/vm/drop_caches"'),
              call('bash -c "source {}; iorapd_readahead_enable"'.
-                    format(run.IORAP_COMMON_BASH_SCRIPT)),
+                  format(run.IORAP_COMMON_BASH_SCRIPT)),
              call('adb shell "date -u +\'%Y-%m-%d %H:%M:%S.%N\'"'),
              call(
                'timeout {timeout} "{DIR}/launch_application" "{package}" "{activity}" | '
@@ -254,7 +258,7 @@
                          DIR=run.DIR,
                          package='music',
                          activity='MainActivity',
-                         timestamp='123:123')),
+                         timestamp='2019-07-02 23:20:06.972674825')),
              call(
                'bash -c "source {script_path}; '
                'iorapd_readahead_wait_until_finished '
@@ -262,7 +266,7 @@
                  format(timeout=10,
                         package='music',
                         activity='MainActivity',
-                        timestamp='123:123',
+                        timestamp='2019-07-02 23:20:06.972674825',
                         script_path=run.IORAP_COMMON_BASH_SCRIPT)),
              call('bash -c "source {}; iorapd_readahead_disable"'.
                     format(run.IORAP_COMMON_BASH_SCRIPT)),