private boolean sendCommandsToRouter(final DomainRouterVO elbVm, Commands cmds)
      throws AgentUnavailableException {
    Answer[] answers = null;
    try {
      answers = _agentMgr.send(elbVm.getHostId(), cmds);
    } catch (OperationTimedoutException e) {
      s_logger.warn("ELB: Timed Out", e);
      throw new AgentUnavailableException(
          "Unable to send commands to virtual elbVm ", elbVm.getHostId(), e);
    }

    if (answers == null) {
      return false;
    }

    if (answers.length != cmds.size()) {
      return false;
    }

    // FIXME: Have to return state for individual command in the future
    if (answers.length > 0) {
      Answer ans = answers[0];
      return ans.getResult();
    }
    return true;
  }
  @Override
  public void shutdown(final NetworkProfile profile, final NetworkOffering offering) {
    final NetworkVO networkObject = networkDao.findById(profile.getId());
    if (networkObject.getBroadcastDomainType() != BroadcastDomainType.Lswitch
        || networkObject.getBroadcastUri() == null) {
      s_logger.warn(
          "BroadcastUri is empty or incorrect for guestnetwork " + networkObject.getDisplayText());
      return;
    }

    final List<NiciraNvpDeviceVO> devices =
        niciraNvpDao.listByPhysicalNetwork(networkObject.getPhysicalNetworkId());
    if (devices.isEmpty()) {
      s_logger.error(
          "No NiciraNvp Controller on physical network " + networkObject.getPhysicalNetworkId());
      return;
    }
    final NiciraNvpDeviceVO niciraNvpDevice = devices.get(0);
    final HostVO niciraNvpHost = hostDao.findById(niciraNvpDevice.getHostId());

    final DeleteLogicalSwitchCommand cmd =
        new DeleteLogicalSwitchCommand(
            BroadcastDomainType.getValue(networkObject.getBroadcastUri()));
    final DeleteLogicalSwitchAnswer answer =
        (DeleteLogicalSwitchAnswer) agentMgr.easySend(niciraNvpHost.getId(), cmd);

    if (answer == null || !answer.getResult()) {
      s_logger.error("DeleteLogicalSwitchCommand failed");
    }

    super.shutdown(profile, offering);
  }
  protected Status testIpAddress(Long hostId, String testHostIp) {
    try {
      Answer pingTestAnswer = _agentMgr.send(hostId, new PingTestCommand(testHostIp));
      if (pingTestAnswer == null) {
        if (s_logger.isDebugEnabled()) {
          s_logger.debug("host (" + testHostIp + ") returns null answer");
        }
        return null;
      }

      if (pingTestAnswer.getResult()) {
        if (s_logger.isDebugEnabled()) {
          s_logger.debug(
              "host (" + testHostIp + ") has been successfully pinged, returning that host is up");
        }
        // computing host is available, but could not reach agent, return false
        return Status.Up;
      } else {
        if (s_logger.isDebugEnabled()) {
          s_logger.debug(
              "host (" + testHostIp + ") cannot be pinged, returning null ('I don't know')");
        }
        return null;
      }
    } catch (AgentUnavailableException e) {
      return null;
    } catch (OperationTimedoutException e) {
      return null;
    }
  }
  @Override
  public boolean configure(String name, Map<String, Object> params) throws ConfigurationException {

    Map<String, String> configs = _configDao.getConfiguration("Network", params);
    _numWorkerThreads =
        NumbersUtil.parseInt(
            configs.get(Config.SecurityGroupWorkerThreads.key()), WORKER_THREAD_COUNT);
    _timeBetweenCleanups =
        NumbersUtil.parseInt(
            configs.get(Config.SecurityGroupWorkCleanupInterval.key()), TIME_BETWEEN_CLEANUPS);
    _globalWorkLockTimeout =
        NumbersUtil.parseInt(configs.get(Config.SecurityGroupWorkGlobalLockTimeout.key()), 300);
    /* register state listener, no matter security group is enabled or not */
    VirtualMachine.State.getStateMachine().registerListener(this);

    _answerListener = new SecurityGroupListener(this, _agentMgr, _workDao);
    _agentMgr.registerForHostEvents(_answerListener, true, true, true);

    _serverId = ((ManagementServer) ComponentLocator.getComponent(ManagementServer.Name)).getId();

    s_logger.info(
        "SecurityGroupManager: num worker threads="
            + _numWorkerThreads
            + ", time between cleanups="
            + _timeBetweenCleanups
            + " global lock timeout="
            + _globalWorkLockTimeout);
    createThreadPools();

    return true;
  }
  private boolean configureSourceNat(
      long vlanId, String guestCidr, PublicIp sourceNatIp, long hostId) {
    boolean add = (sourceNatIp.getState() == IpAddress.State.Releasing ? false : true);
    IpAddressTO ip =
        new IpAddressTO(
            sourceNatIp.getAccountId(),
            sourceNatIp.getAddress().addr(),
            add,
            false,
            sourceNatIp.isSourceNat(),
            sourceNatIp.getVlanTag(),
            sourceNatIp.getGateway(),
            sourceNatIp.getNetmask(),
            sourceNatIp.getMacAddress(),
            null,
            sourceNatIp.isOneToOneNat());
    boolean addSourceNat = false;
    if (sourceNatIp.isSourceNat()) {
      addSourceNat = add;
    }

    SetSourceNatCommand cmd = new SetSourceNatCommand(ip, addSourceNat);
    cmd.setContextParam(NetworkElementCommand.GUEST_VLAN_TAG, Long.toString(vlanId));
    cmd.setContextParam(NetworkElementCommand.GUEST_NETWORK_CIDR, guestCidr);
    Answer answer = _agentMgr.easySend(hostId, cmd);
    return answer.getResult();
  }
  @Override
  public boolean generateVMSetupCommand(Long ssAHostId) {
    HostVO ssAHost = _hostDao.findById(ssAHostId);
    if (ssAHost.getType() != Host.Type.SecondaryStorageVM) {
      return false;
    }
    SecondaryStorageVmVO secStorageVm = _secStorageVmDao.findByInstanceName(ssAHost.getName());
    if (secStorageVm == null) {
      s_logger.warn("secondary storage VM " + ssAHost.getName() + " doesn't exist");
      return false;
    }

    SecStorageVMSetupCommand setupCmd = new SecStorageVMSetupCommand();
    if (_allowedInternalSites != null) {
      List<String> allowedCidrs = new ArrayList<String>();
      String[] cidrs = _allowedInternalSites.split(",");
      for (String cidr : cidrs) {
        if (NetUtils.isValidCIDR(cidr) || NetUtils.isValidIp(cidr)) {
          allowedCidrs.add(cidr);
        }
      }
      List<? extends Nic> nics =
          _networkMgr.getNicsForTraffic(secStorageVm.getId(), TrafficType.Management);
      Nic privateNic = nics.get(0);
      String privateCidr =
          NetUtils.ipAndNetMaskToCidr(privateNic.getIp4Address(), privateNic.getNetmask());
      String publicCidr =
          NetUtils.ipAndNetMaskToCidr(
              secStorageVm.getPublicIpAddress(), secStorageVm.getPublicNetmask());
      if (NetUtils.isNetworkAWithinNetworkB(privateCidr, publicCidr)
          || NetUtils.isNetworkAWithinNetworkB(publicCidr, privateCidr)) {
        s_logger.info(
            "private and public interface overlaps, add a default route through private interface. privateCidr: "
                + privateCidr
                + ", publicCidr: "
                + publicCidr);
        allowedCidrs.add(NetUtils.ALL_CIDRS);
      }
      setupCmd.setAllowedInternalSites(allowedCidrs.toArray(new String[allowedCidrs.size()]));
    }
    String copyPasswd = _configDao.getValue("secstorage.copy.password");
    setupCmd.setCopyPassword(copyPasswd);
    setupCmd.setCopyUserName(TemplateConstants.DEFAULT_HTTP_AUTH_USER);
    Answer answer = _agentMgr.easySend(ssAHostId, setupCmd);
    if (answer != null && answer.getResult()) {
      if (s_logger.isDebugEnabled()) {
        s_logger.debug("Successfully programmed http auth into " + secStorageVm.getHostName());
      }
      return true;
    } else {
      if (s_logger.isDebugEnabled()) {
        s_logger.debug(
            "failed to program http auth into secondary storage vm : "
                + secStorageVm.getHostName());
      }
      return false;
    }
  }
  @Override
  public void CheckAndDestroyTunnel(VirtualMachine vm) {
    if (!_isEnabled) {
      return;
    }

    List<UserVmVO> userVms = _userVmDao.listByAccountIdAndHostId(vm.getAccountId(), vm.getHostId());
    if (vm.getType() == VirtualMachine.Type.User) {
      if (userVms.size() > 1) {
        return;
      }

      List<DomainRouterVO> routers =
          _routerDao.findBy(vm.getAccountId(), vm.getDataCenterIdToDeployIn());
      for (DomainRouterVO router : routers) {
        if (router.getHostId() == vm.getHostId()) {
          return;
        }
      }
    } else if (vm.getType() == VirtualMachine.Type.DomainRouter && userVms.size() != 0) {
      return;
    }

    try {
      /* Now we are last one on host, destroy all tunnels of my account */
      Command cmd = new OvsDestroyTunnelCommand(vm.getAccountId(), "[]");
      Answer ans = _agentMgr.send(vm.getHostId(), cmd);
      handleDestroyTunnelAnswer(ans, vm.getHostId(), 0, vm.getAccountId());

      /* Then ask hosts have peer tunnel with me to destroy them */
      List<OvsTunnelAccountVO> peers =
          _tunnelAccountDao.listByToAccount(vm.getHostId(), vm.getAccountId());
      for (OvsTunnelAccountVO p : peers) {
        cmd = new OvsDestroyTunnelCommand(p.getAccount(), p.getPortName());
        ans = _agentMgr.send(p.getFrom(), cmd);
        handleDestroyTunnelAnswer(ans, p.getFrom(), p.getTo(), p.getAccount());
      }
    } catch (Exception e) {
      s_logger.warn(
          String.format(
              "Destroy tunnel(account:%1$s, hostId:%2$s) failed",
              vm.getAccountId(), vm.getHostId()),
          e);
    }
  }
 // Adapter implementation: (facilitates plug in loading)
 // Required because Discoverer extends Adapter
 // Overrides Adapter.configure to always return true
 // Inherit Adapter.getName
 // Inherit Adapter.stop
 // Inherit Adapter.start
 @Override
 public final boolean configure(final String name, final Map<String, Object> params)
     throws ConfigurationException {
   super.configure(name, params);
   // TODO: allow timeout on we HTTPRequests to be configured
   _agentMgr.registerForHostEvents(this, true, false, true);
   _resourceMgr.registerResourceStateAdapter(this.getClass().getSimpleName(), this);
   return true;
 }
 public int getVncPort(VMInstanceVO vm) {
   if (vm.getHostId() == null) {
     return -1;
   }
   GetVncPortAnswer answer =
       (GetVncPortAnswer)
           _agentMgr.easySend(vm.getHostId(), new GetVncPortCommand(vm.getId(), vm.getHostName()));
   return (answer == null || !answer.getResult()) ? -1 : answer.getPort();
 }
  protected Long stopVM(final HaWorkVO work) {
    final VirtualMachineGuru<VMInstanceVO> mgr = findManager(work.getType());
    final VMInstanceVO vm = mgr.get(work.getInstanceId());
    s_logger.info("Stopping " + vm.toString());
    try {
      if (work.getWorkType() == WorkType.Stop) {
        if (vm.getHostId() != null) {
          if (mgr.stop(vm, 0)) {
            s_logger.info("Successfully stopped " + vm.toString());
            return null;
          }
        } else {
          if (s_logger.isDebugEnabled()) {
            s_logger.debug(vm.toString() + " has already been stopped");
          }
          return null;
        }
      } else if (work.getWorkType() == WorkType.CheckStop) {
        if ((vm.getState() != State.Stopping)
            || vm.getHostId() == null
            || vm.getHostId().longValue() != work.getHostId()) {
          if (s_logger.isDebugEnabled()) {
            s_logger.debug(
                vm.toString()
                    + " is different now.  Scheduled Host: "
                    + work.getHostId()
                    + " Current Host: "
                    + (vm.getHostId() != null ? vm.getHostId() : "none")
                    + " State: "
                    + vm.getState());
          }
          return null;
        } else {
          Command cmd = mgr.cleanup(vm, null);
          Answer ans = _agentMgr.send(work.getHostId(), cmd);
          if (ans.getResult()) {
            mgr.completeStopCommand(vm);
            s_logger.info("Successfully stopped " + vm.toString());
            return null;
          }
          s_logger.debug(
              "Stop for " + vm.toString() + " was unsuccessful. Detail: " + ans.getDetails());
        }
      } else {
        assert false
            : "Who decided there's other steps but didn't modify the guy who does the work?";
      }
    } catch (final AgentUnavailableException e) {
      s_logger.debug("Agnet is not available" + e.getMessage());
    } catch (OperationTimedoutException e) {
      s_logger.debug("operation timed out: " + e.getMessage());
    }

    work.setTimesTried(work.getTimesTried() + 1);
    return (System.currentTimeMillis() >> 10) + _stopRetryInterval;
  }
