blob: b1c1e144ecfe5cd941fd46cffd410ffbecb4e87a [file] [log] [blame]
Sam Chiu81bdc652018-06-29 18:45:08 +08001#!/usr/bin/env python
2#
3# Copyright 2018 - The Android Open Source Project
4#
5# Licensed under the Apache License, Version 2.0 (the "License");
6# you may not use this file except in compliance with the License.
7# You may obtain a copy of the License at
8#
9# http://www.apache.org/licenses/LICENSE-2.0
10#
11# Unless required by applicable law or agreed to in writing, software
12# distributed under the License is distributed on an "AS IS" BASIS,
13# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14# See the License for the specific language governing permissions and
15# limitations under the License.
16r"""host setup runner
17
18A setup sub task runner to support setting up the local host for AVD local
19instance.
20"""
21
22from __future__ import print_function
23
24import getpass
Sam Chiu81bdc652018-06-29 18:45:08 +080025import logging
herbertxue975b8872020-02-12 14:41:41 +080026import os
27import shutil
Sam Chiuaa703b62019-10-04 19:47:43 +080028import sys
herbertxue975b8872020-02-12 14:41:41 +080029import tempfile
Sam Chiu81bdc652018-06-29 18:45:08 +080030
31from acloud.internal import constants
32from acloud.internal.lib import utils
33from acloud.setup import base_task_runner
34from acloud.setup import setup_common
35
herbertxue1512f8a2019-06-27 13:56:23 +080036
Sam Chiu81bdc652018-06-29 18:45:08 +080037logger = logging.getLogger(__name__)
38
herbertxue975b8872020-02-12 14:41:41 +080039# Packages "devscripts" and "equivs" are required for "mk-build-deps".
40_AVD_REQUIRED_PKGS = [
41 "devscripts", "equivs", "libvirt-clients", "libvirt-daemon-system"]
CY Lan7faf3b52020-06-16 03:12:58 +000042_BASE_REQUIRED_PKGS = ["ssvnc", "lzop", "python3-tk"]
herbertxue975b8872020-02-12 14:41:41 +080043_CUTTLEFISH_COMMOM_PKG = "cuttlefish-common"
44_CF_COMMOM_FOLDER = "cf-common"
Sam Chiu81bdc652018-06-29 18:45:08 +080045_LIST_OF_MODULES = ["kvm_intel", "kvm"]
Kevin Chengf756bbd2018-10-11 13:50:00 -070046_UPDATE_APT_GET_CMD = "sudo apt-get update"
herbertxue975b8872020-02-12 14:41:41 +080047_INSTALL_CUTTLEFISH_COMMOM_CMD = [
48 "git clone https://github.com/google/android-cuttlefish.git {git_folder}",
49 "cd {git_folder}",
50 "yes | sudo mk-build-deps -i -r -B",
51 "dpkg-buildpackage -uc -us",
52 "sudo apt-get install -y -f ../cuttlefish-common_*_amd64.deb"]
chojoyce3c5ad5c2021-07-05 10:44:14 +080053_MKCERT_URL = "https://github.com/FiloSottile/mkcert"
54_MKCERT_VERSION = "v1.4.3"
55_MKCERT_INSTALL_PATH = os.path.join(os.path.expanduser("~"), ".config",
56 constants.TOOL_NAME, "mkcert")
57_MKCERT_CAROOT_CMD = "%s/mkcert -install" % _MKCERT_INSTALL_PATH
58_MKCERT_DOWNLOAD_CMD = ("wget -O %(mkcert_install_path)s/mkcert "
59 "%(mkcert_url)s/releases/download/"
60 "%(mkcert_ver)s/mkcert-%(mkcert_ver)s-linux-amd64" %
61 {"mkcert_install_path": _MKCERT_INSTALL_PATH,
62 "mkcert_url": _MKCERT_URL,
63 "mkcert_ver": _MKCERT_VERSION})
Sam Chiu81bdc652018-06-29 18:45:08 +080064
65
Kevin Chengeb997272019-06-05 14:53:18 -070066class BasePkgInstaller(base_task_runner.BaseTaskRunner):
67 """Subtask base runner class for installing packages."""
Sam Chiu81bdc652018-06-29 18:45:08 +080068
Kevin Chengeb997272019-06-05 14:53:18 -070069 # List of packages for child classes to override.
70 PACKAGES = []
Sam Chiu81bdc652018-06-29 18:45:08 +080071
72 def ShouldRun(self):
73 """Check if required packages are all installed.
74
75 Returns:
76 Boolean, True if required packages are not installed.
77 """
Sam Chiu6c738d62018-12-04 10:29:02 +080078 if not utils.IsSupportedPlatform():
Sam Chiu81bdc652018-06-29 18:45:08 +080079 return False
80
81 # Any required package is not installed or not up-to-date will need to
82 # run installation task.
Kevin Chengeb997272019-06-05 14:53:18 -070083 for pkg_name in self.PACKAGES:
Sam Chiu81bdc652018-06-29 18:45:08 +080084 if not setup_common.PackageInstalled(pkg_name):
85 return True
86
87 return False
88
89 def _Run(self):
Kevin Chengeb997272019-06-05 14:53:18 -070090 """Install specified packages."""
Sam Chiuaa703b62019-10-04 19:47:43 +080091 cmd = "\n".join(
92 [setup_common.PKG_INSTALL_CMD % pkg
93 for pkg in self.PACKAGES
94 if not setup_common.PackageInstalled(pkg)])
Sam Chiu81bdc652018-06-29 18:45:08 +080095
Sam Chiuaa703b62019-10-04 19:47:43 +080096 if not utils.GetUserAnswerYes("\nStart to install package(s):\n%s"
herbertxue97af4a62020-11-05 17:12:56 +080097 "\nEnter 'y' to continue, otherwise N or "
98 "enter to exit: " % cmd):
Sam Chiuaa703b62019-10-04 19:47:43 +080099 sys.exit(constants.EXIT_BY_USER)
Sam Chiu81bdc652018-06-29 18:45:08 +0800100
Kevin Chengf756bbd2018-10-11 13:50:00 -0700101 setup_common.CheckCmdOutput(_UPDATE_APT_GET_CMD, shell=True)
Kevin Chengeb997272019-06-05 14:53:18 -0700102 for pkg in self.PACKAGES:
Sam Chiu81bdc652018-06-29 18:45:08 +0800103 setup_common.InstallPackage(pkg)
104
Kevin Chengeb997272019-06-05 14:53:18 -0700105 logger.info("All package(s) installed now.")
106
107
108class AvdPkgInstaller(BasePkgInstaller):
109 """Subtask runner class for installing packages for local instances."""
110
111 WELCOME_MESSAGE_TITLE = ("Install required packages for host setup for "
112 "local instances")
113 WELCOME_MESSAGE = ("This step will walk you through the required packages "
114 "installation for running Android cuttlefish devices "
115 "on your host.")
116 PACKAGES = _AVD_REQUIRED_PKGS
117
118
119class HostBasePkgInstaller(BasePkgInstaller):
120 """Subtask runner class for installing base host packages."""
121
122 WELCOME_MESSAGE_TITLE = "Install base packages on the host"
123 WELCOME_MESSAGE = ("This step will walk you through the base packages "
124 "installation for your host.")
125 PACKAGES = _BASE_REQUIRED_PKGS
Sam Chiu81bdc652018-06-29 18:45:08 +0800126
127
herbertxue975b8872020-02-12 14:41:41 +0800128class CuttlefishCommonPkgInstaller(base_task_runner.BaseTaskRunner):
129 """Subtask base runner class for installing cuttlefish-common."""
130
131 WELCOME_MESSAGE_TITLE = "Install cuttlefish-common packages on the host"
132 WELCOME_MESSAGE = ("This step will walk you through the cuttlefish-common "
133 "packages installation for your host.")
134
135 def ShouldRun(self):
136 """Check if cuttlefish-common package is installed.
137
138 Returns:
139 Boolean, True if cuttlefish-common is not installed.
140 """
141 if not utils.IsSupportedPlatform():
142 return False
143
144 # Any required package is not installed or not up-to-date will need to
145 # run installation task.
146 if not setup_common.PackageInstalled(_CUTTLEFISH_COMMOM_PKG):
147 return True
148 return False
149
150 def _Run(self):
151 """Install cuttlefilsh-common packages."""
152 cf_common_path = os.path.join(tempfile.mkdtemp(), _CF_COMMOM_FOLDER)
153 logger.debug("cuttlefish-common path: %s", cf_common_path)
154 cmd = "\n".join(sub_cmd.format(git_folder=cf_common_path)
155 for sub_cmd in _INSTALL_CUTTLEFISH_COMMOM_CMD)
156
157 if not utils.GetUserAnswerYes("\nStart to install cuttlefish-common :\n%s"
herbertxue97af4a62020-11-05 17:12:56 +0800158 "\nEnter 'y' to continue, otherwise N or "
159 "enter to exit: " % cmd):
herbertxue975b8872020-02-12 14:41:41 +0800160 sys.exit(constants.EXIT_BY_USER)
161 try:
162 setup_common.CheckCmdOutput(cmd, shell=True)
163 finally:
164 shutil.rmtree(os.path.dirname(cf_common_path))
165 logger.info("Cuttlefish-common package installed now.")
166
chojoyce3c5ad5c2021-07-05 10:44:14 +0800167class MkcertPkgInstaller(base_task_runner.BaseTaskRunner):
168 """Subtask base runner class for installing mkcert."""
169
170 WELCOME_MESSAGE_TITLE = "Install mkcert package on the host"
171 WELCOME_MESSAGE = ("This step will walk you through the mkcert "
172 "package installation to your host for "
173 "assuring a secure localhost url connection "
174 "when launching an AVD over webrtc")
175
176 def ShouldRun(self):
177 """Check if mkcert package is installed.
178
179 Returns:
180 Boolean, True if mkcert is not installed.
181 """
182 if not utils.IsSupportedPlatform():
183 return False
184
185 if not os.path.exists(os.path.join(_MKCERT_INSTALL_PATH, "mkcert")):
186 return True
187 return False
188
189 def _Run(self):
190 """Install mkcert packages."""
chojoyce3c5ad5c2021-07-05 10:44:14 +0800191 if not utils.GetUserAnswerYes("\nStart to install mkcert :\n%s"
192 "\nEnter 'y' to continue, otherwise N or "
chojoyce21b280f2021-09-13 13:53:22 +0800193 "enter to exit: " % _MKCERT_DOWNLOAD_CMD):
chojoyce3c5ad5c2021-07-05 10:44:14 +0800194 sys.exit(constants.EXIT_BY_USER)
195
chojoyce49e7cb92021-08-04 12:01:32 +0800196 if not os.path.isdir(_MKCERT_INSTALL_PATH):
197 os.mkdir(_MKCERT_INSTALL_PATH)
chojoyce21b280f2021-09-13 13:53:22 +0800198 setup_common.CheckCmdOutput(_MKCERT_DOWNLOAD_CMD, shell=True)
chojoyce3c5ad5c2021-07-05 10:44:14 +0800199 utils.SetExecutable(os.path.join(_MKCERT_INSTALL_PATH, "mkcert"))
200 utils.CheckOutput(_MKCERT_CAROOT_CMD, shell=True)
201 logger.info("Mkcert package is installed at \"%s\" now.",
202 _MKCERT_INSTALL_PATH)
herbertxue975b8872020-02-12 14:41:41 +0800203
Sam Chiu81bdc652018-06-29 18:45:08 +0800204class CuttlefishHostSetup(base_task_runner.BaseTaskRunner):
205 """Subtask class that setup host for cuttlefish."""
206
207 WELCOME_MESSAGE_TITLE = "Host Enviornment Setup"
208 WELCOME_MESSAGE = (
209 "This step will help you to setup enviornment for running Android "
210 "cuttlefish devices on your host. That includes adding user to kvm "
211 "related groups and checking required linux modules."
212 )
213
214 def ShouldRun(self):
215 """Check host user groups and modules.
216
217 Returns:
218 Boolean: False if user is in all required groups and all modules
219 are reloaded.
220 """
Sam Chiu6c738d62018-12-04 10:29:02 +0800221 if not utils.IsSupportedPlatform():
Sam Chiu81bdc652018-06-29 18:45:08 +0800222 return False
223
herbertxue07293a32018-11-05 20:40:11 +0800224 return not (utils.CheckUserInGroups(constants.LIST_CF_USER_GROUPS)
Sam Chiu81bdc652018-06-29 18:45:08 +0800225 and self._CheckLoadedModules(_LIST_OF_MODULES))
226
227 @staticmethod
Sam Chiu81bdc652018-06-29 18:45:08 +0800228 def _CheckLoadedModules(module_list):
229 """Check if the modules are all in use.
230
231 Args:
232 module_list: The list of module name.
233 Returns:
234 True if all modules are in use.
235 """
236 logger.info("Checking if modules are loaded: %s", module_list)
237 lsmod_output = setup_common.CheckCmdOutput("lsmod", print_cmd=False)
238 current_modules = [r.split()[0] for r in lsmod_output.splitlines()]
239 all_modules_present = True
240 for module in module_list:
241 if module not in current_modules:
242 logger.info("missing module: %s", module)
243 all_modules_present = False
244 return all_modules_present
245
246 def _Run(self):
247 """Setup host environment for local cuttlefish instance support."""
248 # TODO: provide --uid args to let user use prefered username
249 username = getpass.getuser()
250 setup_cmds = [
251 "sudo rmmod kvm_intel",
252 "sudo rmmod kvm",
253 "sudo modprobe kvm",
254 "sudo modprobe kvm_intel"]
Sam Chiuafbc6582018-09-04 20:47:13 +0800255 for group in constants.LIST_CF_USER_GROUPS:
Sam Chiu81bdc652018-06-29 18:45:08 +0800256 setup_cmds.append("sudo usermod -aG %s % s" % (group, username))
257
258 print("Below commands will be run:")
259 for setup_cmd in setup_cmds:
260 print(setup_cmd)
261
262 if self._ConfirmContinue():
263 for setup_cmd in setup_cmds:
264 setup_common.CheckCmdOutput(setup_cmd, shell=True)
265 print("Host environment setup has done!")
266
267 @staticmethod
268 def _ConfirmContinue():
269 """Ask user if they want to continue.
270
271 Returns:
272 True if user answer yes.
273 """
274 answer_client = utils.InteractWithQuestion(
herbertxue97af4a62020-11-05 17:12:56 +0800275 "\nEnter 'y' to continue, otherwise N or enter to exit: ",
Sam Chiu81bdc652018-06-29 18:45:08 +0800276 utils.TextColors.WARNING)
277 return answer_client in constants.USER_ANSWER_YES