Difference between revisions of "Scripts/Site Sync Apex"

From Observer GigaFlow Support | VIAVI Solutions Inc.
Jump to: navigation, search
 
Line 132: Line 132:
 
   //log.warn(ret)
 
   //log.warn(ret)
 
  }
 
  }
 
 
  function getSites(){
 
  function getSites(){
 
   log.debug("getSites with sessionid:"+sessionid);
 
   log.debug("getSites with sessionid:"+sessionid);

Latest revision as of 16:04, 22 March 2022

var serverURL = "https://apex.usa.viavi.solutions";
var user="api";
var password="duijfhdlifhlziuhflsuhfgulh";
//-------Only change whats above this line----------------
var loginURL =  serverURL+'/oa/api/session';
var sitesURL = serverURL+'/oa/api/v1/sites';
var toremove=[];
var now = new Date().getTime();
var utils = Java.type('ros.CROSUtils');
var sessionid="";
var siteData={};
var siteret;
login()
function hasSubnet(group,subnet){
return group.indexOf(subnet)>-1
}
function cleanUP(){
 log.debug("cleanUP");
 var groups = actions.ros.getCTrafficGroups()
 for (var tg in groups.allTrafficGroups){
  //log.debug(groups.allTrafficGroups.get(tg));
  var thisGroup=groups.allTrafficGroups.get(tg);
  if (typeof siteData[thisGroup.name]==='undefined'){
   log.debug("removing:"+thisGroup.name+" "+thisGroup.getId());
   toremove.push(thisGroup.getId())
  }else{
   log.debug("not removing:"+thisGroup.name);
   var groupSubnets=thisGroup.getSubnets();
   var it = groupSubnets.iterator();
   while (it.hasNext()){
    var s =it.next();
    //log.debug(s)
    var key=utils.inet_btoa(s.getStartEntry())+"-"+utils.inet_btoa(s.getEndEntry());
    if (!hasSubnet(siteData[thisGroup.name],key)){
    it.remove();
    actions.getDatabaseManager().executePrepared("delete from trafficgroupsubnets where id=? and startip=? and endip=?",thisGroup.getId(),s.getStartEntry(),s.getEndEntry())
    log.debug("removing subnet from "+thisGroup.name +" "+key+" "+hasSubnet(siteData[thisGroup.name],key));
     }
   }
  }
 }
  for (var i in toremove){
  log.debug("Removing full site:"+toremove[i]);
    actions.ros.removeTrafficGroup(toremove[i]);
    }
}
function findInterfacesForSites(trafficgroup,ip){
  //log.debug("findInterfacesForSites:"+trafficgroup+" "+ip);
  for (var deviceid in actions.getDevices()){
  var device =actions.getDevice(deviceid); 
  for (var d in device.interfaces()){
   var thisIn = device.interfaces().get(d);
   var interfaceIPS = thisIn.getInterfaceIPs()
   if (!interfaceIPS.isEmpty()){
    //log.debug(d+" "+thisIn+" "+interfaceIPS);
    for (var ips in interfaceIPS){
     var thisip = interfaceIPS.get(ips)
     if (utils.isIPInSubnet(ip,utils.inet_btoa(thisip.getIp()),utils.inet_btoa(thisip.getMask()))){
      log.debug("Adding device/interface to group "+ trafficgroup+" device:"+device.getIP()+" ifindex:"+thisIn.getIfindex());
      trafficgroup.addDevice(device.getIP(),thisIn.getIfindex(),actions.ros);
     }
    }
   }
  }
 }
}
function processSites(){
 if (typeof siteret!=='undefined'){
  //log.debug(typeof siteret);
  //log.debug("processSites:"+siteret.length());
  for (var i=0;i<siteret.length();i++){
   var thisone = siteret.getJSONObject(i);
   //log.debug(i+" "+thisone);
   var location = thisone.getJSONObject("location")
   var siteName = thisone.getString("name");
   if (typeof siteData[siteName]==='undefined'){
    siteData[siteName]=[];
   }
   var siteDescription = location.getString("name");
   var subnets = thisone.getJSONArray("subnets");
   for (var s=0;s<subnets.length();s++){
     var thisSubnet=subnets.get(s).getString("value").replace(/\s/g, "");
    //log.debug(i+" "+siteName+" -- "+siteDescription+" "+thisSubnet);
     if (thisSubnet.indexOf("-")>-1){
      var trafficgroup=    actions.ros.addTrafficGroup(now,"script",siteName,siteDescription,utils.inet_atob(thisSubnet.split("-")[0]),utils.inet_atob(thisSubnet.split("-")[1]),false,null,false,-1);
     siteData[siteName].push(thisSubnet.split("-")[0]+"-"+thisSubnet.split("-")[1])
     findInterfacesForSites(trafficgroup,thisSubnet.split("-")[0]);
     }else if (thisSubnet.indexOf("/")>-1){
     //log.debug(thisSubnet);
     var d=utils.getIPRange(thisSubnet.split("/"));
      var trafficgroup= actions.ros.addTrafficGroup(now,"script",siteName,siteDescription,d[0],d[1],false,null,false,-1);
    siteData[siteName].push(utils.inet_btoa(d[0])+"-"+utils.inet_btoa(d[1]))
    findInterfacesForSites(trafficgroup,utils.inet_btoa(d[0]));
    //log.debug(d);
     //log.debug(d[0]+" - "+d[1]);
     }else{
     log.debug("Unknown subent type:"+thisSubnet);
     }
    //actions.ros.addTrafficGroup(now,"script",siteName,siteDescription,utils.inet_atob(
   }
  }
 }else{
  log.debug(typeof siteret);
  log.debug("cant processSites:"+siteret);
 }
   cleanUP()
   log.debug(JSON.stringify(siteData["Denver"]));
}
function logOut(){
 log.debug("logOut with sessionid:"+sessionid);
 var data = {"session" :sessionid}
 var con = new java.net.URL(loginURL).openConnection();
 con.requestMethod = "DELETE";
 con.setRequestProperty("Cookie","SessionApexId="+sessionid+";");
 //con.setRequestProperty("SessionApexId",sessionid);
 var ret = asResponse(con);
 log.warn(ret)
 log.warn(ret.data.toString())
 processSites()
}
function login(){
 log.debug("Doing apex login");
 var data = {"session" : {"username" : user,"password" : password}}
 var ret = httpRequest("POST",loginURL,JSON.stringify(data),"application/json","application/json");
 if (parseInt(ret.statusCode)===200&&sessionid!==""){
  log.warn("Valid login:"+sessionid);
  getSites()
 }else{
  log.warn("Invalid login:"+JSON.parse(ret.statusCode));
 }
 //log.warn(ret.statusCode)
 //log.warn(ret)
}
function getSites(){
 log.debug("getSites with sessionid:"+sessionid);
 var data = {}
 var con = new java.net.URL(sitesURL+"?SessionApexId="+sessionid).openConnection();
 con.requestMethod = "GET";
 con.setRequestProperty("Cookie","SessionApexId="+sessionid+";");
 con.setRequestProperty("Content-Type", "application/json");
 con.setRequestProperty("Accept", "application/json");
 siteret = utils.JSONObject(asResponse(con).data.toString()).getJSONObject("data").getJSONArray("sites");
 //log.warn(siteret)
 //log.warn(siteret.data.toString())
 logOut(sessionid) 
}
//dont touch anything below here
function httpRequest(method,theUrl, data, contentType,contentAccept){
   method = method || "POST";
  contentAccept = contentAccept || "application/json";
   contentType = contentType || "application/json";
   var con = new java.net.URL(theUrl).openConnection();
   con.requestMethod = method;
   con.setRequestProperty("Content-Type", contentType);
   con.setRequestProperty("Accept", contentAccept);
   // Send post request
   con.doOutput=true;
   write(con.outputStream, data);
 var headers = con.getHeaderFields();
 log.debug(con.getHeaderFields())
 if (headers.containsKey("Set-Cookie")){
  var d = headers.get("Set-Cookie")
  log.debug(d);
  for (var e in d){
   log.debug(e+" "+d[e]);
    if (d[e].indexOf("SessionApexId")>-1){
    // 0 SessionApexId=721ea868799a2112dbb81c; Path=/; secure; HttpOnly
    var f = d[e].split("; ");
    for (var g in f){
     if (f[g].indexOf("SessionApexId")>-1){
       sessionid=f[g].split("=")[1];
       log.debug("Setting sessionid:"+sessionid);
     }
    }
   }
  }
 }
   return asResponse(con);
}
function asResponse(con){
   var d = read(con.inputStream);
   return {data : d, statusCode : con.responseCode};
}
function write(outputStream, data){
   var wr = new java.io.DataOutputStream(outputStream);
   wr.writeBytes(data);
   wr.flush();
   wr.close();
}
function read(inputStream){
   var inReader = new java.io.BufferedReader(new java.io.InputStreamReader(inputStream));
   var inputLine;
   var response = new java.lang.StringBuffer();
   while ((inputLine = inReader.readLine()) != null) {
    response.append(inputLine);
   }
   inReader.close();
   return response.toString();
}