Example #11
0
  @Override
  public Boolean fenceOff(VirtualMachine vm, Host host) {
    if (host.getHypervisorType() != HypervisorType.KVM
        && host.getHypervisorType() != HypervisorType.LXC) {
      s_logger.warn("Don't know how to fence non kvm hosts " + host.getHypervisorType());
      return null;
    }

    List<HostVO> hosts = _resourceMgr.listAllHostsInCluster(host.getClusterId());
    FenceCommand fence = new FenceCommand(vm, host);

    int i = 0;
    for (HostVO h : hosts) {
      if (h.getHypervisorType() == HypervisorType.KVM
          || h.getHypervisorType() == HypervisorType.LXC) {
        if (h.getStatus() != Status.Up) {
          continue;
        }

        i++;

        if (h.getId() == host.getId()) {
          continue;
        }
        FenceAnswer answer;
        try {
          answer = (FenceAnswer) _agentMgr.send(h.getId(), fence);
        } catch (AgentUnavailableException e) {
          s_logger.info("Moving on to the next host because " + h.toString() + " is unavailable");
          continue;
        } catch (OperationTimedoutException e) {
          s_logger.info("Moving on to the next host because " + h.toString() + " is unavailable");
          continue;
        }
        if (answer != null && answer.getResult()) {
          return true;
        }
      }
    }

    _alertMgr.sendAlert(
        AlertManager.AlertType.ALERT_TYPE_HOST,
        host.getDataCenterId(),
        host.getPodId(),
        "Unable to fence off host: " + host.getId(),
        "Fencing off host "
            + host.getId()
            + " did not succeed after asking "
            + i
            + " hosts. "
            + "Check Agent logs for more information.");

    s_logger.error("Unable to fence off " + vm.toString() + " on " + host.toString());

    return false;
  }
  @Override
  public boolean configure(String name, Map<String, Object> params) throws ConfigurationException {
    _vmCapacityReleaseInterval =
        NumbersUtil.parseInt(_configDao.getValue(Config.CapacitySkipcountingHours.key()), 3600);
    _storageOverProvisioningFactor =
        NumbersUtil.parseFloat(
            _configDao.getValue(Config.StorageOverprovisioningFactor.key()), 1.0f);

    _executor = Executors.newScheduledThreadPool(1, new NamedThreadFactory("HostCapacity-Checker"));
    VirtualMachine.State.getStateMachine().registerListener(this);
    _agentManager.registerForHostEvents(
        new StorageCapacityListener(_capacityDao, _storageOverProvisioningFactor),
        true,
        false,
        false);
    _agentManager.registerForHostEvents(
        new ComputeCapacityListener(_capacityDao, this), true, false, false);

    return true;
  }
 @Override
 public Answer sendCommand(HypervisorHostEndPoint host, Command command) {
   Answer answer;
   try {
     answer = agentMgr.send(host.getId(), command);
     return answer;
   } catch (AgentUnavailableException e) {
     return null;
   } catch (OperationTimedoutException e) {
     return null;
   }
 }
  public Long migrate(final HaWorkVO work) {
    long vmId = work.getInstanceId();

    long srcHostId = work.getHostId();
    try {
      work.setStep(Step.Migrating);
      _haDao.update(work.getId(), work);

      if (!_itMgr.migrateAway(work.getType(), vmId, srcHostId)) {
        s_logger.warn("Unable to migrate vm from " + srcHostId);
        _agentMgr.maintenanceFailed(srcHostId);
      }
      return null;
    } catch (InsufficientServerCapacityException e) {
      s_logger.warn("Insufficient capacity for migrating a VM.");
      _agentMgr.maintenanceFailed(srcHostId);
      return (System.currentTimeMillis() >> 10) + _migrateRetryInterval;
    } catch (VirtualMachineMigrationException e) {
      s_logger.warn("Looks like VM is still starting, we need to retry migrating the VM later.");
      _agentMgr.maintenanceFailed(srcHostId);
      return (System.currentTimeMillis() >> 10) + _migrateRetryInterval;
    }
  }
  private Map<Long, TemplateInfo> listVolume(HostVO ssHost) {
    ListVolumeCommand cmd = new ListVolumeCommand(ssHost.getStorageUrl());
    Answer answer = _agentMgr.sendToSecStorage(ssHost, cmd);
    if (answer != null && answer.getResult()) {
      ListVolumeAnswer tanswer = (ListVolumeAnswer) answer;
      return tanswer.getTemplateInfo();
    } else {
      if (s_logger.isDebugEnabled()) {
        s_logger.debug("Can not list volumes for secondary storage host " + ssHost.getId());
      }
    }

    return null;
  }
  @Override
  public boolean configure(String name, Map<String, Object> params) throws ConfigurationException {
    _name = name;
    _isEnabled = Boolean.parseBoolean(_configDao.getValue(Config.OvsTunnelNetwork.key()));

    if (_isEnabled) {
      _executorPool = Executors.newScheduledThreadPool(10, new NamedThreadFactory("OVS"));
      _cleanupExecutor = Executors.newScheduledThreadPool(1, new NamedThreadFactory("OVS-Cleanup"));
      _listener = new OvsTunnelListener(_tunnelDao, _hostDao);
      _agentMgr.registerForHostEvents(_listener, true, true, true);
    }

    return true;
  }
 private boolean configureNexusVsmForAsa(
     long vlanId,
     String gateway,
     String vsmUsername,
     String vsmPassword,
     String vsmIp,
     String asaInPortProfile,
     long hostId) {
   ConfigureNexusVsmForAsaCommand cmd =
       new ConfigureNexusVsmForAsaCommand(
           vlanId, gateway, vsmUsername, vsmPassword, vsmIp, asaInPortProfile);
   Answer answer = _agentMgr.easySend(hostId, cmd);
   return answer.getResult();
 }
