~ubuntuone-support/+junk/syncdaemon-perftest

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
#!/usr/bin/env python

import dbus
import time
import os
import dbus.service
import gobject
import sys
import optparse
from dbus.mainloop.glib import DBusGMainLoop
from shutil import rmtree

from u1perftest import PerfTest
from u1perftest.util import (format_speed_value,
        format_size_value, setup_logging)

from random import randint

# Cleanup via rest api
from u1perftest.rest import OAuthHttpClient

TESTDIR="syncdaemon-perftest-tmp"

class SDPerfTest(PerfTest):
    def __init__(self):
        super(SDPerfTest, self).__init__()

        self.state = 'INIT'
        self.error = False

        # "namespace" for benchmarking
        self.bm_temp_files = {}
        self.bm_upload_started = 0

        # Register callbacks here
        # This starts being messy
        self._file_created_cb = self.add_temp_file_info

        DBusGMainLoop(set_as_default=True)

        self.bus = dbus.SessionBus()

        filesystem_proxy = self.bus.get_object(
                'com.ubuntuone.SyncDaemon',
                '/filesystem',
                follow_name_owner_changes=True)

        self.filesystem_if = dbus.Interface(filesystem_proxy,
                'com.ubuntuone.SyncDaemon.FileSystem')

        syncdaemon_proxy = self.bus.get_object(
                'com.ubuntuone.SyncDaemon',
                '/',
                follow_name_owner_changes=True)

        self.syncdaemon_if = dbus.Interface(syncdaemon_proxy,
                'com.ubuntuone.SyncDaemon.SyncDaemon')

        status_proxy = self.bus.get_object(
                'com.ubuntuone.SyncDaemon',
                '/status',
                follow_name_owner_changes=True)

        self.status_if = dbus.Interface(status_proxy,
                'com.ubuntuone.SyncDaemon.Status')

        self.config_if = self.get_sd_proxy('/config',
                'com.ubuntuone.SyncDaemon.Config')

        # Signal handlers
        self.bus.add_signal_receiver(signal_name='StatusChanged',
                dbus_interface='com.ubuntuone.SyncDaemon.Status',
                handler_function=self.handle_sd_StatusChanged)

        self.bus.add_signal_receiver(signal_name='UploadStarted',
                dbus_interface='com.ubuntuone.SyncDaemon.Status',
                handler_function=self.handle_sd_UploadStarted)

        self.bus.add_signal_receiver(signal_name='UploadFinished',
                dbus_interface='com.ubuntuone.SyncDaemon.Status',
                handler_function=self.handle_sd_UploadFinished)

    
    def get_sd_proxy(self, path, interface):
        proxy = self.bus.get_object(
            'com.ubuntuone.SyncDaemon',
            path,
            follow_name_owner_changes=True)
        return dbus.Interface(proxy, interface)

    def handle_sd_StatusChanged(self, status):
        self.logger.debug("State: %s, queues: %s", status['name'], status['queues'])

        if status['name'] == u"QUEUE_MANAGER" and \
                status['queues'] == u"IDLE":
            self.logger.info("Syncdaemon is IDLE (internal state: %s)",
                    self.state)

            if self.state == "UPLOADING":
                return self.handle_UPLOAD_COMPLETED()

            if self.state == "CLEANUP":
                return self.handle_CLEANUP_COMPLETED()

    def add_temp_file_info(self, path, info):
        self.bm_temp_files[path] = info

    def handle_sd_UploadStarted(self, path):
        if not self.bm_upload_started:
            self.bm_upload_started = time.time()

        self.logger.debug("Got UploadStarted notification of %s", path)

        if path not in self.bm_temp_files:
            self.logger.warn("Warning: Not our file - %s - starting", path)
            return

        self.bm_temp_files[path]['upload_started'] = time.time()

    def handle_sd_UploadFinished(self, path, info):
        self.logger.debug("Got UploadFinished notification of %s", path)

        if path not in self.bm_temp_files:
            self.logger.warn("Warning: Not our file - %s - uploaded", path)
            return

        if 'error' in info and info['error']:
            self.logger.warn("Warning: Upload of %s did not complete properly", path)
            self.metrics.increment("upload_error")
            return # for now

        entry = self.bm_temp_files[path]

        entry['uploaded'] = True
        entry['upload_finished'] = time.time()

        delta = entry['upload_finished'] - entry['upload_started']
        speed = int(entry['size'] / delta)

        self.logger.info("Uploaded %s in %d seconds (%s)",
                format_size_value(entry['size']), delta,
                format_speed_value(speed))

        if self.track_speed:
            self.metrics.gauge('upload_speed', speed)

    def run(self, options):
        self._parse_common_options(options)

        self.loop = gobject.MainLoop()
        gobject.timeout_add(0, self.setup)
        self.oauth = options.oauth

        if self.timeout:
            gobject.timeout_add(self.timeout * 1000,
                                self.handle_TIMEOUT)

        self.loop.run()

    def setup(self):
        # Performing cleanup unconditionally
        url = "https://one.ubuntu.com/api/file_storage/"\
                "v1/~/Ubuntu%%20One/%s" % (TESTDIR)
        client = OAuthHttpClient()
        c_key, c_secret, t_key, t_secret = self.oauth.split(':')
        client.set_consumer(c_key, c_secret)
        client.set_token(t_key, t_secret)

        resp, content = client.request(url, "DELETE")
        self.logger.info(
            "Removing %s via REST API: %s", TESTDIR, resp['status'])

        # we need to make sure we don't autoconnect on startup
        if self.config_if.autoconnect_enabled():
            self.config_if.disable_autoconnect()

        # we unconditionally disconnect syncdaemon to prepare the files for
        # upload.
        self.syncdaemon_if.disconnect()

        self.root = self.syncdaemon_if.get_rootdir()
        status = self.status_if.current_status()
        self.logger.info("Current SD status: %s/%s", status['name'],
                                                     status['queues'])

        self.bm_test_started = time.time()
        self.logger.info("Starting end-to-end test")
        # We generate files prior to connection - this way we will be in
        # mainloop when all the reports are coming in preventing infinite
        # upload speeds reading

        self.logger.info("Creating files")
        self._generate_files(TESTDIR)
        self.logger.info("Files created")

        self.handle_CONNECT()
    
    def handle_CONNECT(self):
        # We upload immediately
        self.state = 'UPLOADING'
        self.syncdaemon_if.connect()

    def handle_TIMEOUT(self):
        self.state = "ERROR"
        self.logger.error("Test timeout, shutting down.")
        self.metrics.increment("error", 1)
        # fake result
        self.quit(error=True)

    def cleanup_files(self):
        self.logger.info("Moving existing test folder to trash")

        old = os.path.join(self.root, TESTDIR)
        new = os.path.join(self.root, "..", "trash")

        if os.path.exists(new):
            rmtree(new)

        os.rename(old, new)
        rmtree(new)

    def handle_UPLOAD_COMPLETED(self):
        missing = 0
        for path, info in self.bm_temp_files.items():
            if 'uploaded' not in info:
                # this is not a file, we ignore this item
                continue

            if not info['uploaded']:
                self.logger.debug("NOT UPLOADED: %s", path)
                missing += 1

        if missing:
            self.logger.info("QUEUE_MANAGER/IDLE but %d files"\
                             " are still being uploaded", missing)
            return

        # how much time did it take?
        delta = time.time() - self.bm_upload_started
        rate = self.file_count / delta
        if self.track_queues:
            self.metrics.gauge('meta_queue', rate)

        self.logger.info("Queue completed in %d seconds (%.4f requests/s)",
                delta, rate)

        self.state = 'CLEANUP'
        self.bm_clenup_started = time.time()
        self.cleanup_files()

    def handle_CLEANUP_COMPLETED(self):
        self.state = 'FINALIZE'
        self.syncdaemon_if.disconnect()
        test_delta = time.time() - self.bm_test_started
        cleanup_delta = time.time() - self.bm_clenup_started
        self.logger.info("Cleanup took %d seconds", cleanup_delta)
        self.metrics.gauge('cleanup', cleanup_delta)
        self.logger.info("End-to-end test took %d seconds", test_delta)
        self.quit()

    def quit(self, error=False):
        self.loop.quit()
        # Is it really ok here?
        if error:
            app.error = True

if __name__ == "__main__":
    parser = optparse.OptionParser(usage="%prog options")
    parser.add_option("--log", dest="log", default=None,
                      help="Log file to write to")

    parser.add_option("--graph-prefix", dest="graph_prefix",
                     default="e2eperftest",
                     help="Prefix for Graphite")

    parser.add_option("--file-size", dest="file_size",
                     default=200,
                     help="Size of the files created")

    parser.add_option("--file-count", dest="file_count",
                     default=200,
                     help="Amount of the files to create")

    parser.add_option("--track-speed", dest="track_speed",
                     default=False, action="store_true",
                     help="Calculate transfer speed info")
    parser.add_option("--track-queues", dest="track_queues",
                     default=False, action="store_true",
                     help="Calculate queue processing speed")

    parser.add_option("--timeout", dest="timeout",
                     default=None,
                     help="Test times out after this number of seconds.")

    parser.add_option("--statsd", dest="statsd",
            default=None,
            help="host:port for statsd server")
    parser.add_option("--oauth", dest="oauth",
            default=None,
            help="OAuth Token in the form of a:b:c:d")

    options, args = parser.parse_args()

    app = SDPerfTest()
    app.run(options)

    if app.error:
        sys.exit(1)