aboutsummaryrefslogtreecommitdiff
path: root/list/instance.py
blob: 5b238357f3e84bc2316580642bd3cd707402d1ea (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
# Copyright 2018 - The Android Open Source Project
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
r"""Instance class.

Define the instance class used to hold details about an AVD instance.

The instance class will hold details about AVD instances (remote/local) used to
enable users to understand what instances they've created. This will be leveraged
for the list, delete, and reconnect commands.

The details include:
- instance name (for remote instances)
- creation date/instance duration
- instance image details (branch/target/build id)
- and more!
"""

import collections
import datetime
import json
import logging
import os
import re
import subprocess
import tempfile

# pylint: disable=import-error
import dateutil.parser
import dateutil.tz

from acloud.create import local_image_local_instance
from acloud.internal import constants
from acloud.internal.lib import cvd_runtime_config
from acloud.internal.lib import utils
from acloud.internal.lib.adb_tools import AdbTools
from acloud.internal.lib.local_instance_lock import LocalInstanceLock
from acloud.internal.lib.gcompute_client import GetInstanceIP


logger = logging.getLogger(__name__)

_ACLOUD_CVD_TEMP = os.path.join(tempfile.gettempdir(), "acloud_cvd_temp")
_CVD_CONFIG_FOLDER = "%(cvd_runtime)s/instances/cvd-%(id)d"
_CVD_LOG_FOLDER = _CVD_CONFIG_FOLDER + "/logs"
_CVD_RUNTIME_FOLDER_NAME = "cuttlefish_runtime"
_CVD_BIN = "cvd"
_CVD_BIN_FOLDER = "host_bins/bin"
_CVD_STATUS_BIN = "cvd_status"
_CVD_SERVER = "cvd_server"
_CVD_STOP_ERROR_KEYWORDS = "cvd_internal_stop E"
# Default timeout 30 secs for cvd commands.
_CVD_TIMEOUT = 30
_INSTANCE_ASSEMBLY_DIR = "cuttlefish_assembly"
_LOCAL_INSTANCE_NAME_FORMAT = "local-instance-%(id)d"
_LOCAL_INSTANCE_NAME_PATTERN = re.compile(r"^local-instance-(?P<id>\d+)$")
_ACLOUDWEB_INSTANCE_START_STRING = "cf-"
_MSG_UNABLE_TO_CALCULATE = "Unable to calculate"
_NO_ANDROID_ENV = "android source not available"
_RE_GROUP_ADB = "local_adb_port"
_RE_GROUP_VNC = "local_vnc_port"
_RE_SSH_TUNNEL_PATTERN = (r"((.*\s*-L\s)(?P<%s>\d+):127.0.0.1:%s)"
                          r"((.*\s*-L\s)(?P<%s>\d+):127.0.0.1:%s)"
                          r"(.+%s)")
_RE_TIMEZONE = re.compile(r"^(?P<time>[0-9\-\.:T]*)(?P<timezone>[+-]\d+:\d+)$")
_RE_DEVICE_INFO = re.compile(r"(?s).*(?P<device_info>[{][\s\w\W]+})")

_COMMAND_PS_LAUNCH_CVD = ["ps", "-wweo", "lstart,cmd"]
_RE_RUN_CVD = re.compile(r"(?P<date_str>^[^/]+)(.*run_cvd)")
_DISPLAY_STRING = "%(x_res)sx%(y_res)s (%(dpi)s)"
_RE_ZONE = re.compile(r".+/zones/(?P<zone>.+)$")
_LOCAL_ZONE = "local"
_FULL_NAME_STRING = ("device serial: %(device_serial)s (%(instance_name)s) "
                     "elapsed time: %(elapsed_time)s")
_INDENT = " " * 3
LocalPorts = collections.namedtuple("LocalPorts", [constants.VNC_PORT,
                                                   constants.ADB_PORT])


def GetDefaultCuttlefishConfig():
    """Get the path of default cuttlefish instance config.

    Return:
        String, path of cf runtime config.
    """
    cfg_path = os.path.join(os.path.expanduser("~"), _CVD_RUNTIME_FOLDER_NAME,
                            constants.CUTTLEFISH_CONFIG_FILE)
    if os.path.isfile(cfg_path):
        return cfg_path
    return None


def GetLocalInstanceName(local_instance_id):
    """Get local cuttlefish instance name by instance id.

    Args:
        local_instance_id: Integer of instance id.

    Return:
        String, the instance name.
    """
    return _LOCAL_INSTANCE_NAME_FORMAT % {"id": local_instance_id}


def GetLocalInstanceIdByName(name):
    """Get local cuttlefish instance id by name.

    Args:
        name: String of instance name.

    Return:
        The instance id as an integer if the name is in valid format.
        None if the name does not represent a local cuttlefish instance.
    """
    match = _LOCAL_INSTANCE_NAME_PATTERN.match(name)
    if match:
        return int(match.group("id"))
    return None


def GetLocalInstanceConfigPath(local_instance_id):
    """Get the path of instance config.

    Args:
        local_instance_id: Integer of instance id.

    Return:
        String, path of cf runtime config.
    """
    ins_assembly_dir = os.path.join(GetLocalInstanceHomeDir(local_instance_id),
                                    _INSTANCE_ASSEMBLY_DIR)
    return os.path.join(ins_assembly_dir, constants.CUTTLEFISH_CONFIG_FILE)


def GetLocalInstanceConfig(local_instance_id):
    """Get the path of existed config from local instance.

    Args:
        local_instance_id: Integer of instance id.

    Return:
        String, path of cf runtime config. None for config not exist.
    """
    cfg_path = GetLocalInstanceConfigPath(local_instance_id)
    if os.path.isfile(cfg_path):
        return cfg_path
    return None


def GetAllLocalInstanceConfigs():
    """Get all cuttlefish runtime configs from the known locations.

    Return:
        List of tuples. Each tuple consists of an instance id and a config
        path.
    """
    id_cfg_pairs = []
    # Check if any instance config is under home folder.
    cfg_path = GetDefaultCuttlefishConfig()
    if cfg_path:
        id_cfg_pairs.append((1, cfg_path))

    # Check if any instance config is under acloud cvd temp folder.
    if os.path.exists(_ACLOUD_CVD_TEMP):
        for ins_name in os.listdir(_ACLOUD_CVD_TEMP):
            ins_id = GetLocalInstanceIdByName(ins_name)
            if ins_id is not None:
                cfg_path = GetLocalInstanceConfig(ins_id)
                if cfg_path:
                    id_cfg_pairs.append((ins_id, cfg_path))
    return id_cfg_pairs


def GetLocalInstanceHomeDir(local_instance_id):
    """Get local instance home dir according to instance id.

    Args:
        local_instance_id: Integer of instance id.

    Return:
        String, path of instance home dir.
    """
    return os.path.join(_ACLOUD_CVD_TEMP,
                        GetLocalInstanceName(local_instance_id))


def GetLocalInstanceLock(local_instance_id):
    """Get local instance lock.

    Args:
        local_instance_id: Integer of instance id.

    Returns:
        LocalInstanceLock object.
    """
    file_path = os.path.join(_ACLOUD_CVD_TEMP,
                             GetLocalInstanceName(local_instance_id) + ".lock")
    return LocalInstanceLock(file_path)


def GetLocalInstanceRuntimeDir(local_instance_id):
    """Get instance runtime dir

    Args:
        local_instance_id: Integer of instance id.

    Return:
        String, path of instance runtime dir.
    """
    return os.path.join(GetLocalInstanceHomeDir(local_instance_id),
                        _CVD_RUNTIME_FOLDER_NAME)


def GetLocalInstanceLogDir(local_instance_id):
    """Get local instance log directory.

    Cuttlefish log directories are different between versions:

    In Android 10, the logs are in `<runtime_dir>`.

    In Android 11, the logs are in `<runtime_dir>.<id>`.
    `<runtime_dir>` is a symbolic link to `<runtime_dir>.<id>`.

    In the latest version, the logs are in
    `<runtime_dir>/instances/cvd-<id>/logs`.
    `<runtime_dir>_runtime` and `<runtime_dir>.<id>` are symbolic links to
    `<runtime_dir>/instances/cvd-<id>`.

    This method looks for `<runtime_dir>/instances/cvd-<id>/logs` which is the
    latest known location. If it doesn't exist, this method returns
    `<runtime_dir>` which is compatible with the old versions.

    Args:
        local_instance_id: Integer of instance id.

    Returns:
        The path to the log directory.
    """
    runtime_dir = GetLocalInstanceRuntimeDir(local_instance_id)
    log_dir = _CVD_LOG_FOLDER % {"cvd_runtime": runtime_dir,
                                 "id": local_instance_id}
    return log_dir if os.path.isdir(log_dir) else runtime_dir


def _GetCurrentLocalTime():
    """Return a datetime object for current time in local time zone."""
    return datetime.datetime.now(dateutil.tz.tzlocal())


def _GetElapsedTime(start_time):
    """Calculate the elapsed time from start_time till now.

    Args:
        start_time: String of instance created time.

    Returns:
        datetime.timedelta of elapsed time, _MSG_UNABLE_TO_CALCULATE for
        datetime can't parse cases.
    """
    match = _RE_TIMEZONE.match(start_time)
    try:
        # Check start_time has timezone or not. If timezone can't be found,
        # use local timezone to get elapsed time.
        if match:
            return _GetCurrentLocalTime() - dateutil.parser.parse(start_time)

        return _GetCurrentLocalTime() - dateutil.parser.parse(
            start_time).replace(tzinfo=dateutil.tz.tzlocal())
    except ValueError:
        logger.debug(("Can't parse datetime string(%s)."), start_time)
        return _MSG_UNABLE_TO_CALCULATE

def _IsProcessRunning(process):
    """Check if this process is running.

    Returns:
        Boolean, True for this process is running.
    """
    match_pattern = re.compile(f"(.+)({process} )(.+)")
    process_output = utils.CheckOutput(constants.COMMAND_PS)
    for line in process_output.splitlines():
        process_match = match_pattern.match(line)
        if process_match:
            return True
    return False


# pylint: disable=useless-object-inheritance
class Instance(object):
    """Class to store data of instance."""

    # pylint: disable=too-many-locals
    def __init__(self, name, fullname, display, ip, status=None, adb_port=None,
                 vnc_port=None, ssh_tunnel_is_connected=None, createtime=None,
                 elapsed_time=None, avd_type=None, avd_flavor=None,
                 is_local=False, device_information=None, zone=None,
                 webrtc_port=None, webrtc_forward_port=None):
        self._name = name
        self._fullname = fullname
        self._status = status
        self._display = display  # Resolution and dpi
        self._ip = ip
        self._adb_port = adb_port  # adb port which is forwarding to remote
        self._vnc_port = vnc_port  # vnc port which is forwarding to remote
        self._webrtc_port = webrtc_port
        self._webrtc_forward_port = webrtc_forward_port
        # True if ssh tunnel is still connected
        self._ssh_tunnel_is_connected = ssh_tunnel_is_connected
        self._createtime = createtime
        self._elapsed_time = elapsed_time
        self._avd_type = avd_type
        self._avd_flavor = avd_flavor
        self._is_local = is_local  # True if this is a local instance
        self._device_information = device_information
        self._zone = zone
        self._autoconnect = self._GetAutoConnect()

    def __repr__(self):
        """Return full name property for print."""
        return self._fullname

    def Summary(self):
        """Let's make it easy to see what this class is holding."""
        representation = []
        representation.append(" name: %s" % self._name)
        representation.append("%s IP: %s" % (_INDENT, self._ip))
        representation.append("%s create time: %s" % (_INDENT, self._createtime))
        representation.append("%s elapse time: %s" % (_INDENT, self._elapsed_time))
        representation.append("%s status: %s" % (_INDENT, self._status))
        representation.append("%s avd type: %s" % (_INDENT, self._avd_type))
        representation.append("%s display: %s" % (_INDENT, self._display))
        representation.append("%s vnc: 127.0.0.1:%s" % (_INDENT, self._vnc_port))
        representation.append("%s zone: %s" % (_INDENT, self._zone))
        representation.append("%s autoconnect: %s" % (_INDENT, self._autoconnect))
        representation.append("%s webrtc port: %s" % (_INDENT, self._webrtc_port))
        representation.append("%s webrtc forward port: %s" %
                              (_INDENT, self._webrtc_forward_port))

        if self._adb_port and self._device_information:
            serial_ip = self._ip if self._ip == "0.0.0.0" else "127.0.0.1"
            representation.append("%s adb serial: %s:%s" %
                                  (_INDENT, serial_ip, self._adb_port))
            representation.append("%s product: %s" % (
                _INDENT, self._device_information["product"]))
            representation.append("%s model: %s" % (
                _INDENT, self._device_information["model"]))
            representation.append("%s device: %s" % (
                _INDENT, self._device_information["device"]))
            representation.append("%s transport_id: %s" % (
                _INDENT, self._device_information["transport_id"]))
        else:
            representation.append("%s adb serial: disconnected" % _INDENT)

        return "\n".join(representation)

    def AdbConnected(self):
        """Check AVD adb connected.

        Returns:
            Boolean, True when adb status of AVD is connected.
        """
        if self._adb_port and self._device_information:
            return True
        return False

    def _GetAutoConnect(self):
        """Get the autoconnect of instance.

        Returns:
            String of autoconnect type. None for no autoconnect.
        """
        if self._webrtc_port or self._webrtc_forward_port:
            return constants.INS_KEY_WEBRTC
        if self._vnc_port:
            return constants.INS_KEY_VNC
        if self._adb_port:
            return constants.INS_KEY_ADB
        return None

    @property
    def name(self):
        """Return the instance name."""
        return self._name

    @property
    def fullname(self):
        """Return the instance full name."""
        return self._fullname

    @property
    def ip(self):
        """Return the ip."""
        return self._ip

    @property
    def status(self):
        """Return status."""
        return self._status

    @property
    def display(self):
        """Return display."""
        return self._display

    @property
    def ssh_tunnel_is_connected(self):
        """Return the connect status."""
        return self._ssh_tunnel_is_connected

    @property
    def createtime(self):
        """Return create time."""
        return self._createtime

    @property
    def avd_type(self):
        """Return avd_type."""
        return self._avd_type

    @property
    def avd_flavor(self):
        """Return avd_flavor."""
        return self._avd_flavor

    @property
    def islocal(self):
        """Return if it is a local instance."""
        return self._is_local

    @property
    def adb_port(self):
        """Return adb_port."""
        return self._adb_port

    @property
    def vnc_port(self):
        """Return vnc_port."""
        return self._vnc_port

    @property
    def webrtc_port(self):
        """Return webrtc_port."""
        return self._webrtc_port

    @property
    def webrtc_forward_port(self):
        """Return webrtc_forward_port."""
        return self._webrtc_forward_port

    @property
    def zone(self):
        """Return zone."""
        return self._zone

    @property
    def autoconnect(self):
        """Return autoconnect."""
        return self._autoconnect


class LocalInstance(Instance):
    """Class to store data of local cuttlefish instance."""
    def __init__(self, cf_config_path):
        """Initialize a localInstance object.

        Args:
            cf_config_path: String, path to the cf runtime config.
        """
        self._cf_runtime_cfg = cvd_runtime_config.CvdRuntimeConfig(cf_config_path)
        self._instance_dir = self._cf_runtime_cfg.instance_dir
        self._virtual_disk_paths = self._cf_runtime_cfg.virtual_disk_paths
        self._local_instance_id = int(self._cf_runtime_cfg.instance_id)
        display = _DISPLAY_STRING % {"x_res": self._cf_runtime_cfg.x_res,
                                     "y_res": self._cf_runtime_cfg.y_res,
                                     "dpi": self._cf_runtime_cfg.dpi}
        # TODO(143063678), there's no createtime info in
        # cuttlefish_config.json so far.
        name = GetLocalInstanceName(self._local_instance_id)
        fullname = (_FULL_NAME_STRING %
                    {"device_serial": "0.0.0.0:%s" % self._cf_runtime_cfg.adb_port,
                     "instance_name": name,
                     "elapsed_time": None})
        adb_device = AdbTools(device_serial="0.0.0.0:%s" % self._cf_runtime_cfg.adb_port)
        webrtc_port = local_image_local_instance.LocalImageLocalInstance.GetWebrtcSigServerPort(
            self._local_instance_id)
        cvd_fleet_info = self.GetDevidInfoFromCvdFleet()
        if cvd_fleet_info:
            display = cvd_fleet_info.get("displays")

        device_information = None
        if adb_device.IsAdbConnected():
            device_information = adb_device.device_information

        super().__init__(
            name=name, fullname=fullname, display=display, ip="0.0.0.0",
            status=constants.INS_STATUS_RUNNING,
            adb_port=self._cf_runtime_cfg.adb_port,
            vnc_port=self._cf_runtime_cfg.vnc_port,
            createtime=None, elapsed_time=None, avd_type=constants.TYPE_CF,
            is_local=True, device_information=device_information,
            zone=_LOCAL_ZONE, webrtc_port=webrtc_port)

    def Summary(self):
        """Return the string that this class is holding."""
        instance_home = "%s instance home: %s" % (_INDENT, self._instance_dir)
        return "%s\n%s" % (super().Summary(), instance_home)

    def _GetCvdEnv(self):
        """Get the environment to run cvd commands.

        Returns:
            os.environ with cuttlefish variables updated.
        """
        cvd_env = os.environ.copy()
        cvd_env[constants.ENV_ANDROID_SOONG_HOST_OUT] = os.path.dirname(
            self._cf_runtime_cfg.cvd_tools_path)
        cvd_env[constants.ENV_CUTTLEFISH_CONFIG_FILE] = self._cf_runtime_cfg.config_path
        cvd_env[constants.ENV_CVD_HOME] = GetLocalInstanceHomeDir(self._local_instance_id)
        cvd_env[constants.ENV_CUTTLEFISH_INSTANCE] = str(self._local_instance_id)
        return cvd_env

    def GetDevidInfoFromCvdFleet(self):
        """Get device information from 'cvd fleet'.

        Execute 'cvd fleet' cmd to get device information.

        Returns
            Output of 'cvd fleet'. None for fail to run 'cvd fleet'.
        """
        ins_home_dir = GetLocalInstanceHomeDir(self._local_instance_id)
        try:
            cvd_tool = os.path.join(ins_home_dir, _CVD_BIN_FOLDER, _CVD_BIN)
            cvd_fleet_cmd = f"{cvd_tool} fleet"
            if not os.path.exists(cvd_tool):
                logger.warning("Cvd tools path doesn't exist:%s", cvd_tool)
                return None
            if not _IsProcessRunning(_CVD_SERVER):
                logger.warning("The %s is not active.", _CVD_SERVER)
                return None
            logger.debug("Running cmd [%s] to get device info.", cvd_fleet_cmd)
            process = subprocess.Popen(cvd_fleet_cmd, shell=True, text=True,
                                       env=self._GetCvdEnv(),
                                       stdout=subprocess.PIPE,
                                       stderr=subprocess.PIPE)
            stdout, _ = process.communicate(timeout=_CVD_TIMEOUT)
            logger.debug("Output of cvd fleet: %s", stdout)
            return json.loads(self._ParsingCvdFleetOutput(stdout))
        except (subprocess.CalledProcessError, subprocess.TimeoutExpired,
                json.JSONDecodeError) as error:
            logger.error("Failed to run 'cvd fleet': %s", str(error))
            return None

    @staticmethod
    def _ParsingCvdFleetOutput(output):
        """Parsing the output of cvd fleet.

        The output example:
            WARNING: cvd_server client version (8245608) does not match.
            {
                "adb_serial" : "0.0.0.0:6520",
                "assembly_dir" : "/home/cuttlefish_runtime/assembly",
                "displays" : ["720 x 1280 ( 320 )"],
                "instance_dir" : "/home/cuttlefish_runtime/instances/cvd-1",
                "instance_name" : "cvd-1",
                "status" : "Running",
                "web_access" : "https://0.0.0.0:8443/client.html?deviceId=cvd-1",
                "webrtc_port" : "8443"
            }

        Returns:
            Parsed output filtered warning message.
        """
        device_match = _RE_DEVICE_INFO.match(output)
        if device_match:
            return device_match.group("device_info")
        return ""

    def CvdStatus(self):
        """check if local instance is active.

        Execute cvd_status cmd to check if it exit without error.

        Returns
            True if instance is active.
        """
        if not self._cf_runtime_cfg.cvd_tools_path:
            logger.debug("No cvd tools path found from config:%s",
                         self._cf_runtime_cfg.config_path)
            return False
        try:
            cvd_status_cmd = os.path.join(self._cf_runtime_cfg.cvd_tools_path,
                                          _CVD_STATUS_BIN)
            # TODO(b/150575261): Change the cvd home and cvd artifact path to
            #  another place instead of /tmp to prevent from the file not
            #  found exception.
            if not os.path.exists(cvd_status_cmd):
                logger.warning("Cvd tools path doesn't exist:%s", cvd_status_cmd)
                for env_host_out in [constants.ENV_ANDROID_SOONG_HOST_OUT,
                                     constants.ENV_ANDROID_HOST_OUT]:
                    if os.environ.get(env_host_out, _NO_ANDROID_ENV) in cvd_status_cmd:
                        logger.warning(
                            "Can't find the cvd_status tool (Try lunching a "
                            "cuttlefish target like aosp_cf_x86_64_phone-userdebug "
                            "and running 'make hosttar' before list/delete local "
                            "instances)")
                return False
            logger.debug("Running cmd[%s] to check cvd status.", cvd_status_cmd)
            process = subprocess.Popen(cvd_status_cmd,
                                       stdin=None,
                                       stdout=subprocess.PIPE,
                                       stderr=subprocess.STDOUT,
                                       env=self._GetCvdEnv())
            stdout, _ = process.communicate()
            if process.returncode != 0:
                if stdout:
                    logger.debug("Local instance[%s] is not active: %s",
                                 self.name, stdout.strip())
                return False
            return True
        except subprocess.CalledProcessError as cpe:
            logger.error("Failed to run cvd_status: %s", cpe.output)
            return False

    def Delete(self):
        """Execute "cvd stop" to stop local cuttlefish instance.

        - We should get the same host tool used to delete instance.
        - Add CUTTLEFISH_CONFIG_FILE env variable to tell cvd which cvd need to
          be deleted.
        - Stop adb since local instance use the fixed adb port and could be
         reused again soon.
        """
        ins_home_dir = GetLocalInstanceHomeDir(self._local_instance_id)
        cvd_tool = os.path.join(ins_home_dir, _CVD_BIN_FOLDER, _CVD_BIN)
        stop_cvd_cmd = f"{cvd_tool} stop"
        logger.debug("Running cmd[%s] to delete local cvd", stop_cvd_cmd)
        if not self.instance_dir:
            logger.error("instance_dir is null!! instance[%d] might not be"
                         " deleted", self._local_instance_id)
        try:
            output = subprocess.check_output(
                utils.AddUserGroupsToCmd(stop_cvd_cmd,
                                         constants.LIST_CF_USER_GROUPS),
                stderr=subprocess.STDOUT, shell=True, env=self._GetCvdEnv(),
                text=True, timeout=_CVD_TIMEOUT)
            # TODO: Remove workaround of stop_cvd when 'cvd stop' is stable.
            if _CVD_STOP_ERROR_KEYWORDS in output:
                logger.debug("Fail to stop cvd: %s", output)
                self._ExecuteStopCvd(os.path.join(ins_home_dir, _CVD_BIN_FOLDER))
        except (subprocess.TimeoutExpired, subprocess.CalledProcessError) as e:
            logger.debug("'cvd stop' error: %s", str(e))
            self._ExecuteStopCvd(os.path.join(ins_home_dir, _CVD_BIN_FOLDER))

        adb_cmd = AdbTools(self.adb_port)
        # When relaunch a local instance, we need to pass in retry=True to make
        # sure adb device is completely gone since it will use the same adb port
        adb_cmd.DisconnectAdb(retry=True)

    def _ExecuteStopCvd(self, dir_path):
        """Execute "stop_cvd" to stop local cuttlefish instance.

        Args:
            bin_dir: String, directory path of "stop_cvd".
        """
        stop_cvd_cmd = os.path.join(dir_path, constants.CMD_STOP_CVD)
        subprocess.check_call(
            utils.AddUserGroupsToCmd(
                stop_cvd_cmd, constants.LIST_CF_USER_GROUPS),
            stderr=subprocess.STDOUT, shell=True, env=self._GetCvdEnv())

    def GetLock(self):
        """Return the LocalInstanceLock for this object."""
        return GetLocalInstanceLock(self._local_instance_id)

    @property
    def instance_dir(self):
        """Return _instance_dir."""
        return self._instance_dir

    @property
    def instance_id(self):
        """Return _local_instance_id."""
        return self._local_instance_id

    @property
    def virtual_disk_paths(self):
        """Return virtual_disk_paths"""
        return self._virtual_disk_paths

    @property
    def cf_runtime_cfg(self):
        """Return _cf_runtime_cfg"""
        return self._cf_runtime_cfg


class LocalGoldfishInstance(Instance):
    """Class to store data of local goldfish instance.

    A goldfish instance binds to a console port and an adb port. The console
    port is for `adb emu` to send emulator-specific commands. The adb port is
    for `adb connect` to start a TCP connection. By convention, the console
    port is an even number, and the adb port is the console port + 1. The first
    instance uses port 5554 and 5555, the second instance uses 5556 and 5557,
    and so on.
    """

    _INSTANCE_NAME_PATTERN = re.compile(
        r"^local-goldfish-instance-(?P<id>\d+)$")
    _INSTANCE_NAME_FORMAT = "local-goldfish-instance-%(id)s"
    _EMULATOR_DEFAULT_CONSOLE_PORT = 5554
    _DEFAULT_ADB_LOCAL_TRANSPORT_MAX_PORT = 5585
    _DEVICE_SERIAL_FORMAT = "emulator-%(console_port)s"
    _DEVICE_SERIAL_PATTERN = re.compile(r"^emulator-(?P<console_port>\d+)$")

    def __init__(self, local_instance_id, avd_flavor=None, create_time=None,
                 x_res=None, y_res=None, dpi=None):
        """Initialize a LocalGoldfishInstance object.

        Args:
            local_instance_id: Integer of instance id.
            avd_flavor: String, the flavor of the virtual device.
            create_time: String, the creation date and time.
            x_res: Integer of x dimension.
            y_res: Integer of y dimension.
            dpi: Integer of dpi.
        """
        self._id = local_instance_id
        adb_port = self.console_port + 1
        self._adb = AdbTools(adb_port=adb_port,
                             device_serial=self.device_serial)

        name = self._INSTANCE_NAME_FORMAT % {"id": local_instance_id}

        elapsed_time = _GetElapsedTime(create_time) if create_time else None

        fullname = _FULL_NAME_STRING % {"device_serial": self.device_serial,
                                        "instance_name": name,
                                        "elapsed_time": elapsed_time}

        if x_res and y_res and dpi:
            display = _DISPLAY_STRING % {"x_res": x_res, "y_res": y_res,
                                         "dpi": dpi}
        else:
            display = "unknown"

        device_information = (self._adb.device_information if
                              self._adb.device_information else None)

        super().__init__(
            name=name, fullname=fullname, display=display, ip="127.0.0.1",
            status=None, adb_port=adb_port, avd_type=constants.TYPE_GF,
            createtime=create_time, elapsed_time=elapsed_time,
            avd_flavor=avd_flavor, is_local=True,
            device_information=device_information)

    @staticmethod
    def _GetInstanceDirRoot():
        """Return the root directory of all instance directories."""
        return os.path.join(tempfile.gettempdir(), "acloud_gf_temp")

    @property
    def adb(self):
        """Return the AdbTools to send emulator commands to this instance."""
        return self._adb

    @property
    def console_port(self):
        """Return the console port as an integer."""
        # Emulator requires the console port to be an even number.
        return self._EMULATOR_DEFAULT_CONSOLE_PORT + (self._id - 1) * 2

    @property
    def device_serial(self):
        """Return the serial number that contains the console port."""
        return self._DEVICE_SERIAL_FORMAT % {"console_port": self.console_port}

    @property
    def instance_dir(self):
        """Return the path to instance directory."""
        return os.path.join(self._GetInstanceDirRoot(),
                            self._INSTANCE_NAME_FORMAT % {"id": self._id})

    @classmethod
    def GetIdByName(cls, name):
        """Get id by name.

        Args:
            name: String of instance name.

        Return:
            The instance id as an integer if the name is in valid format.
            None if the name does not represent a local goldfish instance.
        """
        match = cls._INSTANCE_NAME_PATTERN.match(name)
        if match:
            return int(match.group("id"))
        return None

    @classmethod
    def GetLockById(cls, instance_id):
        """Get LocalInstanceLock by id."""
        lock_path = os.path.join(
            cls._GetInstanceDirRoot(),
            (cls._INSTANCE_NAME_FORMAT % {"id": instance_id}) + ".lock")
        return LocalInstanceLock(lock_path)

    def GetLock(self):
        """Return the LocalInstanceLock for this object."""
        return self.GetLockById(self._id)

    @classmethod
    def GetExistingInstances(cls):
        """Get the list of instances that adb can send emu commands to."""
        instances = []
        for serial in AdbTools.GetDeviceSerials():
            match = cls._DEVICE_SERIAL_PATTERN.match(serial)
            if not match:
                continue
            port = int(match.group("console_port"))
            instance_id = (port - cls._EMULATOR_DEFAULT_CONSOLE_PORT) // 2 + 1
            instances.append(LocalGoldfishInstance(instance_id))
        return instances

    @classmethod
    def GetMaxNumberOfInstances(cls):
        """Get number of emulators that adb can detect."""
        max_port = os.environ.get("ADB_LOCAL_TRANSPORT_MAX_PORT",
                                  cls._DEFAULT_ADB_LOCAL_TRANSPORT_MAX_PORT)
        try:
            max_port = int(max_port)
        except ValueError:
            max_port = cls._DEFAULT_ADB_LOCAL_TRANSPORT_MAX_PORT
        if (max_port < cls._EMULATOR_DEFAULT_CONSOLE_PORT or
                max_port > constants.MAX_PORT):
            max_port = cls._DEFAULT_ADB_LOCAL_TRANSPORT_MAX_PORT
        return (max_port + 1 - cls._EMULATOR_DEFAULT_CONSOLE_PORT) // 2


class RemoteInstance(Instance):
    """Class to store data of remote instance."""

    # pylint: disable=too-many-locals
    def __init__(self, gce_instance):
        """Process the args into class vars.

        RemoteInstace initialized by gce dict object. We parse the required data
        from gce_instance to local variables.
        Reference:
        https://cloud.google.com/compute/docs/reference/rest/v1/instances/get

        We also gather more details on client side including the forwarding adb
        port and vnc port which will be used to determine the status of ssh
        tunnel connection.

        The status of gce instance will be displayed in _fullname property:
        - Connected: If gce instance and ssh tunnel and adb connection are all
         active.
        - No connected: If ssh tunnel or adb connection is not found.
        - Terminated: If we can't retrieve the public ip from gce instance.

        Args:
            gce_instance: dict object queried from gce.
        """
        name = gce_instance.get(constants.INS_KEY_NAME)

        create_time = gce_instance.get(constants.INS_KEY_CREATETIME)
        elapsed_time = _GetElapsedTime(create_time)
        status = gce_instance.get(constants.INS_KEY_STATUS)
        zone = self._GetZoneName(gce_instance.get(constants.INS_KEY_ZONE))

        instance_ip = GetInstanceIP(gce_instance)
        ip = instance_ip.external or instance_ip.internal

        # Get metadata, webrtc_port will be removed if "cvd fleet" show it.
        display = None
        avd_type = None
        avd_flavor = None
        webrtc_port = None
        for metadata in gce_instance.get("metadata", {}).get("items", []):
            key = metadata["key"]
            value = metadata["value"]
            if key == constants.INS_KEY_DISPLAY:
                display = value
            elif key == constants.INS_KEY_AVD_TYPE:
                avd_type = value
            elif key == constants.INS_KEY_AVD_FLAVOR:
                avd_flavor = value
            elif key == constants.INS_KEY_WEBRTC_PORT:
                webrtc_port = value
        # TODO(176884236): Insert avd information into metadata of instance.
        if not avd_type and name.startswith(_ACLOUDWEB_INSTANCE_START_STRING):
            avd_type = constants.TYPE_CF

        # Find ssl tunnel info.
        adb_port = None
        vnc_port = None
        webrtc_forward_port = None
        device_information = None
        if ip:
            forwarded_ports = self.GetAdbVncPortFromSSHTunnel(ip, avd_type)
            adb_port = forwarded_ports.adb_port
            vnc_port = forwarded_ports.vnc_port
            ssh_tunnel_is_connected = adb_port is not None
            webrtc_forward_port = utils.GetWebrtcPortFromSSHTunnel(ip)

            adb_device = AdbTools(adb_port)
            if adb_device.IsAdbConnected():
                device_information = adb_device.device_information
                fullname = (_FULL_NAME_STRING %
                            {"device_serial": "127.0.0.1:%d" % adb_port,
                             "instance_name": name,
                             "elapsed_time": elapsed_time})
            else:
                fullname = (_FULL_NAME_STRING %
                            {"device_serial": "not connected",
                             "instance_name": name,
                             "elapsed_time": elapsed_time})
        # If instance is terminated, its ip is None.
        else:
            ssh_tunnel_is_connected = False
            fullname = (_FULL_NAME_STRING %
                        {"device_serial": "terminated",
                         "instance_name": name,
                         "elapsed_time": elapsed_time})

        super().__init__(
            name=name, fullname=fullname, display=display, ip=ip, status=status,
            adb_port=adb_port, vnc_port=vnc_port,
            ssh_tunnel_is_connected=ssh_tunnel_is_connected,
            createtime=create_time, elapsed_time=elapsed_time, avd_type=avd_type,
            avd_flavor=avd_flavor, is_local=False,
            device_information=device_information,
            zone=zone, webrtc_port=webrtc_port,
            webrtc_forward_port=webrtc_forward_port)

    @staticmethod
    def _GetZoneName(zone_info):
        """Get the zone name from the zone information of gce instance.

        Zone information is like:
        "https://www.googleapis.com/compute/v1/projects/project/zones/us-central1-c"
        We want to get "us-central1-c" as zone name.

        Args:
            zone_info: String, zone information of gce instance.

        Returns:
            Zone name of gce instance. None if zone name can't find.
        """
        zone_match = _RE_ZONE.match(zone_info)
        if zone_match:
            return zone_match.group("zone")

        logger.debug("Can't get zone name from %s.", zone_info)
        return None

    @staticmethod
    def GetAdbVncPortFromSSHTunnel(ip, avd_type):
        """Get forwarding adb and vnc port from ssh tunnel.

        Args:
            ip: String, ip address.
            avd_type: String, the AVD type.

        Returns:
            NamedTuple ForwardedPorts(vnc_port, adb_port) holding the ports
            used in the ssh forwarded call. Both fields are integers.
        """
        if avd_type not in utils.AVD_PORT_DICT:
            return utils.ForwardedPorts(vnc_port=None, adb_port=None)

        default_vnc_port = utils.AVD_PORT_DICT[avd_type].vnc_port
        default_adb_port = utils.AVD_PORT_DICT[avd_type].adb_port
        # TODO(165888525): Align the SSH tunnel for the order of adb port and
        # vnc port.
        re_pattern = re.compile(_RE_SSH_TUNNEL_PATTERN %
                                (_RE_GROUP_ADB, default_adb_port,
                                 _RE_GROUP_VNC, default_vnc_port, ip))
        adb_port = None
        vnc_port = None
        process_output = utils.CheckOutput(constants.COMMAND_PS)
        for line in process_output.splitlines():
            match = re_pattern.match(line)
            if match:
                adb_port = int(match.group(_RE_GROUP_ADB))
                vnc_port = int(match.group(_RE_GROUP_VNC))
                break

        logger.debug(("gathering detail for ssh tunnel. "
                      "IP:%s, forwarding (adb:%s, vnc:%s)"), ip, adb_port,
                     vnc_port)

        return utils.ForwardedPorts(vnc_port=vnc_port, adb_port=adb_port)