Example #18
0
  @Override
  public Boolean fenceOff(VMInstanceVO vm, HostVO host) {
    if (host.getHypervisorType() != HypervisorType.Ovm) {
      s_logger.debug("Don't know how to fence non Ovm hosts " + host.getHypervisorType());
      return null;
    }

    List<HostVO> hosts = _resourceMgr.listAllHostsInCluster(host.getClusterId());
    FenceCommand fence = new FenceCommand(vm, host);

    for (HostVO h : hosts) {
      if (h.getHypervisorType() != HypervisorType.Ovm) {
        continue;
      }

      if (h.getStatus() != Status.Up) {
        continue;
      }

      if (h.getId() == host.getId()) {
        continue;
      }

      FenceAnswer answer;
      try {
        answer = (FenceAnswer) _agentMgr.send(h.getId(), fence);
      } catch (AgentUnavailableException e) {
        if (s_logger.isDebugEnabled()) {
          s_logger.debug("Moving on to the next host because " + h.toString() + " is unavailable");
        }
        continue;
      } catch (OperationTimedoutException e) {
        if (s_logger.isDebugEnabled()) {
          s_logger.debug("Moving on to the next host because " + h.toString() + " is unavailable");
        }
        continue;
      }

      if (answer != null && answer.getResult()) {
        return true;
      }
    }

    if (s_logger.isDebugEnabled()) {
      s_logger.debug("Unable to fence off " + vm.toString() + " on " + host.toString());
    }

    return false;
  }
 private Map<String, TemplateInfo> listTemplate(SwiftVO swift) {
   if (swift == null) {
     return null;
   }
   ListTemplateCommand cmd = new ListTemplateCommand(swift.toSwiftTO());
   Answer answer = _agentMgr.sendToSSVM(null, cmd);
   if (answer != null && answer.getResult()) {
     ListTemplateAnswer tanswer = (ListTemplateAnswer) answer;
     return tanswer.getTemplateInfo();
   } else {
     if (s_logger.isDebugEnabled()) {
       s_logger.debug("can not list template for swift " + swift);
     }
   }
   return null;
 }
  @Override
  public boolean configure(String name, Map<String, Object> params) throws ConfigurationException {

    if (s_logger.isInfoEnabled()) {
      s_logger.info("Start configuring AgentBasedConsoleProxyManager");
    }

    _name = name;

    ComponentLocator locator = ComponentLocator.getCurrentLocator();
    ConfigurationDao configDao = locator.getDao(ConfigurationDao.class);
    if (configDao == null) {
      throw new ConfigurationException("Unable to get the configuration dao.");
    }

    Map<String, String> configs = configDao.getConfiguration("management-server", params);
    String value = configs.get("consoleproxy.url.port");
    if (value != null) {
      _consoleProxyUrlPort =
          NumbersUtil.parseInt(value, ConsoleProxyManager.DEFAULT_PROXY_URL_PORT);
    }

    value = configs.get("consoleproxy.port");
    if (value != null) {
      _consoleProxyPort = NumbersUtil.parseInt(value, ConsoleProxyManager.DEFAULT_PROXY_VNC_PORT);
    }

    value = configs.get("consoleproxy.sslEnabled");
    if (value != null && value.equalsIgnoreCase("true")) {
      _sslEnabled = true;
    }

    _instance = configs.get("instance.name");

    _consoleProxyUrlDomain = configs.get("consoleproxy.url.domain");

    _listener = new ConsoleProxyListener(this);
    _agentMgr.registerForHostEvents(_listener, true, true, false);

    _itMgr.registerGuru(VirtualMachine.Type.ConsoleProxy, this);

    if (s_logger.isInfoEnabled()) {
      s_logger.info(
          "AgentBasedConsoleProxyManager has been configured. SSL enabled: " + _sslEnabled);
    }
    return true;
  }
 private boolean createLogicalEdgeFirewall(
     long vlanId,
     String gateway,
     String gatewayNetmask,
     String publicIp,
     String publicNetmask,
     List<String> publicGateways,
     long hostId) {
   CreateLogicalEdgeFirewallCommand cmd =
       new CreateLogicalEdgeFirewallCommand(
           vlanId, publicIp, gateway, publicNetmask, gatewayNetmask);
   for (String publicGateway : publicGateways) {
     cmd.getPublicGateways().add(publicGateway);
   }
   Answer answer = _agentMgr.easySend(hostId, cmd);
   return answer.getResult();
 }
