private Answer execute(SetFirewallRulesCommand cmd) {
    String[] results = new String[cmd.getRules().length];
    for (int i = 0; i < cmd.getRules().length; i++) {
      results[i] = "Failed";
    }
    String routerIp = cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP);

    if (routerIp == null) {
      return new SetFirewallRulesAnswer(cmd, false, results);
    }

    String[][] rules = cmd.generateFwRules();
    final Script command = new Script(_firewallPath, _timeout, s_logger);
    command.add(routerIp);
    command.add("-F");

    StringBuilder sb = new StringBuilder();
    String[] fwRules = rules[0];
    if (fwRules.length > 0) {
      for (int i = 0; i < fwRules.length; i++) {
        sb.append(fwRules[i]).append(',');
      }
      command.add("-a", sb.toString());
    }

    String result = command.execute();
    if (result != null) {
      return new SetFirewallRulesAnswer(cmd, false, results);
    }
    return new SetFirewallRulesAnswer(cmd, true, null);
  }
Exemplo n.º 2
0
  private void startupCleanup(String parent) {
    s_logger.info("Cleanup mounted NFS mount points used in previous session");

    long mshostId = ManagementServerNode.getManagementServerId();

    // cleanup left-over NFS mounts from previous session
    String[] mounts = _storage.listFiles(parent + File.separator + String.valueOf(mshostId) + ".*");
    if (mounts != null && mounts.length > 0) {
      for (String mountPoint : mounts) {
        s_logger.info("umount NFS mount from previous session: " + mountPoint);

        String result = null;
        Script command = new Script(true, "umount", _timeout, s_logger);
        command.add(mountPoint);
        result = command.execute();
        if (result != null) {
          s_logger.warn("Unable to umount " + mountPoint + " due to " + result);
        }
        File file = new File(mountPoint);
        if (file.exists()) {
          file.delete();
        }
      }
    }
  }
