Skip to content

Commit

Permalink
Merge pull request #211 from SonicCloudOrg/dev
Browse files Browse the repository at this point in the history
rc
  • Loading branch information
ZhouYixun authored May 30, 2022
2 parents 61040b3 + 715fca1 commit 714dcd9
Show file tree
Hide file tree
Showing 13 changed files with 249 additions and 76 deletions.
6 changes: 3 additions & 3 deletions config/application-sonic-agent.yml
Original file line number Diff line number Diff line change
Expand Up @@ -40,16 +40,16 @@ modules:
# 如果不需要连接iOS设备,请将true改为false。开启的windows用户请确保本机已安装iTunes
enable: true
# 替换为你自己使用的wda的bundleId,如果没有.xctrunner后缀会自动补全,建议使用公司的开发者证书
wda-bundle-id: com.facebook.WebDriverAgentRunner.xctrunner
wda-bundle-id: com.sonic.WebDriverAgentRunner.xctrunner
appium:
# 是否开启Appium功能
enable: true
webview:
# 是否开启在线webView调试功能
enable: true
enable: false
# 谷歌调试端口,一般不需要修改(默认0使用随机端口,如果需要开启防火墙给外部使用,请设置固定端口如7778)
chrome-driver-debug-port: 0
# 替换为Agent机器上的chrome浏览器的driver路径,可以去http://npm.taobao.org/mirrors/chromedriver/下载
chrome-driver-path: "/Applications/Google Chrome.app/Contents/MacOS/chromedriver"
sgm:
enable: true
enable: false
Binary file modified plugins/sonic-ios-bridge
Binary file not shown.
2 changes: 1 addition & 1 deletion pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
</parent>

<artifactId>sonic-agent</artifactId>
<version>1.4.0-beta</version>
<version>1.4.0-rc</version>
<packaging>jar</packaging>

<dependencies>
Expand Down
2 changes: 1 addition & 1 deletion src/main/docker/docker-compose.yml
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
version: '3'
services:
sonic-agent:
image: "registry.cn-hangzhou.aliyuncs.com/sonic-cloud/sonic-agent-linux:v1.4.0-beta"
image: "registry.cn-hangzhou.aliyuncs.com/sonic-cloud/sonic-agent-linux:v1.4.0-rc"
environment:
- ZOOKEEPER_HOST=192.168.1.1
- ZOOKEEPER_PORT=2181
Expand Down
2 changes: 1 addition & 1 deletion src/main/docker/docker-compose2.yml
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
version: '3'
services:
sonic-agent:
image: "sonicorg/sonic-agent-linux:v1.4.0-beta"
image: "sonicorg/sonic-agent-linux:v1.4.0-rc"
environment:
- ZOOKEEPER_HOST=192.168.1.1
- ZOOKEEPER_PORT=2181
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -108,10 +108,11 @@ public void startIOSDriver(String udId, int wdaPort) throws InterruptedException
desiredCapabilities.setCapability(MobileCapabilityType.PLATFORM_NAME, Platform.IOS);
desiredCapabilities.setCapability(MobileCapabilityType.AUTOMATION_NAME, AutomationName.IOS_XCUI_TEST);
desiredCapabilities.setCapability(MobileCapabilityType.NEW_COMMAND_TIMEOUT, 3600);
desiredCapabilities.setCapability(IOSMobileCapabilityType.COMMAND_TIMEOUTS, 3600);
desiredCapabilities.setCapability(MobileCapabilityType.NO_RESET, true);
desiredCapabilities.setCapability(MobileCapabilityType.DEVICE_NAME, SibTool.getName(udId));
desiredCapabilities.setCapability(MobileCapabilityType.UDID, udId);
desiredCapabilities.setCapability("wdaConnectionTimeout", 10000);
desiredCapabilities.setCapability("wdaConnectionTimeout", 60000);
desiredCapabilities.setCapability(IOSMobileCapabilityType.WEB_DRIVER_AGENT_URL, "http://127.0.0.1:" + wdaPort);
desiredCapabilities.setCapability("useXctestrunFile", false);
desiredCapabilities.setCapability(IOSMobileCapabilityType.SHOW_IOS_LOG, false);
Expand Down
97 changes: 90 additions & 7 deletions src/main/java/org/cloud/sonic/agent/bridge/ios/SibTool.java
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
*/
package org.cloud.sonic.agent.bridge.ios;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.cloud.sonic.agent.common.interfaces.DeviceStatus;
import org.cloud.sonic.agent.common.interfaces.PlatformType;
Expand All @@ -40,6 +41,7 @@
import org.springframework.lang.NonNull;
import org.springframework.stereotype.Component;

