aboutsummaryrefslogtreecommitdiffstatshomepage
path: root/OpenSim/Region/DataSnapshot/SnapshotStore.cs
blob: 7e2c06075ff2d892fb602b9198e80141d6c56fcc (plain)
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
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*     * Redistributions of source code must retain the above copyright
*       notice, this list of conditions and the following disclaimer.
*     * Redistributions in binary form must reproduce the above copyright
*       notice, this list of conditions and the following disclaimer in the
*       documentation and/or other materials provided with the distribution.
*     * Neither the name of the OpenSim Project nor the
*       names of its contributors may be used to endorse or promote products
*       derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
* 
*/

using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;
using System.IO;
using OpenSim.Region.Environment.Scenes;
using OpenSim.Region.DataSnapshot.Interfaces;
using libsecondlife;

namespace OpenSim.Region.DataSnapshot
{
    public class SnapshotStore
    {
        #region Class Members
        private String m_directory = "unyuu"; //not an attempt at adding RM references to core SVN, honest
        private Dictionary<Scene, bool> m_scenes = null;
        private List<IDataSnapshotProvider> m_providers = null;
        private log4net.ILog m_log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
        private Dictionary<String, String> m_gridinfo = null;
        private bool m_cacheEnabled = true;
        private string m_listener_port = "9000"; //TODO: Set default port over 9000
        private string m_hostname = "127.0.0.1";
        #endregion

        public SnapshotStore(string directory, Dictionary<String, String> gridinfo, string port, string hostname) {
            m_directory = directory;
            m_scenes = new Dictionary<Scene, bool>();
            m_providers = new List<IDataSnapshotProvider>();
            m_gridinfo = gridinfo;
            m_listener_port = port;
            m_hostname = hostname;

            if (Directory.Exists(m_directory))
            {
                m_log.Info("[DATASNAPSHOT]: Repsonse and fragment cache directory already exists.");
            }
            else
            {
                // Try to create the directory.
                m_log.Info("[DATASNAPSHOT]: Creating directory " + m_directory);
                try
                {
                    Directory.CreateDirectory(m_directory);
                }
                catch (Exception e)
                {
                    m_log.Error("[DATASNAPSHOT]: Failed to create directory " + m_directory, e);

                    //This isn't a horrible problem, just disable cacheing.
                    m_cacheEnabled = false;
                    m_log.Error("[DATASNAPSHOT]: Could not create directory, response cache has been disabled.");
                }
            }
        }

        public void ForceSceneStale(Scene scene) {
            m_scenes[scene] = true;
        }

        #region Fragment storage
        public XmlNode GetFragment(IDataSnapshotProvider provider, XmlDocument factory)
        {
            XmlNode data = null;

            if (provider.Stale || !m_cacheEnabled)
            {
                data = provider.RequestSnapshotData(factory);

                if (m_cacheEnabled)
                {
                    String path = DataFileNameFragment(provider.GetParentScene, provider.Name);

                    using (XmlTextWriter snapXWriter = new XmlTextWriter(path, Encoding.Default))
                    {
                        snapXWriter.Formatting = Formatting.Indented;
                        snapXWriter.WriteStartDocument();
                        data.WriteTo(snapXWriter);
                        snapXWriter.WriteEndDocument();
                    }
                }

                //mark provider as not stale, parent scene as stale
                provider.Stale = false;
                m_scenes[provider.GetParentScene] = true;

                m_log.Info("[DATASNAPSHOT]: Generated fragment response for provider type " + provider.Name);
            }
            else
            {
                String path = DataFileNameFragment(provider.GetParentScene, provider.Name);

                XmlDocument fragDocument = new XmlDocument();
                fragDocument.PreserveWhitespace = true;
                fragDocument.Load(path);
                foreach (XmlNode node in fragDocument)
                {
                    data = factory.ImportNode(node, true);
                }

                m_log.Info("[DATASNAPSHOT]: Retrieved fragment response for provider type " + provider.Name);
            }

            return data;
        }
        #endregion