Exemplo n.º 3
0
  @Override
  public FormatInfo process(String templatePath, ImageFormat format, String templateName)
      throws InternalErrorException {
    if (format != null) {
      if (s_logger.isInfoEnabled()) {
        s_logger.info("We currently don't handle conversion from " + format + " to OVA.");
      }
      return null;
    }

    s_logger.info(
        "Template processing. templatePath: " + templatePath + ", templateName: " + templateName);
    String templateFilePath =
        templatePath + File.separator + templateName + "." + ImageFormat.OVA.getFileExtension();
    if (!_storage.exists(templateFilePath)) {
      if (s_logger.isInfoEnabled()) {
        s_logger.info("Unable to find the vmware template file: " + templateFilePath);
      }
      return null;
    }

    s_logger.info(
        "Template processing - untar OVA package. templatePath: "
            + templatePath
            + ", templateName: "
            + templateName);
    String templateFileFullPath =
        templatePath + File.separator + templateName + "." + ImageFormat.OVA.getFileExtension();
    File templateFile = new File(templateFileFullPath);

    Script command = new Script("tar", 0, s_logger);
    command.add("--no-same-owner");
    command.add("-xf", templateFileFullPath);
    command.setWorkDir(templateFile.getParent());
    String result = command.execute();
    if (result != null) {
      s_logger.info(
          "failed to untar OVA package due to "
              + result
              + ". templatePath: "
              + templatePath
              + ", templateName: "
              + templateName);
      throw new InternalErrorException("failed to untar OVA package");
    }

    FormatInfo info = new FormatInfo();
    info.format = ImageFormat.OVA;
    info.filename = templateName + "." + ImageFormat.OVA.getFileExtension();
    info.size = _storage.getSize(templateFilePath);
    info.virtualSize = getTemplateVirtualSize(templatePath, info.filename);

    // delete original OVA file
    // templateFile.delete();
    return info;
  }
 protected String getDomRVersion(String routerIP) {
   final Script command = new Script(_getDomRVersionPath, _timeout, s_logger);
   final OutputInterpreter.OneLineParser parser = new OutputInterpreter.OneLineParser();
   command.add(routerIP);
   String result = command.execute(parser);
   if (result == null) {
     return parser.getLine();
   }
   return null;
 }
 public String getRouterStatus(String routerIP) {
   final Script command = new Script(_getRouterStatusPath, _timeout, s_logger);
   final OutputInterpreter.OneLineParser parser = new OutputInterpreter.OneLineParser();
   command.add(routerIP);
   String result = command.execute(parser);
   if (result == null) {
     return parser.getLine();
   }
   return null;
 }
  private Answer execute(SetPortForwardingRulesCommand cmd) {
    String routerIp = cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP);
    String[] results = new String[cmd.getRules().length];
    int i = 0;

    boolean endResult = true;
    for (PortForwardingRuleTO rule : cmd.getRules()) {
      String result = null;
      final Script command = new Script(_firewallPath, _timeout, s_logger);

      command.add(routerIp);
      command.add(rule.revoked() ? "-D" : "-A");
      command.add("-P ", rule.getProtocol().toLowerCase());
      command.add("-l ", rule.getSrcIp());
      command.add("-p ", rule.getStringSrcPortRange());
      command.add("-r ", rule.getDstIp());
      command.add("-d ", rule.getStringDstPortRange());
      result = command.execute();
      if (result == null) {
        results[i++] = null;
      } else {
        results[i++] = "Failed";
        endResult = false;
      }
    }

    return new SetPortForwardingRulesAnswer(cmd, results, endResult);
  }
  private void startAdditionalServices() {

    Script command = new Script("rm", s_logger);
    command.add("-rf");
    command.add(extractMountPoint);
    String result = command.execute();
    if (result != null) {
      s_logger.warn("Error in creating file " + extractMountPoint + " ,error: " + result);
      return;
    }

    command = new Script("touch", s_logger);
    command.add(extractMountPoint);
    result = command.execute();
    if (result != null) {
      s_logger.warn("Error in creating file " + extractMountPoint + " ,error: " + result);
      return;
    }

    command = new Script("/bin/bash", s_logger);
    command.add("-c");
    command.add("ln -sf " + parentDir + " " + extractMountPoint);
    result = command.execute();
    if (result != null) {
      s_logger.warn("Error in linking  err=" + result);
      return;
    }
  }
 protected Answer execute(BumpUpPriorityCommand cmd) {
   final String routerPrivateIPAddress = cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP);
   final Script command = new Script(_bumpUpPriorityPath, _timeout, s_logger);
   final OutputInterpreter.OneLineParser parser = new OutputInterpreter.OneLineParser();
   command.add(routerPrivateIPAddress);
   String result = command.execute(parser);
   if (result != null) {
     return new Answer(cmd, false, "BumpUpPriorityCommand failed: " + result);
   }
   return new Answer(cmd, true, null);
 }
 private boolean isDNSmasqRunning(String dnsmasqName) {
   Script cmd = new Script("/bin/sh", _timeout);
   cmd.add("-c");
   cmd.add("ls -l /var/run/libvirt/network/" + dnsmasqName + ".pid");
   String result = cmd.execute();
   if (result != null) {
     return false;
   } else {
     return true;
   }
 }
 private boolean isBridgeExists(String bridgeName) {
   Script command = new Script("/bin/sh", _timeout);
   command.add("-c");
   command.add("brctl show|grep " + bridgeName);
   final OutputInterpreter.OneLineParser parser = new OutputInterpreter.OneLineParser();
   String result = command.execute(parser);
   if (result != null || parser.getLine() == null) {
     return false;
   } else {
     return true;
   }
 }
