@Override
  public TemplateProfile prepare(RegisterTemplateCmd cmd) throws ResourceAllocationException {
    // check if the caller can operate with the template owner
    Account caller = UserContext.current().getCaller();
    Account owner = _accountMgr.getAccount(cmd.getEntityOwnerId());
    _accountMgr.checkAccess(caller, null, owner);

    return prepare(
        false,
        UserContext.current().getCallerUserId(),
        cmd.getTemplateName(),
        cmd.getDisplayText(),
        cmd.getBits(),
        cmd.isPasswordEnabled(),
        cmd.getRequiresHvm(),
        cmd.getUrl(),
        cmd.isPublic(),
        cmd.isFeatured(),
        cmd.isExtractable(),
        cmd.getFormat(),
        cmd.getOsTypeId(),
        cmd.getZoneId(),
        HypervisorType.getType(cmd.getHypervisor()),
        cmd.getChecksum(),
        true,
        cmd.getTemplateTag(),
        owner,
        cmd.getDetails());
  }
  @Override
  @DB
  @ActionEvent(
      eventType = EventTypes.EVENT_LOAD_BALANCER_CREATE,
      eventDescription = "creating load balancer")
  public LoadBalancer createLoadBalancerRule(CreateLoadBalancerRuleCmd lb, boolean openFirewall)
      throws NetworkRuleConflictException, InsufficientAddressCapacityException {
    UserContext caller = UserContext.current();

    int defPortStart = lb.getDefaultPortStart();
    int defPortEnd = lb.getDefaultPortEnd();

    if (!NetUtils.isValidPort(defPortEnd)) {
      throw new InvalidParameterValueException("privatePort is an invalid value: " + defPortEnd);
    }
    if (defPortStart > defPortEnd) {
      throw new InvalidParameterValueException(
          "private port range is invalid: " + defPortStart + "-" + defPortEnd);
    }
    if ((lb.getAlgorithm() == null) || !NetUtils.isValidAlgorithm(lb.getAlgorithm())) {
      throw new InvalidParameterValueException("Invalid algorithm: " + lb.getAlgorithm());
    }

    LoadBalancer result = _elbMgr.handleCreateLoadBalancerRule(lb, caller.getCaller());
    if (result == null) {
      result = createLoadBalancer(lb, openFirewall);
    }
    return result;
  }
  public TemplateProfile prepareDelete(DeleteTemplateCmd cmd) {
    Long templateId = cmd.getId();
    Long userId = UserContext.current().getCallerUserId();
    Account account = UserContext.current().getCaller();
    Long zoneId = cmd.getZoneId();

    VMTemplateVO template = _tmpltDao.findById(templateId.longValue());
    if (template == null) {
      throw new InvalidParameterValueException("unable to find template with id " + templateId);
    }

    userId =
        accountAndUserValidation(account, userId, null, template, "Unable to delete template ");

    UserVO user = _userDao.findById(userId);
    if (user == null) {
      throw new InvalidParameterValueException("Please specify a valid user.");
    }

    if (template.getFormat() == ImageFormat.ISO) {
      throw new InvalidParameterValueException("Please specify a valid template.");
    }

    return new TemplateProfile(userId, template, zoneId);
  }
 @Override
 public boolean processDisconnect(long agentId, Status state) {
   UserContext context = UserContext.current();
   context.setAccountId(1);
   /* Stopped VMware Host's virtual routers */
   HostVO host = _hostDao.findById(agentId);
   if (host.getHypervisorType() != HypervisorType.VMware) {
     return true;
   }
   List<DomainRouterVO> routers = _routerDao.listByHostId(agentId);
   for (DomainRouterVO router : routers) {
     try {
       State oldState = router.getState();
       _routerMgr.stopRouter(router.getId(), true);
       // In case only vCenter is disconnected, we want to shut down router directly
       if (oldState == State.Running) {
         shutdownRouterVM(router);
       }
     } catch (ResourceUnavailableException e) {
       s_logger.warn(
           "Fail to stop router " + router.getInstanceName() + " when host disconnected!", e);
     } catch (ConcurrentOperationException e) {
       s_logger.warn(
           "Fail to stop router " + router.getInstanceName() + " when host disconnected!", e);
     }
   }
   return true;
 }
  public TemplateProfile prepare(RegisterIsoCmd cmd) throws ResourceAllocationException {
    // check if the caller can operate with the template owner
    Account caller = UserContext.current().getCaller();
    Account owner = _accountMgr.getAccount(cmd.getEntityOwnerId());
    _accountMgr.checkAccess(caller, null, owner);

    return prepare(
        true,
        UserContext.current().getCallerUserId(),
        cmd.getIsoName(),
        cmd.getDisplayText(),
        64,
        false,
        true,
        cmd.getUrl(),
        cmd.isPublic(),
        cmd.isFeatured(),
        cmd.isExtractable(),
        ImageFormat.ISO.toString(),
        cmd.getOsTypeId(),
        cmd.getZoneId(),
        HypervisorType.None,
        cmd.getChecksum(),
        cmd.isBootable(),
        null,
        owner,
        null);
  }
  public static void updateContext(Long userId, Long accountId, String sessionId) {
    UserContext context = current();
    assert (context != null) : "Context should be already setup before you can call this one";

    context.setUserId(userId);
    context.setAccountId(accountId);
    context.setSessionKey(sessionId);
  }
 @Override
 public void interceptComplete(AnnotatedElement element, EventVO event) {
   Method method = (Method) element;
   ActionEvent actionEvent = method.getAnnotation(ActionEvent.class);
   if (actionEvent != null) {
     UserContext ctx = UserContext.current();
     long userId = ctx.getCallerUserId();
     long accountId = ctx.getAccountId();
     long startEventId = ctx.getStartEventId();
     String eventDescription = actionEvent.eventDescription();
     if (ctx.getEventDetails() != null) {
       eventDescription += ". " + ctx.getEventDetails();
     }
     if (actionEvent.create()) {
       // This start event has to be used for subsequent events of this action
       startEventId =
           EventUtils.saveCreatedEvent(
               userId,
               accountId,
               EventVO.LEVEL_INFO,
               actionEvent.eventType(),
               "Successfully created entity for " + eventDescription);
       ctx.setStartEventId(startEventId);
     } else {
       EventUtils.saveEvent(
           userId,
           accountId,
           EventVO.LEVEL_INFO,
           actionEvent.eventType(),
           "Successfully completed " + eventDescription,
           startEventId);
     }
   }
 }
 @Override
 public void interceptException(AnnotatedElement element, EventVO event) {
   Method method = (Method) element;
   ActionEvent actionEvent = method.getAnnotation(ActionEvent.class);
   if (actionEvent != null) {
     UserContext ctx = UserContext.current();
     long userId = ctx.getCallerUserId();
     long accountId = ctx.getAccountId();
     long startEventId = ctx.getStartEventId();
     String eventDescription = actionEvent.eventDescription();
     if (ctx.getEventDetails() != null) {
       eventDescription += ". " + ctx.getEventDetails();
     }
     if (actionEvent.create()) {
       long eventId =
           EventUtils.saveCreatedEvent(
               userId,
               accountId,
               EventVO.LEVEL_ERROR,
               actionEvent.eventType(),
               "Error while creating entity for " + eventDescription);
       ctx.setStartEventId(eventId);
     } else {
       EventUtils.saveEvent(
           userId,
           accountId,
           EventVO.LEVEL_ERROR,
           actionEvent.eventType(),
           "Error while " + eventDescription,
           startEventId);
     }
   }
 }
 public Long getDomainId() {
   if (domainId != null) {
     return domainId;
   } else {
     return UserContext.current().getCaller().getDomainId();
   }
 }
 public String getAccountName() {
   if (accountName != null) {
     return accountName;
   } else {
     return UserContext.current().getCaller().getAccountName();
   }
 }
 @Override
 public List<? extends VpnUser> listVpnUsers(long vpnOwnerId, String userName) {
   Account caller = UserContext.current().getCaller();
   Account owner = _accountDao.findById(vpnOwnerId);
   _accountMgr.checkAccess(caller, null, true, owner);
   return _vpnUsersDao.listByAccount(vpnOwnerId);
 }
  @Override
  public void execute()
      throws ResourceUnavailableException, InsufficientCapacityException,
          ResourceAllocationException {
    try {
      UserContext.current().setEventDetails("Vm Id: " + getId());

      UserVm result;
      result = _userVmService.startVirtualMachine(this);

      if (result != null) {
        UserVmResponse response =
            _responseGenerator.createUserVmResponse("virtualmachine", result).get(0);
        response.setResponseName(getCommandName());
        this.setResponseObject(response);
      } else {
        throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to start a vm");
      }
    } catch (ConcurrentOperationException ex) {
      s_logger.warn("Exception: ", ex);
      throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, ex.getMessage());
    } catch (StorageUnavailableException ex) {
      s_logger.warn("Exception: ", ex);
      throw new ServerApiException(ApiErrorCode.RESOURCE_UNAVAILABLE_ERROR, ex.getMessage());
    } catch (ExecutionException ex) {
      s_logger.warn("Exception: ", ex);
      throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, ex.getMessage());
    }
  }
