forked from Normation/rudder
-
Notifications
You must be signed in to change notification settings - Fork 0
/
NodeInfoService.scala
681 lines (600 loc) · 27.2 KB
/
NodeInfoService.scala
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
/*
*************************************************************************************
* Copyright 2011 Normation SAS
*************************************************************************************
*
* This file is part of Rudder.
*
* Rudder is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* In accordance with the terms of section 7 (7. Additional Terms.) of
* the GNU General Public License version 3, the copyright holders add
* the following Additional permissions:
* Notwithstanding to the terms of section 5 (5. Conveying Modified Source
* Versions) and 6 (6. Conveying Non-Source Forms.) of the GNU General
* Public License version 3, when you create a Related Module, this
* Related Module is not considered as a part of the work and may be
* distributed under the license agreement of your choice.
* A "Related Module" means a set of sources files including their
* documentation that, without modification of the Source Code, enables
* supplementary functions or services in addition to those offered by
* the Software.
*
* Rudder is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Rudder. If not, see <http://www.gnu.org/licenses/>.
*
*************************************************************************************
*/
package com.normation.rudder.services.nodes
import com.normation.inventory.domain._
import org.joda.time.DateTime
import com.normation.ldap.sdk.LDAPConnectionProvider
import com.normation.inventory.ldap.core.InventoryDit
import com.normation.rudder.domain.NodeDit
import net.liftweb.common._
import com.normation.rudder.domain.nodes.{Node, NodeInfo}
import com.normation.rudder.domain.RudderLDAPConstants._
import com.normation.inventory.ldap.core.LDAPConstants._
import com.unboundid.ldap.sdk._
import com.normation.ldap.sdk._
import BuildFilter._
import com.normation.rudder.repository.ldap.LDAPEntityMapper
import com.normation.inventory.ldap.core.InventoryMapper
import com.normation.rudder.domain.logger.TimingDebugLogger
import com.normation.rudder.repository.CachedRepository
import com.normation.inventory.ldap.core.InventoryDit
import com.normation.inventory.ldap.core.InventoryMapper
import com.normation.rudder.domain.Constants
import com.normation.rudder.domain.queries.And
import com.normation.rudder.domain.queries.CriterionComposition
import com.normation.rudder.domain.queries.NodeInfoMatcher
import com.normation.rudder.domain.queries.Or
/*
* General logic for the cache implementation of NodeInfo.
* The general idea is to limit at maximum:
* - the number of request to LDAP server (because I/O, slow)
* - the quantity of data on the wires.
*
* The general tactic is to have a local cache (a map of nodeid -> nodeinfo),
* and before any access, we are checking if an update is necessary with
* a very quick oracle.
* The oracle only look for at least one entry modified since the last oracle
* check, and if one is found, says the cache is dirty.
*
* We use an OpenLDAP specific query syntax to be able to perform one query
* on 3 branches (nodes, inventory node, inventory machine) in one go. As
* this is OpenLDAP specific, we had to to something a little different
* for tests, and so we don't exactly test what we are doing for real.
*
*
* Way to enhance current code:
* - make the oracle be called only every X seconds (because we can tolerate such a
* a latency in datas, and frequently, call to nodeinfoservice are done in batch
* to fill several kind of informations (it should not, but the code is like that)
* - today, when the cache is dirty, we discard it completely and rebuilt it from
* scratch. It's clearly simpler than having to diff/merge it with only dirty
* entries, but it means that the little change on one node lead to 10 000 nodeinfo
* being rebuilt (so, much data on the wires, jvm gb pression, etc).
*/
/**
* A case class used to represent the minimal
* information needed to get a NodeInfo
*/
final case class LDAPNodeInfo(
nodeEntry : LDAPEntry
, nodeInventoryEntry: LDAPEntry
, machineEntry : Option[LDAPEntry]
)
trait NodeInfoService {
/**
* Retrieve minimal information needed for the node info, used (only) by the
* LDAP QueryProcessor.
*/
def getLDAPNodeInfo(nodeIds: Set[NodeId], predicates: Seq[NodeInfoMatcher], composition: CriterionComposition) : Box[Set[LDAPNodeInfo]]
/**
* Return a NodeInfo from a NodeId. First check the ou=Node, then fetch the other data
* @param nodeId
* @return
*/
def getNodeInfo(nodeId: NodeId) : Box[Option[NodeInfo]]
/**
* Get all node infos.
* That method try to return the maximum
* of information, and will not totally fail if some information are
* missing (but the corresponding nodeInfos won't be present)
* So it is possible that getAllIds.size > getAll.size
*/
def getAll() : Box[Map[NodeId, NodeInfo]]
/**
* Get all nodes.
* That method try to return the maximum
* of information, and will not totally fail if some information are
* missing (but the corresponding nodeInfos won't be present)
* So it is possible that getAllIds.size > getAll.size
*/
def getAllNodes() : Box[Map[NodeId, Node]]
/**
* Get all systen node ids, for example
* policy server node ids.
* @return
*/
def getAllSystemNodeIds() : Box[Seq[NodeId]]
/**
* Getting something like a nodeinfo for pending / deleted nodes
*/
def getPendingNodeInfos(): Box[Map[NodeId, NodeInfo]]
def getPendingNodeInfo(nodeId: NodeId): Box[Option[NodeInfo]]
def getDeletedNodeInfos(): Box[Map[NodeId, NodeInfo]]
def getDeletedNodeInfo(nodeId: NodeId): Box[Option[NodeInfo]]
}
object NodeInfoService {
/*
* We need to list actual attributes, because we don't want software ids.
* Really bad idea, these software ids, in node...
*/
val nodeInfoAttributes: Seq[String] = (Set(
// for all: objectClass and ldap object creation datatime
A_OC, A_OBJECT_CREATION_DATE
// node
// id, name, description, isBroken, isSystem
//, isPolicyServer <- this one is special and decided based on objectClasss rudderPolicyServer
//, creationDate, nodeReportingConfiguration, properties
, A_NODE_UUID, A_NAME, A_DESCRIPTION, A_STATE, A_IS_SYSTEM
, A_SERIALIZED_AGENT_RUN_INTERVAL, A_SERIALIZED_HEARTBEAT_RUN_CONFIGURATION, A_NODE_PROPERTY, A_POLICY_MODE
// machine inventory
// MachineUuid
//, machineType <- special: from objectClass
//, systemSerial, manufacturer
, A_MACHINE_UUID, A_SERIAL_NUMBER, A_MANUFACTURER
//node inventory, safe machine and node (above)
// hostname, ips, inventoryDate, publicKey
//, osDetails
//, agentsName, policyServerId, localAdministratorAccountName
//, serverRoles, archDescription, ram, timezone
//, customProperties
, A_NODE_UUID, A_HOSTNAME, A_LIST_OF_IP, A_INVENTORY_DATE, A_PKEYS
, A_OS_NAME, A_OS_FULL_NAME, A_OS_VERSION, A_OS_KERNEL_VERSION, A_OS_SERVICE_PACK, A_WIN_USER_DOMAIN, A_WIN_COMPANY, A_WIN_KEY, A_WIN_ID
, A_AGENTS_NAME, A_POLICY_SERVER_UUID, A_ROOT_USER
, A_SERVER_ROLE, A_ARCH
, A_CONTAINER_DN, A_OS_RAM, A_KEY_STATUS, A_TIMEZONE_NAME, A_TIMEZONE_OFFSET
, A_CUSTOM_PROPERTY
)).toSeq
val A_MOD_TIMESTAMP = "modifyTimestamp"
}
/*
* For test, we need a way to split the cache part from its retrieval.
*/
// our cache is modelized with a Map of entries, their last modification timestamp, and the corresponding entryCSN
final case class LocalNodeInfoCache(
nodeInfos : Map[NodeId, (LDAPNodeInfo, NodeInfo)]
, lastModTime : DateTime
, lastModEntryCSN : Seq[String]
)
trait NodeInfoServiceCached extends NodeInfoService with Loggable with CachedRepository {
import NodeInfoService._
def ldap : LDAPConnectionProvider[RoLDAPConnection]
def nodeDit : NodeDit
def inventoryDit : InventoryDit
def removedDit : InventoryDit
def pendingDit : InventoryDit
def ldapMapper : LDAPEntityMapper
def inventoryMapper: InventoryMapper
/*
* Compare if cache is up to date (based on internal state of the cache)
*/
def isUpToDate(): Boolean = {
nodeCache match {
case Some(cache) => checkUpToDate(cache.lastModTime, cache.lastModEntryCSN)
case None => checkUpToDate(new DateTime(0), Seq())
}
}
/**
* Check is LDAP directory contains updated entries compare
* to the date we pass in arguments.
* Entries may be any entry relevant for our cache, in particular,
* some attention must be provided to deleted entries.
*/
protected[this] def checkUpToDate(lastKnowModification: DateTime, lastModEntryCSN: Seq[String]): Boolean
/**
* This method must return only and all entries under:
* - ou=Nodes,
* - ou=[Node, Machine], ou=Accepted Inventories, etc
*
* attributes is the list of attributes needed in returned entries
*/
def getNodeInfoEntries(con: RoLDAPConnection, attributes: Seq[String], status: InventoryStatus): Seq[LDAPEntry]
/*
* Our cache
*/
private[this] var nodeCache = Option.empty[LocalNodeInfoCache]
// we need modifyTimestamp to search for update and entryCSN to remove already processed entries
private[this] val searchAttributes = nodeInfoAttributes :+ A_MOD_TIMESTAMP :+ "entryCSN"
/**
* That's the method that do all the logic
*/
private[this] def withUpToDateCache[T](label: String)(useCache: Map[NodeId, (LDAPNodeInfo, NodeInfo)] => Box[T]): Box[T] = this.synchronized {
/*
* Get all relevant info from backend along with the
* date of the last modification
*/
def getDataFromBackend(lastKnowModification: DateTime): Box[LocalNodeInfoCache] = {
import scala.collection.mutable.{Map => MutMap}
//some map of things - mutable, yes
val nodes = MutMap[String, LDAPEntry]() //node_uuid -> entry
val nodeInventories = MutMap[String, LDAPEntry]() // node_uuid -> entry
val machineInventories = MutMap[String, LDAPEntry]() // machine_dn -> entry
val t0 = System.currentTimeMillis
// two vars to keep track of the new last modification time and entries csn
var lastModif = lastKnowModification
val entriesCSN = scala.collection.mutable.Buffer[String]()
ldap.flatMap { con =>
val deletedNodes = con.search(
removedDit.NODES.dn
, One
, AND(IS(OC_NODE), GTEQ(A_MOD_TIMESTAMP, GeneralizedTime(lastKnowModification).toString))
, A_MOD_TIMESTAMP , "entryCSN"
)
val allActiveEntries = getNodeInfoEntries(con, searchAttributes, AcceptedInventory)
//look for the maxed timestamp
(deletedNodes ++ allActiveEntries).foreach { e =>
e.getAsGTime(A_MOD_TIMESTAMP) match {
case None => //nothing
case Some(x) =>
if(x.dateTime.isAfter(lastModif)) {
lastModif = x.dateTime
entriesCSN.clear()
}
if(x.dateTime == lastModif) {
e("entryCSN").map(csn => entriesCSN.append(csn))
}
}
}
// now, create the nodeInfo
allActiveEntries.foreach { e =>
if(e.isA(OC_MACHINE)) {
machineInventories += (e.dn.toString -> e)
} else if(e.isA(OC_NODE)) {
nodeInventories += (e.value_!(A_NODE_UUID) -> e)
} else if(e.isA(OC_RUDDER_NODE)) {
nodes += (e.value_!(A_NODE_UUID) -> e)
} else {
// it's an error, don't use
}
}
val t1 = System.currentTimeMillis
TimingDebugLogger.debug(s"Getting node info entries: ${t1-t0}ms")
val res = nodes.flatMap { case (id, nodeEntry) =>
for {
nodeInv <- nodeInventories.get(id).orElse { //log missing elements
logger.debug(s"Node with id '${id}' is in ou=Nodes,cn=rudder-configuration but doesn't have an inventory")
None
}
machineInv = for {
containerDn <- nodeInv(A_CONTAINER_DN)
machineEntry <- machineInventories.get(containerDn)
} yield {
machineEntry
}
ldapNode = LDAPNodeInfo(nodeEntry, nodeInv, machineInv)
nodeInfo <- ldapMapper.convertEntriesToNodeInfos(ldapNode.nodeEntry, ldapNode.nodeInventoryEntry, ldapNode.machineEntry) match {
case Full(nodeInfo) => Some(nodeInfo)
case eb : EmptyBox =>
val fail = eb ?~! s"An error occured while updating node cache: can not unserialize node with id '${id}', it will be ignored"
logger.error(fail.messageChain)
// for now we only log the error message, and keep a None so Node data are not updated
None
}
} yield {
(nodeInfo.id, (ldapNode,nodeInfo))
}
}.toMap
// here, we must ensure that root ID is on the list, else chaos ensue.
// If root is missing, invalidate the case
if(res.get(Constants.ROOT_POLICY_SERVER_ID).isEmpty) {
val msg = "'root' node is missing from the list of nodes. Rudder can not work in that state. We clear the cache now to try" +
"to auto-correct the problem. If it persists, try to run 'rudder agent inventory && rudder agent run' " +
"from the root server and check /var/log/rudder/webapp/ logs for additionnal information."
logger.error(msg)
Failure(msg)
} else {
Full(LocalNodeInfoCache(res, lastModif, entriesCSN))
}
}
}
//actual logic that check what to do (invalidate cache or not)
val t0 = System.currentTimeMillis
val boxInfo = (if(nodeCache.isEmpty || !isUpToDate()) {
val lastUpdate = nodeCache.map(_.lastModTime).getOrElse(new DateTime(0))
getDataFromBackend(lastUpdate) match {
case Full(newCache) =>
logger.debug(s"NodeInfo cache is not up to date, last modification time: '${newCache.lastModTime}', last cache update:"+
s" '${lastUpdate}' => reseting cache with ${newCache.nodeInfos.size} entries")
logger.trace(s"NodeInfo cache updated entries: [${newCache.nodeInfos.keySet.map{ _.value }.mkString(", ")}]")
nodeCache = Some(newCache)
Full(newCache.nodeInfos)
case eb: EmptyBox =>
nodeCache = None
eb ?~! "Could not get node information from database"
}
} else {
logger.debug(s"NodeInfo cache is up to date, ${nodeCache.map(c => s"last modification time: '${c.lastModTime}' for: '${c.lastModEntryCSN.mkString("','")}'").getOrElse("")}")
Full(nodeCache.get.nodeInfos) //get is ok because in a synchronized block with a test on isEmpty
})
val res = for {
info <- boxInfo
x <- useCache(info)
} yield {
x
}
val t1 = System.currentTimeMillis
TimingDebugLogger.debug(s"Get node info (${label}): ${t1-t0}ms")
res
}
/**
* An utility method that gets data from backend for things that are
* node really nodes (pending or deleted).
*/
private[this] def getNotAcceptedNodeDataFromBackend(status: InventoryStatus): Box[Map[NodeId, NodeInfo]] = {
import scala.collection.mutable.{Map => MutMap}
//some map of things - mutable, yes
val nodeInventories = MutMap[String, LDAPEntry]() // node_uuid -> entry
val machineInventories = MutMap[String, LDAPEntry]() // machine_dn -> entry
ldap.map { con =>
val allEntries = getNodeInfoEntries(con, searchAttributes, status)
// now, create the nodeInfo
allEntries.foreach { e =>
if(e.isA(OC_MACHINE)) {
machineInventories += (e.dn.toString -> e)
} else if(e.isA(OC_NODE)) {
nodeInventories += (e.value_!(A_NODE_UUID) -> e)
} else {
// it's an error, don't use
}
}
nodeInventories.flatMap { case (id, nodeEntry) =>
val machineInfo = for {
containerDn <- nodeEntry(A_CONTAINER_DN)
machineEntry <- machineInventories.get(containerDn)
} yield {
machineEntry
}
for {
nodeInfo <- ldapMapper.convertEntriesToSpecialNodeInfos(nodeEntry, machineInfo)
} yield {
(nodeInfo.id, nodeInfo)
}
}.toMap
}
}
override final def getPendingNodeInfos(): Box[Map[NodeId, NodeInfo]] = getNotAcceptedNodeDataFromBackend(PendingInventory)
override final def getDeletedNodeInfos(): Box[Map[NodeId, NodeInfo]] = getNotAcceptedNodeDataFromBackend(RemovedInventory)
private[this] def getNotAcceptedNodeInfo(nodeId: NodeId, status: InventoryStatus): Box[Option[NodeInfo]] = {
val dit = status match {
case AcceptedInventory => inventoryDit
case PendingInventory => pendingDit
case RemovedInventory => removedDit
}
def sureGet(con: RoLDAPConnection, dn: DN): Box[Option[LDAPEntry]] = {
con.get(dn, searchAttributes:_*) match {
case f: Failure => f
case Empty => Full(None)
case Full(e) => Full(Some(e))
}
}
for {
con <- ldap
optNodeEntry <- sureGet(con, dit.NODES.NODE.dn(nodeId))
nodeInfo <- (optNodeEntry match {
case None => Full(None)
case Some(nodeEntry) =>
nodeEntry.getAsDn(A_CONTAINER_DN) match {
case None => Full(None)
case Some(dn) =>
for {
machineEntry <- sureGet(con, dn)
nodeInfo <- ldapMapper.convertEntriesToSpecialNodeInfos(nodeEntry, machineEntry)
} yield {
Some(nodeInfo)
}
}
})
} yield {
nodeInfo
}
}
override final def getPendingNodeInfo(nodeId: NodeId): Box[Option[NodeInfo]] = getNotAcceptedNodeInfo(nodeId, PendingInventory)
override final def getDeletedNodeInfo(nodeId: NodeId): Box[Option[NodeInfo]] = getNotAcceptedNodeInfo(nodeId, RemovedInventory)
/**
* Clear cache. Try a reload asynchronously, disregarding
* the result
*/
override def clearCache(): Unit = this.synchronized {
this.nodeCache = None
}
def getAll(): Box[Map[NodeId, NodeInfo]] = withUpToDateCache("all nodes info") { cache =>
Full(cache.mapValues(_._2))
}
def getAllSystemNodeIds(): Box[Seq[NodeId]] = withUpToDateCache("all system nodes") { cache =>
Full(cache.collect { case(k, (_,x)) if(x.isPolicyServer) => k }.toSeq)
}
def getAllNodes(): Box[Map[NodeId, Node]] = withUpToDateCache("all nodes") { cache =>
Full(cache.mapValues(_._2.node))
}
override def getLDAPNodeInfo(nodeIds: Set[NodeId], predicats: Seq[NodeInfoMatcher], composition: CriterionComposition): Box[Set[LDAPNodeInfo]] = {
def comp(a: Boolean, b: Boolean) = composition match {
case And => a && b
case Or => a || b
}
// utliity to combine predicats according to comp
def combine(a: NodeInfoMatcher, b: NodeInfoMatcher) = new NodeInfoMatcher {
override def matches(node: NodeInfo): Boolean = comp(a.matches(node), b.matches(node))
}
// if there is no predicats (ie no specific filter on NodeInfo), we don't have to filter and and we can get all Nodes information for all ids we got
val p =
if(predicats.isEmpty) {
new NodeInfoMatcher { override def matches(node: NodeInfo): Boolean = true }
} else {
predicats.reduceLeft(combine)
}
withUpToDateCache(s"${nodeIds.size} ldap node info") { cache =>
Full(cache.collect { case(k, (x,y)) if(nodeIds.contains(k) && p.matches(y)) => x }.toSet)
}
}
def getNodeInfo(nodeId: NodeId): Box[Option[NodeInfo]] = withUpToDateCache(s"${nodeId.value} node info") { cache =>
Full(cache.get(nodeId).map( _._2))
}
}
/**
* A testing implementation, that just retrieve node info each time. Not very efficient.
*/
class NaiveNodeInfoServiceCachedImpl(
override val ldap : LDAPConnectionProvider[RoLDAPConnection]
, override val nodeDit : NodeDit
, override val inventoryDit : InventoryDit
, override val removedDit : InventoryDit
, override val pendingDit : InventoryDit
, override val ldapMapper : LDAPEntityMapper
, override val inventoryMapper: InventoryMapper
) extends NodeInfoServiceCached with Loggable {
override def checkUpToDate(lastKnowModification: DateTime, lastModEntryCSN: Seq[String]): Boolean = {
false //yes naive
}
/**
* This method must return only and all entries under:
* - ou=Nodes,
* - ou=[Node, Machine], ou=Accepted Inventories, etc
*/
override def getNodeInfoEntries(con: RoLDAPConnection, searchAttributes: Seq[String], status: InventoryStatus ): Seq[LDAPEntry] = {
val nodeInvs = con.search(inventoryDit.NODES.dn, One, BuildFilter.ALL, searchAttributes:_*)
val machineInvs = con.search(inventoryDit.MACHINES.dn, One, BuildFilter.ALL, searchAttributes:_*)
nodeInvs ++ machineInvs ++ (if(status == AcceptedInventory) {
con.search(nodeDit.NODES.dn, One, BuildFilter.ALL, searchAttributes:_*)
} else {
Seq()
})
}
}
/**
* A cache on top of node info service.
*
*/
class NodeInfoServiceCachedImpl(
override val ldap : LDAPConnectionProvider[RoLDAPConnection]
, override val nodeDit : NodeDit
, override val inventoryDit : InventoryDit
, override val removedDit : InventoryDit
, override val pendingDit : InventoryDit
, override val ldapMapper : LDAPEntityMapper
, override val inventoryMapper: InventoryMapper
) extends NodeInfoServiceCached {
import NodeInfoService._
/*
* Check if node related infos are up to date.
*
* Here, we need to only check for attributeModifyTimestamp
* under ou=AcceptedInventories and under ou=Nodes (onelevel)
* and only for machines, inventory nodes, and node,
* and inventory nodes under ou=RemovedInventories
* Reason:
* - only these three entries are used for node info (and none of their
* subentries)
* - if a node is deleted, it must go to RemovedInventories (and so the
* machine, but we don't care as soon as we know a node went there)
* - for ou=Node, all modifications happen in the entry, so the modifyTimestamp
* is changed accordingly.
*
* Moreover, it is less costly to only do one search and post-filter result
* than to do 2.
*
* We also need to filter out entry in the previous last modify set to not
* have them always matching. The reason is that modifyTimestamp is on
* second. But we can have several modify in a second. If we get our
* lastModificationTimestamp in just before the second modification, that
* modification will be ignore forever (or at least until an other modification
* happens - see ticket https://www.rudder-project.org/redmine/issues/12988)
* The filter is based on entryCSN, which is sure to be unique (by def).
*
* Finally, we limit the result to one, because here, we just need to know if
* some update exists, not WHAT they are, nor the MOST RECENT one. Just that
* at least one exists.
*
* A cleaner implementation could use a two persistent search which would notify
* when a cache becomes invalide and reset it, but the rationnal for that implementation is:
* - it's extremelly simple to understand the logic (if(cache is uptodate) use it else update cache)
* - most of the time (99.99% of it), the search will return 0 result and will be cache on OpenLDAP,
* whatever the number of entries. So we talking of a request taking a couple of ms on the server
* (with a vagrant VM on the same host (so, almost no network), it takes from client to server and
* back ~10ms on a dev machine.
*/
override def checkUpToDate(lastKnowModification: DateTime, lastModEntryCSN: Seq[String]): Boolean = {
val n0 = System.currentTimeMillis
val searchRequest = new SearchRequest(nodeDit.BASE_DN.toString, Sub, DereferencePolicy.NEVER, 1, 0, false
, AND(
OR(
// ou=Removed Inventories,ou=Inventories,cn=rudder-configuration
AND(IS(OC_NODE), Filter.create(s"entryDN:dnOneLevelMatch:=${removedDit.NODES.dn.toString}"))
// ou=Accepted Inventories,ou=Inventories,cn=rudder-configuration
, AND(IS(OC_NODE), Filter.create(s"entryDN:dnOneLevelMatch:=${inventoryDit.NODES.dn.toString}"))
, AND(IS(OC_MACHINE), Filter.create(s"entryDN:dnOneLevelMatch:=${inventoryDit.MACHINES.dn.toString}"))
// ou=Nodes,cn=rudder-configuration - the objectClass is used only here
, AND(IS(OC_RUDDER_NODE), Filter.create(s"entryDN:dnOneLevelMatch:=${nodeDit.NODES.dn.toString}"))
)
, GTEQ(A_MOD_TIMESTAMP, GeneralizedTime(lastKnowModification).toString)
, NOT(OR(lastModEntryCSN.map(csn => EQ("entryCSN", csn)):_*))
)
, "1.1"
)
val res = ldap.map { con =>
//here, I have to rely on low-level LDAP connection, because I need to proceed size-limit exceeded as OK
try {
con.backed.search(searchRequest).getSearchEntries
} catch {
case e:LDAPSearchException if(e.getResultCode == ResultCode.SIZE_LIMIT_EXCEEDED) =>
e.getSearchEntries()
}
} match {
case Full(seq) =>
//we only have interesting entries in the result, so it's up to date if we have exactly 0 entries
val res = seq.size <= 0
logger.trace(s"Cache check for node info gave '${res}' (${seq.size} entry returned)")
res
case eb: EmptyBox =>
val e = eb ?~! "Error when checking for cache expiration: invalidating it"
logger.debug(e.messageChain)
false
}
val n1 = System.currentTimeMillis
TimingDebugLogger.debug(s"Cache for nodes info expire ?: ${n1-n0}ms")
res
}
/**
* This method must return only and all entries under:
* - ou=Nodes,
* - ou=[Node, Machine], ou=Accepted Inventories, etc
*/
override def getNodeInfoEntries(con: RoLDAPConnection, searchAttributes: Seq[String], status: InventoryStatus): Seq[LDAPEntry] = {
val dit = status match {
case AcceptedInventory => inventoryDit
case PendingInventory => pendingDit
case RemovedInventory => removedDit
}
val filter = Seq(
AND(IS(OC_NODE), Filter.create(s"entryDN:dnOneLevelMatch:=${dit.NODES.dn.toString}"))
, AND(IS(OC_MACHINE), Filter.create(s"entryDN:dnOneLevelMatch:=${dit.MACHINES.dn.toString}"))
) ++ (if(status == AcceptedInventory) {
Seq(AND(IS(OC_RUDDER_NODE), Filter.create(s"entryDN:dnOneLevelMatch:=${nodeDit.NODES.dn.toString}")))
} else {
Seq()
}
)
con.search(nodeDit.BASE_DN, Sub, OR(filter:_*), searchAttributes:_*)
}
}