~townsend/unity8-preview-lxc/fix-setup

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
#!/usr/bin/python3
# -*- coding: utf-8 -*-

# Copyright (C) 2013 Canonical Ltd.
# Author: Stéphane Graber <stgraber@ubuntu.com>

# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; version 3 of the License.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

import argparse
import glob
import lxc
import os
import stat
import shutil
import subprocess
import sys
import time
import platform

from distro_info import UbuntuDistroInfo, DistroDataOutdated

CONTAINER_NAME = "unity8-lxc"
SKIP_JOB = ["bluetooth", "lightdm", "plymouth", "plymouth-upstart-bridge",
            "plymouth-shutdown", "ubiquity"]


# Argument parsing
parser = argparse.ArgumentParser(description="Unity8 inside LXC")
parser.add_argument(
    "--rebuild-all", action="store_true",
    help=("Wipe and replace the container rootfs."))
parser.add_argument(
    "--rebuild-rootfs", action="store_true",
    help=("Wipe and replace the container rootfs."))
parser.add_argument(
    "--test", type=int, metavar="SECONDS", default=None,
    help=("Test mode, argument is time in seconds for the session."))
parser.add_argument(
    "--destroy", action="store_true",
    help=("Destroy any existing environment entirely."))
parser.add_argument(
    "--update-lxc", action="store_true",
    help=("Update the packages in the Unity 8 desktop preview LXC."))
args = parser.parse_args()

if os.geteuid():
    parser.error("This tool must be run as root.")


container = lxc.Container(CONTAINER_NAME)
container_path = "%s/%s" % (lxc.default_config_path, CONTAINER_NAME)
rootfs_path = "%s/rootfs" % container_path

(distro, version, codename) = platform.linux_distribution()

# Actions
generate_rootfs = True

def start_container(wait_for_network=True):
    if not container.running:
        print("Starting the container")
        if not container.start():
            parser.error("Unable to start the container.")
        container.wait("RUNNING")

    if wait_for_network and not container.get_ips(timeout=30):
        print("Not able to connect to the network.")
        sys.exit(0)

# Destroy a container entirely
if args.destroy and container.defined:
    container.stop()
    container.destroy()
    sys.exit(0)

# Deal with existing containers
if container.defined:
    generate_rootfs = False

    if not args.test and container.running:
        print("Stopping the existing container.")
        container.stop()

    if args.rebuild_all:
        args.rebuild_rootfs = True

    if args.rebuild_rootfs:
        print("Deleting current unity8-lxc container...")
        generate_rootfs = True
        container.destroy()
        del container
        container = lxc.Container(CONTAINER_NAME)
        #if os.path.exists(container_path):
        #    shutil.rmtree(container_path)

if not generate_rootfs and not args.test and not args.update_lxc:
    parser.error("The container already exists.")

