Canonical Voices

facundo

Atahualpa el filósofo


El otro día estaba en un bar, durante la PyCon Argentina, la tele decía algo de "Urgente" y no recuerdo qué boludez pasaban como contenido. Yo le comenté a alguien al lado mío de qué mal usados eran esos "urgente" o "importante" en los noticieros o canales de noticias/chismes.

Y el otro día justo estaba viendo un programa sobre Atahualpa Yupanqui con Felipe (en Encuentro, "El filósofo") y Don Atahualpa se manda la siguiente frase, tan linda y tan a tono, que osé transcribirla acá.

Atahualpa Yupanqui

Ahora tenemos la televisión, la radio; ahora nos traen una noticia rápidamente, lo que está pasando en Oriente, lo que está pasando en todo el mundo. Al segundo lo sabemos, al minuto lo sabemos.

Lo que no sabemos es cuantos poetas escribieron un poema, ayer y antes de ayer, y el domingo antes de la tormenta, o el viernes después que anocheció.

Ninguna revista, ningún diario nos dice "En Villa Dolores ha salido un poeta; en Buenos Aires, en Arrecife hay un nuevo poema de Fulano; Fulana ha escrito este hermoso poema, acá va señores", enseñándonos como los argentinos pronuncian la poesía o la literatura a través de sus desvelos, de sus impaciencias, de esa locura divina que los hace afirmarse en su continente.

No tenemos. Tenemos sí la noticia de la guerra que viene, de la que se prepara, del discurso que viene, del que se prepara.

¿Y lo otro?

¿Y lo de adentro?

Read more
abeato

As part of the ongoing effort we are doing in Canonical to snappify the world, we are trying to make available more and more software as easily-installable, secure, snaps. One of the things snapd does to isolate applications is to install snaps in separate folders in /snap/<mysnap>, and also creating $HOME/snap/<mysnap> for storing the snap data. Unfortunately, this changes where many applications expects data files to be as per the usual Unix conventions.

Solving this usually implies maintaining patches that change the file paths. If the $SNAP environment variable is set, the patches use it to find files in the right locations. However, this is cumbersome as upstreams are not always willing to accept the patches, at least until snap package format gets more popular. Also, in some cases we might be interested in snappifying proprietary software, where patches are not an option.

To solve these problems, Michael Terry created a library that uses the LD_PRELOAD trick to intercept calls to glibc. Although the library works really well, it has the disadvantage of not working in all cases, like on programs that perform syscalls directly without using the C library, or on statically compiled binaries.

In this post, I have explored an alternative to using LD_PRELOAD that would solve these issues by going to a lower level and intercepting syscalls using the ptrace syscall.

ptrace is used by programs like gdb or strace for debugging purposes. It is a swiss knife tool that lets us access a process’ memory and registers (the tracee) from another process (the tracer). There are many good tutorials around that explain how to use it, like this or this (from which I have borrowed parts of the code), so here I will focus on how it can be used to modify arbitrary syscall arguments. The concrete problem I had at hand was how to change a call to, say, open() so it ends up opening a file in a different path to the one originally specified by the tracee.

I have developed a proof of concept for this that can be found in github. The code is specific to x86_64, although the concepts behind are applicable to other architectures. As a word of caution, I have preferred to not do as many checks as I should to have cleaner code, so please do not consider it production-ready. I will go now through the code, function by function. Skipping the include directives and the forward declarations we get to main():

int main(int argc, char **argv)
{
    pid_t pid;
    int status;

    if (argc < 2) {
        fprintf(stderr, "Usage: %s <prog> <arg1> ... <argN>\n", argv[0]);
        return 1;
    }

    if ((pid = fork()) == 0) {
        ptrace(PTRACE_TRACEME, 0, 0, 0);
        kill(getpid(), SIGSTOP);
        return execvp(argv[1], argv + 1);
    } else {
        waitpid(pid, &status, 0);
        ptrace(PTRACE_SETOPTIONS, pid, 0, PTRACE_O_TRACESYSGOOD);
        process_signals(pid);
        return 0;
    }
}

Here we do all the usual stuff needed when we want to trace a process from the start: we call fork(), then the child executes ptrace() with request PTRACE_TRACEME to indicate that it is willing to be traced. After that, it sends itself a SIGSTOP signal, which makes it stop (the execve call1 will be performed later). At that point, the parent process, which was waiting for a signal from the child, re-starts. The first thing it does is setting ptrace option PTRACE_O_TRACESYSGOOD, which makes the kernel set bit 7 in the signal numbers so we can easily distinguish between system call traps and normal traps. After that, it calls process_signal(), which is defined as

static void process_signals(pid_t child)
{
    const char *file_to_redirect = "ONE.txt";
    const char *file_to_avoid = "TWO.txt";

    while(1) {
        char orig_file[PATH_MAX];

        /* Wait for open syscall start */
        if (wait_for_open(child) != 0) break;

        /* Find out file and re-direct if it is the target */

        read_file(child, orig_file);

        if (strcmp(file_to_avoid, orig_file) == 0)
            redirect_file(child, file_to_redirect);

        /* Wait for open syscall exit */
        if (wait_for_open(child) != 0) break;
    }
}

This function is the main loop of the tracer. It waits for the open() syscall from the child to be started, and for it to exit (ptrace signals us both events) by calling wait_for_open(). When an open() call is detected, we read the file that the child wants to open in read_file(), and then we compare with string “TWO.txt”. If there is a match, we change the syscall arguments so “ONE.txt” is opened instead. Next we analyze the different functions that perform the low level stuff, and that contain architecture specific parts:

static int wait_for_open(pid_t child)
{
    int status;

    while (1) {
        ptrace(PTRACE_SYSCALL, child, 0, 0);
        waitpid(child, &status, 0);
        /* Is it the open syscall (sycall number 2 in x86_64)? */
        if (WIFSTOPPED(status) && WSTOPSIG(status) & 0x80 &&
            ptrace(PTRACE_PEEKUSER, child, sizeof(long)*ORIG_RAX, 0) == 2)
            return 0;
        if (WIFEXITED(status))
            return 1;
    }
}

wait_for_open() is executed until an open() system call is detected. By calling ptrace with argument PTRACE_SYSCALL, we let the child continue until the next signal or syscall enter/exit. The first time this happens the child, which was stopped after sending itself SIGSTOP, continues its execution and calls execve(). The parent then waits for signals from the child. If the child has stopped due to the signal, the signal number has the 7th bit set (should happen if the signal was triggered due to a syscall as we have set PTRACE_O_TRACESYSGOOD option), and it is the open() syscall (system call number 2 for x86_64), then we return with status 0. If the child has actually exited, the return value is 1. If nothing of this happens, we wait for the next signal. Here we are using PTRACE_PEEKUSER request, which lets us access the tracee user area. This area contains an array with the general purpose registers, and we use offsets defined in <sys/reg.h> to access them. When performing a syscall, RAX register contains the syscall number. However, we use ORIG_RAX offset to grab that number instead of the also existing RAX offset. We do this because RAX is also used to store the return value for the syscall, so the kernel stores the syscall number with offset ORIG_RAX and the return value with offset RAX. This needs to be taking into account especially when processing the exit of the system call. More information can be found here.

Next function is

static void read_file(pid_t child, char *file)
{
    char *child_addr;
    int i;

    child_addr = (char *) ptrace(PTRACE_PEEKUSER, child, sizeof(long)*RDI, 0);

    do {
        long val;
        char *p;

        val = ptrace(PTRACE_PEEKTEXT, child, child_addr, NULL);
        if (val == -1) {
            fprintf(stderr, "PTRACE_PEEKTEXT error: %s", strerror(errno));
            exit(1);
        }
        child_addr += sizeof (long);

        p = (char *) &val;
        for (i = 0; i < sizeof (long); ++i, ++file) {
            *file = *p++;
            if (*file == '\0') break;
        }
    } while (i == sizeof (long));
}

The read_file() function uses PTRACE_PEEKUSER as in the previous function to retrieve the first argument to the call function, which is the address of the string with the file name. This parameter is stored in the RDI register. Then it uses PTRACE_PEEKTEXT ptrace request, which lets us copy over data from the traced process’ memory. This is performed by words, so we do this in a loop until we find a null byte that indicates the end of the string.

The last function is