Exemplo n.º 11
0
  protected String mount(String path, String parent) {
    String mountPoint = setupMountPoint(parent);
    if (mountPoint == null) {
      s_logger.warn("Unable to create a mount point");
      return null;
    }

    Script script = null;
    String result = null;
    Script command = new Script(true, "mount", _timeout, s_logger);
    command.add("-t", "nfs");
    // command.add("-o", "soft,timeo=133,retrans=2147483647,tcp,acdirmax=0,acdirmin=0");
    command.add(path);
    command.add(mountPoint);
    result = command.execute();
    if (result != null) {
      s_logger.warn("Unable to mount " + path + " due to " + result);
      File file = new File(mountPoint);
      if (file.exists()) {
        file.delete();
      }
      return null;
    }

    // Change permissions for the mountpoint
    script = new Script(true, "chmod", _timeout, s_logger);
    script.add("777", mountPoint);
    result = script.execute();
    if (result != null) {
      s_logger.warn("Unable to set permissions for " + mountPoint + " due to " + result);
      return null;
    }
    return mountPoint;
  }
Exemplo n.º 12
0
  @Override
  public boolean configure(String name, Map<String, Object> params) throws ConfigurationException {
    ComponentLocator locator = ComponentLocator.getCurrentLocator();
    _configDao = locator.getDao(ConfigurationDao.class);
    _setupAgentPath = Script.findScript(getPatchPath(), "setup_agent.sh");
    _kvmPrivateNic = _configDao.getValue(Config.KvmPrivateNetwork.key());
    if (_kvmPrivateNic == null) {
      _kvmPrivateNic = "cloudbr0";
    }

    _kvmPublicNic = _configDao.getValue(Config.KvmPublicNetwork.key());
    if (_kvmPublicNic == null) {
      _kvmPublicNic = _kvmPrivateNic;
    }

    _kvmGuestNic = _configDao.getValue(Config.KvmGuestNetwork.key());
    if (_kvmGuestNic == null) {
      _kvmGuestNic = _kvmPrivateNic;
    }

    if (_setupAgentPath == null) {
      throw new ConfigurationException("Can't find setup_agent.sh");
    }
    _hostIp = _configDao.getValue("host");
    if (_hostIp == null) {
      throw new ConfigurationException("Can't get host IP");
    }
    _resourceMgr.registerResourceStateAdapter(this.getClass().getSimpleName(), this);
    return true;
  }
