[systemd-devel] [PATCH][V3] systemd-analyze: rewrite in C.

Simon Peeters peeters.simon at gmail.com
Mon Feb 4 12:32:33 PST 2013


Written by Peeters Simon <peeters.simon at gmail.com>. Makefile stuff
and cleaned up a bit by Auke Kok <auke-jan.h.kok at intel.com>.
---

Fixed some stuff and dit some more cleanup.

This should just cover the same usage as the old systemd-analyze, but we can
add more functionality afterwards (systemctl dot, other output formats,...)

This is the rebased version as asked by William.


 Makefile.am                    |  21 +-
 src/analyze/systemd-analyze.c  | 575 +++++++++++++++++++++++++++++++++++++++++
 src/analyze/systemd-analyze.in | 328 -----------------------
 3 files changed, 585 insertions(+), 339 deletions(-)
 create mode 100644 src/analyze/systemd-analyze.c
 delete mode 100755 src/analyze/systemd-analyze.in

diff --git a/Makefile.am b/Makefile.am
index 88662c0..f3ab908 100644
--- a/Makefile.am
+++ b/Makefile.am
@@ -268,7 +268,8 @@ rootbin_PROGRAMS = \
 	systemd-ask-password \
 	systemd-tty-ask-password-agent \
 	systemd-tmpfiles \
-	systemd-machine-id-setup
+	systemd-machine-id-setup \
+	systemd-analyze
 
 bin_PROGRAMS = \
 	systemd-cgls \
@@ -299,14 +300,16 @@ systemgenerator_PROGRAMS = \
 	systemd-system-update-generator \
 	systemd-efi-boot-generator
 
-dist_bin_SCRIPTS = \
-	src/analyze/systemd-analyze
+systemd_analyze_SOURCES = \
+	src/analyze/systemd-analyze.c
 
-EXTRA_DIST += \
-	src/analyze/systemd-analyze.in
+systemd_analyze_CFLAGS = \
+	$(AM_CFLAGS) \
+	$(DBUS_CFLAGS)
 
-CLEANFILES += \
-	src/analyze/systemd-analyze
+systemd_analyze_LDADD = \
+	libsystemd-shared.la \
+	libsystemd-dbus.la
 
 dist_bashcompletion_DATA = \
 	shell-completion/systemd-bash-completion.sh
@@ -3855,10 +3858,6 @@ src/%.policy.in: src/%.policy.in.in Makefile
 	$(SED_PROCESS)
 	$(AM_V_GEN)chmod +x $@
 
-src/analyze/systemd-analyze: %: %.in Makefile
-	$(SED_PROCESS)
-	$(AM_V_GEN)chmod +x $@
-
 src/%.c: src/%.gperf
 	$(AM_V_at)$(MKDIR_P) $(dir $@)
 	$(AM_V_GPERF)$(GPERF) < $< > $@
