Update test cases for change r206465.
[WebKit.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 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         this._remote = null
31     }
32
33     start()
34     {
35         let testConfigContent = this.testConfig();
36         fs.writeFileSync(this._testConfigPath, JSON.stringify(testConfigContent, null, '    '));
37
38         this._ensureTestDatabase();
39         this._ensureDataDirectory();
40
41         return this._startApache();
42     }
43
44     stop()
45     {
46         this._restoreDataDirectory();
47
48         return this._stopApache();
49     }
50
51     remoteAPI()
52     {
53         assert(this._remote);
54         return this._remote;
55     }
56
57     database()
58     {
59         assert(this._databaseName);
60         if (!this._database)
61             this._database = new Database(this._databaseName);
62         return this._database;
63     }
64
65     testConfig()
66     {
67         return {
68             'siteTitle': 'Test Dashboard',
69             'debug': true,
70             'jsonCacheMaxAge': 600,
71             'dataDirectory': Config.value('dataDirectory'),
72             'database': {
73                 'host': Config.value('database.host'),
74                 'port': Config.value('database.port'),
75                 'username': Config.value('database.username'),
76                 'password': Config.value('database.password'),
77                 'name': Config.value('testDatabaseName'),
78             },
79             'universalSlavePassword': null,
80             'maintenanceMode': false,
81             'clusterStart': [2000, 1, 1, 0, 0],
82             'clusterSize': [0, 2, 0],
83             'defaultDashboard': [[]],
84             'dashboards': {},
85             'summaryPages': []
86         }
87     }
88
89     _ensureDataDirectory()
90     {
91         let backupPath = path.resolve(this._dataDirectory, '../original-data');
92         if (fs.existsSync(this._dataDirectory)) {
93             assert.ok(!fs.existsSync(backupPath), `Both ${this._dataDirectory} and ${backupPath} exist. Cannot make a backup of data`);
94             fs.renameSync(this._dataDirectory, backupPath);
95             this._backupDataPath = backupPath;
96         } else 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     _restoreDataDirectory()
102     {
103         childProcess.execFileSync('rm', ['-rf', this._dataDirectory]);
104         if (this._backupDataPath)
105             fs.rename(this._backupDataPath, this._dataDirectory);
106     }
107
108     cleanDataDirectory()
109     {
110         let fileList = fs.readdirSync(this._dataDirectory);
111         for (let filename of fileList)
112             fs.unlinkSync(path.resolve(this._dataDirectory, filename));
113     }
114
115     _ensureTestDatabase()
116     {
117         try {
118             this._executePgsqlCommand('dropdb');
119         } catch (error) { }
120         this._executePgsqlCommand('createdb');
121         this._executePgsqlCommand('psql', ['--command', `grant all privileges on database "${this._databaseName}" to "${this._databaseUser}";`]);
122         this.initDatabase();
123     }
124
125     initDatabase()
126     {
127         if (this._database)
128             this._database.disconnect();
129         this._database = null;
130
131         let initFilePath = Config.pathFromRoot('init-database.sql');
132         this._executePgsqlCommand('psql', ['--username', this._databaseUser, '--file', initFilePath],
133             {stdio: ['ignore', 'ignore', 'ignore']});
134     }
135
136     _executePgsqlCommand(command, args, options)
137     {
138         if (!this._pgsqlDirectory)
139             this._pgsqlDirectory = this._determinePgsqlDirectory();
140         childProcess.execFileSync(path.resolve(this._pgsqlDirectory, command),
141             [this._databaseName, '--host', this._databaseHost, '--port', this._databasePort].concat(args || []), options);
142     }
143
144     _determinePgsqlDirectory()
145     {
146         try {
147             let initdbLocation = childProcess.execFileSync('which', ['initdb']);
148             return path.dirname(initdbLocation);
149         } catch (error) {
150             let serverPgsqlLocation = '/Applications/Server.app/Contents/ServerRoot/usr/bin/';
151             childProcess.execFileSync(path.resolve(serverPgsqlLocation, 'initdb'), ['--version']);
152             return serverPgsqlLocation;
153         }
154     }
155
156     _startApache()
157     {
158         let pidFile = Config.path('testServer.httpdPID');
159         let httpdConfig = Config.path('testServer.httpdConfig');
160         let port = Config.value('testServer.port');
161         let errorLog = Config.path('testServer.httpdErrorLog');
162         let mutexFile = Config.path('testServer.httpdMutexDir');
163
164         if (!fs.existsSync(mutexFile))
165             fs.mkdirSync(mutexFile, 0o755);
166
167         let args = [
168             '-f', httpdConfig,
169             '-c', `SetEnv ORG_WEBKIT_PERF_CONFIG_PATH ${this._testConfigPath}`,
170             '-c', `Listen ${port}`,
171             '-c', `PidFile ${pidFile}`,
172             '-c', `ErrorLog ${errorLog}`,
173             '-c', `Mutex file:${mutexFile}`,
174             '-c', `DocumentRoot ${Config.serverRoot()}`];
175
176         if (this._shouldLog)
177             console.log(args);
178
179         childProcess.execFileSync('httpd', args);
180
181         this._server = {
182             scheme: 'http',
183             host: 'localhost',
184             port: port,
185         }
186         this._pidWaitStart = Date.now();
187         this._pidFile = pidFile;
188
189         this._remote = new RemoteAPI(this._server);
190
191         return new Promise(this._waitForPid.bind(this, true));
192     }
193
194     _stopApache()
195     {
196         if (!this._pidFile)
197             return;
198
199         let pid = fs.readFileSync(this._pidFile, 'utf-8').trim();
200
201         if (this._shouldLog)
202             console.log('Stopping', pid);
203
204         childProcess.execFileSync('kill', ['-TERM', pid]);
205
206         return new Promise(this._waitForPid.bind(this, false));
207     }
208
209     _waitForPid(shouldExist, resolve, reject)
210     {
211         if (fs.existsSync(this._pidFile) != shouldExist) {
212             if (Date.now() - this._pidWaitStart > 8000)
213                 reject();
214             else
215                 setTimeout(this._waitForPid.bind(this, shouldExist, resolve, reject), 100);
216             return;
217         }
218         resolve();
219     }
220
221     inject()
222     {
223         let self = this;
224         before(function () {
225             this.timeout(10000);
226             return self.start();
227         });
228
229         let originalRemote;
230
231         beforeEach(function () {
232             this.timeout(10000);
233             self.initDatabase();
234             self.cleanDataDirectory();
235             originalRemote = global.RemoteAPI;
236             global.RemoteAPI = self._remote;
237             self._remote.clearCookies();
238
239             if (global.PrivilegedAPI) {
240                 global.PrivilegedAPI._token = null;
241                 global.PrivilegedAPI._expiration = null;
242             }
243         });
244
245         after(function () {
246             this.timeout(10000);
247             global.RemoteAPI = originalRemote;
248             return self.stop();
249         });
250     }
251 }
252
253 if (!global.TestServer)
254     global.TestServer = new TestServer;
255
256 if (typeof module != 'undefined')
257     module.exports = global.TestServer;