מעקב אחר תקינות המערכת

השירות Watchdog עוקב אחרי התקינות של שירותי הספק ושל שירות VHAL, ומסיים כל תהליך לא תקין. כשמפסיקים תהליך לא תקין, Watchdog יוצר קובץ dump של סטטוס התהליך ב-/data/anr, כמו במקרים אחרים של קובצי dump של שגיאות מסוג 'האפליקציה לא מגיבה' (ANR). כך קל יותר לבצע את תהליך הניפוי באגים.

מעקב אחר תקינות השירות של ספקים

מתבצע מעקב אחרי שירותי הספק גם בצד המקורי וגם בצד Java. כדי לעקוב אחרי שירות של ספק, השירות צריך לרשום תהליך של בדיקת תקינות ב-Watchdog על ידי ציון של פסק זמן מוגדר מראש. השירות Watchdog עוקב אחרי תקינות התהליך של בדיקת תקינות שנרשם, על ידי שליחת פינגים במרווחים שנקבעו במהלך הרישום, בהתאם לזמן הקצוב לתפוגה. אם תהליך שבוצע לו פינג לא מגיב לפני שחלף הזמן הקצוב לתפוגה, התהליך נחשב כלא תקין.

מעקב מקורי אחרי תקינות השירות

ציון קובץ ה-makefile של Watchdog AIDL

  1. הוספת carwatchdog_aidl_interface-ndk_platform ל-shared_libs.

    Android.bp

    cc_binary {
        name: "sample_native_client",
        srcs: [
            "src/*.cpp"
        ],
        shared_libs: [
            "carwatchdog_aidl_interface-ndk_platform",
            "libbinder_ndk",
        ],
        vendor: true,
    }

הוספה של מדיניות SELinux

  1. כדי להוסיף מדיניות SELinux, מאפשרים לדומיין של שירות הספק להשתמש ב-binder ‏(binder_use מאקרו) ומוסיפים את הדומיין של שירות הספק לדומיין של הלקוח carwatchdog (carwatchdog_client_domain מאקרו). הקוד של sample_client.te ושל file_contexts מופיע בהמשך:

    sample_client.te

    type sample_client, domain;
    type sample_client_exec, exec_type, file_type, vendor_file_type;
    
    carwatchdog_client_domain(sample_client)
    
    init_daemon_domain(sample_client)
    binder_use(sample_client)

    file_contexts

    /vendor/bin/sample_native_client  u:object_r:sample_client_exec:s0

הטמעה של מחלקת לקוח באמצעות ירושה של BnCarWatchdogClient

  1. ב-checkIfAlive, מבצעים בדיקת תקינות. אפשרות אחת היא לפרסם ב-handler של לולאת השרשור. אם הסטרימינג תקין, אפשר להתקשר אל ICarWatchdog::tellClientAlive. הקוד של SampleNativeClient.h ושל SampleNativeClient.cpp מופיע בהמשך:

    SampleNativeClient.h

    class SampleNativeClient : public BnCarWatchdogClient {
    public:
        ndk::ScopedAStatus checkIfAlive(int32_t sessionId, TimeoutLength
            timeout) override;
        ndk::ScopedAStatus prepareProcessTermination() override;
        void initialize();
    
    private:
        void respondToDaemon();
    private:
        ::android::sp<::android::Looper> mHandlerLooper;
        std::shared_ptr<ICarWatchdog> mWatchdogServer;
        std::shared_ptr<ICarWatchdogClient> mClient;
        int32_t mSessionId;
    };

    SampleNativeClient.cpp

    ndk::ScopedAStatus WatchdogClient::checkIfAlive(int32_t sessionId, TimeoutLength timeout) {
        mHandlerLooper->removeMessages(mMessageHandler,
            WHAT_CHECK_ALIVE);
        mSessionId = sessionId;
        mHandlerLooper->sendMessage(mMessageHandler,
            Message(WHAT_CHECK_ALIVE));
        return ndk::ScopedAStatus::ok();
    }
    // WHAT_CHECK_ALIVE triggers respondToDaemon from thread handler
    void WatchdogClient::respondToDaemon() {
      // your health checking method here
      ndk::ScopedAStatus status = mWatchdogServer->tellClientAlive(mClient,
            mSessionId);
    }

התחלת שרשור ב-Binder ורישום הלקוח

