Add () to effect-full nowMillis()
[aquarium] / src / main / scala / gr / grnet / aquarium / store / LocalFSEventStore.scala
1 /*
2  * Copyright 2011-2012 GRNET S.A. All rights reserved.
3  *
4  * Redistribution and use in source and binary forms, with or
5  * without modification, are permitted provided that the following
6  * conditions are met:
7  *
8  *   1. Redistributions of source code must retain the above
9  *      copyright notice, this list of conditions and the following
10  *      disclaimer.
11  *
12  *   2. Redistributions in binary form must reproduce the above
13  *      copyright notice, this list of conditions and the following
14  *      disclaimer in the documentation and/or other materials
15  *      provided with the distribution.
16  *
17  * THIS SOFTWARE IS PROVIDED BY GRNET S.A. ``AS IS'' AND ANY EXPRESS
18  * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
19  * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
20  * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GRNET S.A OR
21  * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
22  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
23  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
24  * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
25  * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
26  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
27  * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
28  * POSSIBILITY OF SUCH DAMAGE.
29  *
30  * The views and conclusions contained in the software and
31  * documentation are those of the authors and should not be
32  * interpreted as representing official policies, either expressed
33  * or implied, of GRNET S.A.
34  */
35
36 package gr.grnet.aquarium.store
37
38 import gr.grnet.aquarium.Configurator
39 import java.io.{FileOutputStream, File}
40 import gr.grnet.aquarium.util.{Loggable, stringOfStackTrace}
41 import gr.grnet.aquarium.util.date.{TimeHelpers, MutableDateCalc}
42 import gr.grnet.aquarium.uid.{EAIOUUIDGenerator, UIDGenerator}
43 import gr.grnet.aquarium.events.{IMEvent, ResourceEvent}
44
45 /**
46  * This is used whenever the property `events.store.folder` is setup in aquarium configuration.
47  *
48  * @author Christos KK Loverdos <loverdos@gmail.com>
49  */
50
51 object LocalFSEventStore extends Loggable {
52   private[this] final val UIDGen: UIDGenerator[_] = EAIOUUIDGenerator
53   private[this] final val NewLine  = "\n".getBytes("UTF-8")
54   private[this] final val NewLine2 = NewLine ++ NewLine
55
56   private[this] def writeToFile(file: File, data: Array[Byte], appendString: Option[String] = None): Unit = {
57     val out = new FileOutputStream(file)
58     out.write(data)
59     appendString match {
60       case Some(s) ⇒
61         out.write(NewLine2)
62         out.write(s.getBytes("UTF-8"))
63       case None ⇒
64     }
65     out.flush()
66     out.close()
67
68     logger.debug("Wrote to file {}", file.getCanonicalPath)
69   }
70
71   private[this] def createResourceEventsFolder(root: File): File = {
72     val folder = new File(root, "rc")
73     folder.mkdirs()
74     folder
75   }
76
77   private[this] def createIMEventsFolder(root: File): File = {
78     val folder = new File(root, "im")
79     folder.mkdirs()
80     folder
81   }
82
83   private[this] def writeJson(tag: String,
84                               folder: File,
85                               jsonPayload: Array[Byte],
86                               occurredString: String,
87                               uid: String,
88                               extraName: Option[String],
89                               isParsed: Boolean,
90                               appendString: Option[String] = None): Unit = {
91     val file = new File(
92       folder,
93       "%s-%s%s.%s.%s.json".format(
94         tag,
95         occurredString,
96         extraName match {
97           case Some(s) ⇒ "-" + s
98           case None    ⇒ ""
99         },
100         uid,
101         if(isParsed) "p" else "u"
102       ))
103
104     writeToFile(file, jsonPayload, appendString)
105   }
106
107   def storeUnparsedResourceEvent(mc: Configurator, initialPayload: Array[Byte], exception: Throwable): Unit = {
108     for(root <- mc.eventsStoreFolder) {
109       val uid = UIDGen.nextUID()
110       val occurredMDC = new MutableDateCalc(TimeHelpers.nowMillis())
111       val occurredString = occurredMDC.toFilename_YYYYMMDDHHMMSSSSS
112       val rcEventsFolder = createResourceEventsFolder(root)
113       val trace = stringOfStackTrace(exception)
114
115       writeJson("rc", rcEventsFolder, initialPayload, occurredString, uid, None, false, Some(trace))
116     }
117   }
118
119   def storeResourceEvent(mc: Configurator, event: ResourceEvent, initialPayload: Array[Byte]): Unit = {
120     require(event ne null, "Resource event must be not null")
121
122     for(root <- mc.eventsStoreFolder) {
123       val uid = UIDGen.nextUID()
124
125       val occurredMDC = new MutableDateCalc(event.occurredMillis)
126       val occurredString = occurredMDC.toFilename_YYYYMMDDHHMMSSSSS
127       val rcEventsFolder = createResourceEventsFolder(root)
128
129       // Store parsed file
130       writeJson(
131         "rc",
132         rcEventsFolder,
133         initialPayload,
134         occurredString,
135         uid,
136         Some("[%s]-[%s]-[%s]-[%s]".format(
137           event.id,
138           event.userID,
139           event.resource,
140           event.instanceID)),
141         true
142       )
143     }
144   }
145
146   def storeUnparsedIMEvent(mc: Configurator, initialPayload: Array[Byte], exception: Throwable): Unit = {
147     for(root <- mc.eventsStoreFolder) {
148       val uid = UIDGen.nextUID()
149       val occurredMDC = new MutableDateCalc(TimeHelpers.nowMillis())
150       val occurredString = occurredMDC.toFilename_YYYYMMDDHHMMSSSSS
151       val imEventsFolder = createIMEventsFolder(root)
152       val trace = stringOfStackTrace(exception)
153
154       writeJson("im", imEventsFolder, initialPayload, occurredString, uid, None, false, Some(trace))
155     }
156   }
157
158   def storeIMEvent(mc: Configurator, event: IMEvent, initialPayload: Array[Byte]): Unit = {
159     require(event ne null, "IM event must be not null")
160     for(root <- mc.eventsStoreFolder) {
161       val uid = UIDGen.nextUID()
162
163       val occurredMDC = new MutableDateCalc(event.occurredMillis)
164       val occurredString = occurredMDC.toFilename_YYYYMMDDHHMMSSSSS
165       val imEventsFolder = createIMEventsFolder(root)
166
167       writeJson(
168         "im",
169         imEventsFolder,
170         initialPayload,
171         occurredString,
172         uid,
173         Some("[%s]-[%s]".format(event.id, event.userID)),
174         true
175       )
176     }
177   }
178 }