blob: c3cbad0f73834c8f6c0c6cd925ad2a495e8d1c57 [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_CF_COMMOM_FOLDER = "cf-common"
Sam Chiu81bdc652018-06-29 18:45:08 +080040_LIST_OF_MODULES = ["kvm_intel", "kvm"]
Kevin Chengf756bbd2018-10-11 13:50:00 -070041_UPDATE_APT_GET_CMD = "sudo apt-get update"
herbertxue975b8872020-02-12 14:41:41 +080042_INSTALL_CUTTLEFISH_COMMOM_CMD = [
43 "git clone https://github.com/google/android-cuttlefish.git {git_folder}",
44 "cd {git_folder}",
45 "yes | sudo mk-build-deps -i -r -B",
46 "dpkg-buildpackage -uc -us",
47 "sudo apt-get install -y -f ../cuttlefish-common_*_amd64.deb"]
chojoyce3c5ad5c2021-07-05 10:44:14 +080048_MKCERT_URL = "https://github.com/FiloSottile/mkcert"
49_MKCERT_VERSION = "v1.4.3"
50_MKCERT_INSTALL_PATH = os.path.join(os.path.expanduser("~"), ".config",
51 constants.TOOL_NAME, "mkcert")
52_MKCERT_CAROOT_CMD = "%s/mkcert -install" % _MKCERT_INSTALL_PATH
53_MKCERT_DOWNLOAD_CMD = ("wget -O %(mkcert_install_path)s/mkcert "
54 "%(mkcert_url)s/releases/download/"
55 "%(mkcert_ver)s/mkcert-%(mkcert_ver)s-linux-amd64" %
56 {"mkcert_install_path": _MKCERT_INSTALL_PATH,
57 "mkcert_url": _MKCERT_URL,
58 "mkcert_ver": _MKCERT_VERSION})
Sam Chiu81bdc652018-06-29 18:45:08 +080059
60
Kevin Chengeb997272019-06-05 14:53:18 -070061class BasePkgInstaller(base_task_runner.BaseTaskRunner):
62 """Subtask base runner class for installing packages."""
Sam Chiu81bdc652018-06-29 18:45:08 +080063
Kevin Chengeb997272019-06-05 14:53:18 -070064 # List of packages for child classes to override.
65 PACKAGES = []
Sam Chiu81bdc652018-06-29 18:45:08 +080066
67 def ShouldRun(self):
68 """Check if required packages are all installed.
69
70 Returns:
71 Boolean, True if required packages are not installed.
72 """
Sam Chiu6c738d62018-12-04 10:29:02 +080073 if not utils.IsSupportedPlatform():
Sam Chiu81bdc652018-06-29 18:45:08 +080074 return False
75
76 # Any required package is not installed or not up-to-date will need to
77 # run installation task.
Kevin Chengeb997272019-06-05 14:53:18 -070078 for pkg_name in self.PACKAGES:
Sam Chiu81bdc652018-06-29 18:45:08 +080079 if not setup_common.PackageInstalled(pkg_name):
80 return True
81
82 return False
83
84 def _Run(self):
Kevin Chengeb997272019-06-05 14:53:18 -070085 """Install specified packages."""
Sam Chiuaa703b62019-10-04 19:47:43 +080086 cmd = "\n".join(
87 [setup_common.PKG_INSTALL_CMD % pkg
88 for pkg in self.PACKAGES
89 if not setup_common.PackageInstalled(pkg)])
Sam Chiu81bdc652018-06-29 18:45:08 +080090
Sam Chiuaa703b62019-10-04 19:47:43 +080091 if not utils.GetUserAnswerYes("\nStart to install package(s):\n%s"
herbertxue97af4a62020-11-05 17:12:56 +080092 "\nEnter 'y' to continue, otherwise N or "
93 "enter to exit: " % cmd):
Sam Chiuaa703b62019-10-04 19:47:43 +080094 sys.exit(constants.EXIT_BY_USER)
Sam Chiu81bdc652018-06-29 18:45:08 +080095
Kevin Chengf756bbd2018-10-11 13:50:00 -070096 setup_common.CheckCmdOutput(_UPDATE_APT_GET_CMD, shell=True)
Kevin Chengeb997272019-06-05 14:53:18 -070097 for pkg in self.PACKAGES:
Sam Chiu81bdc652018-06-29 18:45:08 +080098 setup_common.InstallPackage(pkg)
99
Kevin Chengeb997272019-06-05 14:53:18 -0700100 logger.info("All package(s) installed now.")
101
102
103class AvdPkgInstaller(BasePkgInstaller):
104 """Subtask runner class for installing packages for local instances."""
105
106 WELCOME_MESSAGE_TITLE = ("Install required packages for host setup for "
107 "local instances")
108 WELCOME_MESSAGE = ("This step will walk you through the required packages "
109 "installation for running Android cuttlefish devices "
110 "on your host.")
chojoyce8faf8852021-07-12 12:26:28 +0800111 PACKAGES = constants.AVD_REQUIRED_PKGS
Kevin Chengeb997272019-06-05 14:53:18 -0700112
113
114class HostBasePkgInstaller(BasePkgInstaller):
115 """Subtask runner class for installing base host packages."""
116
117 WELCOME_MESSAGE_TITLE = "Install base packages on the host"
118 WELCOME_MESSAGE = ("This step will walk you through the base packages "
119 "installation for your host.")
chojoyce8faf8852021-07-12 12:26:28 +0800120 PACKAGES = constants.BASE_REQUIRED_PKGS
Sam Chiu81bdc652018-06-29 18:45:08 +0800121
122
herbertxue975b8872020-02-12 14:41:41 +0800123class CuttlefishCommonPkgInstaller(base_task_runner.BaseTaskRunner):
124 """Subtask base runner class for installing cuttlefish-common."""
125
126 WELCOME_MESSAGE_TITLE = "Install cuttlefish-common packages on the host"
127 WELCOME_MESSAGE = ("This step will walk you through the cuttlefish-common "
128 "packages installation for your host.")
129
130 def ShouldRun(self):
131 """Check if cuttlefish-common package is installed.
132
133 Returns:
134 Boolean, True if cuttlefish-common is not installed.
135 """
136 if not utils.IsSupportedPlatform():
137 return False
138
139 # Any required package is not installed or not up-to-date will need to
140 # run installation task.
chojoyce8faf8852021-07-12 12:26:28 +0800141 if not setup_common.PackageInstalled(constants.CUTTLEFISH_COMMOM_PKG):
herbertxue975b8872020-02-12 14:41:41 +0800142 return True
143 return False
144
145 def _Run(self):
146 """Install cuttlefilsh-common packages."""
147 cf_common_path = os.path.join(tempfile.mkdtemp(), _CF_COMMOM_FOLDER)
148 logger.debug("cuttlefish-common path: %s", cf_common_path)
149 cmd = "\n".join(sub_cmd.format(git_folder=cf_common_path)
150 for sub_cmd in _INSTALL_CUTTLEFISH_COMMOM_CMD)
151
152 if not utils.GetUserAnswerYes("\nStart to install cuttlefish-common :\n%s"
herbertxue97af4a62020-11-05 17:12:56 +0800153 "\nEnter 'y' to continue, otherwise N or "
154 "enter to exit: " % cmd):
herbertxue975b8872020-02-12 14:41:41 +0800155 sys.exit(constants.EXIT_BY_USER)
156 try:
157 setup_common.CheckCmdOutput(cmd, shell=True)
158 finally:
159 shutil.rmtree(os.path.dirname(cf_common_path))
160 logger.info("Cuttlefish-common package installed now.")
161
chojoyce3c5ad5c2021-07-05 10:44:14 +0800162class MkcertPkgInstaller(base_task_runner.BaseTaskRunner):
163 """Subtask base runner class for installing mkcert."""
164
165 WELCOME_MESSAGE_TITLE = "Install mkcert package on the host"
166 WELCOME_MESSAGE = ("This step will walk you through the mkcert "
167 "package installation to your host for "
168 "assuring a secure localhost url connection "
169 "when launching an AVD over webrtc")
170
171 def ShouldRun(self):
172 """Check if mkcert package is installed.
173
174 Returns:
175 Boolean, True if mkcert is not installed.
176 """
177 if not utils.IsSupportedPlatform():
178 return False
179
180 if not os.path.exists(os.path.join(_MKCERT_INSTALL_PATH, "mkcert")):
181 return True
182 return False
183
184 def _Run(self):
185 """Install mkcert packages."""
chojoyce3c5ad5c2021-07-05 10:44:14 +0800186 if not utils.GetUserAnswerYes("\nStart to install mkcert :\n%s"
187 "\nEnter 'y' to continue, otherwise N or "
chojoyce21b280f2021-09-13 13:53:22 +0800188 "enter to exit: " % _MKCERT_DOWNLOAD_CMD):
chojoyce3c5ad5c2021-07-05 10:44:14 +0800189 sys.exit(constants.EXIT_BY_USER)
190
chojoyce49e7cb92021-08-04 12:01:32 +0800191 if not os.path.isdir(_MKCERT_INSTALL_PATH):
192 os.mkdir(_MKCERT_INSTALL_PATH)
chojoyce21b280f2021-09-13 13:53:22 +0800193 setup_common.CheckCmdOutput(_MKCERT_DOWNLOAD_CMD, shell=True)
chojoyce3c5ad5c2021-07-05 10:44:14 +0800194 utils.SetExecutable(os.path.join(_MKCERT_INSTALL_PATH, "mkcert"))
195 utils.CheckOutput(_MKCERT_CAROOT_CMD, shell=True)
196 logger.info("Mkcert package is installed at \"%s\" now.",
197 _MKCERT_INSTALL_PATH)
herbertxue975b8872020-02-12 14:41:41 +0800198
Sam Chiu81bdc652018-06-29 18:45:08 +0800199class CuttlefishHostSetup(base_task_runner.BaseTaskRunner):
200 """Subtask class that setup host for cuttlefish."""
201
202 WELCOME_MESSAGE_TITLE = "Host Enviornment Setup"
203 WELCOME_MESSAGE = (
204 "This step will help you to setup enviornment for running Android "
205 "cuttlefish devices on your host. That includes adding user to kvm "
206 "related groups and checking required linux modules."
207 )
208
209 def ShouldRun(self):
210 """Check host user groups and modules.
211
212 Returns:
213 Boolean: False if user is in all required groups and all modules
214 are reloaded.
215 """
Sam Chiu6c738d62018-12-04 10:29:02 +0800216 if not utils.IsSupportedPlatform():
Sam Chiu81bdc652018-06-29 18:45:08 +0800217 return False
218
herbertxue07293a32018-11-05 20:40:11 +0800219 return not (utils.CheckUserInGroups(constants.LIST_CF_USER_GROUPS)
Sam Chiu81bdc652018-06-29 18:45:08 +0800220 and self._CheckLoadedModules(_LIST_OF_MODULES))
221
222 @staticmethod
Sam Chiu81bdc652018-06-29 18:45:08 +0800223 def _CheckLoadedModules(module_list):
224 """Check if the modules are all in use.
225
226 Args:
227 module_list: The list of module name.
228 Returns:
229 True if all modules are in use.
230 """
231 logger.info("Checking if modules are loaded: %s", module_list)
232 lsmod_output = setup_common.CheckCmdOutput("lsmod", print_cmd=False)
233 current_modules = [r.split()[0] for r in lsmod_output.splitlines()]
234 all_modules_present = True
235 for module in module_list:
236 if module not in current_modules:
237 logger.info("missing module: %s", module)
238 all_modules_present = False
239 return all_modules_present
240
241 def _Run(self):
242 """Setup host environment for local cuttlefish instance support."""
243 # TODO: provide --uid args to let user use prefered username
244 username = getpass.getuser()
245 setup_cmds = [
246 "sudo rmmod kvm_intel",
247 "sudo rmmod kvm",
248 "sudo modprobe kvm",
249 "sudo modprobe kvm_intel"]
Sam Chiuafbc6582018-09-04 20:47:13 +0800250 for group in constants.LIST_CF_USER_GROUPS:
Sam Chiu81bdc652018-06-29 18:45:08 +0800251 setup_cmds.append("sudo usermod -aG %s % s" % (group, username))
252
253 print("Below commands will be run:")
254 for setup_cmd in setup_cmds:
255 print(setup_cmd)
256
257 if self._ConfirmContinue():
258 for setup_cmd in setup_cmds:
259 setup_common.CheckCmdOutput(setup_cmd, shell=True)
260 print("Host environment setup has done!")
261
262 @staticmethod
263 def _ConfirmContinue():
264 """Ask user if they want to continue.
265
266 Returns:
267 True if user answer yes.
268 """
269 answer_client = utils.InteractWithQuestion(
herbertxue97af4a62020-11-05 17:12:56 +0800270 "\nEnter 'y' to continue, otherwise N or enter to exit: ",
Sam Chiu81bdc652018-06-29 18:45:08 +0800271 utils.TextColors.WARNING)
272 return answer_client in constants.USER_ANSWER_YES