Beispiel #13
0
  @Override
  public void execute() {
    UserVm result;
    try {
      UserContext.current().setEventDetails("Vm Id: " + getEntityId());
      if (getHypervisor() == HypervisorType.BareMetal) {
        result = _bareMetalVmService.startVirtualMachine(this);
      } else {
        result = _userVmService.startVirtualMachine(this);
      }

      if (result != null) {
        UserVmResponse response =
            _responseGenerator.createUserVmResponse("virtualmachine", result).get(0);
        response.setResponseName(getCommandName());
        this.setResponseObject(response);
      } else {
        throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to deploy vm");
      }
    } catch (ResourceUnavailableException ex) {
      s_logger.warn("Exception: ", ex);
      throw new ServerApiException(BaseCmd.RESOURCE_UNAVAILABLE_ERROR, ex.getMessage());
    } catch (ConcurrentOperationException ex) {
      s_logger.warn("Exception: ", ex);
      throw new ServerApiException(BaseCmd.INTERNAL_ERROR, ex.getMessage());
    } catch (InsufficientCapacityException ex) {
      s_logger.info(ex);
      s_logger.trace(ex);
      throw new ServerApiException(BaseCmd.INSUFFICIENT_CAPACITY_ERROR, ex.getMessage());
    }
  }
 @Override
 public long getEntityOwnerId() {
   Long accountId = finalyzeAccountId(accountName, domainId, null, true);
   if (accountId == null) {
     accountId = UserContext.current().getCaller().getId();
   }
   return accountId;
 }
  @Override
  public long getEntityOwnerId() {
    Long accountId = getAccountId(accountName, domainId, projectId);
    if (accountId == null) {
      return UserContext.current().getCaller().getId();
    }

    return accountId;
  }
  @Override
  @DB
  public RemoteAccessVpnVO startRemoteAccessVpn(long vpnId, boolean openFirewall)
      throws ResourceUnavailableException {
    Account caller = UserContext.current().getCaller();

    RemoteAccessVpnVO vpn = _remoteAccessVpnDao.findById(vpnId);
    if (vpn == null) {
      throw new InvalidParameterValueException("Unable to find your vpn: " + vpnId);
    }

    _accountMgr.checkAccess(caller, null, true, vpn);

    Network network = _networkMgr.getNetwork(vpn.getNetworkId());

    boolean started = false;
    try {
      boolean firewallOpened = true;
      if (openFirewall) {
        firewallOpened = _firewallMgr.applyIngressFirewallRules(vpn.getServerAddressId(), caller);
      }

      if (firewallOpened) {
        for (RemoteAccessVPNServiceProvider element : _vpnServiceProviders) {
          if (element.startVpn(network, vpn)) {
            started = true;
            break;
          }
        }
      }

      return vpn;
    } finally {
      if (started) {
        Transaction txn = Transaction.currentTxn();
        txn.start();
        vpn.setState(RemoteAccessVpn.State.Running);
        _remoteAccessVpnDao.update(vpn.getServerAddressId(), vpn);

        // Start billing of existing VPN users in ADD and Active state
        List<VpnUserVO> vpnUsers = _vpnUsersDao.listByAccount(vpn.getAccountId());
        for (VpnUserVO user : vpnUsers) {
          if (user.getState() != VpnUser.State.Revoke) {
            UsageEventUtils.publishUsageEvent(
                EventTypes.EVENT_VPN_USER_ADD,
                user.getAccountId(),
                0,
                user.getId(),
                user.getUsername(),
                user.getClass().getName(),
                user.getUuid());
          }
        }
        txn.commit();
      }
    }
  }
  @Override
  @ActionEvent(
      eventType = EventTypes.EVENT_LOAD_BALANCER_DELETE,
      eventDescription = "deleting load balancer",
      async = true)
  public boolean deleteLoadBalancerRule(long loadBalancerId, boolean apply) {
    UserContext ctx = UserContext.current();
    Account caller = ctx.getCaller();

    LoadBalancerVO rule = _lbDao.findById(loadBalancerId);
    if (rule == null) {
      throw new InvalidParameterValueException(
          "Unable to find load balancer rule " + loadBalancerId);
    }

    _accountMgr.checkAccess(caller, null, rule);

    return deleteLoadBalancerRule(loadBalancerId, apply, caller, ctx.getCallerUserId());
  }
 @Override
 public void execute() {
   UserContext.current().setEventDetails("Load balancer Id: " + getId());
   boolean result = _lbService.deleteLoadBalancerRule(id, true);
   if (result) {
     SuccessResponse response = new SuccessResponse(getCommandName());
     this.setResponseObject(response);
   } else {
     throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to delete load balancer");
   }
 }
