public void testDeleteKey() throws Exception {

    // default setup already includes a custom key; therefore, let's
    // grab the initial size
    DataResult initialKeys = SystemManager.listDataKeys(admin);

    handler.createKey(admin, "testlabel", "test description");
    DataResult result = SystemManager.listDataKeys(admin);
    assertEquals(initialKeys.size() + 1, result.size());

    boolean foundKey = false;
    for (Iterator itr = result.iterator(); itr.hasNext(); ) {
      CustomDataKeyOverview key = (CustomDataKeyOverview) itr.next();
      if (key.getLabel().equals("testlabel") && key.getDescription().equals("test description")) {
        foundKey = true;
        break;
      }
    }
    assertTrue(foundKey);

    handler.deleteKey(admin, "testlabel");
    result = SystemManager.listDataKeys(admin);
    assertEquals(initialKeys.size(), result.size());

    foundKey = false;
    for (Iterator itr = result.iterator(); itr.hasNext(); ) {
      CustomDataKeyOverview key = (CustomDataKeyOverview) itr.next();
      if (key.getLabel().equals("testlabel") && key.getDescription().equals("test description")) {
        foundKey = true;
        break;
      }
    }
    assertFalse(foundKey);
  }
  /**
   * Get the id of the Package installed for this KS. Here we'll verify that the kickstart package
   * exists in the host server's tools channel. The host server will need it to perform necessary
   * actions on either itself or the target system (if different).
   *
   * @return Long id of Package used for this KS.
   */
  public ValidatorError validateKickstartPackage() {
    if (cobblerOnly) {
      return null;
    }

    Server hostServer = getHostServer();
    Set<Long> serverChannelIds = new HashSet<Long>();
    Iterator<Channel> i = hostServer.getChannels().iterator();
    while (i.hasNext()) {
      Channel c = i.next();
      serverChannelIds.add(c.getId());
    }

    // check for package among channels the server is subscribed to.
    // If one is found, return
    Map<String, Long> pkgToInstall = findKickstartPackageToInstall(hostServer, serverChannelIds);
    if (pkgToInstall != null) {
      this.packagesToInstall.add(pkgToInstall);
      log.debug("    packagesToInstall: " + packagesToInstall);
      return null;
    }

    // otherwise search in channels that can be subscribed.
    // If one is found, subscribe channel and return
    Set<Long> subscribableChannelIds =
        SystemManager.subscribableChannelIds(
            hostServer.getId(), this.user.getId(), hostServer.getBaseChannel().getId());
    pkgToInstall = findKickstartPackageToInstall(hostServer, subscribableChannelIds);

    if (pkgToInstall != null) {
      this.packagesToInstall.add(pkgToInstall);
      log.debug("    packagesToInstall: " + packagesToInstall);
      Long cid = pkgToInstall.get("channel_id");
      log.debug("    Subscribing to: " + cid);
      Channel c = ChannelFactory.lookupById(cid);
      try {
        SystemManager.subscribeServerToChannel(this.user, server, c);
        log.debug("    Subscribed: " + cid);
      } catch (PermissionException pe) {
        return new ValidatorError("kickstart.schedule.cantsubscribe");
      } catch (Exception e) {
        return new ValidatorError(
            "kickstart.schedule.cantsubscribe.channel", c.getName(), server.getName());
      }
      return null;
    }

    return new ValidatorError(
        "kickstart.schedule.nopackage", this.getKsdata().getChannel().getName());
  }
