Blocking.hxx 2.48 KB
Newer Older
1
/*
Max Kellermann's avatar
Max Kellermann committed
2
 * Copyright 2003-2020 The Music Player Daemon Project
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
 * http://www.musicpd.org
 *
 * This program 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 2 of the License, or
 * (at your option) any later version.
 *
 * This program 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 this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 */

#ifndef MPD_BLOCKING_NFS_CALLBACK_HXX
#define MPD_BLOCKING_NFS_CALLBACK_HXX

#include "Callback.hxx"
#include "Lease.hxx"
#include "thread/Mutex.hxx"
#include "thread/Cond.hxx"
27 28

#include <exception>
29 30 31 32 33 34 35 36 37

class NfsConnection;

/**
 * Utility class to implement a blocking NFS call using the libnfs
 * async API.  The actual method call is deferred to the #EventLoop
 * thread, and method Run() waits for completion.
 */
class BlockingNfsOperation : protected NfsCallback, NfsLease {
38 39
	static constexpr std::chrono::steady_clock::duration timeout =
		std::chrono::minutes(1);
40

41 42 43 44 45
	Mutex mutex;
	Cond cond;

	bool finished;

46
	std::exception_ptr error;
47 48 49 50 51

protected:
	NfsConnection &connection;

public:
52
	BlockingNfsOperation(NfsConnection &_connection) noexcept
53 54
		:finished(false), connection(_connection) {}

55 56 57 58
	/**
	 * Throws std::runtime_error on error.
	 */
	void Run();
59 60

private:
61
	bool LockWaitFinished() noexcept {
62
		std::unique_lock<Mutex> lock(mutex);
63
		return cond.wait_for(lock, timeout, [this]{ return finished; });
64 65 66 67 68 69
	}

	/**
	 * Mark the operation as "finished" and wake up the waiting
	 * thread.
	 */
70
	void LockSetFinished() noexcept {
71
		const std::lock_guard<Mutex> protect(mutex);
72
		finished = true;
73
		cond.notify_one();
74 75 76
	}

	/* virtual methods from NfsLease */
77 78 79
	void OnNfsConnectionReady() noexcept final;
	void OnNfsConnectionFailed(std::exception_ptr e) noexcept final;
	void OnNfsConnectionDisconnected(std::exception_ptr e) noexcept final;
80 81

	/* virtual methods from NfsCallback */
82 83
	void OnNfsCallback(unsigned status, void *data) noexcept final;
	void OnNfsError(std::exception_ptr &&e) noexcept final;
84 85

protected:
86
	virtual void Start() = 0;
87
	virtual void HandleResult(unsigned status, void *data) noexcept = 0;
88 89 90
};

#endif