Beispiel #19
0
 @Override
 public void execute() {
   UserContext.current().setEventDetails("Project Id: " + id);
   boolean result = _projectService.deleteProject(id);
   if (result) {
     SuccessResponse response = new SuccessResponse(getCommandName());
     this.setResponseObject(response);
   } else {
     throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to delete project");
   }
 }
 @Override
 public void create() throws ResourceAllocationException {
   UserContext.current().setEventDetails("Project Name: " + getName());
   Project project =
       _projectService.createProject(getName(), getDisplayText(), getAccountName(), getDomainId());
   if (project != null) {
     this.setEntityId(project.getId());
   } else {
     throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to create a project");
   }
 }
  @Override
  public long getEntityOwnerId() {
    Account account = UserContext.current().getCaller();
    if (account != null) {
      return account.getId();
    }

    return Account
        .ACCOUNT_ID_SYSTEM; // no account info given, parent this command to SYSTEM so ERROR events
                            // are tracked
  }
 @Override
 public void execute() {
   UserContext.current().setEventDetails("Vm Id: " + getId());
   VirtualMachine instance = _mgr.startSystemVM(getId());
   if (instance != null) {
     SystemVmResponse response = _responseGenerator.createSystemVmResponse(instance);
     response.setResponseName(getCommandName());
     this.setResponseObject(response);
   } else {
     throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Fail to start system vm");
   }
 }
 @Override
 public void execute() throws ResourceUnavailableException, ConcurrentOperationException {
   UserContext.current().setEventDetails("Vm Id: " + getId());
   VirtualMachine result = _mgr.stopSystemVM(this);
   if (result != null) {
     SystemVmResponse response = _responseGenerator.createSystemVmResponse(result);
     response.setResponseName(getCommandName());
     this.setResponseObject(response);
   } else {
     throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Fail to stop system vm");
   }
 }
 @Override
 public void execute() {
   UserContext.current().setEventDetails("Domain Id: " + getId());
   Domain domain = _mgr.updateDomain(this);
   if (domain != null) {
     DomainResponse response = _responseGenerator.createDomainResponse(domain);
     response.setResponseName(getCommandName());
     this.setResponseObject(response);
   } else {
     throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to update domain");
   }
 }
  @Override
  public List<UserVmVO> listLoadBalancerInstances(ListLoadBalancerRuleInstancesCmd cmd)
      throws PermissionDeniedException {
    Account caller = UserContext.current().getCaller();
    Long loadBalancerId = cmd.getId();
    Boolean applied = cmd.isApplied();

    if (applied == null) {
      applied = Boolean.TRUE;
    }

    LoadBalancerVO loadBalancer = _lbDao.findById(loadBalancerId);
    if (loadBalancer == null) {
      return null;
    }

    _accountMgr.checkAccess(caller, null, loadBalancer);

    List<UserVmVO> loadBalancerInstances = new ArrayList<UserVmVO>();
    List<LoadBalancerVMMapVO> vmLoadBalancerMappings = null;

    vmLoadBalancerMappings = _lb2VmMapDao.listByLoadBalancerId(loadBalancerId);

    List<Long> appliedInstanceIdList = new ArrayList<Long>();
    if ((vmLoadBalancerMappings != null) && !vmLoadBalancerMappings.isEmpty()) {
      for (LoadBalancerVMMapVO vmLoadBalancerMapping : vmLoadBalancerMappings) {
        appliedInstanceIdList.add(vmLoadBalancerMapping.getInstanceId());
      }
    }

    IPAddressVO addr = _ipAddressDao.findById(loadBalancer.getSourceIpAddressId());
    List<UserVmVO> userVms =
        _vmDao.listVirtualNetworkInstancesByAcctAndZone(
            loadBalancer.getAccountId(), addr.getDataCenterId(), loadBalancer.getNetworkId());

    for (UserVmVO userVm : userVms) {
      // if the VM is destroyed, being expunged, in an error state, or in an unknown state, skip it
      switch (userVm.getState()) {
        case Destroyed:
        case Expunging:
        case Error:
        case Unknown:
          continue;
      }

      boolean isApplied = appliedInstanceIdList.contains(userVm.getId());
      if ((isApplied && applied) || (!isApplied && !applied)) {
        loadBalancerInstances.add(userVm);
      }
    }

    return loadBalancerInstances;
  }
  private boolean removeFromLoadBalancerInternal(long loadBalancerId, List<Long> instanceIds) {
    UserContext caller = UserContext.current();

    LoadBalancerVO loadBalancer = _lbDao.findById(Long.valueOf(loadBalancerId));
    if (loadBalancer == null) {
      throw new InvalidParameterException("Invalid load balancer value: " + loadBalancerId);
    }

    _accountMgr.checkAccess(caller.getCaller(), null, loadBalancer);

    try {
      loadBalancer.setState(FirewallRule.State.Add);
      _lbDao.persist(loadBalancer);

      for (long instanceId : instanceIds) {
        LoadBalancerVMMapVO map =
            _lb2VmMapDao.findByLoadBalancerIdAndVmId(loadBalancerId, instanceId);
        map.setRevoke(true);
        _lb2VmMapDao.persist(map);
        s_logger.debug(
            "Set load balancer rule for revoke: rule id "
                + loadBalancerId
                + ", vmId "
                + instanceId);
      }

      if (!applyLoadBalancerConfig(loadBalancerId)) {
        s_logger.warn(
            "Failed to remove load balancer rule id " + loadBalancerId + " for vms " + instanceIds);
        throw new CloudRuntimeException(
            "Failed to remove load balancer rule id " + loadBalancerId + " for vms " + instanceIds);
      }

    } catch (ResourceUnavailableException e) {
      s_logger.warn("Unable to apply the load balancer config because resource is unavaliable.", e);
      return false;
    }

    return true;
  }
  @Override
  public void execute() {
    UserContext.current().setEventDetails("Load balancer stickiness policy Id: " + getId());
    boolean result = _lbService.deleteLBStickinessPolicy(getId(), true);

    if (result) {
      SuccessResponse response = new SuccessResponse(getCommandName());
      this.setResponseObject(response);
    } else {
      throw new ServerApiException(
          ApiErrorCode.INTERNAL_ERROR, "Failed to delete load balancer stickiness policy");
    }
  }
  @Override
  public Pair<List<? extends VpnUser>, Integer> searchForVpnUsers(ListVpnUsersCmd cmd) {
    String username = cmd.getUsername();
    Long id = cmd.getId();
    Account caller = UserContext.current().getCaller();
    List<Long> permittedAccounts = new ArrayList<Long>();

    Ternary<Long, Boolean, ListProjectResourcesCriteria> domainIdRecursiveListProject =
        new Ternary<Long, Boolean, ListProjectResourcesCriteria>(
            cmd.getDomainId(), cmd.isRecursive(), null);
    _accountMgr.buildACLSearchParameters(
        caller,
        id,
        cmd.getAccountName(),
        cmd.getProjectId(),
        permittedAccounts,
        domainIdRecursiveListProject,
        cmd.listAll(),
        false);
    Long domainId = domainIdRecursiveListProject.first();
    Boolean isRecursive = domainIdRecursiveListProject.second();
    ListProjectResourcesCriteria listProjectResourcesCriteria =
        domainIdRecursiveListProject.third();
    Filter searchFilter =
        new Filter(VpnUserVO.class, "username", true, cmd.getStartIndex(), cmd.getPageSizeVal());
    SearchBuilder<VpnUserVO> sb = _vpnUsersDao.createSearchBuilder();
    _accountMgr.buildACLSearchBuilder(
        sb, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria);

    sb.and("id", sb.entity().getId(), SearchCriteria.Op.EQ);
    sb.and("username", sb.entity().getUsername(), SearchCriteria.Op.EQ);
    sb.and("state", sb.entity().getState(), SearchCriteria.Op.EQ);

    SearchCriteria<VpnUserVO> sc = sb.create();
    _accountMgr.buildACLSearchCriteria(
        sc, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria);

    // list only active users
    sc.setParameters("state", State.Active);

    if (id != null) {
      sc.setParameters("id", id);
    }

    if (username != null) {
      sc.setParameters("username", username);
    }

    Pair<List<VpnUserVO>, Integer> result = _vpnUsersDao.searchAndCount(sc, searchFilter);
    return new Pair<List<? extends VpnUser>, Integer>(result.first(), result.second());
  }
  @Override
  public void execute() throws ResourceUnavailableException {

    boolean result = true;
    FirewallRule rule = null;
    try {
      UserContext.current().setEventDetails("Rule Id: " + getEntityId());

      if (getOpenFirewall()) {
        result =
            result
                && _firewallService.applyFirewallRules(
                    ipAddressId, UserContext.current().getCaller());
      }

      result =
          result
              && _rulesService.applyStaticNatRules(ipAddressId, UserContext.current().getCaller());
      rule = _entityMgr.findById(FirewallRule.class, getEntityId());
      StaticNatRule staticNatRule = _rulesService.buildStaticNatRule(rule, false);
      IpForwardingRuleResponse fwResponse =
          _responseGenerator.createIpForwardingRuleResponse(staticNatRule);
      fwResponse.setResponseName(getCommandName());
      this.setResponseObject(fwResponse);
    } finally {
      if (!result || rule == null) {

        if (getOpenFirewall()) {
          _firewallService.revokeRelatedFirewallRule(getEntityId(), true);
        }

        _rulesService.revokeStaticNatRule(getEntityId(), true);

        throw new ServerApiException(
            ApiErrorCode.INTERNAL_ERROR, "Error in creating ip forwarding rule on the domr");
      }
    }
  }
 @Override
 public void execute()
     throws ResourceUnavailableException, InsufficientCapacityException, ServerApiException {
   UserContext.current().setEventDetails("Vm Id: " + getId());
   UserVm result = _userVmService.updateVirtualMachine(this);
   if (result != null) {
     UserVmResponse response =
         _responseGenerator.createUserVmResponse("virtualmachine", result).get(0);
     response.setResponseName(getCommandName());
     this.setResponseObject(response);
   } else {
     throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to update vm");
   }
 }