static void redirect_file(pid_t child, const char *file)
{
    char *stack_addr, *file_addr;

    stack_addr = (char *) ptrace(PTRACE_PEEKUSER, child, sizeof(long)*RSP, 0);
    /* Move further of red zone and make sure we have space for the file name */
    stack_addr -= 128 + PATH_MAX;
    file_addr = stack_addr;

    /* Write new file in lower part of the stack */
    do {
        int i;
        char val[sizeof (long)];

        for (i = 0; i < sizeof (long); ++i, ++file) {
            val[i] = *file;
            if (*file == '\0') break;
        }

        ptrace(PTRACE_POKETEXT, child, stack_addr, *(long *) val);
        stack_addr += sizeof (long);
    } while (*file);

    /* Change argument to open */
    ptrace(PTRACE_POKEUSER, child, sizeof(long)*RDI, file_addr);
}

The redirect_file() function is the most interesting one of this program. It modifies the argument to the open system call, forcing the child to open a different file to the one it originally specified. The main problem with this is that we need to modify the child’s memory space so the new file name is used by the kernel. We can change the tracee’s memory easily by using PTRACE_POKETEXT, the issue is, where can we store it?

A possible option is to save the original string using PTRACE_PEEKTEXT, then overwrite it by using PTRACE_POKETEXT. When we get called after the sycall exits, we copy back the original data. This can work fine in some cases, but it can be problematic if the new file name is longer than the original. We could be overwriting data that is used by other threads, which are not necessarily stopped so they could access that data while the kernel is processing the call. Or that data we are overwriting could be part of another parameter to the syscall, which would not happen for open(), but it is possible for other syscalls like link(). Finally, there is also the possibility that the string we are trying to modify is in a read only segment. Therefore, this is not a safe option.

After noticing this, I considered the option of adding a read-write segment to the binary under study, or to resize an existing one. However, I found there are not that many tools to do this, and those that apparently could do the job like ERESI, were not very intuitive2. Also, we would need to find out where the new segment gets loaded to know where to write, which would complicate the code. Furthermore, I wanted to avoid modifying the binary if possible.

Finally, I concluded that the stack was exactly what I needed: it is of course RW, and a reference address can be found by simply looking at the RSP register. What we have to do is make sure we write in a safe part of the stack. This can be performed by writing to addresses lower than the RSP (that is, the free part of the stack). To achieve this, we “reserve” stack memory so we can write a string of up to PATH_MAX length, and we add up 128 bytes for the red zone (this size is specified by the x86_64 ABI). Note also that syscalls do not write on the process stack: one of the very first things that is done by the Linux kernel syscalls entry point is to switch RSP to a kernel stack. This approach has also the advantage of being automatically thread-friendly, as each one has its own stack. On the other hand, there is the possibility of writing outside the stack. However that risk is quite small nowadays, as stacks of user space programs tend to be big and typically auto-grow on page fault. Another advantage is that we do not need to save and recover memory areas at enter/exit of the syscall, as the tracee should not write anything in the used memory area.

Once it is decided where to write, the implementation is straightforward: first we use PTRACE_PEEKUSER to get the RSP value of the tracee. Then, we write the new file name to a pointer lower than the RSP calculated as explained in the previous paragraph. The data is written by using PTRACE_POKETEXT, word by word. Finally, we change the child’s RDI register so it points to the new address.

Now we can give the program a try. I created a couple of files with content:

$ cat ONE.txt 
This is ONE.txt
$ cat TWO.txt 
This is TWO.txt

Executing the same cat command using redirect we have:

$ gcc redirect.c -o redirect
$ ./redirect cat ONE.txt 
This is ONE.txt
$ ./redirect cat TWO.txt 
This is ONE.txt

Things work as publicized: we modify the file opened by the cat in case it tries to show the content of “TWO.txt”.

Conclusions

As has been seen, the code to make this is remarkably small, which shows the power of the ptrace call. There are indeed parts of this that are very architecture specific, but that is mostly the name of the registers and maybe the red zone size, so it should be relatively straightforward to make it multi-architecture by adding some macros.

Another appreciation is that the example is for the open() syscall, but this technique can be applied to arbitrary arguments which are passed to any syscall as pointers to data in the traced process.

To finish, the main drawback for this solution is performance, as we have to stop (twice) for each syscall invoked by the child, with all the context switches that implies. A possible solution would be to use ptrace in combination with seccomp and seccomp Berkeley Packet Filters, which apparently make possible for the tracer to specify the syscalls that would provoke a trap. That would be, however, matter for another post.

Read more

Looking for the code? Look no further: https://github.com/larryprice/pingus-snap

In my last post, I demonstrated creating a snap package for an application available in the archive. I left that application unconfined, which is taboo in the long run if we want our system to be secure. In a few steps, we can add the necessary components to confine our pingus snap.

For reference, this is the original snapcraft.yaml file for creating a pingus snap, except that we’ve updated the confinement property to strict:

snapcraft.yaml
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
name: pingus
version: '0.1'
summary: Free Lemmings(TM) clone
description: |
    Pingus is a free clone of the popular Lemmings game.
    |
    Your goal is to guide a horde of penguins through a world full of obstacles
    and penguin traps to safety. Although penguins (unlike lemmings) are rather
    smart, they sometimes lack the necessary overview and now rely on you to
    save them.

grade: devel
confinement: strict

parts:
  archives:
    plugin: nil
    stage-packages:
      - pingus
  env:
    plugin: dump
    organize:
      pingus.wrapper: usr/bin/pingus

apps:
  pingus:
    command: pingus

If you’re feeling bold, you can build and install the snap from here, but be warned that this led me into an ncurses nightmare that I had to forcibly kill. That’s largely because pingus depends on X11, which is not available out-of-the-box once we’ve confined our snap. If we want to use X11, we’re going to need to connect to it using the snap-land concept of interfaces. Interfaces allow us to access shared resources and connections provided by the system or other snaps. There’s some terminology to grapple with here, but the bottom line is that a “slot” provides an interface which a “plug” connects to. You can see a big list of available interfaces with descriptions on the wiki. Our pingus app will “plug” into the X11 interface’s “slot”:

snapcraft.yaml
1
2
3
4
5
6
# ...
apps:
  pingus:
    command: pingus
    plugs:
      - x11

You can build and install the new snap with the --dangerous flag for your local confined snap. After that, you can verify the interface connection with the snap interfaces command:

1
2
3
4
5
6
7
8
9
$ snapcraft
$ sudo snap install --dangerous pingus_0.1_amd64.snap
pingus 0.1 installed
$ snap interfaces
Slot                     Plug
:alsa                    -
# ...
:upower-observe          -
:x11                     pingus

Now, when we run pingus… it works! Well, video works. If you want sound, we’ll also need the pulseaudio interface:

snapcraft.yaml
1
2
3
4
5
6
7
# ...
apps:
  pingus:
    command: pingus
    plugs:
      - x11
      - pulseaudio

Once again: build, install, and run… et voilà! Is it just me, or was that surprisingly painless? Of course, not all applications live such isolated lives. Make note that the x11 interface is supposed to be a transitional interface, meaning that we would rather our app fully transition to Mir or some alternative. To go a step further with this snap, we could create a snapcraft.yaml to build from source to get the absolute latest version of our app. At this point, we can change our grade property to stable and feel good about something that we could push to the store for review.

Any code you see here is free software. Find the project here: https://github.com/larryprice/pingus-snap

Read more
deviceguy

Like it says on the Intel IoT developer site, "Without sensors, there's no IoT".

Because I am the maintainer of QtSensors, I like to inquire about  people's use of sensors and if they use QtSensors. Over the years, I have heard quite often something like, 'Qt is thought of as a UI framework'. *sigh*
 
But Qt is more than just a UI framework and it's use is not dependent on widgets or declarative wizardry. It is used in quite a few middleware components without UI elements. One of those middleware frameworks is Sensor Framework.

Sensor framework is a daemon that uses a plugin system written using Qt for reading various sensors such as accelerometer or light sensors. It was originally developed by Nokia for Harmattan and ran on the N9. It was also used in MeeGo and later included in the Mer Project and on Jolla phones and the ill fated tablet. So it has been released onto a few commercial products.

We looked at it when I was working at Nokia on the project that I still cannot name, but we had decided we would come up with our own solution. Looking back, this was the wrong decision, we should have taken the already proven sensor framework and ran with that. Why? Because it existed and works.

I started maintaining it when I was a privateer (contractor) developer for Jolla. No one else had touched it for some time so I grabbed the few not yet merged bug fixes and added support for libhybris/android libhardware adaptors.

Sensor Framework has support for multiple clients with down sampling for different data rates. It uses dbus for control lines (to start and stop, etc) but sends data through a socket. It also has a working backend in QtSensors.

I noticed that Ubuntu's Unity does nothing to respond when I put this into "tablet mode". I have to manually open the virtual keyboard among other things.