示例#3
0
  /** {@inheritDoc} */
  public ActionForward execute(
      ActionMapping mapping,
      ActionForm formIn,
      HttpServletRequest request,
      HttpServletResponse response) {

    RequestContext requestContext = new RequestContext(request);
    User user = requestContext.getCurrentUser();
    Long sid = requestContext.getRequiredParam("sid");
    RhnSet set = getSetDecl(sid).get(user);

    ListRhnSetHelper help = new ListRhnSetHelper(this, request, getSetDecl(sid));
    help.setListName(LIST_NAME);
    String parentURL = request.getRequestURI() + "?sid=" + sid;
    help.setParentUrl(parentURL);

    help.execute();

    if (help.isDispatched()) {
      if (requestContext.wasDispatched("errata.jsp.apply")) {
        return applyErrata(mapping, formIn, request, response);
      }
    }

    String showButton = "true";
    // Show the "Apply Errata" button only when unapplied errata exist:
    if (!SystemManager.hasUnscheduledErrata(user, sid)) {
      showButton = "false";
    }

    Map params = new HashMap();
    Set keys = request.getParameterMap().keySet();
    for (Iterator i = keys.iterator(); i.hasNext(); ) {
      String key = (String) i.next();
      params.put(key, request.getParameter(key));
    }

    Server server = SystemManager.lookupByIdAndUser(sid, user);
    SdcHelper.ssmCheck(request, server.getId(), user);
    request.setAttribute("showApplyErrata", showButton);
    request.setAttribute("set", set);
    request.setAttribute("system", server);
    request.setAttribute("combo", getComboList(request));
    request.setAttribute(SELECTOR, request.getParameter(SELECTOR));

    return getStrutsDelegate()
        .forwardParams(mapping.findForward(RhnHelper.DEFAULT_FORWARD), params);
  }
  /** {@inheritDoc} */
  protected void render(User user, PageControl pc, HttpServletRequest request) {
    LocalizationService ls = LocalizationService.getInstance();
    DataResult<SystemOverview> isdr = SystemManager.inactiveListSortbyCheckinTime(user, pc);
    String inactiveSystemCSSTable = null;
    if (!isdr.isEmpty()) {
      for (Iterator<SystemOverview> i = isdr.iterator(); i.hasNext(); ) {
        SystemOverview so = i.next();
        StringBuilder buffer = new StringBuilder();
        Long lastCheckin = so.getLastCheckinDaysAgo();
        if (lastCheckin.compareTo(new Long(1)) < 0) {
          buffer.append(lastCheckin * 24);
          buffer.append(' ');

          buffer.append(ls.getMessage("filter-form.jspf.hours"));
        } else if (lastCheckin.compareTo(new Long(7)) < 0) {
          buffer.append(so.getLastCheckinDaysAgo().longValue());
          buffer.append(' ');
          buffer.append(ls.getMessage("filter-form.jspf.days"));
        } else if (lastCheckin.compareTo(new Long(7)) >= 0) {
          buffer.append(lastCheckin.longValue() / 7);
          buffer.append(' ');
          buffer.append(ls.getMessage("filter-form.jspf.weeks"));
        }

        so.setLastCheckinString(buffer.toString());
      }
      request.setAttribute(INACTIVE_SYSTEM_LIST, isdr);
    } else {
      inactiveSystemCSSTable =
          RendererHelper.makeEmptyTable(
              true, "inactivelist.jsp.header", "yourrhn.jsp.noinactivesystems");
      request.setAttribute(INACTIVE_SYSTEMS_EMPTY, inactiveSystemCSSTable);
    }
    RendererHelper.setTableStyle(request, INACTIVE_SYSTEMS_CLASS);
  }
 /**
  * Get the list of compatible systems you could sync to
  *
  * @return DataResult of System DTOs
  */
 public List<Map<String, Object>> getCompatibleSystems() {
   if (!isCobblerOnly()) {
     return SystemManager.systemsSubscribedToChannel(
         this.getKsdata().getKickstartDefaults().getKstree().getChannel(), user);
   }
   return Collections.EMPTY_LIST;
 }
  private void scheduleInstalls(SsmInstallPackagesEvent event, User user) {

    log.debug("Scheduling package installations.");
    Date earliest = event.getEarliest();
    Set<String> data = event.getPackages();
    Long channelId = event.getChannelId();

    List<EssentialServerDto> servers =
        SystemManager.systemsSubscribedToChannelInSet(channelId, user, SetLabels.SYSTEM_LIST);

    // Convert the package list to domain objects
    List<PackageListItem> packageListItems = new ArrayList<PackageListItem>(data.size());
    for (String key : data) {
      packageListItems.add(PackageListItem.parse(key));
    }

    // Convert to list of maps
    List<Map<String, Long>> packageListData = PackageListItem.toKeyMaps(packageListItems);

    // Create one action for all servers to which the packages are installed
    List<Long> serverIds = new LinkedList<Long>();
    for (EssentialServerDto dto : servers) {
      serverIds.add(dto.getId());
    }

    log.debug("Scheduling actions.");
    ActionManager.schedulePackageInstall(user, serverIds, packageListData, earliest);
    log.debug("Done scheduling package installations.");
  }
  /** {@inheritDoc} */
  public ActionForward execute(
      ActionMapping mapping,
      ActionForm formIn,
      HttpServletRequest request,
      HttpServletResponse response) {

    RequestContext requestContext = new RequestContext(request);

    if (request.getParameter("dispatch") != null) {
      if (requestContext.wasDispatched("installconfirm.jsp.confirm")) {
        return executePackageAction(mapping, formIn, request, response);
      }
    }

    List<PackageListItem> items = getDataResult(request);

    Server server = requestContext.lookupAndBindServer();

    /*
     * If we are removing a package that is not in a channel the server is
     *  subscribed to, then the rollback will not work, lets give the user
     *  a message telling them that.
     */
    if (this instanceof RemoveConfirmSetupAction
        && server.hasEntitlement(EntitlementManager.PROVISIONING)) {
      for (PackageListItem item : items) {
        Map<String, Long> map = item.getKeyMap();
        if (!SystemManager.hasPackageAvailable(
            server, map.get("name_id"), map.get("arch_id"), map.get("evr_id"))) {
          ActionMessages msgs = new ActionMessages();
          msgs.add(
              ActionMessages.GLOBAL_MESSAGE, new ActionMessage("package.remove.cant.rollback"));
          getStrutsDelegate().saveMessages(request, msgs);
          break;
        }
      }
    }

    DynaActionForm dynaForm = (DynaActionForm) formIn;
    DatePicker picker =
        getStrutsDelegate()
            .prepopulateDatePicker(request, dynaForm, "date", DatePicker.YEAR_RANGE_POSITIVE);
    request.setAttribute("date", picker);

    ActionChainHelper.prepopulateActionChains(request);

    request.setAttribute("system", server);
    requestContext.copyParamToAttributes(RequestContext.SID);
    request.setAttribute(
        ListTagHelper.PARENT_URL, request.getRequestURI() + "?sid=" + server.getId());
    request.setAttribute(WIDGET_SUMMARY, getWidgetSummary());
    request.setAttribute(HEADER_KEY, getHeaderKey());
    request.setAttribute(DATA_SET, items);

    return getStrutsDelegate()
        .forwardParams(mapping.findForward(RhnHelper.DEFAULT_FORWARD), request.getParameterMap());
  }
  public void testListAllKeys() throws Exception {

    // default setup already includes a custom key; therefore, we don't
    // need to add any as part of this test.

    Object[] keys = handler.listAllKeys(admin);

    assertEquals(SystemManager.listDataKeys(admin).size(), keys.length);
  }
  /**
   * @param form the form containing the proxy info
   * @param ctx the request context associated to this request
   * @param cmd the kicktstart command to which the proxy info will be copied..
   */
  protected void storeProxyInfo(
      DynaActionForm form, RequestContext ctx, KickstartScheduleCommand cmd) {
    // if we need to go through a proxy, do it here.
    String phost = form.getString(PROXY_HOST);
    String phostCname = form.getString(PROXY_HOST_CNAME);

    if (!StringUtils.isEmpty(phostCname)) {
      cmd.setProxyHost(phostCname);
    } else if (!StringUtils.isEmpty(phost)) {
      cmd.setProxy(SystemManager.lookupByIdAndOrg(new Long(phost), ctx.getCurrentUser().getOrg()));
    }
  }
  private PackageAction syncToVictim(
      RequestContext requestContext, Long sid, Set pkgIdCombos, String option) {

    PackageAction pa = null;
    Date time = new Date(requestContext.getParamAsLong("time"));

    if (isProfileSync(requestContext)) {
      Long prid = requestContext.getRequiredParam("prid");

      pa =
          ProfileManager.syncToProfile(
              requestContext.getCurrentUser(), sid, prid, pkgIdCombos, option, time);

      if (pa == null) {
        createMessage(requestContext.getRequest(), "message.nopackagestosync");
        return null;
      }

      List args = new ArrayList();
      args.add(sid.toString());
      args.add(pa.getId().toString());
      args.add(requestContext.lookupAndBindServer().getName());
      args.add(
          ProfileManager.lookupByIdAndOrg(prid, requestContext.getCurrentUser().getOrg())
              .getName());

      createMessage(requestContext.getRequest(), "message.syncpackages", args);
    } else if (isSystemSync(requestContext)) {
      Long sid1 = requestContext.getRequiredParam("sid_1");
      pa =
          ProfileManager.syncToSystem(
              requestContext.getCurrentUser(), sid, sid1, pkgIdCombos, option, time);

      if (pa == null) {
        createMessage(requestContext.getRequest(), "message.nopackagestosync");
        return null;
      }

      List args = new ArrayList();
      args.add(sid.toString());
      args.add(pa.getId().toString());
      args.add(requestContext.lookupAndBindServer().getName());
      args.add(SystemManager.lookupByIdAndUser(sid1, requestContext.getCurrentUser()).getName());

      createMessage(requestContext.getRequest(), "message.syncpackages", args);
    }

    addHardwareMessage(pa, requestContext);

    return pa;
  }
  protected List<Long> getAffectedServers(SsmPackageEvent event, User u) {
    SsmInstallPackagesEvent sipe = (SsmInstallPackagesEvent) event;
    Long channelId = sipe.getChannelId();

    List<EssentialServerDto> servers =
        SystemManager.systemsSubscribedToChannelInSet(channelId, u, SetLabels.SYSTEM_LIST);

    // Create one action for all servers to which the packages are installed
    List<Long> serverIds = new LinkedList<Long>();
    for (EssentialServerDto dto : servers) {
      serverIds.add(dto.getId());
    }
    return serverIds;
  }
