public void testSystemPackageList() throws Exception {
    // need a system
    // need to add packages to that system
    // then need to query those values
    PageControl pc = new PageControl();
    pc.setIndexData(false);
    pc.setStart(1);

    user.addRole(RoleFactory.ORG_ADMIN);

    Server server = ServerFactoryTest.createTestServer(user, true);
    PackageManagerTest.addPackageToSystemAndChannel(
        "test-package-name" + TestUtils.randomString(),
        server,
        ChannelFactoryTest.createTestChannel(user));

    DataResult dr = PackageManager.systemPackageList(server.getId(), pc);
    assertNotNull(dr);
    assertEquals(1, dr.size());

    for (Iterator itr = dr.iterator(); itr.hasNext(); ) {
      Object o = itr.next();
      assertTrue(o instanceof PackageListItem);
    }
  }
  /**
   * Cancel existing kickstart sessions on the host server for the system to be kickstarted (the
   * target server).
   */
  private void cancelExistingSessions() {
    Server hostServer = getHostServer();

    List sessions = KickstartFactory.lookupAllKickstartSessionsByServer(hostServer.getId());
    if (sessions != null) {
      log.debug("    Found sessions: " + sessions);
      Iterator i = sessions.iterator();
      while (i.hasNext()) {
        KickstartSession sess = (KickstartSession) i.next();
        if (sess != null && sess.getState() != null) {
          log.debug(
              "    Working with session: " + sess.getState().getLabel() + " id: " + sess.getId());
        }
        KickstartSessionState state = sess.getState();

        if (!state.equals(KickstartFactory.SESSION_STATE_FAILED)
            || !state.equals(KickstartFactory.SESSION_STATE_COMPLETE)) {
          log.debug(
              "    need to cancel this Session this.s: "
                  + hostServer.getId()
                  + " sess.hostServer: "
                  + (sess.getHostServer() == null ? "null" : "" + sess.getHostServer().getId()));
          if (sess.getHostServer() != null
              && sess.getHostServer().getId().equals(hostServer.getId())) {
            log.debug("    Marking session failed.");
            sess.markFailed(
                LocalizationService.getInstance().getMessage("kickstart.session.newsession"));
          }
        }
      }
    }
  }
 public void testCreateNewKeys() throws Exception {
   ActivationKey k = createTestActivationKey(user);
   Server s = k.getServer();
   for (int i = 0; i < 10; i++) {
     ActivationKey tk = createTestActivationKey(s.getCreator(), s);
     System.out.println("tk: " + tk.getKey());
   }
 }