So I thought I could use sensorfw on my Dell 2 in 1. It's one of those converged laptop/tablet devices. It has a few sensors - accelerometer, gyroscope, magnetometer, and lid sensors. One problem... sensorfw does not support lid sensors, or a few other sensors that are around today in IoT (which I will add a bit later). Lid "sensor" might be a bit of a misnomer, as they could be switches but I'd like to think it is more like a hal effect sensor that uses magnets. In any case there are event nodes to use.

First one I chose is to add the lid sensor - to detect when this machine is put into tablet mode, so the UI can better deal with it.

I also noticed that this kernel has support for iio sensor interface for the accel and gyro. Sensorfw only supports sysfs, evdev and hybris interfaces, so I also wanted to add support for that.

I worked on adding iio support first. Well... really just wrote a sensor adaptor plugin. My plugin supports accelerometer, gyroscope and magnetometer, which this device seems to have. I will expand this to support other sensors later, as well as clean it up a bit.

Thanks to QtSensors sensor framework backend, I can make a UI app change with the orientation and lid changes. Better yet, I can create a game that uses accelerometer data like a marble maze game. Or I can upload the data to one of those Node.js data visualization web apps.

And since sensor framework is opensource, others can as well.


Read more
ssweeny

My team at work has been focused on snaps this year and one thing we’ve tried to do internally is establish a set of best practices for snap packaging software. Toward that end I’ve been working on a little tool I’m calling snaplint to encode those practices and verify that we’re following them.