示例#12
0
  /**
   * @param user User that owns parent channel
   * @param channelIn base channel to unsubscribe from.
   */
  private void unsubscribeOrgsFromChannel(User user, Channel channelIn, String accessIn) {
    Org org = channelIn.getOrg();

    // find trusted orgs
    Set<Org> trustedOrgs = org.getTrustedOrgs();
    for (Org o : trustedOrgs) {
      // find systems subscribed in org Trust
      DataResult<Map<String, Object>> dr = SystemManager.sidsInOrgTrust(org.getId(), o.getId());

      for (Map<String, Object> item : dr) {
        Long sid = (Long) item.get("id");
        Server s = ServerFactory.lookupById(sid);
        if (s.isSubscribed(channelIn)) {
          // check if this is a base custom channel
          if (channelIn.getParentChannel() == null) {
            // unsubscribe children first if subscribed
            List<Channel> children = channelIn.getAccessibleChildrenFor(user);
            Iterator<Channel> i = children.iterator();
            while (i.hasNext()) {
              Channel child = i.next();
              if (s.isSubscribed(child)) {
                // unsubscribe server from child channel

                child.getTrustedOrgs().remove(o);
                child.setAccess(accessIn);
                ChannelFactory.save(child);
                s = SystemManager.unsubscribeServerFromChannel(s, child);
              }
            }
          }
          // unsubscribe server from channel
          ChannelFactory.save(channelIn);
          s = SystemManager.unsubscribeServerFromChannel(s, channelIn);
        }
      }
    }
  }
  public void testExecute() throws Exception {
    // Create a config channel and a server
    ConfigChannel channel = ConfigTestUtils.createConfigChannel(user.getOrg());
    Server server =
        ServerFactoryTest.createTestServer(
            user, true, ServerConstants.getServerGroupTypeProvisioningEntitled());
    // associate the two.
    server.subscribe(channel);
    SystemManager.storeServer(server);

    setRequestPathInfo("/systems/details/configuration/ConfigChannelList");
    addRequestParameter("sid", server.getId().toString());
    actionPerform();
    verifyPageList(ConfigChannelDto.class);
  }