Exemplo n.º 13
0
  private void deleteVnetBr(String brName) {
    synchronized (_vnetBridgeMonitor) {
      String cmdout = Script.runSimpleBashScript("ls /sys/class/net/" + brName);
      if (cmdout == null)
        // Bridge does not exist
        return;
      cmdout = Script.runSimpleBashScript("ls /sys/class/net/" + brName + "/brif | tr '\n' ' '");
      if (cmdout != null && cmdout.contains("vnet")) {
        // Active VM remains on that bridge
        return;
      }

      Pattern oldStyleBrNameRegex = Pattern.compile("^cloudVirBr(\\d+)$");
      Pattern brNameRegex = Pattern.compile("^br(\\S+)-(\\d+)$");
      Matcher oldStyleBrNameMatcher = oldStyleBrNameRegex.matcher(brName);
      Matcher brNameMatcher = brNameRegex.matcher(brName);

      String pName = null;
      String vNetId = null;
      if (oldStyleBrNameMatcher.find()) {
        // Actually modifyvlan.sh doesn't require pif name when deleting its bridge so far.
        pName = "undefined";
        vNetId = oldStyleBrNameMatcher.group(1);
      } else if (brNameMatcher.find()) {
        if (brNameMatcher.group(1) != null || !brNameMatcher.group(1).isEmpty()) {
          pName = brNameMatcher.group(1);
        } else {
          pName = "undefined";
        }
        vNetId = brNameMatcher.group(2);
      }

      if (vNetId == null || vNetId.isEmpty()) {
        s_logger.debug("unable to get a vNet ID from name " + brName);
        return;
      }

      String scriptPath = null;
      if (cmdout != null && cmdout.contains("vxlan")) {
        scriptPath = _modifyVxlanPath;
      } else {
        scriptPath = _modifyVlanPath;
      }

      final Script command = new Script(scriptPath, _timeout, s_logger);
      command.add("-o", "delete");
      command.add("-v", vNetId);
      command.add("-p", pName);
      command.add("-b", brName);

      final String result = command.execute();
      if (result != null) {
        s_logger.debug("Delete bridge " + brName + " failed: " + result);
      }
    }
  }
 private void addRouteToInternalIpOrCidr(
     String localgw, String eth1ip, String eth1mask, String destIpOrCidr) {
   s_logger.debug(
       "addRouteToInternalIp: localgw="
           + localgw
           + ", eth1ip="
           + eth1ip
           + ", eth1mask="
           + eth1mask
           + ",destIp="
           + destIpOrCidr);
   if (destIpOrCidr == null) {
     s_logger.debug("addRouteToInternalIp: destIp is null");
     return;
   }
   if (!NetUtils.isValidIp(destIpOrCidr) && !NetUtils.isValidCIDR(destIpOrCidr)) {
     s_logger.warn(" destIp is not a valid ip address or cidr destIp=" + destIpOrCidr);
     return;
   }
   boolean inSameSubnet = false;
   if (NetUtils.isValidIp(destIpOrCidr)) {
     if (eth1ip != null && eth1mask != null) {
       inSameSubnet = NetUtils.sameSubnet(eth1ip, destIpOrCidr, eth1mask);
     } else {
       s_logger.warn(
           "addRouteToInternalIp: unable to determine same subnet: _eth1ip="
               + eth1ip
               + ", dest ip="
               + destIpOrCidr
               + ", _eth1mask="
               + eth1mask);
     }
   } else {
     inSameSubnet =
         NetUtils.isNetworkAWithinNetworkB(
             destIpOrCidr, NetUtils.ipAndNetMaskToCidr(eth1ip, eth1mask));
   }
   if (inSameSubnet) {
     s_logger.debug(
         "addRouteToInternalIp: dest ip "
             + destIpOrCidr
             + " is in the same subnet as eth1 ip "
             + eth1ip);
     return;
   }
   Script command = new Script("/bin/bash", s_logger);
   command.add("-c");
   command.add("ip route delete " + destIpOrCidr);
   command.execute();
   command = new Script("/bin/bash", s_logger);
   command.add("-c");
   command.add("ip route add " + destIpOrCidr + " via " + localgw);
   String result = command.execute();
   if (result != null) {
     s_logger.warn("Error in configuring route to internal ip err=" + result);
   } else {
     s_logger.debug(
         "addRouteToInternalIp: added route to internal ip=" + destIpOrCidr + " via " + localgw);
   }
 }
Exemplo n.º 15
0
  @Override
  public File[] getPrepareScripts() {
    String script = Script.findScript("", "db/schema-2212to2213.sql");
    if (script == null) {
      throw new CloudRuntimeException("Unable to find db/schema-2212to2213.sql");
    }

    return new File[] {new File(script)};
  }
Exemplo n.º 16
0
  @Override
  public File[] getPrepareScripts() {
    String file = Script.findScript("", "db/schema-221to222.sql");
    if (file == null) {
      throw new CloudRuntimeException("Unable to find the upgrade script, schema-221to222.sql");
    }

    return new File[] {new File(file)};
  }
Exemplo n.º 17
0
 public void removeStoragePool(String uuid) {
   synchronized (_storagePool) {
     NfsStoragePool pool = _storagePool.get(uuid);
     if (pool != null) {
       Script.runSimpleBashScript("umount " + pool._mountDestPath);
       _storagePool.remove(uuid);
     }
   }
 }
  private Answer execute(VpnUsersCfgCommand cmd) {
    for (VpnUsersCfgCommand.UsernamePassword userpwd : cmd.getUserpwds()) {
      Script command = new Script(_l2tpVpnPath, _timeout, s_logger);
      command.add(cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP));
      if (!userpwd.isAdd()) {
        command.add("-U ", userpwd.getUsername());
      } else {
        command.add("-u ", userpwd.getUsernamePassword());
      }
      String result = command.execute();
      if (result != null) {
        return new Answer(
            cmd, false, "Configure VPN user failed for user " + userpwd.getUsername());
      }
    }

    return new Answer(cmd);
  }
 private Answer execute(RemoteAccessVpnCfgCommand cmd) {
   Script command = new Script(_l2tpVpnPath, _timeout, s_logger);
   command.add(cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP));
   if (cmd.isCreate()) {
     command.add("-r ", cmd.getIpRange());
     command.add("-p ", cmd.getPresharedKey());
     command.add("-s ", cmd.getVpnServerIp());
     command.add("-l ", cmd.getLocalIp());
     command.add("-c ");
   } else {
     command.add("-d ");
     command.add("-s ", cmd.getVpnServerIp());
   }
   String result = command.execute();
   if (result != null) {
     return new Answer(cmd, false, "Configure VPN failed");
   }
   return new Answer(cmd);
 }
