Mesos+Marathon的JAVA API案例

package example;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;

import mesosphere.marathon.client.Marathon;
import mesosphere.marathon.client.MarathonClient;
import mesosphere.marathon.client.model.v2.App;
import mesosphere.marathon.client.model.v2.Deployment;
import mesosphere.marathon.client.model.v2.GetAppResponse;
import mesosphere.marathon.client.model.v2.GetAppTasksResponse;
import mesosphere.marathon.client.model.v2.GetAppsResponse;
import mesosphere.marathon.client.model.v2.HealthCheck;
import mesosphere.marathon.client.model.v2.Task;
import mesosphere.marathon.client.utils.MarathonException;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.junit.Before;
import org.junit.Test;

public class Example {
	
	Marathon marathon = null;
	
	/**
	 * 創建Marathon的連接
	 */
	@Before
	public void createClient(){
		marathon = MarathonClient.getInstance("http://172.16.12.127:8080");
	}
	
	/**
	 * 在Marathon上面創建一個應用
	 * @throws MarathonException
	 */
	@Test
	public void createAPP() throws MarathonException {
		System.out.println("START");
		
		for (int i = 0; i < 1; i++) {
			App app = new App();
			app.setId("/test/task1" + i);
			app.setCmd("chmod +x maraStart.sh && ./maraStart.sh test 172.16.12.127 /home/test/taskmanager-99413.tar.gz taskmanager-test.tar.gz ftppw1234 $PORT0");
			app.setCpus(0.5);
			app.setMem(10.0);
			List<Integer> ports = new ArrayList<Integer>();
			ports.add(0);
			app.setPorts(ports);
			app.setInstances(1);
			
			List<HealthCheck> healChecks = new ArrayList<HealthCheck>();
			HealthCheck healCheck = new HealthCheck();
			healCheck.setProtocol("TCP");
			healCheck.setPortIndex(0);
			healCheck.setGracePeriodSeconds(300);
			healCheck.setIntervalSeconds(60);
			healCheck.setTimeoutSeconds(20);
			healCheck.setMaxConsecutiveFailures(0);
			healChecks.add(healCheck);
			app.setHealthChecks(healChecks);
			
//			List<String> list = new ArrayList<String>();
//			list.add("hostname");
//			list.add("LIKE");
//			list.add("XCLOUD3[69]");
//			List<List<String>> constraints = new ArrayList<List<String>>();
//			constraints.add(list);
//			System.out.println(constraints);
//			app.setConstraints(constraints);
			
			List<String> uris = new ArrayList<String>();
			uris.add("ftp://test:[email protected]/modifyConfig.py");
			uris.add("ftp://test:[email protected]/maraStart.sh");
			app.setUris(uris);
			System.out.println(app);
			marathon.createApp(app);
		}
		
		System.out.println("success");
	}
	
	/**
	 * 獲取創建的多個APP,輸出APP的信息
	 * @throws MarathonException
	 */
	@Test
	public void testAPPS() throws MarathonException {
		GetAppsResponse getAppsResponse = marathon.getApps();
		System.out.println("GetAppsResponse: " + getAppsResponse);
		List<App> listAPP = getAppsResponse.getApps();
		for (App app : listAPP) {
			System.out.println("APP: " + app);
			
		}
	}
	
	/**
	 * 查看配置的CPU和MEM
	 * @throws MarathonException
	 */
	@Test
	public void testAPP() throws MarathonException {
		System.out.println("--------------");
		GetAppResponse getAppResponse = marathon.getApp("/likexin/start");
		App app = getAppResponse.getApp();
		System.out.println("CPUS: " + app.getCpus());
		System.out.println("MEM: " + app.getMem());
	}
	
	/**
	 * 查看正在部署的APP
	 * @throws MarathonException
	 */
	@Test
	public void testDeployment() throws MarathonException {
		List<Deployment> list = marathon.getDeployments();
		System.out.println(list);
	}
	
	/**
	 * 根據ID獲取task
	 * @throws MarathonException
	 */
	@Test
	public void testTask() throws MarathonException { 
		GetAppTasksResponse getAppTaskResponse = marathon.getAppTasks("/likexin/task1");
		Collection<Task> list = getAppTaskResponse.getTasks();
		System.out.println(list);
	}
	
	/**
	 * 根據ID獲取APP
	 * @throws MarathonException
	 */
	@Test
	public void testStatus() throws MarathonException {
		GetAppResponse getAppResponse = marathon.getApp("task1");
		App app = getAppResponse.getApp();
	}
	
	/**
	 * 刪除APP
	 * @throws MarathonException
	 */
	@Test
	public void testDeleteAPP() throws MarathonException {
		System.out.println("START");
		GetAppsResponse getAppsResponse = marathon.getApps();
		System.out.println("GetAppsResponse: " + getAppsResponse);
		List<App> listAPP = getAppsResponse.getApps();
		for (App app : listAPP) {
			marathon.deleteApp(app.getId());
		}
		System.out.println("SUCCESS");
	}
	
	/**
	 * 獲取任務的ID
	 * @throws MarathonException
	 */
	@Test
	public void testMesos() throws MarathonException {
		GetAppResponse getAppResponse = marathon.getApp("/likexin/start");
		App app = getAppResponse.getApp();
		Collection<Task> tasks = app.getTasks();
		for (Task task : tasks) {
			String taskID = task.getId();
			System.out.println(taskID);
		}
	}
	