示例#14
0
  /** {@inheritDoc} */
  public List getResult(RequestContext context) {
    User user = context.getCurrentUser();
    Long sid = context.getRequiredParam("sid");
    String type = context.getParam(SELECTOR, false);
    String synopsis = "";
    Boolean currency = false;

    LocalizationService ls = LocalizationService.getInstance();

    String eType = new String();

    if (ls.getMessage(SECUR_CRIT).equals(type)) {
      eType = ErrataFactory.ERRATA_TYPE_SECURITY;
      synopsis = "C";
      currency = true;
    } else if (ls.getMessage(SECUR_IMP).equals(type)) {
      eType = ErrataFactory.ERRATA_TYPE_SECURITY;
      synopsis = "I";
      currency = true;
    } else if (ls.getMessage(SECUR_MOD).equals(type)) {
      eType = ErrataFactory.ERRATA_TYPE_SECURITY;
      synopsis = "M";
      currency = true;
    } else if (ls.getMessage(SECUR_LOW).equals(type)) {
      eType = ErrataFactory.ERRATA_TYPE_SECURITY;
      synopsis = "L";
      currency = true;
    }

    if (currency) {
      return SystemManager.relevantCurrencyErrata(user, sid, eType, synopsis);
    }

    List<String> typeList = getTypes(type);
    return SystemManager.relevantErrata(user, sid, typeList);
  }