Exemplo n.º 20
0
  private void shutdownCleanup() {
    s_logger.info("Cleanup mounted NFS mount points used in current session");

    for (String mountPoint : _storageMounts.values()) {
      s_logger.info("umount NFS mount: " + mountPoint);

      String result = null;
      Script command = new Script(true, "umount", _timeout, s_logger);
      command.add(mountPoint);
      result = command.execute();
      if (result != null) {
        s_logger.warn("Unable to umount " + mountPoint + " due to " + result);
      }
      File file = new File(mountPoint);
      if (file.exists()) {
        file.delete();
      }
    }
  }
Exemplo n.º 21
0
 @Override
 protected List<File> getPatchFiles() {
   List<File> files = new ArrayList<File>();
   String patch = "scripts/vm/hypervisor/xenserver/xcpserver/patch";
   String patchfilePath = Script.findScript("", patch);
   if (patchfilePath == null) {
     throw new CloudRuntimeException("Unable to find patch file " + patch);
   }
   File file = new File(patchfilePath);
   files.add(file);
   return files;
 }
Exemplo n.º 22
0
  public static String getDefaultEthDevice() {
    if (SystemUtils.IS_OS_MAC) {
      String defDev =
          Script.runSimpleBashScript(
              "/sbin/route -n get default 2> /dev/null | grep interface | awk '{print $2}'");
      return defDev;
    }
    String defaultRoute = Script.runSimpleBashScript("/sbin/route | grep default");

    if (defaultRoute == null) {
      return null;
    }

    String[] defaultRouteList = defaultRoute.split("\\s+");

    if (defaultRouteList.length != 8) {
      return null;
    }

    return defaultRouteList[7];
  }
 private void deletExitingLinkLocalRoutTable(String linkLocalBr) {
   Script command = new Script("/bin/bash", _timeout);
   command.add("-c");
   command.add("ip route | grep " + NetUtils.getLinkLocalCIDR());
   OutputInterpreter.AllLinesParser parser = new OutputInterpreter.AllLinesParser();
   String result = command.execute(parser);
   boolean foundLinkLocalBr = false;
   if (result == null && parser.getLines() != null) {
     String[] lines = parser.getLines().split("\\n");
     for (String line : lines) {
       String[] tokens = line.split(" ");
       if (!tokens[2].equalsIgnoreCase(linkLocalBr)) {
         Script.runSimpleBashScript("ip route del " + NetUtils.getLinkLocalCIDR());
       } else {
         foundLinkLocalBr = true;
       }
     }
   }
   if (!foundLinkLocalBr) {
     Script.runSimpleBashScript(
         "ifconfig "
             + linkLocalBr
             + " 169.254.0.1;"
             + "ip route add "
             + NetUtils.getLinkLocalCIDR()
             + " dev "
             + linkLocalBr
             + " src "
             + NetUtils.getLinkLocalGateway());
   }
 }
Exemplo n.º 24
0
 private void createControlNetwork(String privBrName) {
   deleteExistingLinkLocalRouteTable(privBrName);
   if (!isBridgeExists(privBrName)) {
     Script.runSimpleBashScript(
         "brctl addbr "
             + privBrName
             + "; ip link set "
             + privBrName
             + " up; ip address add 169.254.0.1/16 dev "
             + privBrName,
         _timeout);
   }
 }
