aboutsummaryrefslogtreecommitdiff
path: root/cddl/usr.sbin/zfsd/zfsd_event.cc
blob: 688e7c0354a280c38831f8bc4d173b9c91fcd33e (plain) (blame)
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
/*-
 * Copyright (c) 2011, 2012, 2013, 2014, 2016 Spectra Logic Corporation
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions, and the following disclaimer,
 *    without modification.
 * 2. Redistributions in binary form must reproduce at minimum a disclaimer
 *    substantially similar to the "NO WARRANTY" disclaimer below
 *    ("Disclaimer") and any redistribution must be conditioned upon
 *    including a substantially similar Disclaimer requirement for further
 *    binary redistribution.
 *
 * NO WARRANTY
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * HOLDERS OR CONTRIBUTORS BE LIABLE FOR 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 DAMAGES.
 *
 * Authors: Justin T. Gibbs     (Spectra Logic Corporation)
 */

/**
 * \file zfsd_event.cc
 */
#include <sys/cdefs.h>
#include <sys/byteorder.h>
#include <sys/time.h>
#include <sys/fs/zfs.h>
#include <sys/vdev_impl.h>

#include <syslog.h>

#include <libzfs.h>
#include <libzutil.h>
/* 
 * Undefine flush, defined by cpufunc.h on sparc64, because it conflicts with
 * C++ flush methods
 */
#undef   flush
#undef	__init
#include <list>
#include <map>
#include <sstream>
#include <string>

#include <devdctl/guid.h>
#include <devdctl/event.h>
#include <devdctl/event_factory.h>
#include <devdctl/exception.h>
#include <devdctl/consumer.h>

#include "callout.h"
#include "vdev_iterator.h"
#include "zfsd_event.h"
#include "case_file.h"
#include "vdev.h"
#include "zfsd.h"
#include "zfsd_exception.h"
#include "zpool_list.h"

__FBSDID("$FreeBSD$");
/*============================ Namespace Control =============================*/
using DevdCtl::Event;
using DevdCtl::Guid;
using DevdCtl::NVPairMap;
using std::stringstream;

/*=========================== Class Implementations ==========================*/

/*-------------------------------- GeomEvent --------------------------------*/

//- GeomEvent Static Public Methods -------------------------------------------
Event *
GeomEvent::Builder(Event::Type type,
		   NVPairMap &nvPairs,
		   const string &eventString)
{
	return (new GeomEvent(type, nvPairs, eventString));
}

//- GeomEvent Virtual Public Methods ------------------------------------------
Event *
GeomEvent::DeepCopy() const
{
	return (new GeomEvent(*this));
}
 
bool
GeomEvent::Process() const
{
	/*
	 * We only use GEOM events to repair damaged pools.  So return early if
	 * there are no damaged pools
	 */
	if (CaseFile::Empty())
		return (false);

	/*
	 * We are only concerned with arrivals and physical path changes,
	 * because those can be used to satisfy online and autoreplace
	 * operations
	 */
	if (Value("type") != "GEOM::physpath" && Value("type") != "CREATE")
		return (false);

	/* Log the event since it is of interest. */
	Log(LOG_INFO);

	string devPath;
	if (!DevPath(devPath))
		return (false);

	int devFd(open(devPath.c_str(), O_RDONLY));
	if (devFd == -1)
		return (false);

	bool inUse;
	bool degraded;
	nvlist_t *devLabel(ReadLabel(devFd, inUse, degraded));

	string physPath;
        bool havePhysPath(PhysicalPath(physPath));

	string devName;
	DevName(devName);
	close(devFd);

	if (inUse && devLabel != NULL) {
		OnlineByLabel(devPath, physPath, devLabel);
	} else if (degraded) {
		syslog(LOG_INFO, "%s is marked degraded.  Ignoring "
		       "as a replace by physical path candidate.\n",
		       devName.c_str());
	} else if (havePhysPath) {
		/* 
		 * TODO: attempt to resolve events using every casefile
		 * that matches this physpath
		 */
		CaseFile *caseFile(CaseFile::Find(physPath));
		if (caseFile != NULL) {
			syslog(LOG_INFO,
			       "Found CaseFile(%s:%s:%s) - ReEvaluating\n",
			       caseFile->PoolGUIDString().c_str(),
			       caseFile->VdevGUIDString().c_str(),
			       zpool_state_to_name(caseFile->VdevState(),
						   VDEV_AUX_NONE));
			caseFile->ReEvaluate(devPath, physPath, /*vdev*/NULL);
		}
	}
	return (false);
}

//- GeomEvent Protected Methods -----------------------------------------------
GeomEvent::GeomEvent(Event::Type type, NVPairMap &nvpairs,
			       const string &eventString)
 : DevdCtl::GeomEvent(type, nvpairs, eventString)
{
}

GeomEvent::GeomEvent(const GeomEvent &src)
 : DevdCtl::GeomEvent::GeomEvent(src)
{
}