示例#15
0
 /** {@inheritDoc} */
 public List<OrgTrust> getResult(RequestContext ctx) {
   Org org = ctx.getCurrentUser().getOrg();
   Set<Org> trustedorgs = org.getTrustedOrgs();
   List<OrgTrust> trusts = new ArrayList<OrgTrust>();
   for (Org o : trustedorgs) {
     DataResult<Map<String, Object>> dr = SystemManager.sidsInOrgTrust(org.getId(), o.getId());
     OrgTrust trust = new OrgTrust(o);
     if (!dr.isEmpty()) {
       for (Map<String, Object> m : dr) {
         Long sid = (Long) m.get("id");
         trust.getSubscribed().add(sid);
       }
     }
     trusts.add(trust);
   }
   return trusts;
 }
  /**
   * Setup the system for provisioning with cobbler.
   *
   * @param mapping ActionMapping for struts
   * @param form DynaActionForm representing the form
   * @param ctx RequestContext request context
   * @param response HttpServletResponse response object
   * @param step WizardStep what step are we on?
   * @return ActionForward struts action forward
   * @throws Exception if something goes amiss
   */
  public ActionForward runFourth(
      ActionMapping mapping,
      DynaActionForm form,
      RequestContext ctx,
      HttpServletResponse response,
      WizardStep step)
      throws Exception {

    log.debug("runFourth");
    if (!validateFirstSelections(form, ctx)) {
      return runFirst(mapping, form, ctx, response, step);
    }
    Long sid = (Long) form.get(RequestContext.SID);
    String cobblerId = form.getString(RequestContext.COBBLER_ID);

    log.debug("runFourth.cobblerId: " + cobblerId);

    User user = ctx.getCurrentUser();
    Server server = SystemManager.lookupByIdAndUser(sid, user);

    Map params = new HashMap();
    params.put(RequestContext.SID, sid);

    log.debug("Creating cobbler system record");
    org.cobbler.Profile profile =
        org.cobbler.Profile.lookupById(CobblerXMLRPCHelper.getConnection(user), cobblerId);

    KickstartData data =
        KickstartFactory.lookupKickstartDataByCobblerIdAndOrg(user.getOrg(), profile.getUid());

    if (showDiskWarning(data, form)) {
      form.set(NEXT_ACTION, "fourth");
      return mapping.findForward("fifth");
    }

    CobblerSystemCreateCommand cmd =
        new CobblerSystemCreateCommand(server, profile.getName(), data);
    cmd.store();
    log.debug("cobbler system record created.");
    String[] args = new String[2];
    args[0] = server.getName();
    args[1] = profile.getName();
    createMessage(ctx.getRequest(), "kickstart.schedule.cobblercreate", args);
    return getStrutsDelegate().forwardParams(mapping.findForward("cobbler-success"), params);
  }
  /**
   * Sets up the proxy information for the wizard. its public in this class because we reuse this in
   * SSM and only this class knows how to format the name nicely.
   *
   * @param ctx the request context needed for user info and things to bind to the request
   */
  public static void setupProxyInfo(RequestContext ctx) {
    List<OrgProxyServer> proxies = SystemManager.listProxies(ctx.getCurrentUser().getOrg());
    if (proxies != null && proxies.size() > 0) {
      List<LabelValueBean> formatted = new LinkedList<LabelValueBean>();

      formatted.add(lvl10n("kickstart.schedule.default.proxy.jsp", ""));
      Map cnames = new HashMap();
      for (OrgProxyServer serv : proxies) {
        formatted.add(lv(serv.getName() + " (" + serv.getCheckin() + ")", serv.getId().toString()));
        List proxyCnames = Config.get().getList(VALID_CNAMES + serv.getId().toString());
        if (!proxyCnames.isEmpty()) {
          cnames.put(serv.getId().toString(), proxyCnames);
        }
      }
      ctx.getRequest().setAttribute(HAS_PROXIES, Boolean.TRUE.toString());
      ctx.getRequest().setAttribute(PROXIES, formatted);
      ctx.getRequest().setAttribute(CNAMES, cnames);
    } else {
      ctx.getRequest().setAttribute(HAS_PROXIES, Boolean.FALSE.toString());
    }
  }
  /** {@inheritDoc} */
  public ActionForward execute(
      ActionMapping mapping,
      ActionForm form,
      HttpServletRequest request,
      HttpServletResponse response) {

    StrutsDelegate strutsDelegate = getStrutsDelegate();

    ActionForward forward = null;
    DynaActionForm f = (DynaActionForm) form;
    RequestContext requestContext = new RequestContext(request);
    Long sid = requestContext.getRequiredParam("sid");
    User user = requestContext.getLoggedInUser();
    Server server = SystemManager.lookupByIdAndUser(sid, user);
    request.setAttribute("system", server);

    DynaActionForm dynaForm = (DynaActionForm) form;
    DatePicker picker =
        getStrutsDelegate()
            .prepopulateDatePicker(request, dynaForm, "date", DatePicker.YEAR_RANGE_POSITIVE);

    request.setAttribute("date", picker);

    if (!isSubmitted(f)) {
      setup(request, f);
      forward =
          strutsDelegate.forwardParams(mapping.findForward("default"), request.getParameterMap());
    } else {
      ActionMessages msgs = processForm(user, server, f, request);
      strutsDelegate.saveMessages(request, msgs);

      String mode = (String) f.get("mode");
      forward =
          strutsDelegate.forwardParams(
              mapping.findForward(getForward(mode)), request.getParameterMap());
    }

    return forward;
  }
  /** {@inheritDoc} */
  public ActionForward execute(
      ActionMapping mapping,
      ActionForm formIn,
      HttpServletRequest request,
      HttpServletResponse response) {
    RequestContext context = new RequestContext(request);
    User user = context.getCurrentUser();
    Long sid = context.getRequiredParam("sid");
    Server server = SystemManager.lookupByIdAndUser(sid, user);
    Long xid = context.getRequiredParam("xid");
    XccdfTestResult testResult = ScapFactory.lookupTestResultByIdAndSid(xid, server.getId());
    request.setAttribute("testResult", testResult);
    request.setAttribute("system", server);

    ListHelper helper = new ListHelper(this, request);
    helper.execute();

    request.setAttribute(
        ListTagHelper.PARENT_URL, request.getRequestURI() + "?sid=" + sid + "&xid=" + xid);
    SdcHelper.ssmCheck(request, sid, user);

    return mapping.findForward(RhnHelper.DEFAULT_FORWARD);
  }
  /** {@inheritDoc} */
  public ValidatorError store() {

    ValidatorError e = this.doValidation();
    if (e != null) {
      return e;
    }

    Server hostServer = getHostServer();
    log.debug("** Server we are operating on: " + hostServer);

    // rhn-kickstart-virtualization conflicts with this package, so we have to
    //  remove it
    List<Map<String, Long>> installed =
        SystemManager.listInstalledPackage(PACKAGE_TO_REMOVE, hostServer);
    Action removal = null;
    if (!installed.isEmpty()) {
      removal = ActionManager.schedulePackageRemoval(user, hostServer, installed, scheduleDate);
    }

    // Install packages on the host server.
    log.debug("** Creating packageAction");
    Action packageAction =
        ActionManager.schedulePackageInstall(
            this.user, hostServer, this.packagesToInstall, scheduleDate);
    packageAction.setPrerequisite(removal);
    log.debug("** Created packageAction ? " + packageAction.getId());

    log.debug("** Cancelling existing sessions.");
    cancelExistingSessions();

    // Make sure we fail all existing sessions for this server since
    // we are scheduling a new one
    if (!cobblerOnly) {
      kickstartSession = this.setupKickstartSession(packageAction);
      storeActivationKeyInfo();
    }
    Action kickstartAction = this.scheduleKickstartAction(packageAction);
    ActionFactory.save(packageAction);

    scheduleRebootAction(kickstartAction);

    String host = this.getKickstartServerName();
    if (!StringUtils.isEmpty(this.getProxyHost())) {
      host = this.getProxyHost();
    }

    CobblerSystemCreateCommand cmd = null;
    if (!cobblerOnly) {
      // Setup Cobbler system profile
      KickstartUrlHelper uhelper = new KickstartUrlHelper(ksdata);
      String tokenList;

      if (ksdata.getRegistrationType(null).equals(RegistrationType.REACTIVATION)) {
        tokenList = KickstartFormatter.generateActivationKeyString(ksdata, kickstartSession);
      } else {
        // RegistrationType.DELETION && RegistrationType.NONE
        CobblerConnection connection =
            CobblerXMLRPCHelper.getConnection(ConfigDefaults.get().getCobblerAutomatedUser());
        tokenList =
            org.cobbler.Profile.lookupById(connection, ksdata.getCobblerId())
                .getRedHatManagementKey();
      }

      cmd =
          getCobblerSystemCreateCommand(
              user,
              server,
              ksdata,
              uhelper.getKickstartMediaPath(kickstartSession, scheduleDate),
              tokenList);
      cmd.setKernelOptions(getExtraOptions());
    } else {
      cmd = new CobblerSystemCreateCommand(user, server, cobblerProfileLabel);
      cmd.setKernelOptions(kernelOptions);
    }
    cmd.setKickstartHost(host);
    cmd.setPostKernelOptions(postKernelOptions);
    cmd.setScheduledAction(kickstartAction);
    cmd.setNetworkInfo(
        isDhcp, networkInterface, this.useIpv6Gateway(), ksdata.getInstallType().getLabel());
    cmd.setBridgeInfo(
        createBond,
        bondInterface,
        bondSlaveInterfaces,
        bondOptions,
        isBondDhcp,
        bondAddress,
        bondNetmask,
        bondGateway);
    ValidatorError cobblerError = cmd.store();
    if (cobblerError != null) {
      return cobblerError;
    }
    SystemRecord rec =
        SystemRecord.lookupById(
            CobblerXMLRPCHelper.getConnection(this.getUser().getLogin()),
            this.getServer().getCobblerId());

    // This is a really really crappy way of doing this, but i don't want to restructure
    //      the actions too much at this point :/
    //      We only want to do this for the non-guest action
    if (kickstartAction instanceof KickstartAction) {
      ((KickstartAction) kickstartAction)
          .getKickstartActionDetails()
          .setCobblerSystemName(rec.getName());
    }

    ActionFactory.save(kickstartAction);
    log.debug("** Created ksaction: " + kickstartAction.getId());

    this.scheduledAction = kickstartAction;

    log.debug("** Done scheduling kickstart session");
    return null;
  }
  /**
   * The first step in the wizard
   *
   * @param mapping ActionMapping for struts
   * @param form DynaActionForm representing the form
   * @param ctx RequestContext request context
   * @param response HttpServletResponse response object
   * @param step WizardStep what step are we on?
   * @return ActionForward struts action forward
   * @throws Exception if something goes amiss
   */
  public ActionForward runFirst(
      ActionMapping mapping,
      DynaActionForm form,
      RequestContext ctx,
      HttpServletResponse response,
      WizardStep step)
      throws Exception {
    log.debug("runFirst");
    Long sid = (Long) form.get(RequestContext.SID);
    User user = ctx.getCurrentUser();

    KickstartScheduleCommand cmd = getKickstartScheduleCommand(sid, user);

    Server system = SystemManager.lookupByIdAndUser(sid, user);
    if (system.isVirtualGuest()
        && VirtualInstanceFactory.getInstance()
            .getParaVirtType()
            .equals(system.getVirtualInstance().getType())) {
      ctx.getRequest().setAttribute(IS_VIRTUAL_GUEST, Boolean.TRUE.toString());

      ctx.getRequest().setAttribute(VIRT_HOST_IS_REGISTERED, Boolean.FALSE.toString());
      if (system.getVirtualInstance().getHostSystem() != null) {
        Long hostSid = system.getVirtualInstance().getHostSystem().getId();
        ctx.getRequest().setAttribute(VIRT_HOST_IS_REGISTERED, Boolean.TRUE.toString());
        ctx.getRequest().setAttribute(HOST_SID, hostSid);
      }
    } else {
      ctx.getRequest().setAttribute(IS_VIRTUAL_GUEST, Boolean.FALSE.toString());
    }

    addRequestAttributes(ctx, cmd, form);
    checkForKickstart(form, cmd, ctx);
    setupProxyInfo(ctx);
    if (StringUtils.isBlank(form.getString(PROXY_HOST))) {
      form.set(PROXY_HOST, "");
    }
    // create and prepopulate the date picker.
    getStrutsDelegate()
        .prepopulateDatePicker(ctx.getRequest(), form, "date", DatePicker.YEAR_RANGE_POSITIVE);

    SdcHelper.ssmCheck(ctx.getRequest(), system.getId(), user);
    Map params = new HashMap<String, String>();
    params.put(RequestContext.SID, sid);
    ListHelper helper = new ListHelper(new Profiles(), ctx.getRequest(), params);
    helper.execute();
    if (!StringUtils.isBlank(form.getString(RequestContext.COBBLER_ID))) {
      ListTagHelper.selectRadioValue(
          ListHelper.LIST, form.getString(RequestContext.COBBLER_ID), ctx.getRequest());
    } else if (system.getCobblerId() != null) {
      // if nothing is selected by the user yet, use the cobbler
      //  system record to pre-select something.
      SystemRecord rec =
          SystemRecord.lookupById(
              CobblerXMLRPCHelper.getConnection(ConfigDefaults.get().getCobblerAutomatedUser()),
              system.getCobblerId());
      if (rec != null) {
        ListTagHelper.selectRadioValue(ListHelper.LIST, rec.getProfile().getId(), ctx.getRequest());
      }
    }

    ActionForward retval = mapping.findForward("first");
    return retval;
  }