שם הממשק של דמון הטיימר המפקח (watchdog) של המכונית הוא android.automotive.watchdog.ICarWatchdog/default.

  1. מחפשים את שירות ה-daemon עם השם ומתקשרים אל ICarWatchdog::registerClient. הקוד של main.cpp ושל SampleNativeClient.cpp מופיע בהמשך:

    main.cpp

    int main(int argc, char** argv) {
        sp<Looper> looper(Looper::prepare(/*opts=*/0));
    
        ABinderProcess_setThreadPoolMaxThreadCount(1);
        ABinderProcess_startThreadPool();
        std::shared_ptr<SampleNativeClient> client =
            ndk::SharedRefBase::make<SampleNatvieClient>(looper);
    
        // The client is registered in initialize()
        client->initialize();
        ...
    }

    SampleNativeClient.cpp

    void SampleNativeClient::initialize() {
        ndk::SpAIBinder binder(AServiceManager_getService(
            "android.automotive.watchdog.ICarWatchdog/default"));
        std::shared_ptr<ICarWatchdog> server =
            ICarWatchdog::fromBinder(binder);
        mWatchdogServer = server;
        ndk::SpAIBinder binder = this->asBinder();
        std::shared_ptr<ICarWatchdogClient> client =
            ICarWatchdogClient::fromBinder(binder)
        mClient = client;
        server->registerClient(client, TimeoutLength::TIMEOUT_NORMAL);
    }

מעקב אחר תקינות שירותים ב-Java

הטמעה של לקוח באמצעות ירושה של CarWatchdogClientCallback

  1. עורכים את הקובץ החדש באופן הבא:
    private final CarWatchdogClientCallback mClientCallback = new CarWatchdogClientCallback() {
        @Override
        public boolean onCheckHealthStatus(int sessionId, int timeout) {
            // Your health check logic here
            // Returning true implies the client is healthy
            // If false is returned, the client should call
            // CarWatchdogManager.tellClientAlive after health check is
            // completed
        }
    
        @Override
        public void onPrepareProcessTermination() {}
    };

רישום הלקוח

  1. חיוג אל CarWatchdogManager.registerClient():
    private void startClient() {
        CarWatchdogManager manager =
            (CarWatchdogManager) car.getCarManager(
            Car.CAR_WATCHDOG_SERVICE);
        // Choose a proper executor according to your health check method
        ExecutorService executor = Executors.newFixedThreadPool(1);
        manager.registerClient(executor, mClientCallback,
            CarWatchdogManager.TIMEOUT_NORMAL);
    }

ביטול הרישום של הלקוח

  1. התקשרות אל CarWatchdogManager.unregisterClient() בסיום השירות:
    private void finishClient() {
        CarWatchdogManager manager =
            (CarWatchdogManager) car.getCarManager(
            Car.CAR_WATCHDOG_SERVICE);
        manager.unregisterClient(mClientCallback);
    }

מעקב אחר תקינות VHAL

בניגוד למעקב אחר תקינות השירות של ספק, Watchdog עוקב אחר תקינות השירות של VHAL על ידי הרשמה לVHAL_HEARTBEAT מאפיין הרכב. הכלי Watchdog מצפה שהערך של המאפיין הזה יתעדכן פעם אחת כל N שניות. אם הדופק לא מתעדכן במהלך הזמן הקצוב הזה, Watchdog מפסיק את השירות VHAL.

הערה: Watchdog עוקב אחרי תקינות שירות VHAL רק אם שירות VHAL תומך במאפיין הרכב VHAL_HEARTBEAT.

