2 * Copyright (c) 2011, 2012, 2013, 2016 Spectra Logic Corporation
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
8 * 1. Redistributions of source code must retain the above copyright
9 * notice, this list of conditions, and the following disclaimer,
10 * without modification.
11 * 2. Redistributions in binary form must reproduce at minimum a disclaimer
12 * substantially similar to the "NO WARRANTY" disclaimer below
13 * ("Disclaimer") and any redistribution must be conditioned upon
14 * including a substantially similar Disclaimer requirement for further
15 * binary redistribution.
18 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR
21 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22 * HOLDERS OR CONTRIBUTORS BE LIABLE FOR SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
23 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
24 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
25 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
26 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
27 * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
28 * POSSIBILITY OF SUCH DAMAGES.
30 * Authors: Justin T. Gibbs (Spectra Logic Corporation)
36 * Implementation of the class hierarchy used to express events
37 * received via the devdctl API.
39 #include <sys/cdefs.h>
41 #include <sys/filio.h>
42 #include <sys/param.h>
63 #include "event_factory.h"
64 #include "exception.h"
66 __FBSDID("$FreeBSD$");
68 /*================================== Macros ==================================*/
69 #define NUM_ELEMENTS(x) (sizeof(x) / sizeof(*x))
71 /*============================ Namespace Control =============================*/
75 using std::stringstream;
80 /*=========================== Class Implementations ==========================*/
81 /*----------------------------------- Event ----------------------------------*/
82 //- Event Static Protected Data ------------------------------------------------
83 const string Event::s_theEmptyString;
85 Event::EventTypeRecord Event::s_typeTable[] =
87 { Event::NOTIFY, "Notify" },
88 { Event::NOMATCH, "No Driver Match" },
89 { Event::ATTACH, "Attach" },
90 { Event::DETACH, "Detach" }
93 //- Event Static Public Methods ------------------------------------------------
95 Event::Builder(Event::Type type, NVPairMap &nvPairs,
96 const string &eventString)
98 return (new Event(type, nvPairs, eventString));
102 Event::CreateEvent(const EventFactory &factory, const string &eventString)
104 NVPairMap &nvpairs(*new NVPairMap);
105 Type type(static_cast<Event::Type>(eventString[0]));
108 ParseEventString(type, eventString, nvpairs);
109 } catch (const ParseException &exp) {
110 if (exp.GetType() == ParseException::INVALID_FORMAT)
116 * Allow entries in our table for events with no system specified.
117 * These entries should specify the string "none".
119 NVPairMap::iterator system_item(nvpairs.find("system"));
120 if (system_item == nvpairs.end())
121 nvpairs["system"] = "none";
123 return (factory.Build(type, nvpairs, eventString));
127 Event::DevName(std::string &name) const
132 /* TODO: simplify this function with C++-11 <regex> methods */
134 Event::IsDiskDev() const
136 const int numDrivers = 2;
137 static const char *diskDevNames[numDrivers] =
145 if (! DevName(devName))
148 size_t find_start = devName.rfind('/');
149 if (find_start == string::npos) {
152 /* Just after the last '/'. */
156 for (dName = &diskDevNames[0];
157 dName <= &diskDevNames[numDrivers - 1]; dName++) {
159 size_t loc(devName.find(*dName, find_start));
160 if (loc == find_start) {
161 size_t prefixLen(strlen(*dName));
163 if (devName.length() - find_start >= prefixLen
164 && isdigit(devName[find_start + prefixLen]))
173 Event::TypeToString(Event::Type type)
175 EventTypeRecord *rec(s_typeTable);
176 EventTypeRecord *lastRec(s_typeTable + NUM_ELEMENTS(s_typeTable) - 1);
178 for (; rec <= lastRec; rec++) {
179 if (rec->m_type == type)
180 return (rec->m_typeName);
185 //- Event Public Methods -------------------------------------------------------
187 Event::Value(const string &varName) const
189 NVPairMap::const_iterator item(m_nvPairs.find(varName));
190 if (item == m_nvPairs.end())
191 return (s_theEmptyString);
193 return (item->second);
197 Event::Contains(const string &varName) const
199 return (m_nvPairs.find(varName) != m_nvPairs.end());
203 Event::ToString() const
207 NVPairMap::const_iterator devName(m_nvPairs.find("device-name"));
208 if (devName != m_nvPairs.end())
209 result << devName->second << ": ";
211 NVPairMap::const_iterator systemName(m_nvPairs.find("system"));
212 if (systemName != m_nvPairs.end()
213 && systemName->second != "none")
214 result << systemName->second << ": ";
216 result << TypeToString(GetType()) << ' ';
218 for (NVPairMap::const_iterator curVar = m_nvPairs.begin();
219 curVar != m_nvPairs.end(); curVar++) {
220 if (curVar == devName || curVar == systemName)
224 << curVar->first << "=" << curVar->second;
228 return (result.str());
234 cout << ToString() << std::flush;
238 Event::Log(int priority) const
240 syslog(priority, "%s", ToString().c_str());
243 //- Event Virtual Public Methods -----------------------------------------------
250 Event::DeepCopy() const
252 return (new Event(*this));
256 Event::Process() const
262 Event::GetTimestamp() const
264 timeval tv_timestamp;
265 struct tm tm_timestamp;
267 if (!Contains("timestamp")) {
268 throw Exception("Event contains no timestamp: %s",
269 m_eventString.c_str());
271 strptime(Value(string("timestamp")).c_str(), "%s", &tm_timestamp);
272 tv_timestamp.tv_sec = mktime(&tm_timestamp);
273 tv_timestamp.tv_usec = 0;
274 return (tv_timestamp);
278 Event::DevPath(std::string &path) const
282 if (!DevName(devName))
285 string devPath(_PATH_DEV + devName);
286 int devFd(open(devPath.c_str(), O_RDONLY));
290 /* Normalize the device name in case the DEVFS event is for a link. */
291 devName = fdevname(devFd);
292 path = _PATH_DEV + devName;
300 Event::PhysicalPath(std::string &path) const
304 if (!DevPath(devPath))
307 int devFd(open(devPath.c_str(), O_RDONLY));
311 char physPath[MAXPATHLEN];
313 bool result(ioctl(devFd, DIOCGPHYSPATH, physPath) == 0);
320 //- Event Protected Methods ----------------------------------------------------
321 Event::Event(Type type, NVPairMap &map, const string &eventString)
324 m_eventString(eventString)
328 Event::Event(const Event &src)
329 : m_type(src.m_type),
330 m_nvPairs(*new NVPairMap(src.m_nvPairs)),
331 m_eventString(src.m_eventString)
336 Event::ParseEventString(Event::Type type,
337 const string &eventString,
348 * <type><device-name><unit> <pnpvars> \
349 * at <location vars> <pnpvars> \
352 * Handle all data that doesn't conform to the
353 * "name=value" format, and let the generic parser
354 * below handle the rest.
356 * Type is a single char. Skip it.
359 end = eventString.find_first_of(" \t\n", start);
360 if (end == string::npos)
361 throw ParseException(ParseException::INVALID_FORMAT,
364 nvpairs["device-name"] = eventString.substr(start, end - start);
366 start = eventString.find(" on ", end);
367 if (end == string::npos)
368 throw ParseException(ParseException::INVALID_FORMAT,
371 end = eventString.find_first_of(" \t\n", start);
372 nvpairs["parent"] = eventString.substr(start, end);
377 throw ParseException(ParseException::DISCARDED_EVENT_TYPE,
380 throw ParseException(ParseException::UNKNOWN_EVENT_TYPE,
384 /* Process common "key=value" format. */
385 for (start = 1; start < eventString.length(); start = end + 1) {
387 /* Find the '=' in the middle of the key/value pair. */
388 end = eventString.find('=', start);
389 if (end == string::npos)
393 * Find the start of the key by backing up until
394 * we hit whitespace or '!' (event type "notice").
395 * Due to the devdctl format, all key/value pair must
396 * start with one of these two characters.
398 start = eventString.find_last_of("! \t\n", end);
399 if (start == string::npos)
400 throw ParseException(ParseException::INVALID_FORMAT,
403 string key(eventString.substr(start, end - start));
406 * Walk forward from the '=' until either we exhaust
407 * the buffer or we hit whitespace.
410 if (start >= eventString.length())
411 throw ParseException(ParseException::INVALID_FORMAT,
413 end = eventString.find_first_of(" \t\n", start);
414 if (end == string::npos)
415 end = eventString.length() - 1;
416 string value(eventString.substr(start, end - start));
418 nvpairs[key] = value;
423 Event::TimestampEventString(std::string &eventString)
425 if (eventString.size() > 0) {
427 * Add a timestamp as the final field of the event if it is
428 * not already present.
430 if (eventString.find(" timestamp=") == string::npos) {
431 const size_t bufsize = 32; // Long enough for a 64-bit int
433 char timebuf[bufsize];
435 size_t eventEnd(eventString.find_last_not_of('\n') + 1);
436 if (gettimeofday(&now, NULL) != 0)
437 err(1, "gettimeofday");
438 snprintf(timebuf, bufsize, " timestamp=%" PRId64,
439 (int64_t) now.tv_sec);
440 eventString.insert(eventEnd, timebuf);
445 /*-------------------------------- DevfsEvent --------------------------------*/
446 //- DevfsEvent Static Public Methods -------------------------------------------
448 DevfsEvent::Builder(Event::Type type, NVPairMap &nvPairs,
449 const string &eventString)
451 return (new DevfsEvent(type, nvPairs, eventString));
454 //- DevfsEvent Static Protected Methods ----------------------------------------
456 DevfsEvent::IsWholeDev(const string &devName)
458 string::const_iterator i(devName.begin());
460 size_t start = devName.rfind('/');
461 if (start == string::npos) {
464 /* Just after the last '/'. */
469 /* alpha prefix followed only by digits. */
470 for (; i < devName.end() && !isdigit(*i); i++)
473 if (i == devName.end())
476 for (; i < devName.end() && isdigit(*i); i++)
479 return (i == devName.end());
482 //- DevfsEvent Virtual Public Methods ------------------------------------------
484 DevfsEvent::DeepCopy() const
486 return (new DevfsEvent(*this));
490 DevfsEvent::Process() const
495 //- DevfsEvent Public Methods --------------------------------------------------
497 DevfsEvent::IsWholeDev() const
501 return (DevName(devName) && IsDiskDev() && IsWholeDev(devName));
505 DevfsEvent::DevName(std::string &name) const
507 if (Value("subsystem") != "CDEV")
510 name = Value("cdev");
511 return (!name.empty());
514 //- DevfsEvent Protected Methods -----------------------------------------------
515 DevfsEvent::DevfsEvent(Event::Type type, NVPairMap &nvpairs,
516 const string &eventString)
517 : Event(type, nvpairs, eventString)
521 DevfsEvent::DevfsEvent(const DevfsEvent &src)
526 /*--------------------------------- GeomEvent --------------------------------*/
527 //- GeomEvent Static Public Methods --------------------------------------------
529 GeomEvent::Builder(Event::Type type, NVPairMap &nvpairs,
530 const string &eventString)
532 return (new GeomEvent(type, nvpairs, eventString));
535 //- GeomEvent Virtual Public Methods -------------------------------------------
537 GeomEvent::DeepCopy() const
539 return (new GeomEvent(*this));
543 GeomEvent::DevName(std::string &name) const
545 if (Value("subsystem") == "disk")
546 name = Value("devname");
548 name = Value("cdev");
549 return (!name.empty());
553 //- GeomEvent Protected Methods ------------------------------------------------
554 GeomEvent::GeomEvent(Event::Type type, NVPairMap &nvpairs,
555 const string &eventString)
556 : Event(type, nvpairs, eventString),
557 m_devname(Value("devname"))
561 GeomEvent::GeomEvent(const GeomEvent &src)
563 m_devname(src.m_devname)
567 /*--------------------------------- ZfsEvent ---------------------------------*/
568 //- ZfsEvent Static Public Methods ---------------------------------------------
570 ZfsEvent::Builder(Event::Type type, NVPairMap &nvpairs,
571 const string &eventString)
573 return (new ZfsEvent(type, nvpairs, eventString));
576 //- ZfsEvent Virtual Public Methods --------------------------------------------
578 ZfsEvent::DeepCopy() const
580 return (new ZfsEvent(*this));
584 ZfsEvent::DevName(std::string &name) const
589 //- ZfsEvent Protected Methods -------------------------------------------------
590 ZfsEvent::ZfsEvent(Event::Type type, NVPairMap &nvpairs,
591 const string &eventString)
592 : Event(type, nvpairs, eventString),
593 m_poolGUID(Guid(Value("pool_guid"))),
594 m_vdevGUID(Guid(Value("vdev_guid")))
598 ZfsEvent::ZfsEvent(const ZfsEvent &src)
600 m_poolGUID(src.m_poolGUID),
601 m_vdevGUID(src.m_vdevGUID)
605 } // namespace DevdCtl