Пример #4
0
  public void testLookupOrgsWithServersInFamily() throws Exception {
    Server s = ServerTestUtils.createTestSystem();
    Channel chan = s.getChannels().iterator().next();
    ChannelFamily family = chan.getChannelFamily();

    List<Org> orgs = OrgFactory.lookupOrgsUsingChannelFamily(family);
    assertEquals(1, orgs.size());
  }
 /**
  * This method is called when the &quot;Unsubscribe from Channel&quot; button is clicked in the
  * Channel Systems page. Unsubscribes the specified systems from the channel.
  *
  * @param form Action form object.
  * @param req The servlet request object
  * @param elementIn The checked element in the set
  * @param userIn logged in user
  * @return true
  */
 public Boolean unsubscribeSystems(
     ActionForm form, HttpServletRequest req, RhnSetElement elementIn, User userIn) {
   ConfigChannel channel = ConfigActionHelper.getChannel(req);
   Server s = ServerFactory.lookupById(elementIn.getElement());
   s.unsubscribe(channel);
   ServerFactory.save(s);
   return Boolean.TRUE;
 }
 public void testGetServerNeededUpdatePackageByName() throws Exception {
   user.addRole(RoleFactory.ORG_ADMIN);
   Server s = ServerFactoryTest.createTestServer(user);
   Channel c = ChannelFactoryTest.createTestChannel(user);
   addPackageToSystemAndChannel("some-test-package", s, c);
   // Not enough time actually test the results of this query for now
   // Just testing that it runs without SQL error. -mmccune
   assertNull(PackageManager.getServerNeededUpdatePackageByName(s.getId(), "some-test-package"));
 }
  /** {@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 testKeyGeneration() throws Exception {

    ActivationKey k = createTestActivationKey(user);
    String note = k.getNote();
    String key = k.getKey();

    TestUtils.saveAndFlush(k);

    ActivationKey k2 = ActivationKeyFactory.lookupByKey(key);
    assertEquals(key, k2.getKey());
    assertEquals(note, k2.getNote());

    ActivationKey k3 = ActivationKeyFactory.lookupByKey(TestUtils.randomString());
    assertNull(k3);

    // Make sure we got the entitlements correct
    Server server = k2.getServer();
    assertEquals(1, server.getEntitlements().size());
    assertEquals(1, k2.getEntitlements().size());

    Entitlement e = server.getEntitlements().iterator().next();
    ServerGroupType t2 = k2.getEntitlements().iterator().next();
    assertEquals(e.getLabel(), t2.getLabel());

    // test out ActivationKeyManager.findByServer while we're here...
    ActivationKey k4 =
        ActivationKeyManager.getInstance().findByServer(server, user).iterator().next();
    assertNotNull(k4);
    assertEquals(key, k4.getKey());

    try {
      k3 = ActivationKeyManager.getInstance().findByServer(null, user).iterator().next();
      String msg =
          "Permission check failed :(.."
              + " Activation key should not have existed"
              + " for a server of 'null' id. An exception "
              + "should have been raised for this.";
      fail(msg);
    } catch (Exception ie) {
      // great!.. Exception for passing in invalid keys always welcome
    }

    User user1 = UserTestUtils.findNewUser("testuser", "testorg");
    Server server2 = ServerFactoryTest.createTestServer(user1);
    try {
      k3 = ActivationKeyManager.getInstance().findByServer(server2, user1).iterator().next();
      String msg =
          "Permission check failed :(.."
              + " Activation key should not have existed"
              + " for a server of the associated id. An exception "
              + "should have been raised for this.";
      fail(msg);
    } catch (Exception ie) {
      // great!.. Exception for passing in invalid keys always welcome
    }
  }
Пример #9
0
  /**
   * Migrate systems from one organization to another. If executed by a Satellite administrator, the
   * systems will be migrated from their current organization to the organization specified by the
   * toOrgId. If executed by an organization administrator, the systems must exist in the same
   * organization as that administrator and the systems will be migrated to the organization
   * specified by the toOrgId. In any scenario, the origination and destination organizations must
   * be defined in a trust.
   *
   * @param sessionKey User's session key.
   * @param toOrgId destination organization ID.
   * @param sids System IDs.
   * @return list of systems migrated.
   * @throws FaultException A FaultException is thrown if: - The user performing the request is not
   *     an organization administrator - The user performing the request is not a satellite
   *     administrator, but the from org id is different than the user's org id. - The from and to
   *     org id provided are the same. - One or more of the servers provides do not exist - The
   *     origination or destination organization does not exist - The user is not defined in the
   *     destination organization's trust
   * @xmlrpc.doc Migrate systems from one organization to another. If executed by a Satellite
   *     administrator, the systems will be migrated from their current organization to the
   *     organization specified by the toOrgId. If executed by an organization administrator, the
   *     systems must exist in the same organization as that administrator and the systems will be
   *     migrated to the organization specified by the toOrgId. In any scenario, the origination and
   *     destination organizations must be defined in a trust.
   * @xmlrpc.param #param("string", "sessionKey")
   * @xmlrpc.param #param_desc("int", "toOrgId", "ID of the organization where the system(s) will be
   *     migrated to.")
   * @xmlrpc.param #array_single("int", "systemId")
   * @xmlrpc.returntype #array_single("int", "serverIdMigrated")
   */
  public Object[] migrateSystems(String sessionKey, Integer toOrgId, List<Integer> sids)
      throws FaultException {

    // the user executing the request must at least be an org admin to perform
    // a system migration
    User admin = getOrgAdmin(sessionKey);

    Org toOrg = verifyOrgExists(toOrgId);

    List<Server> servers = new LinkedList<Server>();

    for (Integer sid : sids) {
      Long serverId = new Long(sid.longValue());
      Server server = null;
      try {
        server = ServerFactory.lookupById(serverId);

        // throw a no_such_system exception if the server was not found.
        if (server == null) {
          throw new NoSuchSystemException("No such system - sid[" + sid + "]");
        }
      } catch (LookupException e) {
        throw new NoSuchSystemException("No such system - sid[" + sid + "]");
      }
      servers.add(server);

      // As a pre-requisite to performing the actual migration, verify that each
      // server that is planned for migration passes the criteria that follows.
      // If any of the servers fails that criteria, none will be migrated.

      // unless the user is a satellite admin, they are not permitted to migrate
      // systems from an org that they do not belong to
      if ((!admin.hasRole(RoleFactory.SAT_ADMIN)) && (!admin.getOrg().equals(server.getOrg()))) {
        throw new PermissionCheckFailureException(server);
      }

      // do not allow the user to migrate systems to/from the same org.  doing so
      // would essentially remove entitlements, channels...etc from the systems
      // being migrated.
      if (toOrg.equals(server.getOrg())) {
        throw new MigrationToSameOrgException(server);
      }

      // if the originating org is not defined within the destination org's trust
      // the migration should not be permitted.
      if (!toOrg.getTrustedOrgs().contains(server.getOrg())) {
        throw new OrgNotInTrustException(server);
      }
    }

    List<Long> serversMigrated = MigrationManager.migrateServers(admin, toOrg, servers);
    return serversMigrated.toArray();
  }
  /**
   * 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());
  }
  /** {@inheritDoc} */
  @Override
  public ActionForward execute(
      ActionMapping mapping,
      ActionForm formIn,
      HttpServletRequest request,
      HttpServletResponse response) {

    RequestContext requestContext = new RequestContext(request);
    Server server = requestContext.lookupAndBindServer();
    Long aid = requestContext.getRequiredParam("aid");

    request.setAttribute("aid", aid);
    request.setAttribute("referrerLink", "History.do");
    request.setAttribute("linkLabel", "system.event.return");
    request.setAttribute("headerLabel", "system.event.header");

    Action action;
    ServerAction serverAction;
    try {
      action = ActionManager.lookupAction(requestContext.getCurrentUser(), aid);
      serverAction = ActionFactory.getServerActionForServerAndAction(server, action);
    } catch (LookupException e) {
      ServerHistoryEvent event = ActionFactory.lookupHistoryEventById(aid);
      request.setAttribute("actiontype", event.getSummary());
      request.setAttribute("earliestaction", event.getCreated());
      request.setAttribute("actionnotes", event.getDetails());
      request.setAttribute("failed", false);
      return mapping.findForward(RhnHelper.DEFAULT_FORWARD);
    }
    ActionFormatter af = action.getFormatter();
    request.setAttribute("actionname", af.getName());
    request.setAttribute("actiontype", af.getActionType());
    request.setAttribute("scheduler", af.getScheduler());
    request.setAttribute("earliestaction", af.getEarliestDate());
    request.setAttribute("actionnotes", af.getDetails(server, requestContext.getCurrentUser()));
    request.setAttribute("failed", serverAction.getStatus().equals(ActionFactory.STATUS_FAILED));
    if (!serverAction.getStatus().equals(ActionFactory.STATUS_COMPLETED)
        && !serverAction.getStatus().equals(ActionFactory.STATUS_FAILED)) {
      request.setAttribute("referrerLink", "Pending.do");
      request.setAttribute("linkLabel", "system.event.pendingReturn");
      request.setAttribute("headerLabel", "system.event.pendingHeader");
    }
    if (isSubmitted((DynaActionForm) formIn)) {
      createSuccessMessage(request, "system.event.rescheduled", action.getName());
      ActionFactory.rescheduleSingleServerAction(action, 5L, server.getId());
      return mapping.findForward("continue");
    }

    return mapping.findForward(RhnHelper.DEFAULT_FORWARD);
  }