Example #22
0
  @Override
  public DeleteHostAnswer deleteHost(HostVO host, boolean isForced, boolean isForceDeleteStorage)
      throws UnableDeleteHostException {
    if (host.getType() != Host.Type.Routing || host.getHypervisorType() != HypervisorType.KVM) {
      return null;
    }

    _resourceMgr.deleteRoutingHost(host, isForced, isForceDeleteStorage);
    try {
      ShutdownCommand cmd = new ShutdownCommand(ShutdownCommand.DeleteHost, null);
      _agentMgr.send(host.getId(), cmd);
    } catch (AgentUnavailableException e) {
      s_logger.warn("Sending ShutdownCommand failed: ", e);
    } catch (OperationTimedoutException e) {
      s_logger.warn("Sending ShutdownCommand failed: ", e);
    }

    return new DeleteHostAnswer(true);
  }
  @Override
  public boolean configure(String name, Map<String, Object> params) {
    final Map<String, String> configs = _configDao.getConfiguration("management-server", params);
    _proxy = configs.get(Config.SecStorageProxy.key());

    String cert = configs.get("secstorage.ssl.cert.domain");
    if (!"realhostip.com".equalsIgnoreCase(cert)) {
      s_logger.warn(
          "Only realhostip.com ssl cert is supported, ignoring self-signed and other certs");
    }

    _copyAuthPasswd = configs.get("secstorage.copy.password");

    DownloadListener dl = new DownloadListener(this);
    ComponentContext.inject(dl);
    _agentMgr.registerForHostEvents(dl, true, false, false);

    return true;
  }
  protected void handleVmMigrated(VMInstanceVO vm) {
    if (!isVmSecurityGroupEnabled(vm.getId())) return;
    if (vm.getType() != VirtualMachine.Type.User) {
      Commands cmds = null;
      NetworkRulesSystemVmCommand nrc =
          new NetworkRulesSystemVmCommand(vm.getInstanceName(), vm.getType());
      cmds = new Commands(nrc);
      try {
        _agentMgr.send(vm.getHostId(), cmds);
      } catch (AgentUnavailableException e) {
        s_logger.debug(e.toString());
      } catch (OperationTimedoutException e) {
        s_logger.debug(e.toString());
      }

    } else {
      List<Long> affectedVms = new ArrayList<Long>();
      affectedVms.add(vm.getId());
      scheduleRulesetUpdateToHosts(affectedVms, true, null);
    }
  }
  @Override
  public boolean rebootSecStorageVm(long secStorageVmId) {
    final SecondaryStorageVmVO secStorageVm = _secStorageVmDao.findById(secStorageVmId);

    if (secStorageVm == null || secStorageVm.getState() == State.Destroyed) {
      return false;
    }

    if (secStorageVm.getState() == State.Running && secStorageVm.getHostId() != null) {
      final RebootCommand cmd = new RebootCommand(secStorageVm.getInstanceName());
      final Answer answer = _agentMgr.easySend(secStorageVm.getHostId(), cmd);

      if (answer != null && answer.getResult()) {
        if (s_logger.isDebugEnabled()) {
          s_logger.debug("Successfully reboot secondary storage vm " + secStorageVm.getHostName());
        }

        SubscriptionMgr.getInstance()
            .notifySubscribers(
                ALERT_SUBJECT,
                this,
                new SecStorageVmAlertEventArgs(
                    SecStorageVmAlertEventArgs.SSVM_REBOOTED,
                    secStorageVm.getDataCenterIdToDeployIn(),
                    secStorageVm.getId(),
                    secStorageVm,
                    null));

        return true;
      } else {
        String msg = "Rebooting Secondary Storage VM failed - " + secStorageVm.getHostName();
        if (s_logger.isDebugEnabled()) {
          s_logger.debug(msg);
        }
        return false;
      }
    } else {
      return startSecStorageVm(secStorageVmId) != null;
    }
  }
  private Boolean testUserVM(VirtualMachine vm, Nic nic, VirtualRouter router) {
    String privateIp = nic.getIp4Address();
    String routerPrivateIp = router.getPrivateIpAddress();

    List<Long> otherHosts = new ArrayList<Long>();
    if (vm.getHypervisorType() == HypervisorType.XenServer
        || vm.getHypervisorType() == HypervisorType.KVM) {
      otherHosts.add(router.getHostId());
    } else {
      otherHosts = findHostByPod(router.getPodIdToDeployIn(), null);
    }
    for (Long hostId : otherHosts) {
      try {
        Answer pingTestAnswer =
            _agentMgr.easySend(hostId, new PingTestCommand(routerPrivateIp, privateIp));
        if (pingTestAnswer != null && pingTestAnswer.getResult()) {
          if (s_logger.isDebugEnabled()) {
            s_logger.debug(
                "user vm's "
                    + vm.getHostName()
                    + " ip address "
                    + privateIp
                    + "  has been successfully pinged from the Virtual Router "
                    + router.getHostName()
                    + ", returning that vm is alive");
          }
          return Boolean.TRUE;
        }
      } catch (Exception e) {
        if (s_logger.isDebugEnabled()) {
          s_logger.debug("Couldn't reach due to", e);
        }
        continue;
      }
    }
    if (s_logger.isDebugEnabled()) {
      s_logger.debug(vm + " could not be pinged, returning that it is unknown");
    }
    return null;
  }
  @Override
  public void processConnect(Host host, StartupCommand cmd, boolean forRebalance) {
    if (s_logger.isInfoEnabled()) s_logger.info("Received a host startup notification");

    if (cmd instanceof StartupRoutingCommand) {
      // if (Boolean.toString(true).equals(host.getDetail("can_bridge_firewall"))) {
      try {
        int interval =
            MIN_TIME_BETWEEN_CLEANUPS + _cleanupRandom.nextInt(MIN_TIME_BETWEEN_CLEANUPS / 2);
        CleanupNetworkRulesCmd cleanupCmd = new CleanupNetworkRulesCmd(interval);
        Commands c = new Commands(cleanupCmd);
        _agentMgr.send(host.getId(), c, this);
        if (s_logger.isInfoEnabled())
          s_logger.info("Scheduled network rules cleanup, interval=" + cleanupCmd.getInterval());
      } catch (AgentUnavailableException e) {
        // usually hypervisors that do not understand sec group rules.
        s_logger.debug("Unable to schedule network rules cleanup for host " + host.getId(), e);
      }
      if (_workTracker != null) {
        _workTracker.processConnect(host.getId());
      }
    }
  }
  @Override
  public boolean configure(String name, Map<String, Object> params) {
    final Map<String, String> configs = _configDao.getConfiguration("ManagementServer", params);
    _sslCopy = Boolean.parseBoolean(configs.get("secstorage.encrypt.copy"));
    _proxy = configs.get(Config.SecStorageProxy.key());

    _ssvmUrlDomain = configs.get("secstorage.ssl.cert.domain");

    _copyAuthPasswd = configs.get("secstorage.copy.password");

    _agentMgr.registerForHostEvents(new DownloadListener(this), true, false, false);

    ReadyTemplateStatesSearch = _vmTemplateHostDao.createSearchBuilder();
    ReadyTemplateStatesSearch.and(
        "download_state",
        ReadyTemplateStatesSearch.entity().getDownloadState(),
        SearchCriteria.Op.EQ);
    ReadyTemplateStatesSearch.and(
        "destroyed", ReadyTemplateStatesSearch.entity().getDestroyed(), SearchCriteria.Op.EQ);
    ReadyTemplateStatesSearch.and(
        "host_id", ReadyTemplateStatesSearch.entity().getHostId(), SearchCriteria.Op.EQ);

    SearchBuilder<VMTemplateVO> TemplatesWithNoChecksumSearch = _templateDao.createSearchBuilder();
    TemplatesWithNoChecksumSearch.and(
        "checksum", TemplatesWithNoChecksumSearch.entity().getChecksum(), SearchCriteria.Op.NULL);

    ReadyTemplateStatesSearch.join(
        "vm_template",
        TemplatesWithNoChecksumSearch,
        TemplatesWithNoChecksumSearch.entity().getId(),
        ReadyTemplateStatesSearch.entity().getTemplateId(),
        JoinBuilder.JoinType.INNER);
    TemplatesWithNoChecksumSearch.done();
    ReadyTemplateStatesSearch.done();

    return true;
  }