ההטמעה הפנימית של VHAL יכולה להשתנות מספק לספק. אפשר להשתמש בדוגמאות הקוד הבאות כהפניות.

  1. רושמים את מאפיין הרכב VHAL_HEARTBEAT.

    כשמפעילים את שירות VHAL, צריך לרשום את VHAL_HEARTBEAT מאפיין הרכב. בדוגמה שלמטה, נעשה שימוש ב-unordered_map, שממפה את מזהה הנכס להגדרה, כדי להכיל את כל ההגדרות הנתמכות. ההגדרה של VHAL_HEARTBEAT נוספת למפה, כך שכאשר מתבצעת שאילתה לגבי VHAL_HEARTBEAT, ההגדרה המתאימה מוחזרת.

    void registerVhalHeartbeatProperty() {
            const VehiclePropConfig config = {
                    .prop = toInt(VehicleProperty::VHAL_HEARTBEAT),
                    .access = VehiclePropertyAccess::READ,
                    .changeMode = VehiclePropertyChangeMode::ON_CHANGE,
            };
           // mConfigsById is declared as std::unordered_map<int32_t, VehiclePropConfig>.
           mConfigsById[config.prop] = config;
    }
  2. עדכון של מאפיין רכב VHAL_HEARTBEAT.

    בהתאם לתדירות של בדיקת תקינות ה-VHAL (שמוסברת במאמר הגדרת התדירות של בדיקת תקינות ה-VHAL), צריך לעדכן את מאפיין הרכב VHAL_HEARTBEAT פעם אחת בכל N שניות. אחת הדרכים לעשות זאת היא באמצעות RecurrentTimer כדי להפעיל את הפעולה שבודקת את תקינות ה-VHAL ומעדכנת את מאפיין VHAL_HEARTBEAT vehicle בתוך הזמן הקצוב לתפוגה.

    למטה מוצגת הטמעה לדוגמה באמצעות RecurrentTimer:

    int main(int argc, char** argv) {
            RecurrentTimer recurrentTimer(updateVhalHeartbeat);
            recurrentTimer.registerRecurrentEvent(kHeartBeatIntervalNs,
                                               static_cast<int32_t>(VehicleProperty::VHAL_HEARTBEAT));
             Run service 
            recurrentTimer.unregisterRecurrentEvent(
                    static_cast<int32_t>(VehicleProperty::VHAL_HEARTBEAT));
    }
    
    void updateVhalHeartbeat(const std::vector<int32_t>& cookies) {
           for (int32_t property : cookies) {
                  if (property != static_cast<int32_t>(VehicleProperty::VHAL_HEARTBEAT)) {
                         continue;
                  }
    
                  // Perform internal health checking such as retrieving a vehicle property to ensure
                  // the service is responsive.
                  doHealthCheck();
    
                  // Construct the VHAL_HEARTBEAT property with system uptime.
                  VehiclePropValuePool valuePool;
                  VehicleHal::VehiclePropValuePtr propValuePtr = valuePool.obtainInt64(uptimeMillis());
                  propValuePtr->prop = static_cast<int32_t>(VehicleProperty::VHAL_HEARTBEAT);
                  propValuePtr->areaId = 0;
                  propValuePtr->status = VehiclePropertyStatus::AVAILABLE;
                  propValuePtr->timestamp = elapsedRealtimeNano();
    
                  // Propagate the HAL event.
                  onHalEvent(std::move(propValuePtr));
           }
    }
  3. (אופציונלי) מגדירים את התדירות של בדיקת תקינות VHAL.

    מאפיין המוצר ro.carwatchdog.vhal_healthcheck.interval לקריאה בלבד של Watchdog מגדיר את התדירות של בדיקת תקינות VHAL. ברירת המחדל של התדירות של בדיקת תקינות (כשהמאפיין הזה לא מוגדר) היא שלוש שניות. אם שלוש שניות לא מספיקות לשירות VHAL לעדכן את מאפיין הרכב VHAL_HEARTBEAT, צריך להגדיר את התדירות של בדיקת התקינות של VHAL בהתאם לזמן התגובה של השירות.

ניפוי באגים בתהליכים לא תקינים שהופסקו על ידי Watchdog

השירות Watchdog מבצע dump של מצב התהליך ומסיים תהליכים לא תקינים. כשמפסיקים תהליך לא תקין, Watchdog רושם את הטקסט carwatchdog terminated <process name> (pid:<process id>) ב-logcat. שורת היומן הזו מספקת מידע על התהליך שהופסק, כמו שם התהליך ומזהה התהליך.

  1. כדי לחפש את הטקסט שצוין ב-logcat, מריצים את הפקודה:
    $ adb logcat -s CarServiceHelper | fgrep "carwatchdog killed"

    לדוגמה, אם אפליקציית KitchenSink היא לקוח רשום של Watchdog והיא לא מגיבה לפינגים של Watchdog, ‏ Watchdog רושם ביומן שורה כמו השורה שמוצגת בהמשך כשהוא מסיים את התהליך הרשום של KitchenSink.

    05-01 09:50:19.683   578  5777 W CarServiceHelper: carwatchdog killed com.google.android.car.kitchensink (pid: 5574)
  2. כדי לזהות את הסיבה העיקרית לחוסר התגובה, משתמשים ב-process dump שמאוחסן ב-/data/anr בדיוק כמו שמשתמשים בו במקרים של פעילות ANR. כדי לאחזר את קובץ ה-dump של התהליך שהופסק, משתמשים בפקודות הבאות.
    $ adb root
    $ adb shell grep -Hn "pid process_pid" /data/anr/*

    הפלט לדוגמה הבא הוא ספציפי לאפליקציית KitchenSink:

    $ adb shell su root grep -Hn "pid 5574" /data/anr/*.
    /data/anr/anr_2020-05-01-09-50-18-290:3:----- pid 5574 at 2020-05-01 09:50:18 -----
    /data/anr/anr_2020-05-01-09-50-18-290:285:----- Waiting Channels: pid 5574 at 2020-05-01 09:50:18 -----

    קובץ ה-dump של תהליך KitchenSink שהופסק נמצא בנתיב /data/anr/anr_2020-05-01-09-50-18-290. מתחילים את הניתוח באמצעות קובץ ה-ANR dump של התהליך שהופסק.