Right now you can run snaplint against your snapcraft project directory
and it will scan the prime subdirectory for the following things:

  • copyright (basically that you included usr/share/doc/*copyright*) for
    any stage-packages
  • developer cruft (things like header and object files or static libs
    that might have made their way into your snap)
  • libraries (examine the ELF files in your snap and look for libraries
    which aren’t used)

The next things I’m planning on adding are:

  • checking for copyright info from apps/parts themselves.
  • checking for mixing of incompatible licenses

I would love to hear suggestions on further improvements.

You can find the source at https://github.com/ssweeny/snaplint

And, of course if you’re running Ubuntu 16.04 or later you can try it on your own machine with:
$ snap install snaplint
$ snaplint path/to/your/project

Read more
Dustin Kirkland


From Linux kernel livepatches to encryption to ASLR to compiler optimizations and configuration hardening, we strive to ensure that Ubuntu 16.04 LTS is the most secure Linux distribution out of the box.

These slides try to briefly explain:

  • what we do to secure Ubuntu
  • how the underlying technology works
  • when the features took effect in Ubuntu

I hope you find this slide deck informative and useful!  The information herein is largely collected from the Ubuntu Security Features wiki page, where you can always find up to date information.



Cheers,
Dustin

Read more

If you haven’t heard, snaps are a new, modern packaging format made by the guys at Ubuntu. Snaps give every app a confined environment to live in, making desktops more secure and dependencies less of a hassle. One common way to create a snap is to simply use existing packages from the Ubuntu archives.

Let’s try to create a snap for the game pingus. pingus is a great little Lemmings clone that we can easily convert to a snap. We’ll start by installing the necessary dependencies for snap building (see the snapcraft website for more):

1
$ sudo apt install snapcraft

Now we can initialize a project directory with snapcraft:

1
2
$ mkdir -p pingus-snap && cd pingus-snap
$ snapcraft init

snapcraft init creates the following sample file to give us an idea of what we’ll need to provide.

snapcraft.yaml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
name: my-snap-name # you probably want to 'snapcraft register <name>'
version: '0.1' # just for humans, typically '1.2+git' or '1.3.2'
summary: Single-line elevator pitch for your amazing snap # 79 char long summary
description: |
  This is my-snap's description. You have a paragraph or two to tell the
  most important story about your snap. Keep it under 100 words though,
  we live in tweetspace and your description wants to look good in the snap
  store.

grade: devel # must be 'stable' to release into candidate/stable channels
confinement: devmode # use 'strict' once you have the right plugs and slots

parts:
  my-part:
    # See 'snapcraft plugins'
    plugin: nil

Most of these values for our pingus snap should be obvious. The interesting markup here is in parts, which is where we’ll describe how to build our snap. We’ll start by taking advantage of the nil plugin to simply unpack the pingus deb from the archive. We define our list of debs to install in a list called stage-packages. We’ll also define another section, apps, to tell snapcraft what binaries we want to be able to execute. In our case, this will just be the pingus command. Here’s what my first draft looks like:

snapcraft.yaml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
name: pingus
version: '0.1'
summary: Free Lemmings(TM) clone
description: |
    Pingus is a free clone of the popular Lemmings game.
    |
    Your goal is to guide a horde of penguins through a world full of obstacles
    and penguin traps to safety. Although penguins (unlike lemmings) are rather
    smart, they sometimes lack the necessary overview and now rely on you to
    save them.

grade: devel
confinement: devmode

parts:
  archives:
    plugin: nil
    stage-packages:
      - pingus

apps:
  pingus:
    command: usr/games/pingus

Nice, right? Building and installing our snap is easy:

1
2
3
$ snapcraft
$ sudo snap install --devmode pingus_0.1_amd64.snap
pingus 0.1 installed

We used devmode here because our app will be running unconfined (a topic for another blog post). Now, for the moment of truth! The snap tools automatically put our new app in PATH, so we can just run pingus:

1
2
$ pingus
/snap/pingus/x2/usr/games/pingus: 2: exec: /usr/lib/games/pingus/pingus: not found

¡Ay, caramba! We’ve run into a fairly common issue while snapping legacy software: hardcoded paths. Fortunately, the corresponding pingus executable is very simple. It’s trying to execute a command living in /usr/lib/games/pingus, which is not in our snap’s PATH. The easiest way to fix this is to fix the pingus executable. Since we don’t want to spend time modifying the upstream to use a relative path, we can create our own version of the pingus wrapper locally and copy it into our snap. The only change to this new wrapper will be prepending the snap’s install path $SNAP to the absolute paths:

pingus.wrapper
1
2
#!/bin/sh
exec $SNAP/usr/lib/games/pingus/pingus --datadir $SNAP/usr/share/games/pingus/data $@

Now we can update our yaml file with a new part called env which will use the dump plugin to copy our wrapper file into the snap. We’ll also update our command to call the wrapper:

snapcraft.yaml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# ...

parts:
  archives:
    plugin: nil
    stage-packages:
      - pingus
  env:
    plugin: dump
    organize:
      pingus.wrapper: usr/bin/pingus

apps:
  pingus:
    command: pingus

When you run snapcraft this time, the env part will be built. After performing another install, you can run pingus, and you should be greeted with one of the best Lemmings clones available! Because we’re running unconfined in devmode, this all just works without any issues. I intend to write another blog post in the near future with the details on confining pingus, so look out for that soon. I may also go into detail on building more complex cases, such as building snaps from source and building custom plugins, or reviewing a case study such as the libertine snap.

For much, much more on snaps, be sure to visit snapcraft.io. If you’re looking for a published version of pingus as a snap, you can try sudo snap install --devmode --beta pingus-game, and you can run the game with pingus-game.pingus.

Source code available at https://github.com/larryprice/pingus-snap.

Read more
Stéphane Graber

LXD logo

Introduction

The LXD and AppArmor teams have been working to support loading AppArmor policies inside LXD containers for a while. This support which finally landed in the latest Ubuntu kernels now makes it possible to install snap packages.

Snap packages are a new way of distributing software, directly from the upstream and with a number of security features wrapped around them so that these packages can’t interfere with each other or cause harm to your system.

Requirements

There are a lot of moving pieces to get all of this working. The initial enablement was done on Ubuntu 16.10 with Ubuntu 16.10 containers, but all the needed bits are now progressively being pushed as updates to Ubuntu 16.04 LTS.

The easiest way to get this to work is with:

  • Ubuntu 16.10 host
  • Stock Ubuntu kernel (4.8.0)
  • Stock LXD (2.4.1 or higher)
  • Ubuntu 16.10 container with “squashfuse” manually installed in it

Installing the nextcloud snap

First, lets get ourselves an Ubuntu 16.10 container with “squashfuse” installed inside it.

lxc launch ubuntu:16.10 nextcloud
lxc exec nextcloud -- apt update
lxc exec nextcloud -- apt dist-upgrade -y
lxc exec nextcloud -- apt install squashfuse -y

And then, lets install that “nextcloud” snap with:

lxc exec nextcloud -- snap install nextcloud

Finally, grab the container’s IP and access “http://<IP>” with your web browser:

stgraber@castiana:~$ lxc list nextcloud
+-----------+---------+----------------------+----------------------------------------------+
|    NAME   |  STATE  |         IPV4         |                     IPV6                     |
+-----------+---------+----------------------+----------------------------------------------+
| nextcloud | RUNNING | 10.148.195.47 (eth0) | fd42:ee2:5d34:25c6:216:3eff:fe86:4a49 (eth0) |
+-----------+---------+----------------------+----------------------------------------------+

Nextcloud Login screen

Installing the LXD snap in a LXD container

First, lets get ourselves an Ubuntu 16.10 container with “squashfuse” installed inside it.
This time with support for nested containers.

lxc launch ubuntu:16.10 lxd -c security.nesting=true
lxc exec lxd -- apt update
lxc exec lxd -- apt dist-upgrade -y
lxc exec lxd -- apt install squashfuse -y

Now lets clear the LXD that came pre-installed with the container so we can replace it by the snap.

lxc exec lxd -- apt remove --purge lxd lxd-client -y

Because we already have a stable LXD on the host, we’ll make things a bit more interesting by installing the latest build from git master rather than the latest stable release:

lxc exec lxd -- snap install lxd --edge

The rest is business as usual for a LXD user:

stgraber@castiana:~$ lxc exec lxd bash
root@lxd:~# lxd init
Name of the storage backend to use (dir or zfs) [default=dir]:

We detected that you are running inside an unprivileged container.
This means that unless you manually configured your host otherwise,
you will not have enough uid and gid to allocate to your containers.

LXD can re-use your container's own allocation to avoid the problem.
Doing so makes your nested containers slightly less safe as they could
in theory attack their parent container and gain more privileges than
they otherwise would.

Would you like to have your containers share their parent's allocation (yes/no) [default=yes]?
Would you like LXD to be available over the network (yes/no) [default=no]?
Would you like stale cached images to be updated automatically (yes/no) [default=yes]?
Would you like to create a new network bridge (yes/no) [default=yes]?
What should the new bridge be called [default=lxdbr0]?
What IPv4 subnet should be used (CIDR notation, “auto” or “none”) [default=auto]?
What IPv6 subnet should be used (CIDR notation, “auto” or “none”) [default=auto]?
LXD has been successfully configured.

root@lxd:~# lxd.lxc launch images:archlinux arch
If this is your first time using LXD, you should also run: sudo lxd init
To start your first container, try: lxc launch ubuntu:16.04

Creating arch
Starting arch

root@lxd:~# lxd.lxc list
+------+---------+----------------------+-----------------------------------------------+------------+-----------+
| NAME |  STATE  |         IPV4         |                      IPV6                     |    TYPE    | SNAPSHOTS |
+------+---------+----------------------+-----------------------------------------------+------------+-----------+
| arch | RUNNING | 10.106.137.64 (eth0) | fd42:2fcd:964b:eba8:216:3eff:fe8f:49ab (eth0) | PERSISTENT | 0         |
+------+---------+----------------------+-----------------------------------------------+------------+-----------+

And that’s it, you now have the latest LXD build installed inside a LXD container and running an archlinux container for you. That LXD build will update very frequently as we publish new builds to the edge channel several times a day.

Conclusion

It’s great to have snaps now install properly inside LXD containers. Production users can now setup hundreds of different containers, network them the way they want, setup their storage and resource limits through LXD and then install snap packages inside them to get the latest upstream releases of the software they want to run.

That’s not to say that everything is perfect yet. This is all built on some really recent kernel work, using unprivileged FUSE filesystem mounts and unprivileged AppArmor profile stacking and namespacing. There very likely still are some issues that need to get resolved in order to get most snaps to work identically to when they’re installed directly on the host.

If you notice discrepancies between a snap running directly on the host and a snap running inside a LXD container, you’ll want to look at the “dmesg” output, looking for any DENIED entry in there which would indicate AppArmor rejecting some request from the snap.

This typically indicates either a bug in AppArmor itself or in the way the AppArmor profiles are generated by snapd. If you find one of those issues, you can report it in #snappy on irc.freenode.net or file a bug at https://launchpad.net/snappy/+filebug so it can be investigated.

Extra information

More information on snap packages can be found at: http://snapcraft.io

The main LXD website is at: https://linuxcontainers.org/lxd
Development happens on Github at: https://github.com/lxc/lxd
Mailing-list support happens on: https://lists.linuxcontainers.org
IRC support happens in: #lxcontainers on irc.freenode.net
Try LXD online: https://linuxcontainers.org/lxd/try-it

Read more
liam zheng

为了庆祝Ubuntu Core 16正式发布,我们在IoT领域高手云集的深圳,专为欲大展拳脚的各路开发高手,创客团队举办了主题为“Jamming with Ubuntu Core”的黑客松活动。

为了庆祝Ubuntu Core 16正式发布,我们在IoT领域高手云集的深圳,专为欲大展拳脚的各路开发高手,创客团队举办了主题为“Jamming with Ubuntu Core”的黑客松活动。本次活动也是第一次以Ubuntu Core为开发主题的开发活动。活动吸引了来自不同行业的软硬件开发者踊跃参与,他们也通过Ubuntu Core展示了他们独特且创意的作品。

目前,Ubuntu Core 在柜顶交换机、工业网关、家庭网关、无线接入网络、数字标牌机器人和无人机等领域得到了广泛应用。部分活动开发者也来自于上述行业,在36小时的hack时间内,创意和作品将是他们对物联网的完美诠释。

与以往Hackathon活动相比,这次Ubuntu Hackathon多了一些不同,因为不同从而产生不同创意之作。本次活动迎来了远从台北而来的QNAP开发者,致力于在Ubuntu Core上打造IoT与NAS存储器的应用解决方案,同时也有上一届Hackathon的参赛者,更重要的是赢了很多新的开发者参与。他们的精彩项目也为本次黑客松活动添加了特别的气氛。

作品及项目:短短36小时,开发者们为Ubuntu Core带来了8个佳作。他们分别是:

 

天台聚落

团队:Jarvis Chung,Lucas Lu

项目介绍:(snap:water-iot-service)

天台聚落是指在IoT 物联⽹环境下监控⽔质,在不同环境下实现远程监控对水质的监控,解决了因为环境问题而不能时刻掌握水质的困境。该项目利用Ubuntu Core稳定且时刻保持最新的优势将传感器收集的信息传输到NAS再通过web服务显示在前端,实现了数据的采集和分析。

项目的愿景:为水资源的监测和管理提供更加便捷、直观、科学的思路,可用水库、蓄水池、水塔等无人照看且检修、监测困难水资源管理领域。

团队介绍:

威联通科技股份有限公司 (QNAP Systems, Inc.) ,公司专注于提供专业级的网络附加存储(NAS)和网络视频录像机(NVR)解决方案, 威联通的集成技术和设计带来优质的产品,其文件共享,虚拟化应用程序,存储管理和商业环境检测有效地提高企业运行效率。官网:(www.qnap.com/zh-cn)

 

Cooltools

团队:郝建林

项目介绍:(snap:sensor-gw)

用蓝牙连接TI Sensor Tag传感器套件,收集光照传感器数据,并通过本地WebServer实时显示在网页上。结合照明控制系统可以实现用Sensor Tag的物理按键开关灯,以及在环境亮度过小时自动开灯,整个系统都是通过高通 Dragonboard 410c与Ubuntu Core16 连接实现。在现实生活中,本项目可用于自动化环境光照控制,无需派人控制,也可避免因固定设置产生的能源浪费。

团队介绍:参赛团队来自深圳市酷图软件开发有限公司,公司专注于物联网应用开发,目前主要业务是为硬件产品开发APP。正在实践将物联网技术应用于实际生产生活,欢迎各界朋友交流合作。邮箱:cooltools@qq.com

 

Crazyou

团队:张研

项目介绍:(snap:crazy-app)

Crazyou来着深圳,是一家致力于打造智能机器人及开发板的初创团队,本次活动展示的项目则是可远程获取机器人运行状态,可远程开发调试,远程控制机器人或获取机器人摄像头捕捉的图像内容,绘制3D地图等。

团队介绍:趣之科技通过互联网构建实时远控能力,为Robotic类物联产品提供实时远控云应用服务与开放式核心硬件模块,致力用远程技术消除感知的空间距离。官网:www.crazyou.com

 

Simcaffe

团队:老梁

项目介绍:(snap:simcaffe)

simcaffe采用了高通DragonBoard 410c硬件计算能力,整合Ubuntu Cor以及Caffe深度识别平台,用斯坦福的开源深度学习算法, 用Python调用Caffe得到的识别结果实现图片分析和识别。未来可用在视频监控领域,并且该项目也是基于高通 Dragonboard 410c。Github:github.com/curiousguy98

团队介绍:

ABI Hackerspace管理员,目前为多家创业公司合伙人。从事研发工作近20年,在各类型公司实现过量产产品,辅助创业公司十多家。多次获得各类创意比赛大奖。小米硬件黑客马拉松第一名, Global Urban Datafest全球第三名, Moser穿戴式设备大赛一等奖。

 

PCBA

团队:臧鹏,Batur

项目介绍:(snap:sutop/movieword)

sutop是一款系统使用snap应用,基于node.js编写,可进行系统任务、资源、性能监控,并且以图形化的方式展示,界面简洁直观。PCBA团队另外一个项目则是movie word,可对字幕文件进行处理,去除数字、标点、去重,从而从电影字幕学习英语单词。

团队介绍:

臧鹏,热爱科技、电子产品,热爱开源,热爱ubuntu等一些有趣的事;目前致力于嵌入式软件;期望自由,做一些可以改变自己生活、改变自己世界的事,然后影响更多人。

Batur, 一个梦想成为大神的菜鸟。喜欢新奇的技术,最近正在学函数式编程。

 

我的衣柜

团队:黎健成

项目介绍:

使用树莓派上的Ubuntu Core进行衣服图片的自动分类,并存储起来,方便以后进行浏览和搭配。图片暂时使用上传的方式,之后有摄像头可通过摄像头获取。

关于开发者:黎健成,在读研究生,目前从事计算机视觉与深度学习的研究。除了对算法与数据结构等感兴趣外,对嵌入式、IoT等方面的开发也有所关注。喜欢参加各种各样的比赛,与各路大牛交流。个人博客(http://lijiancheng0614.github.io/)

团队介绍:

黎健成,在读研究生,目前从事计算机视觉与深度学习的研究。除了对算法与数据结构等感兴趣外,对嵌入式、IoT等方面的开发也有所关注。喜欢参加各种各样的比赛,与各路大牛交流。

 

Cellboot

团队:沈建丰

项目介绍:

使用Ubuntu Core进行物计算,将多台Ubuntu Core设备建立连接,可计算共享,每台设备都是计算集群的一部分。

团队介绍:

关于开发者:沈建丰是一名Ubuntu的用户,同时也是传媒公司的负责人,运营“华强北那些事儿”微信平台,主要擅长web应用开发。官网(http://www.editrobot.com)

 

在开发者们的精彩demo中,本次Ubuntu Core 16深圳黑客松活动圆满落下了帷幕,在2天的时间里开发者们用自己的code表达、诠释了心中的IoT是什么以及自己会如何去做。没有再见,只有再一次相见,期待与你相遇在下一站活动中。

 

Read more
facundo

Incubadora de eventos


Una de los roles claves de la Asociación Civil de Python Argentina (en adelante "AC") debería ser que la gente se junte y comparta conocimiento. En consonancia con esto, estuve armando la siguiente idea para ayudar a que se generen eventos y reuniones.

Hay distintas formas en la cual la AC puede ayudar a los organizadores de un evento, entre ellas:

  • Ayuda logística: transmitir experiencia, ayudar a resolver inconvenientes que se produzcan en la operatoria del día a día
  • Ayuda financiera: como es normal que algunos sponsors se comprometan a aportar dinero, pero luego ese aporte se demora (por el sponsor en sí, o trámites de todo tipo, especialmente internacionales), la AC puede adelantarle dinero al organizador, el cual ingresará a la AC luego cuando el sponsor efectivice.
  • Ayuda económica: Partiendo de la idea base de que el evento salga hecho, o incluso genere dinero para la AC, hay dos puntos en que se puede ayudar económicamente: siendo sponsors de un evento muy chico (ej: pagando unas pizzas para un sprint), pero me parece más importante poder ser una red de contención, en el caso de que por fallos en la planificación conjunta se pierde algo de dinero: que la pérdida la cubra la AC y no la persona que organizó.
  • Ayuda institucional: Por un lado es útil tener una entidad legal para poder presentarse a más sponsors, o al estado, dando más seriedad al evento, y además es imprescindible que los sponsorships o donaciones para el evento se hagan a una entidad ya formada, y no a individuos; esto le saca un quilombo personal al organizador, y permite pagos internacionales.

Para poder ejecutar estas ayudas, los organizadores del evento y la AC tienen que colaborar, seguir ciertos pasos y reglas. ¿Quizás incluso firmar algún contrato?

Describo la metodología a grandes rasgos en los siguientes puntos. Pero esto hay que pensarlo, refinarlo, y escribirlo bien en detalle, para lograr dos cosas:

  • que el organizador u organizadores entienda bien como la AC va a jugar en esto
  • que la AC corra la menor cantidad de riesgos innecesarios posibles

Entonces, la idea es tener un presupuesto base, un template de lo que sería el presupuesto final del evento, con todo lo que podamos pensar y se nos pueda ocurrir de eventos anteriores. Se recorre el mismo con el organizador, en una primera instancia, y se elije lo que el organizador "quiere hacer"; luego el organizador mismo tiene que poner un estimado de costo a cada ítem, y separar los ítems en tres secciones (o quizás sólo dos para eventos chicos):

  • de mínima: sin esto el evento no sale
  • intermedio: con esto el evento está lindo
  • de máxima: si se logra esto es un golazo

En función de todo lo elegido, hay que planificar los sponsorships necesarios, en base a niveles: definirlos, incluyendo el costo y las retribuciones. Es imprescindible que la AC de "el visto bueno" sobre esta planificación, y que luego realice un "seguimiento en el tiempo" de la evolución de la ejecución del presupuesto. Acá la AC también puede jugar un rol centralizador, básicamente armando un folleto de "hay un nuevo evento, ¿querés ser sponsor?" y mandándolo a todos las empresas, instituciones, o lo que sea que tengamos en carpeta.

También en esta interacción AC/organizador se pueden pedir más cosas, o hacerlas obligatorias, ejemplo (¡hay que pensar más!):

  • que el evento tenga un código de conducta; incluso la AC puede proveerlo, junto con un pequeño texto de "qué hacer si se recibe una denuncia"
  • que el sitio web del evento sea "exportable a estático", así la AC lo guarda y sirve a futuro; también la AC podría dar un sitio web base, y hostearlo.

Por último, un detalle: estaría bueno que la AC también cumpla el rol de "paraguas legal" (básicamente, lo que arriba describo como "ayuda institucional") para ayudar a otros grupos relacionados con el software y/o cultura libre, para que puedan ellos hacer sus eventos.

Read more
Michael Hall

Below is a guest post written by Ryan Sipes, Community Manager at System76


Last week System76 engineers participated in a call with Martin Wimpress of the Ubuntu Desktop team to discuss HiDPI support in Ubuntu, specifically Unity 7. HiDPI support exists in Unity 7, but there are areas that could use improvement, and the call focused around those. The conversation was primarily focused around bugs that still remain in the out-of-the-box HiDPI experience; specifically around enabling automatic scaling and Ubuntu recognizing when a HiDPI display is present so that it can adjust accordingly.

This has become a focus of System76 as it has worked to provide a good experience for users purchasing their new 4K HiDPI displays now available on the Oryx Pro and BonoboWS laptops.

“With our HiDPI laptops, everything is twice as crisp; it's like a high-quality printed magazine instead of a traditional computer display. The user interface is clearer, text is sharper, photos are more detailed, games are higher res, and videos can be viewed in full lifelike 4K. This is great whether you're anyone from a casual computer user to a video editor producing high end content or a professional developer who wants a better display for your code editor.”, says Cassidy James Blaede, a developer at System76 and a co-founder of elementary OS, an Ubuntu-based distribution that has put a lot of work into HiDPI support. Cassidy recently wrote a blog post explaining HiDPI, diving into the specifics of how it works.

Some patches that improve HiDPI support are in review and they are expected to land in Ubuntu soon. In order to accelerate this process HiDPI bugs in Launchpad are being tagged accordingly and will make it easier for contributors to focus their efforts more easily. System76 will be contributing heavily to this process, but many other Ubuntu community members have expressed interest in contributing as well, so this will likely be a hot spot in the near future.

Read more
Alan Griffiths

Mircade

Mircade

I’ve been playing with the “kiosk” concept implemented by miral-kiosk. Kevin Gunn and Alberto Aguirre have been using it to demonstrate Mir snaps (kg’s blog) so I decided to join the fun.

Mircade is a very basic kiosk-launcher for whatever games are installed on a system. It tries to work out whether the game will run natively on Mir and, if not, will try running them on Xmir (if installed).

To play, you need the latest miral-examples and libmiral-dev installed. You can “apt install miral-examples” from Zesty archive/Xenial “stable phone overlay” PPA, or build it from source on Xenial or later.

$ sudo apt install miral-examples libmiral-dev mir-graphics-drivers-desktop xmir

Once you have that sorted, Mircade is available from github. It has a few dependencies (I’ve tried to list them, but have probably missed one).

$ git clone https://github.com/AlanGriffiths/mircade.git
$ sudo apt install libfreetype6-dev libboost-filesystem-dev libboost-system-dev cmake
$ cd mircade/
$ cmake .
$ make
$ miral-desktop -kiosk -launcher ./mircade

Navigation is by arrow keys (left/right) and selection by Space or Enter. When your game exits you return to the mircade launcher.

Not all games work perfectly on Mir (yet):

  • Most of the GTK based games (like gnome-chess) run, but sometimes fail to “fullscreen”;
  • SDL2 based games (like 7kaa) have a tendency to segfault on exit; and,
  • X11 based games using Xmir may or may not work.

Have fun!

Read more
facundo

PyCon Argentina 2016


El fin de semana pasado fue la octava edición de la conferencia nacional de Python en Argentina. Se realizó en Bahía Blanca, tres días de talleres y charlas.

Yo dí una charla, "Bindings, mutable default arguments, y otros quilom... detalles", y asistí a otras; las que más me gustaron fueron "Poniéndonos un poco más serios con Kivy" por Sofía Martin y alguien más que no recuerdo, "Compartiendo memoria eficientemente con proxies" por Claudio Freire, "Argentina en Python: comunidad, sueños, viajes y aprendizaje" por Humitos, "MicroPython en EDU-CIAA" por Martín Ribelotta, "Redes neuronales con Python utilizando Keras" por Fisa, "Deep learning: aprendiendo con la escafandra" por Javi Mansilla, e "Introducción a programación paralela con PyOpenCL" por Celia Cintas.

Mi charla, renovada

Las keynotes estuvieron muy bien, también. Fernando Schapachnik, de la Fundación Sadosky nos habló del problema de género en las comunidades informáticas (con datos, análisis, y una arenga política al final que estuvo bárbara). Ángel Medinilla nos dío una charla-show-standup sobre metodologías ágiles (excelente presentación). Y la última fue de Victoria Martínez de la Cruz, contando las ventajas y desventajas de trabajar de forma remota (algo que se está imponiendo más y más en las comunidades de software y que está lleno de mitos, así que era muy necesaria).

La organización del evento también estuvo impecable. Se nota que laburaron un montón y salió todo muy bien.

Los asistentes a punto de escuchar una plenaria

Más allá del costado técnico, y de lo que sucede en estos eventos de charlas que se generan, reencuentros, etc, tanto en pasillos como luego de la conferencia en bares o por ahí, quiero destacar el lado "humano"que tuvo esta conferencia.

No sólo las keynotes hablaron de las personas o sus grupos de trabajo, sino que también tuvimos charlas que hicieron lagrimear a varios, como la de Humitos que mencioné arriba o la de Roberto Alsina ("Cómo desarrollar software libre (o no) y no morir en el intento (o no)", que no pude ver pero me contaron). Pero había algo más en el ambiente. Gente comentando lo copada que son organizadores y asistentes en este evento, que cómo te ayudan con todo, que se preocupan, etc. Había muy buena onda por todos lados.

Relajando un poco, en el almuerzo del primer día

Trabajando en uno de los espacios abiertos que había

Hubo una anécdota interesante, también. Resulta que una señora vio en un kiosco a unos asistentes a la conferencia que tenían algo de Python encima. Entonces fue a la escuela de su hijo mayor, de 13 años, lo sacó antes de hora y volvieron a la zona del kiosco (que obviamente, era muy cerca del edificio de la conferencia). Justo pasábamos otros chicos y yo, vieron un pin de Python que llevo en la mochila, y nos preguntaron qué onda. Les contamos de la conferencia, Diego M. les regaló el librito del evento, y listo.

Nosotros pensábamos que terminaba ahí. Nada más lejos.

Al rato volvemos al edificio donde se desarrollaba el evento y vemos que sube a la zona de la conferencia la madre y los dos niños. El pibe de 13 se colgó todo el día yendo de charla en charla, mientras la mamá le hacía el aguante en una zona con sillones. No sólo eso, sino que fueron el sábado y el domingo a la conferencia, y se pasaron todo el finde allí. Notable.

Todas las manos todas

Para cerrar les dejo las fotos que saqué, más esta búsqueda de tuiter que está buena.

Read more
Alan Griffiths

MirAL 0.5

There’s a new MirAL release (0.5.0) available in ‘Zesty Zapus’ (Ubuntu 17.04) and the so-called “stable phone overlay” ppa for ‘Xenial Xerus’. MirAL is a project aimed at simplifying the development of Mir servers and particularly providing a stable ABI and sensible default behaviors.

Unsurprisingly, given the project’s original goal, the ABI is unchanged. The changes in 0.5.0 fall are:

  1. Some utility scripts to for common tasks;
  2. Improved “–window-manager tiling” mode of miral-shell;
  3. More configuration options for miral-kiosk;
  4. miral::DebugExtension; and,
  5. Some minor bug fixes.

Some utility scripts to for common tasks

There are two of these: miral-desktop and miral-screencast.

miral-desktop creates a pseudo-desktop session:

miral-desktop - Handy launch script for a miral "desktop session"
Usage: miral-desktop [options] [shell options]
Options are:
    -kiosk               use miral-kiosk instead of miral-shell
    -launcher <launcher> use <launcher> instead of 'gnome-terminal --app-id com.canonical.miral.Terminal'
    -vt       <termid>   set the virtual terminal [4]
    -socket   <socket>   set the mir socket [/run/user/1000/mir_socket]
    -bindir   <bindir>   path to the miral executable

For example, I use this to test the “tiling” window management with a UK keyboard layout:

$ miral-desktop -launcher qterminal --window-manager tiling --keymap gb

miral-screencast captures the Mir display (until you press enter) and then encodes it as an mp4:

miral-screencast - screencast capture script for use with Mir servers
Usage: /usr/bin/miral-screencast [options]
Options are:
    --width   set the capture width   [1920]
    --height  set the capture height  [1080]
    --output  set the output filename [screencast.mp4]
    --socket  set the mir socket      [/run/user/1000/mir_socket]

Improved “–window-manager tiling” mode of miral-shell

This has been updated to keep the focused window on the left half of the display (unless there’s only one window) and divide the right side vertically between the remaining windows. There’s also been a general refresh of the code that fixed a lot of minor issues.

More configuration options for miral-kiosk

The miral-kiosk now supports a few more options:

  • –keymap allows for non-US keyboard layout;
  • –kiosk-maximize-root-window kiosk has a new default behavior of maximizing root window, but this can be changed;
  • –kiosk-startup-apps-only prevents new connections after startup

miral::DebugExtension

This allows shells to enable (or disable) the client API “debug” extensions dynamically (AFAICS only useful for automated testing).

Some minor bug fixes

There was a race condition handling fullscreen surfaces when reconfiguring the display for hardware changes, the gmock version in zesty caused a FTBFS, and the clang version in zesty picked up some template instantiation issues.

Read more
UbuntuTouch

在一个Ubuntu Core的系统中,我们可以利用snapweb来进行安装,删除或查看我们已经安装过的应用.那么我们该如何操作呢?



1)首先我们找到我们设备的IP地址


对于还没有安装好Ubuntu Core的板子来说,我们可以参考文章"如何为树莓派安装Ubuntu Core并在Snap系统中进行交叉汇编"来安装我们的系统.同样的方法也使用于对高通的snapdragon及其它的板子.我们必须按照该文章中介绍的方法检查snapweb是否正在运行(尽管一般情况下是这样的).

a) 我们可以在Ubuntu Core系统中,打入如下的命令:

liu-xiao-guo@localhost:~$ ifconfig
enxb827ebcd46fa Link encap:Ethernet  HWaddr b8:27:eb:cd:46:fa  
          inet addr:192.168.1.105  Bcast:192.168.1.255  Mask:255.255.255.0
          inet6 addr: fe80::ba27:ebff:fecd:46fa/64 Scope:Link
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:1533 errors:0 dropped:0 overruns:0 frame:0
          TX packets:724 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000 
          RX bytes:204190 (204.1 KB)  TX bytes:452766 (452.7 KB)

lo        Link encap:Local Loopback  
          inet addr:127.0.0.1  Mask:255.0.0.0
          inet6 addr: ::1/128 Scope:Host
          UP LOOPBACK RUNNING  MTU:65536  Metric:1
          RX packets:327 errors:0 dropped:0 overruns:0 frame:0
          TX packets:327 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1 
          RX bytes:26013 (26.0 KB)  TX bytes:26013 (26.0 KB)

wlan0     Link encap:Ethernet  HWaddr b8:27:eb:98:13:af  
          UP BROADCAST MULTICAST  MTU:1500  Metric:1
          RX packets:53 errors:0 dropped:19 overruns:0 frame:0
          TX packets:0 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000 
          RX bytes:23502 (23.5 KB)  TX bytes:0 (0.0 B)

通过这样的方法,我们可以找到我们的运行Ubuntu Core系统的IP地址.当然这个方法适合我们已经登陆系统的设备.对于还没有登陆过系统的设备来说,我们可以通过如下的方法来找到我们设备的IP地址.

b) 通过路由器的设置来找到板子的IP地址


我们也可以参照我之前的文章"如何在装上Snappy Ubuntu的树莓派上启动WiFi"来通过网关的方法来找到我们板子的IP地址.


c) 使用nmap命令来找到我们的设备的IP地址


如果我们的desktop电脑和我们的Ubuntu Core设备同处于一个局域网中,我们也可以通过如下的方法来找到我们板子的IP地址.我们在我们的桌面电脑的terminal中打入如下的命令:

liuxg@liuxg:~$ nmap -sn 192.168.1.1/24

Starting Nmap 7.01 ( https://nmap.org ) at 2016-10-31 10:27 CST
Nmap scan report for 192.168.1.1
Host is up (0.0021s latency).
Nmap scan report for 192.168.1.100
Host is up (0.0032s latency).
Nmap scan report for 192.168.1.101
Host is up (0.015s latency).
Nmap scan report for 192.168.1.103
Host is up (0.00011s latency).
Nmap scan report for 192.168.1.104
Host is up (0.032s latency).
Nmap scan report for 192.168.1.105
Host is up (0.0069s latency).
Nmap done: 256 IP addresses (6 hosts up) scanned in 2.72 seconds

注意这里的"192.168.1.1"是我们路由器的地址.它显示了所有目前正在运行的连接到该网关的设备地址.我们的Ubuntu Core的IP地址肯定是其中的一个.我们可以通过如下的命令:

$ ssh liu-xiao-guo@192.168.1.100

来逐一试上面的每个地址.如果成功的话,我们会进入到ubuntu core的登陆环境.这里注意的是"liu-xiao-guo"是我在launchpad上的用户名.开发者必须根据自己的账号进行修改.


d) 通过snapweb.local来查看我们的Ubuntu Core设备地址


只要我们的设备和我们的桌面电脑处于一个局域网中,我们可以通过如下的方法来得到Ubuntu Core设备的地址.在我们的桌面电脑中,打入如下的命令:

$ ping snapweb.local

liuxg@liuxg:~$ ping snapweb.local
PING snapweb.local (192.168.1.105) 56(84) bytes of data.
64 bytes from 192.168.1.105: icmp_seq=1 ttl=64 time=2.46 ms
64 bytes from 192.168.1.105: icmp_seq=2 ttl=64 time=1.19 ms
64 bytes from 192.168.1.105: icmp_seq=3 ttl=64 time=1.71 ms
64 bytes from 192.168.1.105: icmp_seq=4 ttl=64 time=1.97 ms

它将自动显示我们的Ubuntu Core设备的IP 地址.

一旦得到我们的Ubuntu Core设备的IP地址,我们可以通过在桌面的terminal来进行登陆:



我们可以安装文章" 如何为树莓派安装Ubuntu Core并在Snap系统中进行编译"中介绍的方法来确保snapweb运行正常.


2)在桌面电脑浏览器中查看我们已经安装的应用


我们可以在我们的桌面电脑中的浏览器中的地址中键入:

ip_address_of_ubuntu_core_device:4200

虽然下面的图片章展示的是4201口地址.当我们键入上述的地址后:




它要求我们在我们的Ubuntu Core设备上键入命令:



我们可以拷贝上面生产的token,并输入到上面的浏览器中的输入框中.这样我们就可以看见:



在这个页面中,我们可以看到已经安装的所有的snap应用.这和我们在Ubuntu Core系统中的如下的命令类似:

liu-xiao-guo@localhost:~$ snap list
Name         Version       Rev  Developer  Notes
bluez        5.37-1        7    canonical  -
classic      16.04         14   canonical  devmode
lights-app   0.1           x1              devmode
livevideo    0.1           x1              devmode
pi2-kernel   4.4.0-1030-3  22   canonical  -
pi3          16.04-0.5     6    canonical  -
piglow-app   1.0           x2              devmode
sensortag    1.0           x3              devmode
snapweb      0.21.2        25   canonical  -
ubuntu-core  16.04.1       760  canonical  -

有了这个snapweb界面,我们可以对我们的应用进行管理,比如删除.当然我们也可以对我们的系统进行安装其它的已经在商店中的应用,就像我们文章开始介绍的画面一下.

对于Ubuntu 16.04的桌面snap开发者来说,你们也可以安装snapweb(如果还没有安装的话)来管理自己在桌面环境中的所有snap应用.

细心的读者可能已经看到,我们的许多的应用没有自己的icon.我们只能看到一个默认的Ubuntu的icon.在我们的实际设计中,我们可以在我们项目的根目录下创建一个如下的目录及文件:

setup/gui/icon.png

这样整个项目的文件如:

liuxg@liuxg:~/snappy/desktop/livevideo_snap$ tree -L 3
.
├── setup
│   └── gui
│       └── icon.png
└── snapcraft.yaml


当我们build完我们的应用并安装后,我们可以在我们的Ubuntu Store里看见这个应用的icon:




作者:UbuntuTouch 发表于2016/10/31 10:50:07 原文链接
阅读:390 评论:0 查看评论

Read more
UbuntuTouch

大家如果使用snap的话,你可以发现如下的命令:

liuxg@liuxg:~$ snap --help
Usage:
  snap [OPTIONS] <command>

The snap tool interacts with the snapd daemon to control the snappy software platform.


Application Options:
      --version  Print the version and exit

Help Options:
  -h, --help     Show this help message

Available commands:
  abort        Abort a pending change
  ack          Adds an assertion to the system
  buy          Buys a snap
  change       List a change's tasks
  changes      List system changes
  connect      Connects a plug to a slot
  create-user  Creates a local system user
  disable      Disables a snap in the system
  disconnect   Disconnects a plug from a slot
  download     Download a given snap
  enable       Enables a snap in the system
  find         Finds packages to install
  get          Get snap configuration
  help         Help
  install      Installs a snap to the system
  interfaces   Lists interfaces in the system
  known        Shows known assertions of the provided type
  list         List installed snaps
  login        Authenticates on snapd and the store
  logout       Log out of the store
  refresh      Refreshes a snap in the system
  remove       Removes a snap from the system
  revert       Reverts the given snap to the previous state
  run          Run the given snap command
  set          Set snap configuration
  try          Tests a snap in the system

大家可以发现一个叫做"run"的命令.在大多数的情况下,我们并不需要运行这个命令.它在我们运行应用的时候被自动调用.但是,它有一个选项"--shell"非常有用,可以帮助我们调试我们的应用.比如,我们可以通过如下的方式:

$ snap try prime --devmode
$ cp /usr/bin/strace prime
$ sudo snap run --shell <snap.app>
$ (sudo) ./strace

这样我们就可以在一个shell中来调试我们的应用.我们以https://github.com/liu-xiao-guo/helloworld-snap例子为例.在安装完我们的snap应用后.我们可以使用如下的命令查看我们的环境:

liuxg@liuxg:~$ env | grep SNAP
liuxg@liuxg:~$ sudo -S snap run --shell hello-xiaoguo.hello-world
[sudo] password for liuxg: 
root@liuxg:/home/liuxg# env | grep SNAP
SNAP_USER_COMMON=/root/snap/hello-xiaoguo/common
SNAP_REEXEC=
SNAP_LIBRARY_PATH=/var/lib/snapd/lib/gl:
SNAP_COMMON=/var/snap/hello-xiaoguo/common
SNAP_USER_DATA=/root/snap/hello-xiaoguo/x1
SNAP_DATA=/var/snap/hello-xiaoguo/x1
SNAP_REVISION=x1
SNAP_NAME=hello-xiaoguo
SNAP_ARCH=amd64
SNAP_VERSION=1.0
SNAP=/snap/hello-xiaoguo/x1

从上面我们可以看出来,在shell中已经有我们的snap的环境变量等信息.





作者:UbuntuTouch 发表于2016/10/26 9:57:28 原文链接
阅读:378 评论:0 查看评论

Read more
UbuntuTouch

当我们完成一个Ubuntu Core应用的时候,可能需要我们的Ubuntu Core应用根据我们的设置需要来配置我们的运行所需要的一些参数,比如,我想确消我们Ubuntu Core系统的自动更新功能,或对我们的Ubuntu Core应用进行分别的设置从而改变该应用的运行.在今天的教程中,我们来展示如何在Ubuntu Core应用中进行配置.


为了展示,我们已经开发一个例程.在如下的地址可以找到我的例程:

https://github.com/liu-xiao-guo/helloworld-configure

我们的snapcraft.yaml文件如下:

name: hello
version: "1.0"
summary: The 'hello-world' of snaps
description: |
    This is a simple snap example that includes a few interesting binaries
    to demonstrate snaps and their confinement.
    * hello-world.env  - dump the env of commands run inside app sandbox
    * hello-world.evil - show how snappy sandboxes binaries
    * hello-world.sh   - enter interactive shell that runs in app sandbox
    * hello-world      - simply output text
confinement: strict
type: app  #it can be gadget or framework

apps:
 env:
   command: bin/env
 evil:
   command: bin/evil
 sh:
   command: bin/sh
 hello-world:
   command: bin/echo
   plugs: [home,unity7,opengl]
 createfile:
   command: bin/createfile
 createfiletohome:
   command: bin/createfiletohome

parts:
 hello:
  plugin: copy
  files:
    ./bin: bin
 config:
  plugin: dump
  source: .
  organize:
    configure: meta/hooks/configure
    


在未来,也许我们的snapcraft工具做得更好,以更方便地支持configure.这样我们可能不必要使用dump来安装这个文件.在这里最关键的是:我们需要把一个叫做configure的可以执行的文件打包于meta/hooks/目录下.这样就可以了.我们的configure的内容如下:

configure

#!/bin/sh

if ! username=$(snapctl get username); then
    echo "Username is required"
    exit 1
fi

if ! password=$(snapctl get password); then
    echo "Password is required"
    exit 1
fi

# Handle username and password, perhaps write to a credential file of some sort.
echo "user=$username" > $SNAP_DATA/credentials
echo "password=$password" >> $SNAP_DATA/credentials
chmod 600 $SNAP_DATA/credentials
在这个脚本中,我们读取username及password,并把它们存于到$SNAP_DATA/credentials的文件中.

等我们打包成功后,再安装好我们的hello snap应用.

liu-xiao-guo@localhost:~$ snap list
Name         Version       Rev  Developer  Notes
bluez        5.37-1        7    canonical  -
classic      16.04         14   canonical  devmode
hello        1.0           x1              -
lights-app   0.1           x1              devmode
livevideo    0.1           x1              devmode
pi2-kernel   4.4.0-1030-3  22   canonical  -
pi3          16.04-0.5     6    canonical  -
piglow-app   1.0           x2              devmode
sensortag    1.0           x3              devmode
snapweb      0.21.2        25   canonical  -
ubuntu-core  16.04.1       760  canonical  -

我们可以运行我们的hello.env应用:

liu-xiao-guo@localhost:~$ sudo hello.env | grep SNAP
SNAP_USER_COMMON=/root/snap/hello/common
SNAP_REEXEC=
SNAP_LIBRARY_PATH=/var/lib/snapd/lib/gl:
SNAP_COMMON=/var/snap/hello/common
SNAP_USER_DATA=/root/snap/hello/x1
SNAP_DATA=/var/snap/hello/x1
SNAP_REVISION=x1
SNAP_NAME=hello
SNAP_ARCH=armhf
SNAP_VERSION=1.0
SNAP=/snap/hello/x1

从上面我们可以看出来我们的SNAP_DATA目录位于/var/snap/hello/current目录中.

我们再打入如下的命令:

liu-xiao-guo@localhost:~$ sudo snap set hello username=foo1 password=bar1

如果没有任何的错误,我们可以看出来我们的设置已经成功运行.在上面的命令执行后,我们的项目中的configure脚本会自动被调用,并把我们所需要的设置置于我们所需要的文件中.我们可以通过如下的命令来检查我们给应用所做的设置:

liu-xiao-guo@localhost:~$ sudo snap set hello username=foo1 password=bar1
liu-xiao-guo@localhost:~$ cd /var/snap/hello/current
liu-xiao-guo@localhost:/var/snap/hello/current$ cat credentials 
cat: credentials: Permission denied
liu-xiao-guo@localhost:/var/snap/hello/current$ sudo cat credentials 
user="foo1"
password="bar1"

通过上面的测试,我们可以看出来,我们已经把我们想要的设置放入到我们所需要的目录中.在我们运行我们的应用时,我们可以根据这些设置来做不同的事情.

我们也可以通过如下的方法来得到我们的设置:

liu-xiao-guo@localhost:~$ snap get hello username
foo

由于一些原因,目前我在ubuntu的设备上测试成功,在16.04的桌面上snapd的支持还有一点问题.







作者:UbuntuTouch 发表于2016/10/31 13:52:00 原文链接
阅读:461 评论:0 查看评论

Read more
UbuntuTouch

[原]LeMaker Guitar Snappy Ubuntu安装体验

我们知道LeMaker的版子是支持Ubuntu Core的.具体的信息可以在地址找到.在这篇文章中,我们介绍如何安装Ubuntu Core到LeMaker的板子中去.


1.准备工作


LeMaker Guitar + LeMaker Guitar Baseboard Rev.B 一套

电源适配器一套
PC主机一套
Snappy Ubuntu SD卡镜像(http://mirror.lemaker.org/Snappy_Ubuntu_16_For_Guitar_SD_Beta2.7z


2.更新升级EMMC里面的系统


虽然我们用的是SD卡的镜像,但是由于LeMaker Guitar的早期板子的出厂emmc系统使用的旧版本固件,新旧固件在显示框架上面有很大的改动,不能混用,所以建议首先将板子emmc里面系统镜像升级到最新目前网站上面提供的任意系统的最新版本。

系统下载:http://www.lemaker.org/product-guitar-resource.html , 任意选择一个系统的最新emmc版本的下载。
EMMC系统安装方法见说明,很容易:http://wiki.lemaker.org/LeMaker_Guitar:Quick_Start#Installing_OS_image_into_eMMC_NAND_Flash


EMMC里面的系统升级安装完成后,先插上电源,不要插SD卡,确认EMMC里面的系统是跑起来了,然后断开电源。如果EMMC系统运行没问题,才能开始下面一步。


3. 将下载的SD卡的系统镜像烧录到SD卡中


我使用的windows电脑。下载一个SDFormatter软件和win32 Disk Imager。

(1)将SD卡通过USB读卡器插入到电脑上面,建议一定要USB读卡器,否则会导致烧录不成功。
(2)使用SDFormatter软件格式化SD卡。
(3)使用win32 disk imager软件载入下载的系统镜像,并且烧录到SD卡中。
烧录成功后拔下SD卡。


当然你也可以用Linux的电脑来完成上面步骤,可以先通过fdisk和mkfs等命令格式化SD卡,然后通过dd命令烧录系统镜像即可。我相信,玩Linux的人应该这几个命令是比较熟悉的。


4.将SD卡插入到Guitar板子中上电启动。由于Snappy Ubuntu Core不带桌面,所以HDMI输出显示的是命令行模式。

作者:UbuntuTouch 发表于2016/9/12 7:21:00 原文链接
阅读:535 评论:0 查看评论

Read more
UbuntuTouch

[原]如何把魅族Pro 5刷成Ubuntu手机

对于一下Ubuntu的粉丝来说,能够把魅族的手机刷成Ubuntu手机是一件非常幸运的事.我找到了一篇这样的文章.不过大家需要小心.我对下面这个链接的内容没有做任何的验证.希望大家本着自己对自己负责的原则.我们对里面的内容,不做任何的负责.


How to flash Meizu Pro 5 to Ubuntu Touch


中文教程:http://weibo.com/ttarticle/p/show?id=2309404019204142568347

作者:UbuntuTouch 发表于2016/9/12 14:02:55 原文链接
阅读:1513 评论:0 查看评论

Read more