import javax.websocket.Session;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
Expand All @@ -48,6 +50,8 @@
import java.util.ArrayList;
import java.util.List;

import static org.cloud.sonic.agent.tools.BytesTool.sendText;

@ConditionalOnProperty(value = "modules.ios.enable", havingValue = "true")
@DependsOn({"iOSThreadPoolInit"})
@Component
Expand Down Expand Up @@ -147,6 +151,7 @@ public static void sendDisConnectStatus(JSONObject jsonObject) {
deviceStatus.put("status", DeviceStatus.DISCONNECTED);
deviceStatus.put("size", IOSInfoMap.getSizeMap().get(jsonObject.getString("serialNumber")));
deviceStatus.put("agentId", AgentZookeeperRegistry.currentAgent.getId());
deviceStatus.put("platform", PlatformType.IOS);
logger.info("iOS devices: " + jsonObject.getString("serialNumber") + " OFFLINE!");
SpringTool.getBean(AgentManagerTool.class).devicesStatus(deviceStatus);
IOSDeviceManagerMap.getMap().remove(jsonObject.getString("serialNumber"));
Expand Down Expand Up @@ -239,16 +244,94 @@ public static void install(String udId, String path) {
ProcessCommandTool.getProcessLocalCommand(String.format(commandLine, sib, udId, path));
}

public static JSONObject getAppList(String udId) {
String commandLine = "%s app list -u %s -j";
String a = ProcessCommandTool.getProcessLocalCommandStr(String.format(commandLine, sib, udId));
if (a.length() > 0) {
return JSONObject.parseObject(a);
} else {
return new JSONObject();
public static void stopSysLog(String udId) {
String processName = String.format("process-%s-syslog", udId);
if (GlobalProcessMap.getMap().get(processName) != null) {
Process ps = GlobalProcessMap.getMap().get(processName);
ps.children().forEach(ProcessHandle::destroy);
ps.destroy();
}
}

public static void getSysLog(String udId, String filter, Session session) {
new Thread(() -> {
stopSysLog(udId);
String system = System.getProperty("os.name").toLowerCase();
Process ps = null;
String commandLine = "%s syslog -u %s";
if (filter != null && filter.length() > 0) {
commandLine += String.format(" -f %s", filter);
}
try {
if (system.contains("win")) {
ps = Runtime.getRuntime().exec(new String[]{"cmd", "/c", String.format(commandLine, sib, udId)});
} else if (system.contains("linux") || system.contains("mac")) {
ps = Runtime.getRuntime().exec(new String[]{"sh", "-c", String.format(commandLine, sib, udId)});
}
String processName = String.format("process-%s-syslog", udId);
GlobalProcessMap.getMap().put(processName, ps);
BufferedReader stdInput = new BufferedReader(new
InputStreamReader(ps.getInputStream()));
String s;
while (ps.isAlive()) {
if ((s = stdInput.readLine()) != null) {
logger.info(s);
try {
JSONObject appList = new JSONObject();
appList.put("msg", "logDetail");
appList.put("detail", s);
sendText(session, appList.toJSONString());
} catch (Exception e) {
logger.info(s);
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}).start();
}

public static void getAppList(String udId, Session session) {
Process appListProcess = null;
String commandLine = "%s app list -u %s -j -i";
String system = System.getProperty("os.name").toLowerCase();
try {
if (system.contains("win")) {
appListProcess = Runtime.getRuntime().exec(new String[]{"cmd", "/c", String.format(commandLine, sib, udId)});
} else if (system.contains("linux") || system.contains("mac")) {
appListProcess = Runtime.getRuntime().exec(new String[]{"sh", "-c", String.format(commandLine, sib, udId)});
}
BufferedReader stdInput = new BufferedReader(new
InputStreamReader(appListProcess.getInputStream()));
String s;
while (appListProcess.isAlive()) {
if ((s = stdInput.readLine()) != null) {
try {
JSONObject appList = new JSONObject();
appList.put("msg", "appListDetail");
appList.put("detail", JSON.parseObject(s));
sendText(session, appList.toJSONString());
} catch (Exception e) {
logger.info(s);
}
}
}
} catch (Exception e) {

}
}

public static void locationUnset(String udId) {
String commandLine = "%s location unset -u %s";
ProcessCommandTool.getProcessLocalCommand(String.format(commandLine, sib, udId));
}

public static void locationSet(String udId, String longitude, String latitude) {
String commandLine = "%s location set -u %s --long %s --lat %s";
ProcessCommandTool.getProcessLocalCommand(String.format(commandLine, sib, udId, longitude, latitude));
}

public static JSONObject getAllDevicesBattery() {
String commandLine = "%s battery -j";
String res = ProcessCommandTool.getProcessLocalCommandStr(commandLine.formatted(sib));
Expand Down
8 changes: 5 additions & 3 deletions src/main/java/org/cloud/sonic/agent/tests/TaskManager.java
Original file line number Diff line number Diff line change
Expand Up @@ -251,9 +251,11 @@ public static void forceStopSuite(int platform, int resultId, int caseId, String
// 清理map
bootThreadsMap.remove(key);
Set<Thread> removed = childThreadsMap.remove(key);
for (Thread thread : removed) {
if (thread instanceof RunStepThread) {
((RunStepThread) thread).setStopped(true);
if (!CollectionUtils.isEmpty(removed)) {
for (Thread thread : removed) {
if (thread instanceof RunStepThread) {
((RunStepThread) thread).setStopped(true);
}
}
}
runningTestsMap.remove(resultId + "");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -47,10 +47,10 @@
* @date 2021/10/30 23:35
*/
@Component
@ServerEndpoint(value = "/websockets/terminal/{key}/{udId}", configurator = MyEndpointConfigure.class)
public class TerminalWSServer {
@ServerEndpoint(value = "/websockets/android/terminal/{key}/{udId}/{token}", configurator = MyEndpointConfigure.class)
public class AndroidTerminalWSServer {

private final Logger logger = LoggerFactory.getLogger(TerminalWSServer.class);
private final Logger logger = LoggerFactory.getLogger(AndroidTerminalWSServer.class);
@Value("${sonic.agent.key}")
private String key;
private Map<Session, IDevice> udIdMap = new ConcurrentHashMap<>();
Expand All @@ -60,8 +60,9 @@ public class TerminalWSServer {
private Map<Session, Future<?>> logcatMap = new ConcurrentHashMap<>();

@OnOpen
public void onOpen(Session session, @PathParam("key") String secretKey, @PathParam("udId") String udId) throws Exception {
if (secretKey.length() == 0 || (!secretKey.equals(key))) {
public void onOpen(Session session, @PathParam("key") String secretKey,
@PathParam("udId") String udId, @PathParam("token") String token) throws Exception {
if (secretKey.length() == 0 || (!secretKey.equals(key)) || token.length() == 0) {
logger.info("拦截访问!");
return;
}
Expand Down
74 changes: 41 additions & 33 deletions src/main/java/org/cloud/sonic/agent/websockets/AndroidWSServer.java
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@
import java.util.concurrent.TimeUnit;

@Component
@ServerEndpoint(value = "/websockets/android/{key}/{udId}/{token}", configurator = MyEndpointConfigure.class)
@ServerEndpoint(value = "/websockets/android/{key}/{udId}/{token}/{isAutoInit}", configurator = MyEndpointConfigure.class)
public class AndroidWSServer implements IAndroidWSServer {

private final Logger logger = LoggerFactory.getLogger(AndroidWSServer.class);
Expand All @@ -80,8 +80,8 @@ public class AndroidWSServer implements IAndroidWSServer {

@OnOpen
public void onOpen(Session session, @PathParam("key") String secretKey,
@PathParam("udId") String udId, @PathParam("token") String token) throws Exception {
if (secretKey.length() == 0 || (!secretKey.equals(key)) || token.length() == 0) {
@PathParam("udId") String udId, @PathParam("token") String token, @PathParam("isAutoInit") Integer isAutoInit) throws Exception {
if (secretKey.length() == 0 || (!secretKey.equals(key)) || token.length() == 0 || isAutoInit == null) {
logger.info("拦截访问!");
return;
}
Expand Down Expand Up @@ -270,6 +270,10 @@ public boolean isCancelled() {
adbkit.put("isEnable", false);
BytesTool.sendText(session, adbkit.toJSONString());
}

if (isAutoInit == 1) {
openDriver(iDevice, session);
}
}

@OnClose
Expand Down Expand Up @@ -446,10 +450,10 @@ public void onMessage(String message, Session session) {
JSONObject result = new JSONObject();
result.put("msg", "pullResult");
String url = AndroidDeviceBridgeTool.pullFile(iDevice, msg.getString("path"));
if(url!=null){
if (url != null) {
result.put("status", "success");
result.put("url",url);
}else {
result.put("url", url);
} else {
result.put("status", "fail");
}
BytesTool.sendText(session, result.toJSONString());
Expand Down Expand Up @@ -494,33 +498,7 @@ public void onMessage(String message, Session session) {
AndroidStepHandler androidStepHandler = HandlerMap.getAndroidMap().get(session.getId());
if (androidStepHandler == null || androidStepHandler.getAndroidDriver() == null) {
if (msg.getString("detail").equals("openDriver")) {
if (isEnableAppium) {
androidStepHandler = new AndroidStepHandler();
androidStepHandler.setTestMode(0, 0, iDevice.getSerialNumber(), DeviceStatus.DEBUGGING, session.getId());
JSONObject result = new JSONObject();
AndroidStepHandler finalAndroidStepHandler1 = androidStepHandler;
AndroidDeviceThreadPool.cachedThreadPool.execute(() -> {
try {
AndroidDeviceLocalStatus.startDebug(iDevice.getSerialNumber());
finalAndroidStepHandler1.startAndroidDriver(iDevice.getSerialNumber());
result.put("status", "success");
result.put("detail", "初始化Driver完成!");
HandlerMap.getAndroidMap().put(session.getId(), finalAndroidStepHandler1);
JSONObject port = new JSONObject();
port.put("port", AppiumServer.serviceMap.get(iDevice.getSerialNumber()).getUrl().getPort());
port.put("msg", "appiumPort");
BytesTool.sendText(session, port.toJSONString());
} catch (Exception e) {
logger.error(e.getMessage());
result.put("status", "error");
result.put("detail", "初始化Driver失败!部分功能不可用!请联系管理员");
finalAndroidStepHandler1.closeAndroidDriver();
} finally {
result.put("msg", "openDriver");
BytesTool.sendText(session, result.toJSONString());
}
});
}
openDriver(iDevice, session);
}
break;
}
Expand Down Expand Up @@ -610,6 +588,36 @@ public void onMessage(String message, Session session) {
}
}

private void openDriver(IDevice iDevice, Session session) {
if (isEnableAppium) {
AndroidStepHandler androidStepHandler = new AndroidStepHandler();
androidStepHandler.setTestMode(0, 0, iDevice.getSerialNumber(), DeviceStatus.DEBUGGING, session.getId());
JSONObject result = new JSONObject();
AndroidStepHandler finalAndroidStepHandler1 = androidStepHandler;
AndroidDeviceThreadPool.cachedThreadPool.execute(() -> {
try {
AndroidDeviceLocalStatus.startDebug(iDevice.getSerialNumber());
finalAndroidStepHandler1.startAndroidDriver(iDevice.getSerialNumber());
result.put("status", "success");
result.put("detail", "初始化Driver完成!");
HandlerMap.getAndroidMap().put(session.getId(), finalAndroidStepHandler1);
JSONObject port = new JSONObject();
port.put("port", AppiumServer.serviceMap.get(iDevice.getSerialNumber()).getUrl().getPort());
port.put("msg", "appiumPort");
BytesTool.sendText(session, port.toJSONString());
} catch (Exception e) {
logger.error(e.getMessage());
result.put("status", "error");
result.put("detail", "初始化Driver失败!部分功能不可用!请联系管理员");
finalAndroidStepHandler1.closeAndroidDriver();
} finally {
result.put("msg", "openDriver");
BytesTool.sendText(session, result.toJSONString());
}
});
}
}

private void exit(Session session) {
AndroidDeviceLocalStatus.finish(session.getUserProperties().get("udId") + "");
IDevice iDevice = udIdMap.get(session);
Expand Down
Loading

0 comments on commit 714dcd9

Please sign in to comment.