1 /*
2    Copyright (c) 2009-2017, Intel Corporation
3    All rights reserved.
4 
5    Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
6 
7  * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
8  * 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.
9  * Neither the name of Intel Corporation nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
10 
11  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 MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR 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.
12  */
13 // written by Steven Briscoe
14 
15 #include <cstdlib>
16 #include <iostream>
17 #include <unistd.h>
18 #include <sys/types.h>
19 #include <sys/ipc.h>
20 #include <sys/shm.h>
21 #include <errno.h>
22 #include <sstream>
23 #include <exception>
24 #include <stdexcept>
25 #include <grp.h>
26 #include <stdio.h>
27 #include <stdlib.h>
28 
29 #include "../daemon/common.h"
30 #include "client.h"
31 
32 namespace PCMDaemon {
33 
Client()34 	Client::Client()
35 	: pollIntervalMs_(0), shmIdLocation_(DEFAULT_SHM_ID_LOCATION), shmAttached_(false), lastUpdatedClientTsc_(0)
36 	{}
37 
setSharedMemoryIdLocation(const std::string & location)38 	void Client::setSharedMemoryIdLocation(const std::string& location)
39 	{
40 		if(shmAttached_)
41 		{
42 			throw std::runtime_error("Shared memory segment already attached. You must call this method before the .connect() method.");
43 		}
44 		shmIdLocation_ = location;
45 	}
46 
setPollInterval(int pollMs)47 	void Client::setPollInterval(int pollMs)
48 	{
49 		pollIntervalMs_ = pollMs;
50 	}
51 
connect()52 	void Client::connect()
53 	{
54 		setupSharedMemory();
55 
56 		//Set last updated timestamp to avoid a detected change
57 		//when the client starts
58 		lastUpdatedClientTsc_ = sharedPCMState_->lastUpdateTscEnd;
59 	}
60 
read()61 	PCMDaemon::SharedPCMState& Client::read()
62 	{
63 		if(pollIntervalMs_ <= 0)
64 		{
65 			throw std::runtime_error("The poll interval is not set or is negative.");
66 		}
67 
68 		if(!shmAttached_)
69 		{
70 			throw std::runtime_error("Not attached to shared memory segment. Call .connect() method.");
71 		}
72 
73 		while(true)
74 		{
75 			// Check client version matches daemon version
76 			if(strlen(sharedPCMState_->version) > 0 && strcmp(sharedPCMState_->version, VERSION) != 0)
77 			{
78 				std::cout << sharedPCMState_->lastUpdateTscEnd << " " << lastUpdatedClientTsc_ << "\n";
79 				std::stringstream ss;
80 				ss << "Out of date PCM daemon client. Client version: " << VERSION << " Daemon version: " << sharedPCMState_->version;
81 
82 				throw std::runtime_error(ss.str());
83 			}
84 
85 			if(countersHaveUpdated())
86 			{
87 				//There is new data
88 				lastUpdatedClientTsc_ = sharedPCMState_->lastUpdateTscEnd;
89 
90 				return *sharedPCMState_;
91 			}
92 			else
93 			{
94 				//Nothing has changed since we last checked
95 				usleep(pollIntervalMs_ * 1000);
96 			}
97 		}
98 	}
99 
countersHaveUpdated()100 	bool Client::countersHaveUpdated()
101 	{
102 		return lastUpdatedClientTsc_ != sharedPCMState_->lastUpdateTscEnd;
103 	}
104 
setupSharedMemory()105 	void Client::setupSharedMemory()
106 	{
107 		int sharedMemoryId;
108 		FILE *fp = fopen (shmIdLocation_.c_str(), "r");
109 		if (!fp)
110 		{
111 			std::cerr << "Failed to open to shared memory key location: " << shmIdLocation_ << "\n";
112 			exit(EXIT_FAILURE);
113 		}
114 		int maxCharsToRead = 11;
115 		char readBuffer[maxCharsToRead];
116 		fread(&readBuffer, maxCharsToRead, 1, fp);
117 		fclose (fp);
118 
119 		sharedMemoryId = atoi(readBuffer);
120 
121 		sharedPCMState_ = (PCMDaemon::SharedPCMState*)shmat(sharedMemoryId, NULL, 0);
122 		if (sharedPCMState_ == (void *)-1)
123 		{
124 			std::stringstream ss;
125 			ss << "Failed to attach shared memory segment (errno=" << errno << ")";
126 
127 			throw std::runtime_error(ss.str());
128 		}
129 
130 		shmAttached_ = true;
131 	}
132 
133 }
134