787cdfd9e962a4c64a8c91e7236b1e7a747d7494
[WebKit-https.git] / Websites / perf.webkit.org / server-tests / resources / test-server.js
1 'use strict';
2
3 let assert = require('assert');
4 let childProcess = require('child_process');
5 let fs = require('fs');
6 let path = require('path');
7
8 let Config = require('../../tools/js/config.js');
9 let Database = require('../../tools/js/database.js');
10 let RemoteAPI = require('../../tools/js/remote.js').RemoteAPI;
11
12 let TestServer = (new class TestServer {
13     constructor()
14     {
15         this._pidFile = null;
16         this._testConfigPath = Config.path('testServer.config');
17         this._dataDirectory = Config.path('dataDirectory');
18         this._backupDataPath = null;
19         this._pidWaitStart = null;
20         this._shouldLog = false;
21         this._pgsqlDirectory = null;
22         this._server = null;
23
24         this._databaseName = Config.value('testDatabaseName');
25         this._databaseUser = Config.value('database.username');
26         this._databaseHost = Config.value('database.host');
27         this._databasePort = Config.value('database.port');
28         this._database = null;
29     }
30
31     start()
32     {        
33         let testConfigContent = this._constructTestConfig(this._dataDirectory);
34         fs.writeFileSync(this._testConfigPath, JSON.stringify(testConfigContent, null, '    '));
35
36         this._ensureTestDatabase();
37         this._ensureDataDirectory();
38
39         return this._startApache();
40     }
41
42     stop()
43     {
44         this._restoreDataDirectory();
45
46         return this._stopApache();
47     }
48
49     remoteAPI()
50     {
51         assert(this._server);
52         RemoteAPI.configure(this._server);
53         return RemoteAPI;
54     }
55
56     database()
57     {
58         assert(this._databaseName);
59         if (!this._database)
60             this._database = new Database(this._databaseName);
61         return this._database;
62     }
63
64     _constructTestConfig(dataDirectory)
65     {
66         return {
67             'siteTitle': 'Test Dashboard',
68             'debug': true,
69             'jsonCacheMaxAge': 600,
70             'dataDirectory': dataDirectory,
71             'database': {
72                 'host': Config.value('database.host'),
73                 'port': Config.value('database.port'),
74                 'username': Config.value('database.username'),
75                 'password': Config.value('database.password'),
76                 'name': Config.value('testDatabaseName'),
77             },
78             'universalSlavePassword': null,
79             'maintenanceMode': false,
80             'clusterStart': [2000, 1, 1, 0, 0],
81             'clusterSize': [0, 2, 0],
82             'defaultDashboard': [[]],
83             'dashboards': {}
84         }
85     }
86
87     _ensureDataDirectory()
88     {
89
90         let backupPath = path.resolve(this._dataDirectory, '../original-data');
91         if (fs.existsSync(this._dataDirectory)) {
92             assert.ok(!fs.existsSync(backupPath), `Both ${this._dataDirectory} and ${backupPath} exist. Cannot make a backup of data`);
93             fs.rename(this._dataDirectory, backupPath);
94             this._backupDataPath = backupPath;
95         } else {
96             if (fs.existsSync(backupPath)) // Assume this is a backup from the last failed run
97                 this._backupDataPath = backupPath;
98             fs.mkdirSync(this._dataDirectory, 0o755);
99         }
100     }
101
102     _restoreDataDirectory()
103     {
104         childProcess.execFileSync('rm', ['-rf', this._dataDirectory]);
105         if (this._backupDataPath)
106             fs.rename(this._backupDataPath, this._dataDirectory);
107     }
108
109     _ensureTestDatabase()
110     {
111         this._executePgsqlCommand('dropdb');
112         this._executePgsqlCommand('createdb');
113         this._executePgsqlCommand('psql', ['--command', `grant all privileges on database "${this._databaseName}" to "${this._databaseUser}";`]);
114         this.initDatabase();
115     }
116
117     initDatabase()
118     {
119         if (this._database)
120             this._database.disconnect();
121         this._database = null;
122
123         let initFilePath = Config.pathFromRoot('init-database.sql');
124         this._executePgsqlCommand('psql', ['--username', this._databaseUser, '--file', initFilePath],
125             {stdio: ['ignore', 'ignore', 'ignore']});
126     }
127
128     _executePgsqlCommand(command, args, options)
129     {
130         if (!this._pgsqlDirectory)
131             this._pgsqlDirectory = this._determinePgsqlDirectory();
132         childProcess.execFileSync(path.resolve(this._pgsqlDirectory, command),
133             [this._databaseName, '--host', this._databaseHost, '--port', this._databasePort].concat(args || []), options);
134     }
135
136     _determinePgsqlDirectory()
137     {
138         try {
139             let initdbLocation = childProcess.execFileSync('which', ['initdb']);
140             return path.dirname(initdbLocation);
141         } catch (error) {
142             let serverPgsqlLocation = '/Applications/Server.app/Contents/ServerRoot/usr/bin/';
143             childProcess.execFileSync(path.resolve(serverPgsqlLocation, 'initdb'), ['--version']);
144             return serverPgsqlLocation;
145         }
146     }
147
148     _startApache()
149     {
150         let pidFile = Config.path('testServer.httpdPID');
151         let httpdConfig = Config.path('testServer.httpdConfig');
152         let port = Config.value('testServer.port');
153         let errorLog = Config.path('testServer.httpdErrorLog');
154         let mutexFile = Config.path('testServer.httpdMutexDir');
155
156         if (!fs.existsSync(mutexFile))
157             fs.mkdirSync(mutexFile, 0o755);
158
159         let args = [
160             '-f', httpdConfig,
161             '-c', `SetEnv ORG_WEBKIT_PERF_CONFIG_PATH ${this._testConfigPath}`,
162             '-c', `Listen ${port}`,
163             '-c', `PidFile ${pidFile}`,
164             '-c', `ErrorLog ${errorLog}`,
165             '-c', `Mutex file:${mutexFile}`,
166             '-c', `DocumentRoot ${Config.serverRoot()}`];
167
168         if (this._shouldLog)
169             console.log(args);
170
171         childProcess.execFileSync('httpd', args);
172
173         this._server = {
174             scheme: 'http',
175             host: 'localhost',
176             port: port,
177         }
178         this._pidWaitStart = Date.now();
179         this._pidFile = pidFile;
180         return new Promise(this._waitForPid.bind(this, true));
181     }
182
183     _stopApache()
184     {
185         if (!this._pidFile)
186             return;
187
188         let pid = fs.readFileSync(this._pidFile, 'utf-8').trim();
189
190         if (this._shouldLog)
191             console.log('Stopping', pid);
192
193         childProcess.execFileSync('kill', ['-TERM', pid]);
194
195         return new Promise(this._waitForPid.bind(this, false));
196     }
197
198     _waitForPid(shouldExist, resolve, reject)
199     {
200         if (fs.existsSync(this._pidFile) != shouldExist) {
201             if (Date.now() - this._pidWaitStart > 5000)
202                 reject();
203             else
204                 setTimeout(this._waitForPid.bind(this, shouldExist, resolve, reject), 100);
205             return;
206         }
207         resolve();
208     }
209 });
210
211
212 before(function () {
213     this.timeout(5000);
214     return TestServer.start();
215 });
216
217 beforeEach(function () {
218     this.timeout(5000);
219     return TestServer.initDatabase();
220 });
221
222 after(function () {
223     this.timeout(5000);
224     return TestServer.stop();
225 });
226
227 if (typeof module != 'undefined')
228     module.exports = TestServer;