Пример #12
0
  /** {@inheritDoc} */
  public DataResult<ManagedServerGroup> getResult(RequestContext context) {

    Server server = context.lookupAndBindServer();
    ServerGroupManager manager = ServerGroupManager.getInstance();
    List<ManagedServerGroup> serverGroups = server.getManagedGroups();
    List<ManagedServerGroup> all = context.getCurrentUser().getOrg().getManagedServerGroups();
    List<ManagedServerGroup> ret = new LinkedList<ManagedServerGroup>();
    for (ManagedServerGroup group : all) {
      if (!serverGroups.contains(group) && manager.canAccess(context.getCurrentUser(), group)) {
        ret.add(group);
      }
    }
    return new DataResult<ManagedServerGroup>(ret);
  }
Пример #13
0
  // See BZ: 191007
  public void testCreateWithCustomGroups() throws Exception {
    Server s =
        ServerFactoryTest.createTestServer(
            user, true, ServerConstants.getServerGroupTypeEnterpriseEntitled());
    ServerGroup testGroup = ServerGroupTestUtils.createManaged(user);
    s.getManagedGroups().add((ManagedServerGroup) testGroup);

    // Three, one for the server entitlement, one for the user permission to the
    // server, one as the testGroup.
    assertEquals(1, s.getManagedGroups().size());
    ActivationKey key = createTestActivationKey(user, s);
    assertNotNull(key);
    key = (ActivationKey) reload(key);
    assertNotNull(key.getId());
  }