示例#22
0
 protected DataResult<SystemOverview> getDataResult(User user, PageControl pc, ActionForm formIn) {
   return SystemManager.ungroupedList(user, pc);
 }
  /**
   * Executes the appropriate PackageAction
   *
   * @param mapping ActionMapping
   * @param formIn ActionForm
   * @param request ServletRequest
   * @param response ServletResponse
   * @return The ActionForward to go to next.
   */
  public ActionForward executePackageAction(
      ActionMapping mapping,
      ActionForm formIn,
      HttpServletRequest request,
      HttpServletResponse response) {

    RequestContext requestContext = new RequestContext(request);
    StrutsDelegate strutsDelegate = getStrutsDelegate();

    Long sid = requestContext.getRequiredParam("sid");
    User user = requestContext.getCurrentUser();
    // updateList(newactions, user.getId());

    List<Map<String, Long>> data = PackageListItem.toKeyMaps(getDataResult(request));
    int numPackages = data.size();

    // Archive the actions
    Server server = SystemManager.lookupByIdAndUser(sid, user);

    // The earliest time to perform the action.
    DynaActionForm dynaActionForm = (DynaActionForm) formIn;
    Date earliest =
        getStrutsDelegate().readDatePicker(dynaActionForm, "date", DatePicker.YEAR_RANGE_POSITIVE);

    // The action chain to append this action to, if any
    ActionChain actionChain = ActionChainHelper.readActionChain(dynaActionForm, user);

    PackageAction pa = schedulePackageAction(formIn, requestContext, data, earliest, actionChain);

    // Remove the actions from the users set
    SessionSetHelper.obliterate(request, getDecl(sid));

    ActionMessages msgs = new ActionMessages();

    if (actionChain == null) {
      /**
       * If there was only one action archived, display the "action" archived message, else display
       * the "actions" archived message.
       */
      if (numPackages == 1) {
        msgs.add(
            ActionMessages.GLOBAL_MESSAGE,
            new ActionMessage(
                getMessageKeyForOne(),
                LocalizationService.getInstance().formatNumber(numPackages),
                pa.getId().toString(),
                sid.toString(),
                StringUtil.htmlifyText(server.getName())));
      } else {
        msgs.add(
            ActionMessages.GLOBAL_MESSAGE,
            new ActionMessage(
                getMessageKeyForMany(),
                LocalizationService.getInstance().formatNumber(numPackages),
                pa.getId().toString(),
                sid.toString(),
                StringUtil.htmlifyText(server.getName())));
      }
    } else {
      msgs.add(
          ActionMessages.GLOBAL_MESSAGE,
          new ActionMessage(
              "message.addedtoactionchain",
              actionChain.getId(),
              StringUtil.htmlifyText(actionChain.getLabel())));
    }

    strutsDelegate.saveMessages(request, msgs);
    Map params = new HashMap();
    processParamMap(formIn, request, params);
    return strutsDelegate.forwardParams(mapping.findForward(RhnHelper.CONFIRM_FORWARD), params);
  }
 @Override
 protected DataResult<PackageListItem> getDataResult(Server server) {
   return SystemManager.listExtraPackages(server.getId());
 }
 /** {@inheritDoc} */
 public List getResult(RequestContext contextIn) {
   return SystemManager.inSet(contextIn.getCurrentUser(), RhnSetDecl.SYSTEMS.getLabel());
 }