nvlist_t *
GeomEvent::ReadLabel(int devFd, bool &inUse, bool &degraded)
{
	pool_state_t poolState;
	char        *poolName;
	boolean_t    b_inuse;
	int          nlabels;

	inUse    = false;
	degraded = false;
	poolName = NULL;
	if (zpool_in_use(g_zfsHandle, devFd, &poolState,
			 &poolName, &b_inuse) == 0) {
		nvlist_t *devLabel = NULL;

		inUse = b_inuse == B_TRUE;
		if (poolName != NULL)
			free(poolName);

		if (zpool_read_label(devFd, &devLabel, &nlabels) != 0)
			return (NULL);
		/*
		 * If we find a disk with fewer than the maximum number of
		 * labels, it might be the whole disk of a partitioned disk
		 * where ZFS resides on a partition.  In that case, we should do
		 * nothing and wait for the partition to appear.  Or, the disk
		 * might be damaged.  In that case, zfsd should do nothing and
		 * wait for the sysadmin to decide.
		 */
		if (nlabels != VDEV_LABELS || devLabel == NULL) {
			nvlist_free(devLabel);
			return (NULL);
		}

		try {
			Vdev vdev(devLabel);
			degraded = vdev.State() != VDEV_STATE_HEALTHY;
			return (devLabel);
		} catch (ZfsdException &exp) {
			string devName = fdevname(devFd);
			string devPath = _PATH_DEV + devName;
			string context("GeomEvent::ReadLabel: "
				     + devPath + ": ");

			exp.GetString().insert(0, context);
			exp.Log();
			nvlist_free(devLabel);
		}
	}
	return (NULL);
}

bool
GeomEvent::OnlineByLabel(const string &devPath, const string& physPath,
			      nvlist_t *devConfig)
{
	try {
		/*
		 * A device with ZFS label information has been
		 * inserted.  If it matches a device for which we
		 * have a case, see if we can solve that case.
		 */
		syslog(LOG_INFO, "Interrogating VDEV label for %s\n",
		       devPath.c_str());
		Vdev vdev(devConfig);
		CaseFile *caseFile(CaseFile::Find(vdev.PoolGUID(),
						  vdev.GUID()));
		if (caseFile != NULL)
			return (caseFile->ReEvaluate(devPath, physPath, &vdev));

	} catch (ZfsdException &exp) {
		string context("GeomEvent::OnlineByLabel: " + devPath + ": ");

		exp.GetString().insert(0, context);
		exp.Log();
	}
	return (false);
}


/*--------------------------------- ZfsEvent ---------------------------------*/
//- ZfsEvent Static Public Methods ---------------------------------------------
DevdCtl::Event *
ZfsEvent::Builder(Event::Type type, NVPairMap &nvpairs,
		  const string &eventString)
{
	return (new ZfsEvent(type, nvpairs, eventString));
}

//- ZfsEvent Virtual Public Methods --------------------------------------------
Event *
ZfsEvent::DeepCopy() const
{
	return (new ZfsEvent(*this));
}

bool
ZfsEvent::Process() const
{
	string logstr("");

	if (!Contains("class") && !Contains("type")) {
		syslog(LOG_ERR,
		       "ZfsEvent::Process: Missing class or type data.");
		return (false);
	}

	/* On config syncs, replay any queued events first. */
	if (Value("type").find("misc.fs.zfs.config_sync") == 0) {
		/*
		 * Even if saved events are unconsumed the second time
		 * around, drop them.  Any events that still can't be
		 * consumed are probably referring to vdevs or pools that
		 * no longer exist.
		 */
		ZfsDaemon::Get().ReplayUnconsumedEvents(/*discard*/true);
		CaseFile::ReEvaluateByGuid(PoolGUID(), *this);
	}

	if (Value("type").find("misc.fs.zfs.") == 0) {
		/* Configuration changes, resilver events, etc. */
		ProcessPoolEvent();
		return (false);
	}

	if (!Contains("pool_guid") || !Contains("vdev_guid")) {
		/* Only currently interested in Vdev related events. */
		return (false);
	}

	CaseFile *caseFile(CaseFile::Find(PoolGUID(), VdevGUID()));
	if (caseFile != NULL) {
		Log(LOG_INFO);
		syslog(LOG_INFO, "Evaluating existing case file\n");
		caseFile->ReEvaluate(*this);
		return (false);
	}

	/* Skip events that can't be handled. */
	Guid poolGUID(PoolGUID());
	/* If there are no replicas for a pool, then it's not manageable. */
	if (Value("class").find("fs.zfs.vdev.no_replicas") == 0) {
		stringstream msg;
		msg << "No replicas available for pool "  << poolGUID;
		msg << ", ignoring";
		Log(LOG_INFO);
		syslog(LOG_INFO, "%s", msg.str().c_str());
		return (false);
	}

	/*
	 * Create a case file for this vdev, and have it
	 * evaluate the event.
	 */
	ZpoolList zpl(ZpoolList::ZpoolByGUID, &poolGUID);
	if (zpl.empty()) {
		stringstream msg;
		int priority = LOG_INFO;
		msg << "ZfsEvent::Process: Event for unknown pool ";
		msg << poolGUID << " ";
		msg << "queued";
		Log(LOG_INFO);
		syslog(priority, "%s", msg.str().c_str());
		return (true);
	}

	nvlist_t *vdevConfig = VdevIterator(zpl.front()).Find(VdevGUID());
	if (vdevConfig == NULL) {
		stringstream msg;
		int priority = LOG_INFO;
		msg << "ZfsEvent::Process: Event for unknown vdev ";
		msg << VdevGUID() << " ";
		msg << "queued";
		Log(LOG_INFO);
		syslog(priority, "%s", msg.str().c_str());
		return (true);
	}

	Vdev vdev(zpl.front(), vdevConfig);
	caseFile = &CaseFile::Create(vdev);
	if (caseFile->ReEvaluate(*this) == false) {
		stringstream msg;
		int priority = LOG_INFO;
		msg << "ZfsEvent::Process: Unconsumed event for vdev(";
		msg << zpool_get_name(zpl.front()) << ",";
		msg << vdev.GUID() << ") ";
		msg << "queued";
		Log(LOG_INFO);
		syslog(priority, "%s", msg.str().c_str());
		return (true);
	}
	return (false);
}