Exemplo n.º 25
0
  @Override
  public void configure(Map<String, Object> params) throws ConfigurationException {

    super.configure(params);

    // Set the domr scripts directory
    params.put("domr.scripts.dir", "scripts/network/domr/kvm");

    String networkScriptsDir = (String) params.get("network.scripts.dir");
    if (networkScriptsDir == null) {
      networkScriptsDir = "scripts/vm/network/vnet";
    }

    bridgeNameSchema = (String) params.get("network.bridge.name.schema");

    String value = (String) params.get("scripts.timeout");
    _timeout = NumbersUtil.parseInt(value, 30 * 60) * 1000;

    _modifyVlanPath = Script.findScript(networkScriptsDir, "modifyvlan.sh");
    if (_modifyVlanPath == null) {
      throw new ConfigurationException("Unable to find modifyvlan.sh");
    }
    _modifyVxlanPath = Script.findScript(networkScriptsDir, "modifyvxlan.sh");
    if (_modifyVxlanPath == null) {
      throw new ConfigurationException("Unable to find modifyvxlan.sh");
    }

    libvirtVersion = (Long) params.get("libvirtVersion");
    if (libvirtVersion == null) {
      libvirtVersion = 0L;
    }

    try {
      createControlNetwork();
    } catch (LibvirtException e) {
      throw new ConfigurationException(e.getMessage());
    }
  }
 public void createControlNetwork(String privBrName) {
   deletExitingLinkLocalRoutTable(privBrName);
   if (!isBridgeExists(privBrName)) {
     Script.runSimpleBashScript(
         "brctl addbr "
             + privBrName
             + "; ifconfig "
             + privBrName
             + " up; ifconfig "
             + privBrName
             + " 169.254.0.1",
         _timeout);
   }
 }
Exemplo n.º 27
0
  public static String getDefaultEthDevice() {
    String defaultRoute = Script.runSimpleBashScript("/sbin/route | grep default");

    if (defaultRoute == null) {
      return null;
    }

    String[] defaultRouteList = defaultRoute.split("\\s+");

    if (defaultRouteList.length != 8) {
      return null;
    }

    return defaultRouteList[7];
  }
  protected synchronized Answer execute(final DhcpEntryCommand cmd) {
    final Script command = new Script(_dhcpEntryPath, _timeout, s_logger);
    command.add("-r", cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP));
    command.add("-v", cmd.getVmIpAddress());
    command.add("-m", cmd.getVmMac());
    command.add("-n", cmd.getVmName());

    if (cmd.getDefaultRouter() != null) {
      command.add(" -d " + cmd.getDefaultRouter());
    }
    if (cmd.getStaticRoutes() != null) {
      command.add(" -s " + cmd.getStaticRoutes());
    }

    if (cmd.getDefaultDns() != null) {
      command.add(" -N " + cmd.getDefaultDns());
    }

    final String result = command.execute();
    return new Answer(cmd, result == null, result);
  }
  public synchronized String savePassword(
      final String privateIpAddress,
      final String vmIpAddress,
      final String password,
      final String localPath) {
    final Script command = new Script(_savepasswordPath, _startTimeout, s_logger);
    command.add("-r", privateIpAddress);
    command.add("-v", vmIpAddress);
    command.add("-p", password);
    command.add(localPath);

    return command.execute();
  }
  public String assignPublicIpAddress(
      final String vmName,
      final long id,
      final String vnet,
      final String privateIpAddress,
      final String macAddress,
      final String publicIpAddress) {

    final Script command = new Script(_ipassocPath, _timeout, s_logger);
    command.add("-A");
    command.add("-f"); // first ip is source nat ip
    command.add("-r", vmName);
    command.add("-i", privateIpAddress);
    command.add("-a", macAddress);
    command.add("-l", publicIpAddress);

    return command.execute();
  }