forked from uyuni-project/uyuni
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ServerFactory.java
1450 lines (1304 loc) · 53.2 KB
/
ServerFactory.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* Copyright (c) 2009--2016 Red Hat, Inc.
*
* This software is licensed to you under the GNU General Public License,
* version 2 (GPLv2). There is NO WARRANTY for this software, express or
* implied, including the implied warranties of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
* along with this software; if not, see
* http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
*
* Red Hat trademarks are not licensed under GPLv2. No permission is
* granted to use or replicate Red Hat trademarks that are incorporated
* in this software or its documentation.
*/
package com.redhat.rhn.domain.server;
import static java.util.stream.Collectors.toMap;
import com.redhat.rhn.common.client.ClientCertificate;
import com.redhat.rhn.common.client.InvalidCertificateException;
import com.redhat.rhn.common.db.datasource.CallableMode;
import com.redhat.rhn.common.db.datasource.DataResult;
import com.redhat.rhn.common.db.datasource.ModeFactory;
import com.redhat.rhn.common.db.datasource.SelectMode;
import com.redhat.rhn.common.db.datasource.WriteMode;
import com.redhat.rhn.common.hibernate.HibernateFactory;
import com.redhat.rhn.common.validator.ValidatorError;
import com.redhat.rhn.domain.channel.ChannelArch;
import com.redhat.rhn.domain.dto.SystemIDInfo;
import com.redhat.rhn.domain.entitlement.Entitlement;
import com.redhat.rhn.domain.org.CustomDataKey;
import com.redhat.rhn.domain.org.Org;
import com.redhat.rhn.domain.rhnpackage.PackageEvrFactory;
import com.redhat.rhn.domain.user.User;
import com.redhat.rhn.frontend.dto.HistoryEvent;
import com.redhat.rhn.frontend.xmlrpc.ChannelSubscriptionException;
import com.redhat.rhn.frontend.xmlrpc.ServerNotInGroupException;
import com.redhat.rhn.manager.entitlement.EntitlementManager;
import com.redhat.rhn.manager.rhnset.RhnSetDecl;
import com.redhat.rhn.manager.system.UpdateBaseChannelCommand;
import com.suse.manager.model.maintenance.MaintenanceSchedule;
import com.suse.manager.webui.services.pillar.MinionPillarManager;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.hibernate.criterion.Subqueries;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.JoinType;
import javax.persistence.criteria.Path;
import javax.persistence.criteria.Root;
/**
* ServerFactory - the singleton class used to fetch and store
* com.redhat.rhn.domain.server.Server objects from the database.
*/
public class ServerFactory extends HibernateFactory {
private static Logger log = Logger.getLogger(ServerFactory.class);
public static final ServerFactory SINGLETON = new ServerFactory();
private ServerFactory() {
super();
}
/**
* Looks up the CustomDataValue given CustomDataKey and Server objects.
* @param key The Key for the value you would like to lookup
* @param server The Server in question
* @return Returns the CustomDataValue object if found, null if not.
*/
protected static CustomDataValue getCustomDataValue(CustomDataKey key,
Server server) {
// Make sure we didn't recieve any nulls
if (key == null || server == null) {
return null;
}
Session session = HibernateFactory.getSession();
return (CustomDataValue) session.getNamedQuery(
"CustomDataValue.findByServerAndKey").setParameter("server",
server).setParameter("key", key)
// Retrieve from cache if there
.setCacheable(true).uniqueResult();
}
/**
* Remove the custom data values associated with a server.
* @param server The server
*/
public static void removeCustomDataValues(Server server) {
for (Object value : server.getCustomDataValues()) {
SINGLETON.removeObject(value);
}
server.getCustomDataValues().clear();
server.asMinionServer().ifPresent(minion -> {
MinionPillarManager.INSTANCE.generatePillar(minion, false,
MinionPillarManager.PillarSubset.CUSTOM_INFO);
});
}
/**
* Remove the custom data value associated with the custom data key
* provided for the given server.
* @param server The server
* @param key The custom data key
*/
public static void removeCustomDataValue(Server server, CustomDataKey key) {
CustomDataValue value = server.getCustomDataValue(key);
server.getCustomDataValues().remove(value);
if (value != null) {
SINGLETON.removeObject(value);
}
server.asMinionServer().ifPresent(minion -> {
MinionPillarManager.INSTANCE.generatePillar(minion, false,
MinionPillarManager.PillarSubset.CUSTOM_INFO);
});
}
/**
* Lookup all CustomDataValues associated with the CustomDataKey.
* @param key The Key for the values you would like to lookup
* @return List of custom data values.
*/
public static List<CustomDataValue> lookupCustomDataValues(CustomDataKey key) {
Map<String, Object> params = new HashMap<String, Object>();
params.put("key", key);
return SINGLETON.listObjectsByNamedQuery(
"CustomDataValue.findByKey", params);
}
/**
* Lookup all MinionServers subscribed to the channel.
* @param cid The channel id
* @return List of minions.
*/
public static List<MinionServer> listMinionsByChannel(long cid) {
Map<String, Object> params = new HashMap<String, Object>();
params.put("cid", cid);
return SINGLETON.listObjectsByNamedQuery(
"Server.listMinionsByChannel", params);
}
/**
* Lookup all the systems with the specified CustomDataKey.
* @param userId The User ID of the user doing the query
* @param cikid The ID of the Key for the values you would like to lookup
* @return List of systems
*/
public static List lookupServersWithCustomKey(Long userId, Long cikid) {
SelectMode m = ModeFactory.getMode("System_queries",
"users_systems_with_value_for_key");
Map inParams = new HashMap();
inParams.put("user_id", userId);
inParams.put("cikid", cikid);
return m.execute(inParams);
}
/**
* Lookup all storage Devices associated with the server.
* @param s The server for the values you would like to lookup
* @return List of devices
*/
public static List<Device> lookupStorageDevicesByServer(Server s) {
Map<String, Object> params = new HashMap<String, Object>();
params.put("server", s);
return SINGLETON.listObjectsByNamedQuery(
"Device.findStorageByServer", params);
}
/**
* Looks up a proxy server by hostname.
* @param name the hostname
* @return the server, if it is found
*/
@SuppressWarnings("unchecked")
public static Optional<Server> lookupProxyServer(String name) {
boolean nameIsFullyQualified = name.contains(".");
if (!nameIsFullyQualified) {
log.warn("Specified master name \"" + name + "\" is not fully-qualified," +
"proxy attachment might not be correct");
log.warn("Please use a FQDN in /etc/salt/minion.d/susemanager.conf");
}
DetachedCriteria proxyIds = DetachedCriteria.forClass(ProxyInfo.class)
.setProjection(Projections.property("server.id"));
Optional<Server> result = findByFqdn(name);
if (result.isPresent()) {
return result;
}
result = HibernateFactory.getSession()
.createCriteria(Server.class)
.add(Subqueries.propertyIn("id", proxyIds))
.add(Restrictions.eq("hostname", name))
.list()
.stream()
.findFirst();
if (result.isPresent()) {
return result;
}
// precise search did not work, try imprecise
if (nameIsFullyQualified) {
String srippedHostname = name.split("\\.")[0];
return HibernateFactory.getSession()
.createCriteria(Server.class)
.add(Subqueries.propertyIn("id", proxyIds))
.add(Restrictions.eq("hostname", srippedHostname))
.list()
.stream()
.findFirst();
}
else {
return HibernateFactory.getSession()
.createCriteria(Server.class)
.add(Subqueries.propertyIn("id", proxyIds))
.add(Restrictions.like("hostname", name + ".", MatchMode.START))
.list()
.stream()
.findFirst();
}
}
/**
* Return a map from Salt minion IDs to System IDs.
* Map entries are limited to systems that are visible by the specified user.
*
* @param id a user ID
* @return the minion ID to system ID map
*/
public static Map<String, Long> getMinionIdMap(Long id) {
var params = new HashMap<String, Object>();
params.put("user_id", id);
List<Object[]> result = SINGLETON.listObjectsByNamedQuery("Server.listMinionIdMappings", params);
return result.stream().collect(toMap(
row -> (String)(row[0]),
row -> (Long)(row[1]))
);
}
/**
* Get the Logger for the derived class so log messages show up on the
* correct class
*/
@Override
protected Logger getLogger() {
return log;
}
/**
* Create a new Server from scratch
* @return the Server created
*/
public static Server createServer() {
return new Server();
}
/**
* Creates a set of new {@link ServerPath} objects using the <code>proxyServer</code>'s
* server path (if any).
*
* @param server the server
* @param proxyServer the proxy server to which <code>server</code> connects directly
* @param proxyHostname the proxy hostname
* @return a set of {@link ServerPath} objects where the proxy to which the
* <code>server</code> connects directly has position 0, the second proxy
* has position 1, etc
*/
public static Set<ServerPath> createServerPaths(Server server, Server proxyServer,
String proxyHostname) {
Set<ServerPath> paths = new HashSet<>();
for (ServerPath parentPath : proxyServer.getServerPaths()) {
ServerPath path = findServerPath(server, parentPath.getId().getProxyServer()).orElseGet(() -> {
ServerPath newPath = new ServerPath();
newPath.setId(new ServerPathId(server, parentPath.getId().getProxyServer()));
newPath.setPosition(parentPath.getPosition() + 1);
newPath.setHostname(parentPath.getHostname());
return newPath;
});
paths.add(path);
}
ServerPath path = findServerPath(server, proxyServer).orElseGet(() -> {
ServerPath newPath = new ServerPath();
newPath.setId(new ServerPathId(server, proxyServer));
// the first proxy is the one to which
// the server connects directly
newPath.setPosition(0L);
newPath.setHostname(proxyHostname);
return newPath;
});
paths.add(path);
return paths;
}
private static Optional<ServerPath> findServerPath(Server server, Server proxyServer) {
if (server.getId() == null) {
// not yet persisted, return empty to avoid Hibernate error
// on query with a transient object
return Optional.empty();
}
CriteriaBuilder builder = HibernateFactory.getSession().getCriteriaBuilder();
CriteriaQuery<ServerPath> criteria = builder.createQuery(ServerPath.class);
Root<ServerPath> root = criteria.from(ServerPath.class);
Path<ServerPathId> id = root.get("id");
criteria.where(builder.and(
builder.equal(id.get("server"), server),
builder.equal(id.get("proxyServer"), proxyServer)));
return getSession().createQuery(criteria).uniqueResultOptional();
}
/**
* Adds Servers to a server group.
* @param servers the servers to add
* @param serverGroup The group to add the servers to
*/
public static void addServersToGroup(Collection<Server> servers, ServerGroup serverGroup) {
List<Long> serverIdsToAdd = servers.stream().filter(s -> s.getOrgId().equals(serverGroup.getOrgId()))
.map(Server::getId).collect(Collectors.toList());
boolean serversUpdated = insertServersToGroup(serverIdsToAdd, serverGroup.getId());
if (serversUpdated) {
servers.stream().forEach(s -> s.addGroup(serverGroup));
if (serverGroup.isManaged()) {
updatePermissionsForServerGroup(serverGroup.getId());
}
}
}
private static boolean insertServersToGroup(List<Long> serverIds, Long sgid) {
WriteMode m = ModeFactory.getWriteMode("System_queries", "add_servers_to_server_group");
Map params = new HashMap();
params.put("sgid", sgid);
int insertsCount = m.executeUpdate(params, serverIds);
if (insertsCount > 0) {
updateCurrentMembersOfServerGroup(sgid, insertsCount);
return true;
}
return false;
}
private static void updateCurrentMembersOfServerGroup(Long sgid, int membersCount) {
WriteMode mode = ModeFactory.getWriteMode("System_queries", "update_current_members_of_server_group");
Map params = new HashMap();
params.put("sgid", sgid);
params.put("members_count", membersCount);
mode.executeUpdate(params);
}
private static void updatePermissionsForServerGroup(Long sgid) {
CallableMode m = ModeFactory.getCallableMode("System_queries",
"update_permissions_for_server_group");
Map params = new HashMap();
params.put("sgid", sgid);
m.execute(params, new HashMap());
}
/**
* Adds a Server to a group.
* @param serverIn The server to add
* @param serverGroupIn The group to add the server to
*/
public static void addServerToGroup(Server serverIn, ServerGroup serverGroupIn) {
addServersToGroup(Arrays.asList(serverIn), serverGroupIn);
}
/**
* Adds a server history event after an entitlement event occurred
* @param server the server
* @param ent the entitlement
* @param summary the summary of the event
*/
public static void addServerHistoryWithEntitlementEvent(Server server, Entitlement ent, String summary) {
Map<String, Object> in = new HashMap<String, Object>();
in.put("sid", server.getId());
in.put("entitlement_label", ent.getLabel());
in.put("summary", summary);
WriteMode m = ModeFactory.getWriteMode("System_queries", "update_server_history_for_entitlement_event");
m.executeUpdate(in);
log.debug("update_server_history_for_entitlement_event mode query executed.");
}
/**
* Removes Servers from a server group.
* @param servers The servers to remove
* @param serverGroup The group to remove the servers from
*/
public static void removeServersFromGroup(Collection<Server> servers, ServerGroup serverGroup) {
List<Long> serverIdsToAdd = servers.stream().filter(s -> s.getOrgId().equals(serverGroup.getOrgId()))
.map(Server::getId).collect(Collectors.toList());
boolean serversUpdated = removeServersFromGroup(serverIdsToAdd, serverGroup.getId());
if (serversUpdated) {
servers.stream().forEach(s -> s.removeGroup(serverGroup));
if (serverGroup.isManaged()) {
updatePermissionsForServerGroup(serverGroup.getId());
}
}
else {
throw new ServerNotInGroupException();
}
}
private static boolean removeServersFromGroup(List<Long> serverIds, Long sgid) {
WriteMode m = ModeFactory.getWriteMode("System_queries", "delete_from_servergroup");
Map params = new HashMap();
params.put("sgid", sgid);
int removesCount = m.executeUpdate(params, serverIds);
if (removesCount > 0) {
updateCurrentMembersOfServerGroup(sgid, -removesCount);
return true;
}
return false;
}
/**
* Removes a Server from a group.
* @param serverIn The server to remove
* @param serverGroupIn The group to remove the server from
*/
public static void removeServerFromGroup(Server serverIn, ServerGroup serverGroupIn) {
removeServersFromGroup(Arrays.asList(serverIn), serverGroupIn);
}
/**
* Lookup a Server with the ClientCertificate.
* @param clientcert ClientCertificate for the server wanted.
* @return the Server found if certificate is valid, null otherwise.
* @throws InvalidCertificateException thrown if certificate is invalid.
*/
public static Server lookupByCert(ClientCertificate clientcert)
throws InvalidCertificateException {
String idstr = clientcert.getValueByName(ClientCertificate.SYSTEM_ID);
String[] parts = StringUtils.split(idstr, '-');
if (parts != null && parts.length > 0) {
Long sid = Long.valueOf(parts[1]);
Server s = ServerFactory.lookupById(sid);
if (s != null) {
clientcert.validate(s.getSecret());
return s;
}
}
return null;
}
/**
* Retrieves the ids of the unscheduled erratas for a given set of servers
* @param user the ids of the servers
* @param serverIds the ids of the servers
* @return the ids of the erratas grouped by server id
*/
public static Map<Long, List<Long>> findUnscheduledErrataByServerIds(User user, List<Long> serverIds) {
Map<String, Object> params = new HashMap<String, Object>();
params.put("user_id", user.getId());
List<Object[]> result = (SINGLETON.listObjectsByNamedQuery("Server.findUnscheduledErrataByServerIds",
params, serverIds, "serverIds"));
return result.stream().collect(
Collectors.groupingBy(
row -> Long.valueOf(row[0].toString()),
Collectors.mapping(row -> Long.valueOf(row[1].toString()), Collectors.toList())
)
);
}
/**
* Lookup a list of servers by their ids
* @param serverIds the server ids to search for
* @param org the organization who owns the server
* @return the list of servers
*/
public static List<Server> lookupByIdsAndOrg(Set<Long> serverIds, Org org) {
Map<String, Object> params = new HashMap<String, Object>();
params.put("orgId", org.getId());
return SINGLETON.listObjectsByNamedQuery("Server.findByIdsAndOrgId", params, serverIds, "serverIds");
}
/**
* Retrieves the ids of the non-zypper traditional clients given a set of server ids
* @param ids the server ids to search for
* @return the list of non-zypper server ids
*/
public static List<Long> findNonZypperTradClientsIds(Set<Long> ids) {
Map<String, Object> params = new HashMap<String, Object>();
return SINGLETON.listObjectsByNamedQuery("Server.findNonZypperTradClientsIds", params, ids,
"serverIds");
}
/**
* Lookup a Server by their id
* @param id the id to search for
* @param orgIn Org who owns the server
* @return the Server found (null if not or not member if orgIn)
*/
public static Server lookupByIdAndOrg(Long id, Org orgIn) {
Map<String, Object> params = new HashMap<String, Object>();
params.put("sid", id);
params.put("orgId", orgIn.getId());
return (Server) SINGLETON.lookupObjectByNamedQuery(
"Server.findByIdandOrgId", params);
}
/**
* Looks up server objects from the given list of server IDs.
*
* @param serverIds List of server IDs.
* @param user who wants to lookup the Server
* @return list of server objects
*/
public static List<Server> lookupByIdsAndUser(List<Long> serverIds, User user) {
Map<String, Object> parameters = new HashMap<String, Object>();
parameters.put("orgId", user.getOrg().getId());
return findByIds(serverIds, "Server.findByIdsAndOrgId", "serverIds", parameters);
}
/**
* Returns list of the ID information of all systems visible to user and are entitled with the passed entitlement.
* @param user the logged in user.
* @param entitlement the entitlement.
*
* @return list of system IDs.
*/
public List<SystemIDInfo> lookupSystemsVisibleToUserWithEntitlement(User user, String entitlement) {
SelectMode mode = ModeFactory.getMode("System_queries", "systems_visible_to_user_with_entitlement", Map.class);
Map<String, Object> params = new HashMap<>();
params.put("user_id", user.getId());
params.put("entitlement_label", entitlement);
DataResult<Map<String, Object>> dr = mode.execute(params);
return dr.stream().map(m -> new SystemIDInfo((Long) m.get("id"), (String) m.get("name")))
.collect(Collectors.toList());
}
/**
* Lookup a Server by their id
* @param id the id to search for
* @return the Server found
*/
public static Server lookupById(Long id) {
return HibernateFactory.getSession().get(Server.class, id);
}
/**
* lookup System with specified digital server id which are foreign_entitled
*
* @param id the digital server id
* @return server corresponding to the given id
*/
@SuppressWarnings("unchecked")
public static Server lookupForeignSystemByDigitalServerId(String id) {
Criteria criteria = getSession().createCriteria(Server.class);
criteria.add(Restrictions.eq("digitalServerId", id));
for (Server server : (List<Server>) criteria.list()) {
if (server.hasEntitlement(EntitlementManager.getByName("foreign_entitled"))) {
return server;
}
}
return null;
}
/**
* Lookup Servers by their ids
* @param ids the ids to search for
* @return the Servers found
*/
public static List<Server> lookupByIds(List<Long> ids) {
return lookupByServerIds(ids, "Server.findByIds");
}
/**
* Lookup Servers by their ids
* @param <T> the type of the returned servers
* @param ids the ids to search for
* @param queryName the name of the query to be executed
* @return the Servers found
*/
public static <T extends Server> List<T> lookupByServerIds(List<Long> ids, String queryName) {
return findByIds(ids, queryName, "serverIds");
}
/**
* Lookup a ServerGroupType by its label
* @param label The label to search for
* @return The ServerGroupType
*/
public static ServerGroupType lookupServerGroupTypeByLabel(String label) {
return (ServerGroupType) HibernateFactory.getSession().getNamedQuery("ServerGroupType.findByLabel")
.setString("label", label)
// Retrieve from cache if there
.setCacheable(true).uniqueResult();
}
/**
* Insert or Update a Server.
* @param serverIn Server to be stored in database.
*/
public static void save(Server serverIn) {
if (serverIn.isSatellite()) {
SatelliteServer ss = (SatelliteServer) serverIn;
PackageEvrFactory.lookupOrCreatePackageEvr(ss.getVersion());
}
SINGLETON.saveObject(serverIn);
updateServerPerms(serverIn);
}
/**
* Insert or Update a ServerPath.
* @param pathIn ServerPath to be stored in database.
*/
public static void save(ServerPath pathIn) {
SINGLETON.saveObject(pathIn);
}
/**
* Insert or Update InstalledProduct
* @param productIn product to store in database
*/
public static void save(InstalledProduct productIn) {
SINGLETON.saveObject(productIn);
}
/**
* Save a custom data key
* @param keyIn the key to save
*/
public static void saveCustomKey(CustomDataKey keyIn) {
SINGLETON.saveObject(keyIn);
}
/**
* Remove a custom data key. This will also remove all systems'
* values for the key.
* @param keyIn the key to remove
*/
public static void removeCustomKey(CustomDataKey keyIn) {
// If the CustomKey is being removed, any system that has a
// "Custom Info" value associated with it must have that
// value removed...
List<CustomDataValue> values = lookupCustomDataValues(keyIn);
for (Iterator itr = values.iterator(); itr.hasNext();) {
CustomDataValue value = (CustomDataValue) itr.next();
Server server = value.getServer();
server.getCustomDataValues().remove(value);
SINGLETON.removeObject(value);
server.asMinionServer().ifPresent(minion -> {
MinionPillarManager.INSTANCE.generatePillar(minion, false,
MinionPillarManager.PillarSubset.CUSTOM_INFO);
});
}
SINGLETON.removeObject(keyIn);
}
/**
* Remove proxy info object associated to the server.
* @param server the server to deProxify
*/
public static void deproxify(Server server) {
if (server.getProxyInfo() != null) {
ProxyInfo info = server.getProxyInfo();
SINGLETON.removeObject(info);
server.setProxyInfo(null);
}
}
/**
* Deletes a server
*
* @param server The server to delete
*/
public static void delete(Server server) {
HibernateFactory.getSession().evict(server);
CallableMode m = ModeFactory.getCallableMode("System_queries",
"delete_server");
Map in = new HashMap();
in.put("server_id", server.getId());
m.execute(in, new HashMap());
HibernateFactory.getSession().clear();
}
private static void updateServerPerms(Server server) {
CallableMode m = ModeFactory.getCallableMode("System_queries",
"update_perms_for_server");
Map inParams = new HashMap();
inParams.put("sid", server.getId());
m.execute(inParams, new HashMap());
}
/**
* Lookup a ServerArch by its label
* @param label The label to search for
* @return The ServerArch
*/
public static ServerArch lookupServerArchByLabel(String label) {
Session session = HibernateFactory.getSession();
return (ServerArch) session.getNamedQuery("ServerArch.findByLabel")
.setString("label", label)
// Retrieve from cache if there
.setCacheable(true).uniqueResult();
}
/**
* Lookup a ServerArch by its name
* @param name The name to search for
* @return The first ServerArch found
*/
@SuppressWarnings("unchecked")
public static ServerArch lookupServerArchByName(String name) {
Map<String, Object> params = new HashMap<>();
params.put("name", name);
List<ServerArch> archs = SINGLETON.listObjectsByNamedQuery(
"ServerArch.findByName",
params);
if (archs != null && archs.size() > 0) {
return archs.get(0);
}
return null;
}
/**
* Lookup a CPUArch by its name
* @param name The name to search for
* @return The CPUArch
*/
public static CPUArch lookupCPUArchByName(String name) {
Session session = HibernateFactory.getSession();
return (CPUArch) session.getNamedQuery("CPUArch.findByName")
.setString("name", name)
// Retrieve from cache if there
.setCacheable(true).uniqueResult();
}
/**
* Returns a list of Servers which are compatible with the given server.
* @param user User owner
* @param server Server whose profiles we want.
* @return a list of Servers which are compatible with the given server.
*/
public static List<Map<String, Object>> compatibleWithServer(User user, Server server) {
SelectMode m = ModeFactory.getMode("System_queries",
"compatible_with_server");
Map<String, Object> params = new HashMap<String, Object>();
params.put("sid", server.getId());
params.put("user_id", user.getId());
return m.execute(params);
}
/**
* Returns the admins of a given server This includes
* @param server the server to find the admins of
* @return list of User objects that can administer the system
*/
public static List<User> listAdministrators(Server server) {
Map<String, Object> params = new HashMap<String, Object>();
params.put("sid", server.getId());
params.put("org_id", server.getOrg().getId());
return SINGLETON.listObjectsByNamedQuery("Server.lookupAdministrators",
params);
}
/**
* For a {@link ServerArch}, find the compatible {@link ChannelArch}.
* @param serverArch server arch
* @return channel arch
*/
public static ChannelArch findCompatibleChannelArch(ServerArch serverArch) {
Map<String, Object> params = new HashMap<>();
params.put("server_arch_id", serverArch.getId());
return (ChannelArch) SINGLETON.lookupObjectByNamedQuery("ServerArch.findCompatibleChannelArch",
params, true);
}
/**
* gets a server's history sorted by creation time. This includes items from
* the rhnServerHistory and rhnAction* tables
* @param server the server who's history you want
* @return A list of ServerHistoryEvents
*/
public static List<HistoryEvent> getServerHistory(Server server) {
SelectMode m = ModeFactory.getMode("Action_queries",
"system_events_history");
Map<String, Long> params = new HashMap<String, Long>();
params.put("sid", server.getId());
return m.execute(params);
}
/**
* List all proxies for a given org
* @param user the user, who's accessible proxies will be returned.
* @return a list of Proxy Server objects
*/
public static List<Server> lookupProxiesByOrg(User user) {
Map<String, Object> params = new HashMap<String, Object>();
params.put("userId", user.getId());
params.put("orgId", user.getOrg().getId());
List<Number> ids = SINGLETON.listObjectsByNamedQuery(
"Server.listProxies", params);
List<Server> servers = new ArrayList(ids.size());
for (Number id : ids) {
servers.add(lookupById(id.longValue()));
}
return servers;
}
/**
* Clear out all subscriptions for a particular server
* @param user User doing the un-subscription
* @param server Server that is unsubscribing
* @return new Server object showing all the new channel info.
*/
public static Server unsubscribeFromAllChannels(User user, Server server) {
UpdateBaseChannelCommand command = new UpdateBaseChannelCommand(user,
server, -1L);
ValidatorError error = command.store();
if (error != null) {
throw new ChannelSubscriptionException(error.getKey());
}
return (Server) HibernateFactory.reload(server);
}
/**
* Returns a list of Server objects currently selected in the System Set
* Manager. This list will <strong>not</strong> contain servers that are
* proxies.
*
* @param user User requesting.
* @return List of servers.
*/
public static List<Server> listSystemsInSsm(User user) {
Map<String, Object> params = new HashMap<String, Object>();
params.put("userId", user.getId());
params.put("label", RhnSetDecl.SYSTEMS.getLabel());
return SINGLETON.listObjectsByNamedQuery("Server.findInSet", params);
}
/**
* Returns a global multi org spanning list of
* servers that are config enabled.
* Basically used by taskomatic.
* @return a list of config enabled systems
*/
public static List<Server> listConfigEnabledSystems() {
return SINGLETON.listObjectsByNamedQuery(
"Server.listConfigEnabledSystems", Collections.EMPTY_MAP);
}
/**
* Returns a List of FQDNs associated to the system
* @param sid the server id to check for. Required.
* @return a list of FQDNs
*/
public static List<String> listFqdns(Long sid) {
Map<String, Object> params = new HashMap<String, Object>();
params.put("sid", sid);
return SINGLETON.listObjectsByNamedQuery("Server.listFqdns", params);
}
/**
* Lookup a Server by their FQDN
* @param name of the FQDN to search for
* @return the Server found
*/
public static Optional<Server> findByFqdn(String name) {
Map<String, Object> params = new HashMap<String, Object>();
params.put("name", name);
return Optional.ofNullable((Server) SINGLETON
.lookupObjectByNamedQuery("Server.findByFqdn", params));
}
/**
* Returns a global multi org spanning list of
* servers that are config-diff enabled.
* Basically used by taskomatic.
* @return a list of config-diff enabled systems
*/
public static List<Server> listConfigDiffEnabledSystems() {
return SINGLETON.listObjectsByNamedQuery(
"Server.listConfigDiffEnabledSystems", Collections.EMPTY_MAP);
}
/**
* List snapshots associated with a server.
*
* A user may optionally provide a start and end date to narrow the snapshots that
* will be listed. For example,
* - If user provides startDate only, all snapshots created either on or after the
* date provided will be returned
* - If user provides startDate and endDate, all snapshots created on or between the
* dates provided will be returned
* - If the user doesn't provide a startDate and endDate, all snapshots associated with
* the server will be returned.
*
* @param org the org doing the request. Required.
* @param server the server to check for. Required.
* @param startDate the start date. Optional, unless endDate is provided.
* @param endDate the end date. Optional.
* @return list of ServerSnapshot objects
*/
public static List<ServerSnapshot> listSnapshots(Org org, Server server,
Date startDate, Date endDate) {
Map<String, Object> params = new HashMap<String, Object>();
params.put("org", org);
params.put("server", server);
List<ServerSnapshot> snaps = null;
if ((startDate != null) && (endDate != null)) {
params.put("start_date", startDate);
params.put("end_date", endDate);
snaps = SINGLETON.listObjectsByNamedQuery(
"ServerSnapshot.findBetweenDates", params);
}
else if (startDate != null) {
params.put("start_date", startDate);
snaps = SINGLETON.listObjectsByNamedQuery(
"ServerSnapshot.findAfterDate", params);
}
else {
snaps = SINGLETON.listObjectsByNamedQuery(
"ServerSnapshot.findForServer", params);
}
return snaps;
}
/**
* Looks up a server snapshot by it's id
* @param id the snap id
* @return the server snapshot
*/
public static ServerSnapshot lookupSnapshotById(Integer id) {
Map<String, Object> params = new HashMap<String, Object>();
params.put("snapId", Long.valueOf(id));
return (ServerSnapshot) SINGLETON.lookupObjectByNamedQuery(
"ServerSnapshot.findById", params);
}
/**
* Looks up a latest snapshot for a sever
* @param server server
* @return the server snapshot
*/
public static ServerSnapshot lookupLatestForServer(Server server) {
Map params = new HashMap();
params.put("sid", server);