//- ZfsEvent Protected Methods -------------------------------------------------
ZfsEvent::ZfsEvent(Event::Type type, NVPairMap &nvpairs,
			   const string &eventString)
 : DevdCtl::ZfsEvent(type, nvpairs, eventString)
{
}

ZfsEvent::ZfsEvent(const ZfsEvent &src)
 : DevdCtl::ZfsEvent(src)
{
}

/*
 * Sometimes the kernel won't detach a spare when it is no longer needed.  This
 * can happen for example if a drive is removed, then either the pool is
 * exported or the machine is powered off, then the drive is reinserted, then
 * the machine is powered on or the pool is imported.  ZFSD must detach these
 * spares itself.
 */
void
ZfsEvent::CleanupSpares() const
{
	Guid poolGUID(PoolGUID());
	ZpoolList zpl(ZpoolList::ZpoolByGUID, &poolGUID);
	if (!zpl.empty()) {
		zpool_handle_t* hdl;

		hdl = zpl.front();
		VdevIterator(hdl).Each(TryDetach, (void*)hdl);
	}
}

void
ZfsEvent::ProcessPoolEvent() const
{
	bool degradedDevice(false);

	/* The pool is destroyed.  Discard any open cases */
	if (Value("type") == "misc.fs.zfs.pool_destroy") {
		Log(LOG_INFO);
		CaseFile::ReEvaluateByGuid(PoolGUID(), *this);
		return;
	}

	CaseFile *caseFile(CaseFile::Find(PoolGUID(), VdevGUID()));
	if (caseFile != NULL) {
		if (caseFile->VdevState() != VDEV_STATE_UNKNOWN
		 && caseFile->VdevState() < VDEV_STATE_HEALTHY)
			degradedDevice = true;

		Log(LOG_INFO);
		caseFile->ReEvaluate(*this);
	}
	else if (Value("type") == "misc.fs.zfs.resilver_finish")
	{
		/*
		 * It's possible to get a resilver_finish event with no
		 * corresponding casefile.  For example, if a damaged pool were
		 * exported, repaired, then reimported.
		 */
		Log(LOG_INFO);
		CleanupSpares();
	}

	if (Value("type") == "misc.fs.zfs.vdev_remove"
	 && degradedDevice == false) {

		/* See if any other cases can make use of this device. */
		Log(LOG_INFO);
		ZfsDaemon::RequestSystemRescan();
	}
}

bool
ZfsEvent::TryDetach(Vdev &vdev, void *cbArg)
{
	/*
	 * Outline:
	 * if this device is a spare, and its parent includes one healthy,
	 * non-spare child, then detach this device.
	 */
	zpool_handle_t *hdl(static_cast<zpool_handle_t*>(cbArg));

	if (vdev.IsSpare()) {
		std::list<Vdev> siblings;
		std::list<Vdev>::iterator siblings_it;
		boolean_t cleanup = B_FALSE;

		Vdev parent = vdev.Parent();
		siblings = parent.Children();

		/* Determine whether the parent should be cleaned up */
		for (siblings_it = siblings.begin();
		     siblings_it != siblings.end();
		     siblings_it++) {
			Vdev sibling = *siblings_it;

			if (!sibling.IsSpare() &&
			     sibling.State() == VDEV_STATE_HEALTHY) {
				cleanup = B_TRUE;
				break;
			}
		}

		if (cleanup) {
			syslog(LOG_INFO, "Detaching spare vdev %s from pool %s",
			       vdev.Path().c_str(), zpool_get_name(hdl));
			zpool_vdev_detach(hdl, vdev.Path().c_str());
		}

	}

	/* Always return false, because there may be other spares to detach */
	return (false);
}