	/**
	 * 獲取mesos監控界面上面顯示的CPU和內存的使用率,通過HTTP來拿到數據的
	 * @throws InterruptedException
	 */
	@Test
	public void tesMonitor() throws InterruptedException {
		while(true){
			JSONObject jsonObject0 = getJSONObject("likexin_task3.5103f40f-54ca-11e7-9fc1-002590300172");
			double cpus_limit = jsonObject0.getDouble("cpus_limit");
			double cpus_system_time_secs0 = jsonObject0.getDouble("cpus_system_time_secs");
			double cpus_user_time_secs0 = jsonObject0.getDouble("cpus_user_time_secs");
			double timestamp0 = jsonObject0.getDouble("timestamp");
			Thread.sleep(1000);
			JSONObject jsonObject1 = getJSONObject("likexin_task3.5103f40f-54ca-11e7-9fc1-002590300172");
			double cpus_system_time_secs1 = jsonObject1.getDouble("cpus_system_time_secs");
			double cpus_user_time_secs1 = jsonObject1.getDouble("cpus_user_time_secs");
			double timestamp1 = jsonObject1.getDouble("timestamp");
			double cpus_time_total0 = cpus_system_time_secs0 + cpus_user_time_secs0;
			double cpus_time_total1 = cpus_system_time_secs1 + cpus_user_time_secs1;
			double cpus_time_delta = cpus_time_total1 - cpus_time_total0;
			double timestamp_delta = timestamp1 - timestamp0;
			double percent = cpus_time_delta / timestamp_delta;
			System.out.println("percent : " +percent);
			System.out.println("likexin_task2.0d959f48-54c1-11e7-9fc1-002590300172 : " +cpus_limit*percent);
		}
	}
	
	/**
	 * 將界面返回的JSON串轉換爲對象
	 * @param executor_id
	 * @return
	 */
	public JSONObject getJSONObject(String executor_id) {
		String result = sendPost("http://172.16.12.126:5051/monitor/statistics.json","");
		JSONArray jsonArr = JSONArray.fromObject(result);
		for (int i = 0; i < jsonArr.size(); i++) {
			JSONObject jsonObject = jsonArr.getJSONObject(i);
			if(executor_id.trim().equals(jsonObject.get("executor_id"))){
				String statistics = jsonObject.getString("statistics");
				JSONObject statObject = JSONObject.fromObject(statistics);
				return statObject;
			}
		}
		return null;
	}
	

	/**
	 * 向指定URL發送GET方法的請求
	 * 
	 * @param url
	 *            發送請求的URL
	 * @param param
	 *            請求參數,請求參數應該是 name1=value1&name2=value2 的形式。
	 * @return URL 所代表遠程資源的響應結果
	 */
	public static String sendGet(String url, String param) {
	    String result = "";
	    BufferedReader in = null;
	    try {
	        String urlNameString = url + "?" + param;
	        URL realUrl = new URL(urlNameString);
	        // 打開和URL之間的連接
	        URLConnection connection = realUrl.openConnection();
	        // 設置通用的請求屬性
	        connection.setRequestProperty("accept", "*/*");
	        connection.setRequestProperty("connection", "Keep-Alive");
	        connection.setRequestProperty("user-agent",
	                "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
	        // 建立實際的連接
	        connection.connect();
	        // 獲取所有響應頭字段
	        Map<String, List<String>> map = connection.getHeaderFields();
	        // 遍歷所有的響應頭字段
	        for (String key : map.keySet()) {
	            System.out.println(key + "--->" + map.get(key));
	        }
	        // 定義 BufferedReader輸入流來讀取URL的響應
	        in = new BufferedReader(new InputStreamReader(
	                connection.getInputStream()));
	        String line;
	        while ((line = in.readLine()) != null) {
	            result += line;
	        }
	    } catch (Exception e) {
	        System.out.println("發送GET請求出現異常!" + e);
	        e.printStackTrace();
	    }
	    // 使用finally塊來關閉輸入流
	    finally {
	        try {
	            if (in != null) {
	                in.close();
	            }
	        } catch (Exception e2) {
	            e2.printStackTrace();
	        }
	    }
	    return result;
	}
		
	/**
     * 向指定 URL 發送POST方法的請求
     * 
     * @param url
     *            發送請求的 URL
     * @param param
     *            請求參數,請求參數應該是 name1=value1&name2=value2 的形式。
     * @return 所代表遠程資源的響應結果
     */
    public static String sendPost(String url, String param) {
        PrintWriter out = null;
        BufferedReader in = null;
        String result = "";
        try {
            URL realUrl = new URL(url);
            // 打開和URL之間的連接
            URLConnection conn = realUrl.openConnection();
            // 設置通用的請求屬性
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 發送POST請求必須設置如下兩行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            // 獲取URLConnection對象對應的輸出流
            out = new PrintWriter(conn.getOutputStream());
            // 發送請求參數
            out.print(param);
            // flush輸出流的緩衝
            out.flush();
            // 定義BufferedReader輸入流來讀取URL的響應
            in = new BufferedReader(
                    new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            System.out.println("發送 POST 請求出現異常!"+e);
            e.printStackTrace();
        }
        //使用finally塊來關閉輸出流、輸入流
        finally{
            try{
                if(out!=null){
                    out.close();
                }
                if(in!=null){
                    in.close();
                }
            }
            catch(IOException ex){
                ex.printStackTrace();
            }
        }
        return result;
    } 
    
    @Test
    public void testJSON() {
    	String jsonStr = "{name:'likexin',age:'hah',money:12.23}";
    	JSONObject jsonObject = JSONObject.fromObject(jsonStr);
		double cpus_limit = jsonObject.getDouble("money");
		System.out.println(cpus_limit);
    }
}
注意:在Marathon上面運行的APP一定是服務,能長時間運行

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章