Пример #14
0
  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);
  }
Пример #15
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);
  }
  /**
   * 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);
  }
  public void testUpgradable() throws Exception {
    Map info =
        ErrataCacheManagerTest.createServerNeededPackageCache(user, ErrataFactory.ERRATA_TYPE_BUG);
    Server s = (Server) info.get("server");
    Package p = (Package) info.get("package");
    p = (Package) TestUtils.saveAndReload(p);

    DataResult<UpgradablePackageListItem> dr = PackageManager.upgradable(s.getId(), null);
    assertFalse(dr.isEmpty());
    boolean containsSamePackage = false;
    for (UpgradablePackageListItem item : dr) {
      if (p.getPackageName().getName().equals(item.getName())) {
        containsSamePackage = true;
      }
      assertTrue(item.getIdCombo().split("\\|").length == 3);
    }
    assertTrue(containsSamePackage);
  }
Пример #18
0
 /** {@inheritDoc} */
 public ActionForward execute(
     ActionMapping mapping,
     ActionForm formIn,
     HttpServletRequest request,
     HttpServletResponse response) {
   RequestContext ctx = new RequestContext(request);
   Server server = ctx.lookupAndBindServer();
   User user = ctx.getCurrentUser();
   SdcHelper.ssmCheck(ctx.getRequest(), server.getId(), user);
   DynaActionForm form = (DynaActionForm) formIn;
   SystemRecord rec = (SystemRecord) getCobblerObject(server.getCobblerId(), user);
   if (isSubmitted(form)) {
     if (!Boolean.valueOf(rec.isNetbootEnabled()).equals(form.get(NETBOOT_ENABLED))) {
       rec.enableNetboot(Boolean.TRUE.equals(form.get(NETBOOT_ENABLED)));
       rec.save();
     }
   }
   form.set(NETBOOT_ENABLED, rec.isNetbootEnabled());
   return super.execute(mapping, formIn, request, response);
 }