        #region Response storage
        public XmlNode GetScene(Scene scene, XmlDocument factory)
        {
            m_log.Debug("[DATASNAPSHOT]: Data requested for scene " + scene.RegionInfo.RegionName);

            if (!m_scenes.ContainsKey(scene)) {
                m_scenes.Add(scene, true); //stale by default
            }

            XmlNode regionElement = null;

            if (!m_scenes[scene])
            {
                m_log.Info("[DATASNAPSHOT]: Attempting to retrieve snapshot from cache.");
                //get snapshot from cache
                String path = DataFileNameScene(scene);

                XmlDocument fragDocument = new XmlDocument();
                fragDocument.PreserveWhitespace = true;

                fragDocument.Load(path);

                foreach (XmlNode node in fragDocument)
                {
                    regionElement = factory.ImportNode(node, true);
                }

                m_log.Info("[DATASNAPSHOT]: Obtained snapshot from cache for " + scene.RegionInfo.RegionName);
            }
            else
            {
                m_log.Info("[DATASNAPSHOT]: Attempting to generate snapshot.");
                //make snapshot
                regionElement = MakeRegionNode(scene, factory);

                regionElement.AppendChild(GetGridSnapshotData(factory));
                XmlNode regionData = factory.CreateNode(XmlNodeType.Element, "data", "");

                foreach (IDataSnapshotProvider dataprovider in m_providers)
                {
                    if (dataprovider.GetParentScene == scene)
                    {
                        regionData.AppendChild(GetFragment(dataprovider, factory));
                    }
                }

                regionElement.AppendChild(regionData);

                factory.AppendChild(regionElement);

                //save snapshot
                String path = DataFileNameScene(scene);

                using (XmlTextWriter snapXWriter = new XmlTextWriter(path, Encoding.Default))
                {
                    snapXWriter.Formatting = Formatting.Indented;
                    snapXWriter.WriteStartDocument();
                    regionElement.WriteTo(snapXWriter);
                    snapXWriter.WriteEndDocument();
                }

                m_scenes[scene] = false;

                m_log.Info("[DATASNAPSHOT]: Generated new snapshot for " + scene.RegionInfo.RegionName);
            }

            return regionElement;
        }

        #endregion

        #region Helpers
        private string DataFileNameFragment(Scene scene, String fragmentName)
        {
            return Path.Combine(m_directory, Path.ChangeExtension(scene.RegionInfo.RegionName + "_" + fragmentName, "xml"));
        }

        private string DataFileNameScene(Scene scene)
        {
            return Path.Combine(m_directory, Path.ChangeExtension(scene.RegionInfo.RegionName, "xml"));
            //return (m_snapsDir + Path.DirectorySeparatorChar + scene.RegionInfo.RegionName + ".xml");
        }

        private XmlNode MakeRegionNode(Scene scene, XmlDocument basedoc)
        {
            XmlNode docElement = basedoc.CreateNode(XmlNodeType.Element, "region", "");

            XmlAttribute attr = basedoc.CreateAttribute("category");
            attr.Value = GetRegionCategory(scene);
            docElement.Attributes.Append(attr);

            attr = basedoc.CreateAttribute("entities");
            attr.Value = scene.Entities.Count.ToString();
            docElement.Attributes.Append(attr);

            //attr = basedoc.CreateAttribute("parcels");
            //attr.Value = scene.LandManager.landList.Count.ToString();
            //docElement.Attributes.Append(attr);


            XmlNode infoblock = basedoc.CreateNode(XmlNodeType.Element, "info", "");

            XmlNode infopiece = basedoc.CreateNode(XmlNodeType.Element, "uuid", "");
            infopiece.InnerText = scene.RegionInfo.RegionID.ToString();
            infoblock.AppendChild(infopiece);

            infopiece = basedoc.CreateNode(XmlNodeType.Element, "url", "");
            infopiece.InnerText = "http://" + m_hostname + ":" + m_listener_port;
            infoblock.AppendChild(infopiece);

            infopiece = basedoc.CreateNode(XmlNodeType.Element, "name", "");
            infopiece.InnerText = scene.RegionInfo.RegionName;
            infoblock.AppendChild(infopiece);

            docElement.AppendChild(infoblock);

            m_log.Debug("[DATASNAPSHOT]: Generated region node");
            return docElement;
        }

        private String GetRegionCategory(Scene scene)
        {

            //Boolean choice between:
            //  "PG" - Mormontown
            //  "Mature" - Sodom and Gomorrah
            //  (Depreciated) "Patriotic Nigra Testing Sandbox" - Abandon Hope All Ye Who Enter Here
            if ((scene.RegionInfo.EstateSettings.simAccess & Simulator.SimAccess.Mature) == Simulator.SimAccess.Mature)
            {
                return "Mature";
            }
            else if ((scene.RegionInfo.EstateSettings.simAccess & Simulator.SimAccess.PG) == Simulator.SimAccess.PG)
            {
                return "PG";
            }
            else
            {
                return "Unknown";
            }
        }

        private XmlNode GetGridSnapshotData(XmlDocument factory)
        {
            XmlNode griddata = factory.CreateNode(XmlNodeType.Element, "grid", "");

            foreach (KeyValuePair<String, String> GridData in m_gridinfo)
            {
                //TODO: make it lowercase tag names for diva
                XmlNode childnode = factory.CreateNode(XmlNodeType.Element, GridData.Key, "");
                childnode.InnerText = GridData.Value;
                griddata.AppendChild(childnode);
            }

            m_log.Debug("[DATASNAPSHOT]: Got grid snapshot data");

            return griddata;
        }
        #endregion

        #region Manage internal collections
        public void AddScene(Scene newScene)
        {
            m_scenes.Add(newScene, true);
        }

        public void RemoveScene(Scene deadScene)
        {
            m_scenes.Remove(deadScene);
        }

        public void AddProvider(IDataSnapshotProvider newProvider)
        {
            m_providers.Add(newProvider);
        }

        public void RemoveProvider(IDataSnapshotProvider deadProvider)
        {
            m_providers.Remove(deadProvider);
        }
        #endregion
    }
}