diff --git a/src/analyze/systemd-analyze.c b/src/analyze/systemd-analyze.c
new file mode 100644
index 0000000..8aaf238
--- /dev/null
+++ b/src/analyze/systemd-analyze.c
@@ -0,0 +1,575 @@
+#include <stdio.h>
+#include <stdlib.h>
+#include <getopt.h>
+#include <locale.h>
+
+#include "install.h"
+#include "log.h"
+#include "dbus-common.h"
+#include "build.h"
+#include "util.h"
+
+#define svg(...) printf(__VA_ARGS__)
+#define svg_bar(class, begin, end) \
+        svg("  <rect class=\"%s\" x=\"%.03f\" y=\"%.03f\" width=\"%.03f\" height=\"%.03f\" />\n", \
+                        (class), \
+                        scale_x * (begin) * 0.000001, scale_y * barcount, \
+                        scale_x * ((end) - (begin)) * 0.000001, scale_y - 1.0)
+#define svg_text_nl(begin, format, ...) \
+        svg("  <text x=\"%.03f\" y=\"%.03f\">"format"</text>\n", \
+                        scale_x * (begin) * 0.000001 + 5.0, \
+                        (scale_y * barcount++) + 14.0, ## __VA_ARGS__)
+#define svg_bar_text_nl(class, begin, end, text_format, ...) do { \
+                svg_bar(class, begin, end); \
+                svg_text_nl(begin, text_format, ## __VA_ARGS__); \
+        }while (false)
+
+static UnitFileScope arg_scope = UNIT_FILE_SYSTEM;
+
+double scale_x = 100.0;
+double scale_y = 20.0;
+
+static int barcount = 0;
+
+struct boot_times {
+        uint64_t firmware_time;
+        uint64_t loader_time;
+        uint64_t kernel_time;
+        uint64_t kernel_done_time;
+        uint64_t initrd_time;
+        uint64_t userspace_time;
+        uint64_t finish_time;
+};
+struct unit_times {
+        char *name;
+        uint64_t ixt;
+        uint64_t iet;
+        uint64_t axt;
+        uint64_t aet;
+        uint64_t time;
+};
+
+static uint64_t property_getu64(
+                DBusConnection *bus,
+                const char *dest,
+                const char *path,
+                const char *interface,
+                const char *property)
+{
+        int err = errno; //back up errno to prevent accidentally setting it.
+        _cleanup_dbus_message_unref_ DBusMessage *reply = NULL;
+        DBusMessageIter iter, sub;
+        uint64_t result = 0;
+
+        errno = -bus_method_call_with_reply (bus, dest, path,
+                        "org.freedesktop.DBus.Properties", "Get",
+                        &reply, NULL,
+                        DBUS_TYPE_STRING, &interface,
+                        DBUS_TYPE_STRING, &property,
+                        DBUS_TYPE_INVALID);
+        if (errno)
+                return 0;
+
+        if (!dbus_message_iter_init(reply, &iter) ||
+                        dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT)
+                goto fail;
+
+        dbus_message_iter_recurse(&iter, &sub);
+
+        if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_UINT64)
+                goto fail;
+
+        dbus_message_iter_get_basic(&sub, &result);
+
+        errno = err;
+        return result;
+fail:
+        log_error("Failed to parse reply.");
+        errno = EIO;
+        return 0;
+}
+
+static int compare_unit_time(const void *a, const void *b)
+{
+        const struct unit_times *u = a, *v = b;
+
+        if (u->time > v->time)
+                return -1;
+        if (u->time < v->time)
+                return 1;
+        return 0;
+}
+
+static int compare_unit_start(const void *a, const void *b)
+{
+        const struct unit_times *u = a, *v = b;
+
+        if (u->ixt > v->ixt)
+                return 1;
+        if (u->ixt < v->ixt)
+                return -1;
+        return 0;
+}
+
+static int acquire_time_data(DBusConnection *bus, struct unit_times **out)
+{
+        _cleanup_dbus_message_unref_ DBusMessage *reply = NULL;
+        DBusMessageIter iter, sub, sub2;
+        int c = 0, n_units = 0;
+        struct unit_times *unit_times = NULL;
+        int r;
+
+        r = bus_method_call_with_reply (
+                        bus,
+                        "org.freedesktop.systemd1",
+                        "/org/freedesktop/systemd1",
+                        "org.freedesktop.systemd1.Manager",
+                        "ListUnits",
+                        &reply,
+                        NULL,
+                        DBUS_TYPE_INVALID);
+        if (r)
+                goto fail;
+
+        if (!dbus_message_iter_init(reply, &iter) ||
+                        dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
+                        dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_STRUCT)  {
+                log_error("Failed to parse reply.");
+                r = -EIO;
+                goto fail;
+        }
+
+        dbus_message_iter_recurse(&iter, &sub);
+
+        while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
+                struct unit_times *u;
+                char *path;
+                char *name;
+
+                if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRUCT) {
+                        log_error("Failed to parse reply.");
+                        r = -EIO;
+                        goto fail;
+                }
+
+                if (c >= n_units) {
+                        struct unit_times *w;
+
+                        n_units = MAX(2*c, 16);
+                        w = realloc(unit_times, sizeof(struct unit_times) * n_units);
+
+                        if (!w) {
+                                log_error("Failed to allocate unit array.");
+                                r = -ENOMEM;
+                                goto fail;
+                        }
+
+                        unit_times = w;
+                }
+                u = unit_times+c;
+                u->name = NULL;
+
+                dbus_message_iter_recurse(&sub, &sub2);
+
+                if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &name, true) < 0 ||
+                                !dbus_message_iter_next(&sub2) ||
+                                !dbus_message_iter_next(&sub2) ||
+                                !dbus_message_iter_next(&sub2) ||
+                                !dbus_message_iter_next(&sub2) ||
+                                !dbus_message_iter_next(&sub2) ||
+                                bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_OBJECT_PATH, &path, true) < 0) {
+                        log_error("Failed to parse reply.");
+                        r = -EIO;
+                        goto fail;
+                }
+                errno = 0;
+                u->ixt = property_getu64(bus,
+                                "org.freedesktop.systemd1",
+                                path,
+                                "org.freedesktop.systemd1.Unit",
+                                "InactiveExitTimestampMonotonic");
+                u->iet = property_getu64(bus,
+                                "org.freedesktop.systemd1",
+                                path,
+                                "org.freedesktop.systemd1.Unit",
+                                "InactiveEnterTimestampMonotonic");
+                u->axt = property_getu64(bus,
+                                "org.freedesktop.systemd1",
+                                path,
+                                "org.freedesktop.systemd1.Unit",
+                                "ActiveExitTimestampMonotonic");
+                u->aet = property_getu64(bus,
+                                "org.freedesktop.systemd1",
+                                path,
+                                "org.freedesktop.systemd1.Unit",
+                                "ActiveEnterTimestampMonotonic");
+                if (errno) {
+                        r = -errno;
+                        goto fail;
+                }
+                if (u->aet >= u->ixt)
+                        u->time = u->aet - u->ixt;
+                else if (u->iet >= u->ixt)
+                        u->time = u->iet - u->ixt;
+                else
+                        u->time = 0;
+                dbus_message_iter_next(&sub);
+                if (u->ixt == 0)
+                        continue;
+
+                u->name = strdup(name);
+                if (u->name == NULL) {
+                        r = -ENOMEM;
+                        goto fail;
+                }
+                c++;
+        }
+
+        *out = unit_times;
+        return c;
+fail:
+        for (; c >= 0; c--)
+                free(unit_times[c].name);
+        free(unit_times);
+        return r;
+}
+
+static void svg_graph_box(int height, int64_t begin, int64_t end)
+{
+        /* outside box, fill */
+        svg("<rect class=\"box\" x=\"0\" y=\"0\" width=\"%.03f\" height=\"%.03f\" />\n",
+            scale_x * (end - begin) * 0.000001, scale_y * height);
+
+        for (int i = begin/100000; i <= end/100000; i++) {
+                /* lines for each second */
+                double x = scale_x * i * 0.1;
+                if (i % 50 == 0)
+                        svg("  <line class=\"sec5\" x1=\"%.03f\" y1=\"0\" x2=\"%.03f\" y2=\"%.03f\" />\n"
+                            "  <text class=\"sec\" x=\"%.03f\" y=\"%.03f\" >%.01fs</text>\n",
+                            x, x, scale_y * height, x, -5.0, 0.1 * i);
+                else if (i % 10 == 0)
+                        svg("  <line class=\"sec1\" x1=\"%.03f\" y1=\"0\" x2=\"%.03f\" y2=\"%.03f\" />\n"
+                            "  <text class=\"sec\" x=\"%.03f\" y=\"%.03f\" >%.01fs</text>\n",
+                            x, x, scale_y * height, x, -5.0, 0.1 * i);
+                else
+                        svg("  <line class=\"sec01\" x1=\"%.03f\" y1=\"0\" x2=\"%.03f\" y2=\"%.03f\" />\n",
+                            x, x, scale_y * height);
+        }
+}
+
+static int get_boot_times(DBusConnection *bus, struct boot_times *t)
+{
+        errno = 0;
+        t->firmware_time = property_getu64(bus,
+                        "org.freedesktop.systemd1",
+                        "/org/freedesktop/systemd1",
+                        "org.freedesktop.systemd1.Manager",
+                        "FirmwareTimestampMonotonic");
+        t->loader_time = property_getu64(bus,
+                        "org.freedesktop.systemd1",
+                        "/org/freedesktop/systemd1",
+                        "org.freedesktop.systemd1.Manager",
+                        "LoaderTimestampMonotonic");
+        t->kernel_time = property_getu64(bus,
+                        "org.freedesktop.systemd1",
+                        "/org/freedesktop/systemd1",
+                        "org.freedesktop.systemd1.Manager",
+                        "KernelTimestamp");
+        t->initrd_time = property_getu64(bus,
+                        "org.freedesktop.systemd1",
+                        "/org/freedesktop/systemd1",
+                        "org.freedesktop.systemd1.Manager",
+                        "InitRDTimestampMonotonic");
+        t->userspace_time = property_getu64(bus,
+                        "org.freedesktop.systemd1",
+                        "/org/freedesktop/systemd1",
+                        "org.freedesktop.systemd1.Manager",
+                        "UserspaceTimestampMonotonic");
+        t->finish_time = property_getu64(bus,
+                        "org.freedesktop.systemd1",
+                        "/org/freedesktop/systemd1",
+                        "org.freedesktop.systemd1.Manager",
+                        "FinishTimestampMonotonic");
+        if (t->initrd_time)
+                t->kernel_done_time = t->initrd_time;
+        else
+                t->kernel_done_time = t->userspace_time;
+
+        if (errno)
+                return -errno;
+        return 0;
+}
+
+static int analyze_plot(DBusConnection *bus)
+{
+        struct unit_times *times;
+        struct boot_times boot;
+        int n, m = 1;
+        double width;
+
+        n = get_boot_times(bus, &boot);
+        if (n)
+                return n;
+
+        n = acquire_time_data(bus, &times);
+        if (n<=0)
+                return n;
+
+        qsort(times, n, sizeof(struct unit_times), compare_unit_start);
+
+        width = 80 + (scale_x * (boot.firmware_time + boot.finish_time) * 0.000001);
+        if (width < 800.0)
+                width = 800.0;
+
+        if (boot.firmware_time > boot.loader_time)
+                m++;
+        if (boot.loader_time) {
+                m++;
+                if (width < 1000.0)
+                        width = 1000.0;
+        }
+        if (boot.initrd_time)
+                m++;
+        if (boot.kernel_time)
+                m++;
+
+        for (int i=0; i < n; i++)
+                if (times[i].ixt >= boot.userspace_time && times[i].ixt <= boot.finish_time)
+                        m++;
+
+        svg("<?xml version=\"1.0\" standalone=\"no\"?>\n");
+        svg("<!DOCTYPE svg PUBLIC \"-//W3C//DTD SVG 1.1//EN\" ");
+        svg("\"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd\">\n");
+
+        svg("<svg width=\"%.0fpx\" height=\"%.0fpx\" version=\"1.1\" ",
+                        80.0 + (scale_x * (boot.firmware_time + boot.finish_time) * 0.000001),
+                        150.0 + (m *scale_y));
+        svg("xmlns=\"http://www.w3.org/2000/svg\">\n\n");
+
+        /* write some basic info as a comment, including some help */
+        svg("<!-- This file is a systemd-analyze SVG file. It is best rendered in a   -->\n"
+            "<!-- browser such as Chrome/Chromium, firefox. Other applications that   -->\n"
+            "<!-- render these files properly but much more slow are ImageMagick,     -->\n"
+            "<!-- gimp, inkscape, etc.. To display the files on your system, just     -->\n"
+            "<!-- point your browser to file:///var/log/ and click.                   -->\n\n"
+            "<!-- this plot was generated by systemd-analyze version %-16.16s -->\n\n", VERSION);
+
+        /* style sheet */
+        svg("<defs>\n  <style type=\"text/css\">\n    <![CDATA[\n"
+            "      rect       { stroke-width: 1; stroke-opacity: 0; }\n"
+            "      rect.activating   { fill: rgb(255,0,0); fill-opacity: 0.7; }\n"
+            "      rect.active       { fill: rgb(200,150,150); fill-opacity: 0.7; }\n"
+            "      rect.deactivating { fill: rgb(150,100,100); fill-opacity: 0.7; }\n"
+            "      rect.kernel       { fill: rgb(150,150,150); fill-opacity: 0.7; }\n"
+            "      rect.initrd       { fill: rgb(150,150,150); fill-opacity: 0.7; }\n"
+            "      rect.firmware     { fill: rgb(150,150,150); fill-opacity: 0.7; }\n"
+            "      rect.loader       { fill: rgb(150,150,150); fill-opacity: 0.7; }\n"
+            "      rect.userspace    { fill: rgb(150,150,150); fill-opacity: 0.7; }\n"
+            "      rect.box   { fill: rgb(240,240,240); stroke: rgb(192,192,192); }\n"
+            "      line       { stroke: rgb(64,64,64); stroke-width: 1; }\n"
+            "//    line.sec1  { }\n"
+            "      line.sec5  { stroke-width: 2; }\n"
+            "      line.sec01 { stroke: rgb(224,224,224); stroke-width: 1; }\n"
+            "      text       { font-family: Verdana, Helvetica; font-size: 10; }\n"
+            "      text.sec   { font-size: 8; }\n"
+            "    ]]>\n   </style>\n</defs>\n\n");
+
+        svg("<text x=\"20\" y=\"40\">Startup finished in ");
+
+        if (boot.firmware_time > boot.loader_time)
+                svg("%llums (firmware) + ", (boot.firmware_time - boot.loader_time) / 1000);
+        if (boot.loader_time)
+                svg("%llums (loader) + ", boot.loader_time / 1000);
+        if (boot.kernel_time)
+                svg("%llums (kernel) + ", boot.kernel_done_time  / 1000);
+        if (boot.initrd_time)
+                svg("%llums (initrd) + ", (boot.userspace_time - boot.initrd_time) / 1000);
+        svg("%llums (userspace) ", (boot.finish_time - boot.userspace_time) / 1000);
+        if (boot.kernel_time)
+                svg("= %llums\n", (boot.firmware_time + boot.finish_time) / 1000);
+        else
+                svg("= %llums\n", (boot.finish_time - boot.userspace_time) / 1000);
+        svg("</text>");
+
+        svg("<g transform=\"translate(%.3f,100)\">\n", 20.0 + (scale_x * boot.firmware_time *0.000001));
+        svg_graph_box(m, -boot.firmware_time, boot.finish_time);
+
+        if (boot.firmware_time > boot.loader_time)
+                svg_bar_text_nl("firmware", -(int64_t) boot.firmware_time, -(int64_t) boot.loader_time, "firmware");
+        if (boot.loader_time > 0)
+                svg_bar_text_nl("loader", -(int64_t) boot.loader_time, 0, "loader");
+        if (boot.kernel_time > 0)
+                svg_bar_text_nl("kernel", 0, boot.kernel_done_time, "kernel");
+        if (boot.initrd_time > 0)
+                svg_bar_text_nl("initrd", boot.initrd_time, boot.userspace_time, "initrd");
+        svg_bar_text_nl("userspace", boot.userspace_time, boot.finish_time, "userspace");
+
+        for (int i=0; i < n; i++) {
+                struct unit_times *u = times + i;
+                if (u->ixt < boot.userspace_time || u->ixt > boot.finish_time)
+                        continue;
+                if (u->iet > u->ixt && u->iet <= boot.finish_time
+                                && u->aet == 0 && u->axt == 0) {
+                        svg_bar("activating",   u->ixt, u->iet);
+                } else if (u->aet < u->ixt || u->aet > boot.finish_time) {
+                        svg_bar("activating",   u->ixt, boot.finish_time);
+                } else if (u->axt < u->aet || u->aet > boot.finish_time) {
+                        svg_bar("activating",   u->ixt, u->aet);
+                        svg_bar("active",       u->aet, boot.finish_time);
+                } else if (u->iet < u->axt || u->iet > boot.finish_time) {
+                        svg_bar("activating",   u->ixt, u->aet);
+                        svg_bar("active",       u->aet, u->axt);
+                        svg_bar("deactivating", u->axt, boot.finish_time);
+                } else {
+                        svg_bar("activating",   u->ixt, u->aet);
+                        svg_bar("active",       u->aet, u->axt);
+                        svg_bar("deactivating", u->axt, u->iet);
+                }
+                if (u->time > 0)
+                        svg_text_nl(u->ixt, "%s (%llums)", u->name, u->time/1000);
+                else
+                        svg_text_nl(u->ixt, "%s", u->name);
+
+        }
+        svg("</g>\n\n");
+
+        svg("</svg>");
+        return 0;
+}
+
+static int analyze_blame(DBusConnection *bus)
+{
+        struct unit_times *times;
+        int n = acquire_time_data(bus, &times);
+        if (n<=0)
+                return n;
+
+        qsort(times, n, sizeof(struct unit_times), compare_unit_time);
+
+        for (int i = 0; i < n; i++) {
+                if (times[i].time)
+                        printf("%6llums %s\n", times[i].time / 1000, times[i].name);
+        }
+        return 0;
+}
+
+static int analyze_time(DBusConnection *bus)
+{
+        struct boot_times t;
+        int r;
+        r = get_boot_times(bus, &t);
+        if (r)
+                return r;
+
+        printf("Startup finished in ");
+
+        if (t.firmware_time > t.loader_time)
+                printf("%llums (firmware) + ", (t.firmware_time - t.loader_time) / 1000);
+        if (t.loader_time)
+                printf("%llums (loader) + ", t.loader_time / 1000);
+        if (t.kernel_time)
+                printf("%llums (kernel) + ", t.kernel_done_time  / 1000);
+        if (t.initrd_time > 0)
+                printf("%llums (initrd) + ", (t.userspace_time - t.initrd_time) / 1000);
+
+        printf("%llums (userspace) ", (t.finish_time - t.userspace_time) / 1000);
+
+        if (t.kernel_time > 0)
+                printf("= %llums\n", (t.firmware_time + t.finish_time) / 1000);
+        else
+                printf("= %llums\n", (t.finish_time - t.userspace_time) / 1000);
+
+        return 0;
+}
+
+static void analyze_help(void)
+{
+        printf("%s [OPTIONS...] {COMMAND} ...\n\n"
+               "Process systemd profiling information\n\n"
+               "  -h --help           Show this help\n"
+               "     --version        Show package version\n"
+               "     --system         Connect to system manager\n"
+               "     --user           Connect to user service manager\n\n"
+               "Commands:\n"
+               "  time      print time spent in the kernel before reaching userspace\n"
+               "  blame     print list of running units ordered by time to init\n"
+               "  plot      output SVG graphic showing service initialization\n\n",
+               program_invocation_short_name);
+}
+
+static int parse_argv(int argc, char *argv[])
+{
+        enum {
+                ARG_VERSION = 0x100,
+                ARG_USER,
+                ARG_SYSTEM
+        };
+
+        static const struct option options[] = {
+                { "help",      no_argument,       NULL, 'h'           },
+                { "version",   no_argument,       NULL, ARG_VERSION   },
+                { "user",      no_argument,       NULL, ARG_USER      },
+                { "system",    no_argument,       NULL, ARG_SYSTEM    },
+                { NULL,        0,                 NULL, 0             }
+        };
+
+        assert(argc >= 0);
+        assert(argv);
+
+        while (true) {
+                switch (getopt_long(argc, argv, "h", options, NULL)) {
+                        case 'h':
+                                analyze_help();
+                                return 0;
+                        case ARG_VERSION:
+                                puts(PACKAGE_STRING "\n" SYSTEMD_FEATURES);
+                                return 0;
+                        case ARG_USER:
+                                arg_scope = UNIT_FILE_USER;
+                                break;
+                        case ARG_SYSTEM:
+                                arg_scope = UNIT_FILE_SYSTEM;
+                                break;
+                        case -1:
+                                return 1;
+                        case '?':
+                                return -EINVAL;
+                        default:
+                                assert_not_reached("Unhandled option");
+                }
+        }
+}
+
+int main(int argc, char*argv[]) {
+        int r;
+        DBusConnection *bus = NULL;
+
+        setlocale(LC_ALL, "");
+        log_parse_environment();
+        log_open();
+
+        r = parse_argv(argc, argv);
+        if (r < 0)
+                return 1;
+        if (r == 0)
+                return 0;
+
+        bus = dbus_bus_get(arg_scope == UNIT_FILE_SYSTEM ? DBUS_BUS_SYSTEM : DBUS_BUS_SESSION, NULL);
+        if (!bus)
+                return 1;
+
+        if (!argv[optind] || streq(argv[optind], "time"))
+                r = analyze_time(bus);
+        else if (streq(argv[optind], "blame"))
+                r = analyze_blame(bus);
+        else if (streq(argv[optind], "plot"))
+                r = analyze_plot(bus);
+        else
+                log_error("Unknown operation '%s'.", argv[optind]);
+
+        dbus_connection_unref(bus);
+
+        if (r)
+                return 1;
+        return 0;
+}
diff --git a/src/analyze/systemd-analyze.in b/src/analyze/systemd-analyze.in
deleted file mode 100755
index e964bb3..0000000
--- a/src/analyze/systemd-analyze.in
+++ /dev/null
@@ -1,328 +0,0 @@
-#!@PYTHON_BINARY@
-# -*-python-*-
-
-#  This file is part of systemd.
-#
-#  Copyright 2010-2013 Lennart Poettering
-#
-#  systemd is free software; you can redistribute it and/or modify it
-#  under the terms of the GNU Lesser General Public License as published by
-#  the Free Software Foundation; either version 2.1 of the License, or
-#  (at your option) any later version.
-#
-#  systemd 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
-#  Lesser General Public License for more details.
-#
-#  You should have received a copy of the GNU Lesser General Public License
-#  along with systemd; If not, see <http://www.gnu.org/licenses/>.
-
-import sys, os
-import argparse
-from gi.repository import Gio
-try:
-        import cairo
-except ImportError:
-        cairo = None
-
-def acquire_time_data():
-        manager = Gio.DBusProxy.new_for_bus_sync(bus, Gio.DBusProxyFlags.NONE,
-                None, 'org.freedesktop.systemd1', '/org/freedesktop/systemd1', 'org.freedesktop.systemd1.Manager', None)
-        units = manager.ListUnits()
-
-        l = []
-
-        for i in units:
-                if i[5] != "":
-                        continue
-
-                properties = Gio.DBusProxy.new_for_bus_sync(bus, Gio.DBusProxyFlags.NONE,
-                        None, 'org.freedesktop.systemd1', i[6], 'org.freedesktop.DBus.Properties', None)
-
-                ixt = properties.Get('(ss)', 'org.freedesktop.systemd1.Unit', 'InactiveExitTimestampMonotonic')
-                aet = properties.Get('(ss)', 'org.freedesktop.systemd1.Unit', 'ActiveEnterTimestampMonotonic')
-                axt = properties.Get('(ss)', 'org.freedesktop.systemd1.Unit', 'ActiveExitTimestampMonotonic')
-                iet = properties.Get('(ss)', 'org.freedesktop.systemd1.Unit', 'InactiveEnterTimestampMonotonic')
-
-                l.append((str(i[0]), ixt, aet, axt, iet))
-
-        return l
-
-def acquire_start_time():
-        properties = Gio.DBusProxy.new_for_bus_sync(bus, Gio.DBusProxyFlags.NONE,
-                None, 'org.freedesktop.systemd1', '/org/freedesktop/systemd1', 'org.freedesktop.DBus.Properties', None)
-
-        # Note that the firmware/loader times are returned as positive
-        # values but are actually considered negative from the point
-        # in time of kernel initialization. Also, the monotonic kernel
-        # time will always be 0 since that's the epoch of the
-        # monotonic clock. Since we want to know whether the kernel
-        # timestamp is set at all we will instead ask for the realtime
-        # clock for this timestamp.
-
-        firmware_time = properties.Get('(ss)', 'org.freedesktop.systemd1.Manager', 'FirmwareTimestampMonotonic')
-        loader_time = properties.Get('(ss)', 'org.freedesktop.systemd1.Manager', 'LoaderTimestampMonotonic')
-        kernel_time = properties.Get('(ss)', 'org.freedesktop.systemd1.Manager', 'KernelTimestamp')
-        initrd_time = properties.Get('(ss)', 'org.freedesktop.systemd1.Manager', 'InitRDTimestampMonotonic')
-        userspace_time = properties.Get('(ss)', 'org.freedesktop.systemd1.Manager', 'UserspaceTimestampMonotonic')
-        finish_time = properties.Get('(ss)', 'org.freedesktop.systemd1.Manager', 'FinishTimestampMonotonic')
-
-        if finish_time == 0:
-                sys.exit("Bootup is not yet finished. Please try again later.")
-
-        assert firmware_time >= loader_time
-        assert initrd_time <= userspace_time
-        assert userspace_time <= finish_time
-
-        return firmware_time, loader_time, kernel_time, initrd_time, userspace_time, finish_time
-
-def draw_box(context, j, k, l, m, r = 0, g = 0, b = 0):
-        context.save()
-        context.set_source_rgb(r, g, b)
-        context.rectangle(j, k, l, m)
-        context.fill()
-        context.restore()
-
-def draw_text(context, x, y, text, size = 12, r = 0, g = 0, b = 0, vcenter = 0.5, hcenter = 0.5):
-        context.save()
-
-        context.set_source_rgb(r, g, b)
-        context.select_font_face("Sans", cairo.FONT_SLANT_NORMAL, cairo.FONT_WEIGHT_NORMAL)
-        context.set_font_size(size)
-
-        if vcenter or hcenter:
-                x_bearing, y_bearing, width, height = context.text_extents(text)[:4]
-
-                if hcenter:
-                        x = x - width*hcenter - x_bearing
-
-                if vcenter:
-                        y = y - height*vcenter - y_bearing
-
-        context.move_to(x, y)
-        context.show_text(text)
-
-        context.restore()
-
-def time():
-
-        firmware_time, loader_time, kernel_time, initrd_time, userspace_time, finish_time = acquire_start_time()
-
-        sys.stdout.write("Startup finished in ")
-
-        if firmware_time > 0:
-                sys.stdout.write("%lums (firmware) + " % ((firmware_time - loader_time) / 1000))
-        if loader_time > 0:
-                sys.stdout.write("%lums (loader) + " % (loader_time / 1000))
-        if initrd_time > 0:
-                sys.stdout.write("%lums (kernel) + %lums (initrd) + " % (initrd_time / 1000, (userspace_time - initrd_time) / 1000))
-        elif kernel_time > 0:
-                sys.stdout.write("%lums (kernel) + " % (userspace_time  / 1000))
-
-        sys.stdout.write("%lums (userspace) " % ((finish_time - userspace_time) / 1000))
-
-        if kernel_time > 0:
-                sys.stdout.write("= %lums\n" % ((firmware_time + finish_time) / 1000))
-        else:
-                sys.stdout.write("= %lums\n" % ((finish_time - userspace_time) / 1000))
-
-def blame():
-
-        data = acquire_time_data()
-        s = sorted(data, key = lambda i: i[2] - i[1], reverse = True)
-
-        for name, ixt, aet, axt, iet in s:
-
-                if ixt <= 0 or aet <= 0:
-                        continue
-
-                if aet <= ixt:
-                        continue
-
-                sys.stdout.write("%6lums %s\n" % ((aet - ixt) / 1000, name))
-
-def plot():
-        if cairo is None:
-                sys.exit("Failed to initilize python-cairo required for 'plot' verb.")
-        firmware_time, loader_time, kernel_time, initrd_time, userspace_time, finish_time = acquire_start_time()
-        data = acquire_time_data()
-        s = sorted(data, key = lambda i: i[1])
-
-        # Account for kernel and initramfs bars if they exist
-        if initrd_time > 0:
-                count = 3
-        else:
-                count = 2
-
-        for name, ixt, aet, axt, iet in s:
-
-                if (ixt >= userspace_time and ixt <= finish_time) or \
-                                (aet >= userspace_time and aet <= finish_time) or \
-                                (axt >= userspace_time and axt <= finish_time):
-                        count += 1
-
-        border = 100
-        bar_height = 20
-        bar_space = bar_height * 0.1
-
-        # 1000px = 10s, 1px = 10ms
-        width = finish_time/10000 + border*2
-        height = count * (bar_height + bar_space) + border * 2
-
-        if width < 1000:
-                width = 1000
-
-        surface = cairo.SVGSurface(sys.stdout, width, height)
-        context = cairo.Context(surface)
-
-        draw_box(context, 0, 0, width, height, 1, 1, 1)
-
-        context.translate(border + 0.5, border + 0.5)
-
-        context.save()
-        context.set_line_width(1)
-        context.set_source_rgb(0.7, 0.7, 0.7)
-
-        for x in range(0, int(finish_time/10000) + 100, 100):
-                context.move_to(x, 0)
-                context.line_to(x, height-border*2)
-
-        context.move_to(0, 0)
-        context.line_to(width-border*2, 0)
-
-        context.move_to(0, height-border*2)
-        context.line_to(width-border*2, height-border*2)
-
-        context.stroke()
-        context.restore()
-
-        osrel = "Linux"
-        if os.path.exists("/etc/os-release"):
-                for line in open("/etc/os-release"):
-                        if line.startswith('PRETTY_NAME='):
-                                osrel = line[12:]
-                                osrel = osrel.strip('\"\n')
-                                break
-
-        banner = "{} {} ({} {}) {}".format(osrel, *(os.uname()[1:5]))
-        draw_text(context, 0, -15, banner, hcenter = 0, vcenter = 1)
-
-        for x in range(0, int(finish_time/10000) + 100, 100):
-                draw_text(context, x, -5, "%lus" % (x/100), vcenter = 0, hcenter = 0)
-
-        y = 0
-
-        # draw boxes for kernel and initramfs boot time
-        if initrd_time > 0:
-                draw_box(context, 0, y, initrd_time/10000, bar_height, 0.7, 0.7, 0.7)
-                draw_text(context, 10, y + bar_height/2, "kernel", hcenter = 0)
-                y += bar_height + bar_space
-
-                draw_box(context, initrd_time/10000, y, userspace_time/10000-initrd_time/10000, bar_height, 0.7, 0.7, 0.7)
-                draw_text(context, initrd_time/10000 + 10, y + bar_height/2, "initramfs", hcenter = 0)
-                y += bar_height + bar_space
-
-        else:
-                draw_box(context, 0, y, userspace_time/10000, bar_height, 0.6, 0.6, 0.6)
-                draw_text(context, 10, y + bar_height/2, "kernel", hcenter = 0)
-                y += bar_height + bar_space
-
-        draw_box(context, userspace_time/10000, y, finish_time/10000-userspace_time/10000, bar_height, 0.7, 0.7, 0.7)
-        draw_text(context, userspace_time/10000 + 10, y + bar_height/2, "userspace", hcenter = 0)
-        y += bar_height + bar_space
-
-        for name, ixt, aet, axt, iet in s:
-
-                drawn = False
-                left = -1
-
-                if ixt >= userspace_time and ixt <= finish_time:
-
-                        # Activating
-                        a = ixt
-                        b = min(filter(lambda x: x >= ixt, (aet, axt, iet, finish_time))) - ixt
-
-                        draw_box(context, a/10000, y, b/10000, bar_height, 1, 0, 0)
-                        drawn = True
-
-                        if left < 0:
-                                left = a
-
-                if aet >= userspace_time and aet <= finish_time:
-
-                        # Active
-                        a = aet
-                        b = min(filter(lambda x: x >= aet, (axt, iet, finish_time))) - aet
-
-                        draw_box(context, a/10000, y, b/10000, bar_height, .8, .6, .6)
-                        drawn = True
-
-                        if left < 0:
-                                left = a
-
-                if axt >= userspace_time and axt <= finish_time:
-
-                        # Deactivating
-                        a = axt
-                        b = min(filter(lambda x: x >= axt, (iet, finish_time))) - axt
-
-                        draw_box(context, a/10000, y, b/10000, bar_height, .6, .4, .4)
-                        drawn = True
-
-                        if left < 0:
-                                left = a
-
-                if drawn:
-                        x = left/10000
-
-                        if x < width/2-border:
-                                draw_text(context, x + 10, y + bar_height/2, name, hcenter = 0)
-                        else:
-                                draw_text(context, x - 10, y + bar_height/2, name, hcenter = 1)
-
-                        y += bar_height + bar_space
-
-        draw_text(context, 0, height-border*2, "Legend: Red = Activating; Pink = Active; Dark Pink = Deactivating", hcenter = 0, vcenter = -1)
-
-        if initrd_time > 0:
-                draw_text(context, 0, height-border*2 + bar_height, "Startup finished in %lums (kernel) + %lums (initramfs) + %lums (userspace) = %lums" % ( \
-                        initrd_time/1000, \
-                        (userspace_time - initrd_time)/1000, \
-                        (finish_time - userspace_time)/1000, \
-                        finish_time/1000), hcenter = 0, vcenter = -1)
-        else:
-                draw_text(context, 0, height-border*2 + bar_height, "Startup finished in %lums (kernel) + %lums (userspace) = %lums" % ( \
-                        userspace_time/1000, \
-                        (finish_time - userspace_time)/1000, \
-                        finish_time/1000), hcenter = 0, vcenter = -1)
-
-        surface.finish()
-
-parser = argparse.ArgumentParser(formatter_class=argparse.RawDescriptionHelpFormatter,
-                                 version='systemd-analyze @PACKAGE_VERSION@',
-                                 description='Process systemd profiling information',
-                                 epilog='''\
-time - print time spent in the kernel before reaching userspace
-blame - print list of running units ordered by time to init
-plot - output SVG graphic showing service initialization
-''')
-
-parser.add_argument('action', choices=('time', 'blame', 'plot'),
-                    default='time', nargs='?',
-                    help='action to perform (default: time)')
-parser.add_argument('--user', action='store_true',
-                    help='use the session bus')
-
-args = parser.parse_args()
-
-if args.user:
-        bus = Gio.BusType.SESSION
-else:
-        bus = Gio.BusType.SYSTEM
-
-verb = {'time' : time,
-        'blame': blame,
-        'plot' : plot,
-        }
-verb.get(args.action)()
-- 
1.8.1



More information about the systemd-devel mailing list