Example #29
0
  @Override
  public boolean sendCommandsToRouter(final VirtualRouter router, final Commands cmds)
      throws AgentUnavailableException, ResourceUnavailableException {
    if (!checkRouterVersion(router)) {
      s_logger.debug(
          "Router requires upgrade. Unable to send command to router:"
              + router.getId()
              + ", router template version : "
              + router.getTemplateVersion()
              + ", minimal required version : "
              + NetworkOrchestrationService.MinVRVersion.valueIn(router.getDataCenterId()));
      throw new ResourceUnavailableException(
          "Unable to send command. Router requires upgrade", VirtualRouter.class, router.getId());
    }
    Answer[] answers = null;
    try {
      answers = _agentMgr.send(router.getHostId(), cmds);
    } catch (final OperationTimedoutException e) {
      s_logger.warn("Timed Out", e);
      throw new AgentUnavailableException(
          "Unable to send commands to virtual router ", router.getHostId(), e);
    }

    if (answers == null || answers.length != cmds.size()) {
      return false;
    }

    // FIXME: Have to return state for individual command in the future
    boolean result = true;
    for (final Answer answer : answers) {
      if (!answer.getResult()) {
        result = false;
        break;
      }
    }
    return result;
  }
  protected Long destroyVM(HaWorkVO work) {
    final VirtualMachineGuru<VMInstanceVO> mgr = findManager(work.getType());
    final VMInstanceVO vm = mgr.get(work.getInstanceId());
    s_logger.info("Destroying " + vm.toString());
    try {
      if (vm.getState() != State.Destroyed) {
        s_logger.info("VM is no longer in Destroyed state " + vm.toString());
        return null;
      }

      if (vm.getHostId() != null) {
        Command cmd = mgr.cleanup(vm, null);
        Answer ans = _agentMgr.send(work.getHostId(), cmd);
        if (ans.getResult()) {
          mgr.completeStopCommand(vm);
          if (mgr.destroy(vm)) {
            s_logger.info("Successfully stopped " + vm.toString());
            return null;
          }
        }
        s_logger.debug(
            "Stop for " + vm.toString() + " was unsuccessful. Detail: " + ans.getDetails());
      } else {
        if (s_logger.isDebugEnabled()) {
          s_logger.debug(vm.toString() + " has already been stopped");
        }
        return null;
      }
    } catch (final AgentUnavailableException e) {
      s_logger.debug("Agnet is not available" + e.getMessage());
    } catch (OperationTimedoutException e) {
      s_logger.debug("operation timed out: " + e.getMessage());
    }

    work.setTimesTried(work.getTimesTried() + 1);
    return (System.currentTimeMillis() >> 10) + _stopRetryInterval;
  }