Пример #19
0
  /** {@inheritDoc} */
  public ActionForward execute(
      ActionMapping mapping,
      ActionForm formIn,
      HttpServletRequest request,
      HttpServletResponse response) {

    RequestContext context = new RequestContext(request);
    context.copyParamToAttributes("sid");
    Server server = context.lookupAndBindServer();

    ListRhnSetHelper helper =
        new ListRhnSetHelper(this, request, RhnSetDecl.setForSystemCrashes(server));
    helper.execute();
    if (helper.isDispatched()) {
      return handleSubmit(mapping, context, server);
    }

    SdcHelper.ssmCheck(request, server.getId(), context.getCurrentUser());

    return mapping.findForward(RhnHelper.DEFAULT_FORWARD);
  }
  private List<NetworkInterface> getPublicNetworkInterfaces(Server server) {
    List<NetworkInterface> nics = new LinkedList<NetworkInterface>(server.getNetworkInterfaces());

    for (Iterator<NetworkInterface> itr = nics.iterator(); itr.hasNext(); ) {
      NetworkInterface nic = itr.next();
      if (nic.isDisabled() || "127.0.0.1".equals(nic.getIpaddr())) {
        itr.remove();
      }
    }

    return nics;
  }
  /**
   * This method inserts a record into the rhnServerPackage mapping table to associate a given
   * Server with a particular Package. The web code doesn't actually create any of these records,
   * but this will be needed by the backend code.
   *
   * @param srvr Server to associate with the packages
   * @param p The package
   */
  public static void associateSystemToPackage(Server srvr, Package p) {
    try {
      WriteMode m = ModeFactory.getWriteMode("test_queries", "insert_into_rhnServerPackageSimple");
      Map params = new HashMap();
      params.put("server_id", srvr.getId());
      params.put("name_id", p.getPackageName().getId());
      params.put("evr_id", p.getPackageEvr().getId());

      m.executeUpdate(params);
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
  /** {@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);
  }
Пример #23
0
 protected ActionForward handleSubmit(ActionMapping mapping, RequestContext ctx, Server server) {
   User user = ctx.getCurrentUser();
   RhnSet set = RhnSetDecl.setForSystemCrashes(server).get(user);
   // until we delete crash files from taskomatic, we have to delete them one by one
   for (Iterator<Long> iter =
           RhnSetDecl.setForSystemCrashes(server).get(user).getElementValues().iterator();
       iter.hasNext(); ) {
     CrashManager.deleteCrash(user, iter.next());
   }
   createSuccessMessage(ctx.getRequest(), "message.crashesdeleted", Integer.toString(set.size()));
   Map<String, Object> params = new HashMap<String, Object>();
   params.put("sid", server.getId());
   return getStrutsDelegate().forwardParams(mapping.findForward("delete"), params);
 }
  private void setupNetworkInfo(
      DynaActionForm form, RequestContext context, KickstartScheduleCommand cmd) {
    Server server = cmd.getServer();
    List<NetworkInterface> nics = getPublicNetworkInterfaces(server);

    if (nics.isEmpty()) {
      return;
    }

    context.getRequest().setAttribute(NETWORK_INTERFACES, nics);

    if (StringUtils.isBlank(form.getString(NETWORK_INTERFACE))) {
      String defaultInterface = ConfigDefaults.get().getDefaultKickstartNetworkInterface();
      for (NetworkInterface nic : nics) {
        if (nic.getName().equals(defaultInterface)) {
          form.set(NETWORK_INTERFACE, ConfigDefaults.get().getDefaultKickstartNetworkInterface());
        }
      }
      if (StringUtils.isBlank(form.getString(NETWORK_INTERFACE))) {
        form.set(NETWORK_INTERFACE, server.findPrimaryNetworkInterface().getName());
      }
    }
  }
Пример #25
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);
        }
      }
    }
  }
  /**
   * Do the validation needed for this command. This ensures that the system hosting the kickstart
   * has the necessary resources to do so.
   *
   * @return Returns a ValidatorError, if any errors occur
   */
  public ValidatorError doValidation() {
    ValidatorError error = validateNetworkInterface();
    if (error != null) {
      return error;
    }
    if (isCobblerOnly()) {
      return null;
    }
    Server hostServer = getHostServer();

    // Check base channel.
    log.debug("** Checking basechannel.");
    if (hostServer.getBaseChannel() == null) {
      return new ValidatorError("kickstart.schedule.nobasechannel", hostServer.getName());
    }

    // Check that we have a valid ks package
    log.debug("** Checking validkspackage");
    error = validateKickstartPackage();
    if (error != null) {
      return error;
    }

    if (ksdata.isRhel()) {
      // Check that we have a valid up2date version
      log.debug("** Checking valid up2date");
      error = validateUp2dateVersion();
      if (error != null) {
        return error;
      }
    }

    // we already shall be subscribed to the tools channel
    // (since validateKickstartPackage), so no other actions needed
    return null;
  }
  private void showMessages(
      ActionMessages msgs, Action action, Server server, int pkgcnt, String mode) {
    String key = null;

    if (MODE_INSTALL.equals(mode)) {
      key = "message.packageinstall";
    } else if (MODE_REMOVAL.equals(mode)) {
      key = "message.packageremoval";
    } else { // must be upgrade
      key = "message.packageupgrade";
    }

    /**
     * If there was only one action archived, display the "action" archived message, else display
     * the "actions" archived message.
     */
    if (pkgcnt == 1) {
      msgs.add(
          ActionMessages.GLOBAL_MESSAGE,
          new ActionMessage(
              key,
              LocalizationService.getInstance().formatNumber(new Integer(pkgcnt)),
              action.getId().toString(),
              server.getId().toString(),
              server.getName()));
    } else {
      msgs.add(
          ActionMessages.GLOBAL_MESSAGE,
          new ActionMessage(
              key + "s",
              LocalizationService.getInstance().formatNumber(new Integer(pkgcnt)),
              action.getId().toString(),
              server.getId().toString(),
              server.getName()));
    }
  }
  /**
   * This method inserts a record into the rhnServerPackage mapping table to associate a given
   * Server with a particular Package. The web code doesn't actually create any of these records,
   * but this will be needed by the backend code.
   *
   * @param srvr Server to associate with the packages
   * @param pn The package name to associate
   * @param pe The package evr (version and release).
   */
  public static void associateSystemToPackage(Server srvr, PackageName pn, PackageEvr pe) {
    try {
      WriteMode m = ModeFactory.getWriteMode("test_queries", "insert_into_rhnServerPackage");
      Map params = new HashMap();
      params.put("server_id", srvr.getId());
      params.put("pn_id", pn.getId());
      params.put("p_epoch", pe.getEpoch());
      params.put("p_version", pe.getVersion());
      params.put("p_release", pe.getRelease());

      m.executeUpdate(params);
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
  public void testUpgradablePackagesFromServerSet() throws Exception {
    // Setup
    User admin = UserTestUtils.findNewUser("ssmUpgradeUser1", "ssmUpgradeOrg1");
    Org org = admin.getOrg();

    //   Create the server and add to the SSM
    Server server = ServerTestUtils.createTestSystem(admin);
    ServerTestUtils.addServersToSsm(admin, server.getId());

    //   Create upgraded package EVR so package will show up from the query
    PackageEvr upgradedPackageEvr = PackageEvrFactory.createPackageEvr("1", "1.0.0", "2");
    upgradedPackageEvr = (PackageEvr) TestUtils.saveAndReload(upgradedPackageEvr);

    ServerTestUtils.populateServerErrataPackages(
        org, server, upgradedPackageEvr, ErrataFactory.ERRATA_TYPE_SECURITY);
    ServerTestUtils.populateServerErrataPackages(
        org, server, upgradedPackageEvr, ErrataFactory.ERRATA_TYPE_BUG);

    // Test
    DataResult result = PackageManager.upgradablePackagesFromServerSet(admin);

    assertTrue(result != null);
    assertEquals(2, result.size());
  }
Пример #30
0
  /** {@inheritDoc} */
  @Override
  public ActionForward execute(
      ActionMapping mapping,
      ActionForm formIn,
      HttpServletRequest request,
      HttpServletResponse response) {

    RequestContext context = new RequestContext(request);
    User user = context.getCurrentUser();
    Server server = context.lookupAndBindServer();
    ListSessionSetHelper helper = new ListSessionSetHelper(this, request);
    helper.execute();

    if (helper.isDispatched()) {
      ServerGroupManager manager = ServerGroupManager.getInstance();
      List<Server> servers = new LinkedList<Server>();
      servers.add(server);

      for (String id : helper.getSet()) {
        ServerGroup group = manager.lookup(Long.valueOf(id), user);
        manager.addServers(group, servers, user);
      }
      helper.destroy();
      getStrutsDelegate()
          .saveMessage(
              "systems.groups.jsp.added",
              new String[] {String.valueOf(helper.getSet().size())},
              request);

      Map<String, Object> params = new HashMap<String, Object>();
      params.put(RequestContext.SID, server.getId().toString());
      StrutsDelegate strutsDelegate = getStrutsDelegate();
      return strutsDelegate.forwardParams(mapping.findForward("success"), params);
    }
    return mapping.findForward(RhnHelper.DEFAULT_FORWARD);
  }