forked from appium/appium
-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
233 lines (210 loc) · 6.59 KB
/
server.js
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
"use strict";
var http = require('http')
, express = require('express')
, path = require('path')
, fs = require('fs')
, logger = require('./logger').get('appium')
, appium = require('./app/appium')
, bodyParser = require('./middleware').parserWrap
, status = require('./app/uiauto/lib/status')
, appiumVer = require('./package.json').version
, appiumRev = null
, async = require('async')
, _ = require("underscore")
, parser = require('./app/parser')
, io = require('socket.io')
, gridRegister = require('./grid_register');
var allowCrossDomain = function(req, res, next) {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Methods', 'GET,POST,PUT,OPTIONS,DELETE');
res.header('Access-Control-Allow-Headers', 'origin, content-type, accept');
// need to respond 200 to OPTIONS
if ('OPTIONS' == req.method) {
res.send(200);
} else {
next();
}
};
var winstonStream = {
write: function(msg) {
msg = msg.replace(/$\s*$/m, "");
msg = msg.replace(/\[[^\]]+\] /, "");
logger.log('debug', msg);
}
};
var catchAllHandler = function(e, req, res, next) {
res.send(500, {
status: status.codes.UnknownError.code
, value: "ERROR running Appium command: " + e.message
});
next(e);
};
var checkArgs = function(args) {
var exclusives = [
['noReset', 'fullReset']
, ['ipa', 'app', 'safari']
, ['forceIphone', 'forceIpad']
];
_.each(exclusives, function(exSet) {
var numFoundInArgs = 0;
_.each(exSet, function(opt) {
if (_.has(args, opt) && args[opt]) {
numFoundInArgs++;
}
});
if (numFoundInArgs > 1) {
console.error(("You can't pass in more than one argument from the set " +
JSON.stringify(exSet) + ", since they are mutually exclusive").red);
process.exit(1);
}
});
};
var main = function(args, readyCb, doneCb) {
checkArgs(args);
if (typeof doneCb === "undefined") {
doneCb = function() {};
}
var rest = express()
, server = http.createServer(rest);
rest.configure(function() {
rest.use(express.favicon());
rest.use(express.static(path.join(__dirname, '/app/static')));
rest.use(allowCrossDomain);
if (!args.quiet) {
rest.use(express.logger('dev'));
}
if (args.log || args.webhook) {
rest.use(express.logger({stream: winstonStream}));
}
rest.use(bodyParser);
rest.use(express.methodOverride());
rest.use(rest.router);
rest.use(catchAllHandler);
});
// Instantiate the appium instance
var appiumServer = appium(args);
// Hook up REST http interface
appiumServer.attachTo(rest);
var checkSetup = function(cb) {
var configFile = path.resolve(__dirname, ".appiumconfig");
fs.readFile(configFile, function(err, data) {
if (err) {
logger.error("Could not find config file; looks like config hasn't " +
"been run! Please run reset.sh or appium configure.");
return cb(err);
}
var rawConfig;
try {
rawConfig = JSON.parse(data.toString('utf8'));
} catch (e) {
logger.error("Error parsing configuration json, please re-run config");
return cb(e);
}
var versionMismatches = {};
_.each(rawConfig, function(deviceConfig, key) {
if (deviceConfig.version !== appiumVer && key !== "git-sha") {
versionMismatches[key] = deviceConfig.version;
} else if (key === "git-sha") {
appiumRev = rawConfig['git-sha'];
}
});
if (_.keys(versionMismatches).length) {
logger.error("Got some configuration version mismatches. Appium is " +
"at " + appiumVer + ".");
_.each(versionMismatches, function(mismatchedVer, key) {
logger.error(key + " configured at " + mismatchedVer);
});
logger.error("Please re-run reset.sh or config");
return cb(new Error("Appium / config version mismatch"));
} else {
appiumServer.registerConfig(rawConfig);
cb(null);
}
});
};
var conditionallyPreLaunch = function(cb) {
if (args.launch) {
logger.info("Starting Appium in pre-launch mode".cyan);
appiumServer.preLaunch(function(err) {
if (err) {
logger.error("Could not pre-launch appium: " + err);
cb(err);
} else {
cb(null);
}
});
} else {
cb(null);
}
};
var startAlertSocket = function() {
var alerts = io.listen(server, {'flash policy port': -1});
alerts.configure(function() {
alerts.set('log level', 1);
alerts.set("polling duration", 10);
alerts.set("transports", ['websocket', 'flashsocket']);
});
alerts.sockets.on("connection", function (socket) {
socket.set('log level', 1);
logger.info("Client connected: " + (socket.id).toString());
socket.on('disconnect', function(data) {
logger.info("Client disconnected: " + data);
});
});
// add web socket so we can emit events
appiumServer.attachSocket(alerts);
};
var startListening = function(cb) {
var alreadyReturned = false;
server.listen(args.port, args.address, function() {
var welcome = "Welcome to Appium v" + appiumVer;
if (appiumRev) {
welcome += " (REV " + appiumRev + ")";
}
logger.info(welcome.cyan);
var logMessage = "Appium REST http interface listener started on " +
args.address + ":" + args.port;
logger.info(logMessage.cyan);
startAlertSocket();
if (args.nodeconfig !== null) {
gridRegister.registerNode(args.nodeconfig);
}
});
server.on('error', function(err) {
if (err.code === 'EADDRNOTAVAIL') {
logger.error("Couldn't start Appium REST http interface listener. Requested address is not available.");
} else {
logger.error("Couldn't start Appium REST http interface listener. Requested port is already in use. Please make sure there's no other instance of Appium running already.");
}
if (!alreadyReturned) {
alreadyReturned = true;
cb(err);
}
});
setTimeout(function() {
if (!alreadyReturned) {
alreadyReturned = true;
cb(null);
}
}, 1000);
};
async.series([
checkSetup
, conditionallyPreLaunch
, startListening
], function(err) {
if (err) {
process.exit(1);
} else if (typeof readyCb === "function") {
readyCb(appiumServer);
}
});
server.on('close', doneCb);
return server;
};
if (require.main === module) {
// Parse the command line arguments
var args = parser().parseArgs();
main(args);
}
module.exports.run = main;