if generate_rootfs:
    # Setup the container rootfs

    ## Figure out the host architecture
    dpkg = subprocess.Popen(['dpkg', '--print-architecture'],
                            stdout=subprocess.PIPE,
                            universal_newlines=True)
    if dpkg.wait() != 0:
        parser.error("Failed to determine the local architecture.")

    architecture = dpkg.stdout.read().strip()

    try:
        current_release = UbuntuDistroInfo().devel()
    except DistroDataOutdated:
        current_release = UbuntuDistroInfo().stable()

    print("Creating the new unity8-lxc container...")
    container.create("download", 0,
                     {"dist": "ubuntu",
                      "release": current_release,
                      "arch": architecture})

    ## Configure
    print("Configuring the Unity8 LXC...")

    ### Generate /etc/hostname
    with open(os.path.join(rootfs_path, "etc", "hostname"), "w+") as fd:
        fd.write("unity8-lxc\n")

    ### Generate /etc/hosts
    with open(os.path.join(rootfs_path, "etc", "hosts"), "w+") as fd:
        fd.write("""127.0.0.1   localhost
127.0.1.1   unity8-lxc

# The following lines are desirable for IPv6 capable hosts
::1     localhost ip6-localhost ip6-loopback
ff02::1 ip6-allnodes
ff02::2 ip6-allrouters
""")

    # Generate the package install policy override
    with open(os.path.join(rootfs_path, 'usr', 'sbin', 'policy-rc.d'), 'w+') as fd:
        fd.write("""#!/bin/sh
while true; do
case \"$1\" in
  -*) shift ;;
  makedev) exit 0;;
  *)  exit 101;;
esac
done
""")
        fd.close()

    os.chmod(os.path.join(rootfs_path, 'usr', 'sbin', 'policy-rc.d'), 0o755)

    start_container()

    # Copy the ubuntu-desktop-next metapackage to the rootfs
    lxc_archive = os.path.join(rootfs_path, 'tmp', 'ubuntu-desktop-next.deb')
    glob_name = "ubuntu-desktop-next_*_%s.deb" % architecture
    metapackage = glob.glob(os.path.join('/', 'usr', 'share', 'unity8-lxc', glob_name))
    shutil.copy(metapackage[0], lxc_archive)

    # Remove the default ubuntu user in the container
    container.attach_wait(lxc.attach_run_command,
                          ["userdel", "-r", "ubuntu"])

    container.attach_wait(lxc.attach_run_command,
                          ["apt-get", "update"])

    container.attach_wait(lxc.attach_run_command,
                          ["dpkg", "-i", os.path.join('/', 'tmp', 'ubuntu-desktop-next.deb')])
    container.attach_wait(lxc.attach_run_command,
                          ["apt-get", "install", "-f", "-y"])

    container.attach_wait(lxc.attach_run_command,
                          ["systemctl", "disable", "lightdm.service"]) 
    container.stop()

    # Disable some upstart jobs
    for job in glob.glob("%s/etc/init/*.conf" % rootfs_path):
        if os.path.basename(job).rsplit(".conf", 1)[0] in SKIP_JOB:
            with open("%s.override" % job.rsplit(".conf", 1)[0], "w+") as fd:
                fd.write("manual")

    with open(os.path.join(container_path, 'config'), 'a') as fd:
        fd.write("lxc.include = " + os.path.join('/', 'usr', 'share', 'unity8-lxc', 'unity8-lxc.conf'))
        fd.close()

if args.test:
    # Start a test session

    if not container.running:
        print("Starting the container")
        if not container.start():
            parser.error("Unable to start the container.")
        container.wait("RUNNING")

    # Retrieve the current VT number
    fgconsole = subprocess.Popen(['fgconsole'],
                                 stdout=subprocess.PIPE,
                                 universal_newlines=True)
    if fgconsole.wait() != 0:
        parser.error("Failed to get current VT number.")

    current_vt = fgconsole.stdout.read().strip()

    def start_unity8():
        ## Setup the environment
        os.environ['HOME'] = "/root"
        os.environ['QT_QPA_PLATFORM'] = "ubuntumirclient"
        os.environ['XDG_RUNTIME_DIR'] = "/run/user/0/"
        os.environ['DESKTOP_SESSION'] = "unity8-mir"
        os.environ['UBUNTU_PLATFORM_API_BACKEND'] = "desktop_mirserver"

        ## Reset the config
        for path in ("/root/.cache", "/root/.config", "/root/.local"):
            if os.path.exists(path):
                shutil.rmtree(path)

        ## Create runtime dir
        if not os.path.exists("/run/user/0"):
            os.makedirs("/run/user/0")

        ## Get the multiarch triplet
        gcc = subprocess.Popen(['gcc', '--print-multiarch'],
                               stdout=subprocess.PIPE,
                               universal_newlines=True)
        if gcc.wait() != 0:
            parser.error("Failed to determine the multiarch triplet.")

        triplet = gcc.stdout.read().strip()

        ## Run url-dispatcher
        dispatcher_path = "/usr/lib/%s/url-dispatcher/" \
                          "update-directory" % triplet

        subprocess.call([dispatcher_path, "/usr/share/url-dispatcher/urls/"])

        ## Start the session
        unity8 = subprocess.Popen(["openvt", "-s", "-f", "-w", "-c", "12",
                                   "--",
                                   "init", "--user"])
        time.sleep(args.test)
        unity8.kill()
        unity8.wait()

        ## Switch back to original VT
        subprocess.call(["chvt", current_vt])

    container.attach_wait(start_unity8)

    ## Stopping the container
    container.stop()

if args.update_lxc:
    # Update packages inside the LXC
    start_container()

    container.attach_wait(lxc.attach_run_command,
                          ["umount", "/etc/localtime"])

    container.attach_wait(lxc.attach_run_command,
                          ["umount", "/etc/timezone"])

    print("Updating packages inside the LXC...")
    container.attach_wait(lxc.attach_run_command,
                          ["apt-get", "update"])

    container.attach_wait(lxc.attach_run_command,
                          ["apt-get", "dist-upgrade", "-y"])

    ## Stopping the container
    container.stop()