Merge branch 'master' into resource-container
[platform/upstream/iotivity.git] / service / resource-encapsulation / src / serverBuilder / src / RCSResourceObject.cpp
1 //******************************************************************
2 //
3 // Copyright 2015 Samsung Electronics All Rights Reserved.
4 //
5 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
6 //
7 // Licensed under the Apache License, Version 2.0 (the "License");
8 // you may not use this file except in compliance with the License.
9 // You may obtain a copy of the License at
10 //
11 //      http://www.apache.org/licenses/LICENSE-2.0
12 //
13 // Unless required by applicable law or agreed to in writing, software
14 // distributed under the License is distributed on an "AS IS" BASIS,
15 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 // See the License for the specific language governing permissions and
17 // limitations under the License.
18 //
19 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
20
21 #include "RCSResourceObject.h"
22
23 #include <string>
24 #include <functional>
25 #include <vector>
26
27 #include "RequestHandler.h"
28 #include "AssertUtils.h"
29 #include "AtomicHelper.h"
30 #include "ResourceAttributesConverter.h"
31 #include "ResourceAttributesUtils.h"
32 #include "RCSRequest.h"
33
34 #include "logger.h"
35 #include "OCPlatform.h"
36
37 #define LOG_TAG "RCSResourceObject"
38
39 namespace
40 {
41     using namespace OIC::Service;
42
43     inline bool hasProperty(uint8_t base, uint8_t target)
44     {
45         return (base & target) == target;
46     }
47
48     inline uint8_t makePropertyFlags(uint8_t base, uint8_t target, bool add)
49     {
50         if (add)
51         {
52             return base | target;
53         }
54
55         return base & ~target;
56     }
57
58     template <typename RESPONSE>
59     OCEntityHandlerResult sendResponse(RCSResourceObject& resource,
60             const std::shared_ptr< OC::OCResourceRequest >& ocRequest, RESPONSE&& response)
61     {
62         auto ocResponse = response.getHandler()->buildResponse(resource);
63         ocResponse->setRequestHandle(ocRequest->getRequestHandle());
64         ocResponse->setResourceHandle(ocRequest->getResourceHandle());
65
66         try
67         {
68             if (OC::OCPlatform::sendResponse(ocResponse) == OC_STACK_OK)
69             {
70                 return OC_EH_OK;
71             }
72         }
73         catch (const OC::OCException& e)
74         {
75             OC_LOG_V(WARNING, LOG_TAG, "Error (%s)", e.what());
76         }
77
78         return OC_EH_ERROR;
79     }
80
81     RCSResourceAttributes getAttributesFromOCRequest(
82             const std::shared_ptr< OC::OCResourceRequest >& request)
83     {
84         return ResourceAttributesConverter::fromOCRepresentation(
85                 request->getResourceRepresentation());
86     }
87
88     template< typename HANDLER, typename RESPONSE =
89             typename std::decay<HANDLER>::type::result_type >
90     RESPONSE invokeHandler(RCSResourceAttributes& attrs,
91             const std::shared_ptr< OC::OCResourceRequest >& ocRequest,
92             std::shared_ptr< HANDLER > handler)
93     {
94         if (handler)
95         {
96             return (*handler)(RCSRequest{ ocRequest->getResourceUri() }, attrs);
97         }
98
99         return RESPONSE::defaultAction();
100     }
101
102     typedef void (RCSResourceObject::* AutoNotifyFunc)
103             (bool, RCSResourceObject::AutoNotifyPolicy) const;
104
105     std::function<void()> createAutoNotifyInvoker(AutoNotifyFunc autoNotifyFunc,
106             const RCSResourceObject& resourceObject, const RCSResourceAttributes& resourceAttributes,
107             RCSResourceObject::AutoNotifyPolicy autoNotifyPolicy)
108     {
109         if(autoNotifyPolicy == RCSResourceObject::AutoNotifyPolicy::UPDATED)
110         {
111             auto&& compareAttributesFunc =
112                     std::bind(std::not_equal_to<RCSResourceAttributes>(),
113                                 resourceAttributes,
114                                 std::cref(resourceAttributes));
115             return std::bind(autoNotifyFunc,
116                     &resourceObject, std::move(compareAttributesFunc), autoNotifyPolicy);
117         }
118         else if(autoNotifyPolicy == RCSResourceObject::AutoNotifyPolicy::ALWAYS)
119         {
120             return std::bind(autoNotifyFunc,
121                     &resourceObject, true, autoNotifyPolicy);
122         }
123         return {};
124     }
125 } // unnamed namespace
126
127
128 namespace OIC
129 {
130     namespace Service
131     {
132
133         RCSResourceObject::Builder::Builder(const std::string& uri, const std::string& type,
134                 const std::string& interface) :
135                 m_uri{ uri },
136                 m_type{ type },
137                 m_interface{ interface },
138                 m_properties{ OC_DISCOVERABLE | OC_OBSERVABLE },
139                 m_resourceAttributes{ }
140         {
141         }
142
143         RCSResourceObject::Builder& RCSResourceObject::Builder::setDiscoverable(
144                 bool discoverable)
145         {
146             m_properties = ::makePropertyFlags(m_properties, OC_DISCOVERABLE, discoverable);
147             return *this;
148         }
149
150         RCSResourceObject::Builder& RCSResourceObject::Builder::setObservable(
151                 bool observable)
152         {
153             m_properties = ::makePropertyFlags(m_properties, OC_OBSERVABLE, observable);
154             return *this;
155         }
156
157         RCSResourceObject::Builder& RCSResourceObject::Builder::setAttributes(
158                 const RCSResourceAttributes& attrs)
159         {
160             m_resourceAttributes = attrs;
161             return *this;
162         }
163
164         RCSResourceObject::Builder& RCSResourceObject::Builder::setAttributes(
165                 RCSResourceAttributes&& attrs)
166         {
167             m_resourceAttributes = std::move(attrs);
168             return *this;
169         }
170
171         RCSResourceObject::Ptr RCSResourceObject::Builder::build()
172         {
173             OCResourceHandle handle{ nullptr };
174
175             RCSResourceObject::Ptr server {
176                 new RCSResourceObject{ m_properties, std::move(m_resourceAttributes) } };
177
178             OC::EntityHandler entityHandler{ std::bind(&RCSResourceObject::entityHandler,
179                     server.get(), std::placeholders::_1) };
180
181             typedef OCStackResult (*RegisterResource)(OCResourceHandle&, std::string&,
182                     const std::string&, const std::string&, OC::EntityHandler, uint8_t);
183
184             invokeOCFunc(static_cast<RegisterResource>(OC::OCPlatform::registerResource),
185                     handle, m_uri, m_type, m_interface, entityHandler, m_properties);
186
187             server->m_resourceHandle = handle;
188
189             return server;
190         }
191
192
193         RCSResourceObject::RCSResourceObject(uint8_t properties, RCSResourceAttributes&& attrs) :
194                 m_properties { properties },
195                 m_resourceHandle{ },
196                 m_resourceAttributes{ std::move(attrs) },
197                 m_getRequestHandler{ },
198                 m_setRequestHandler{ },
199                 m_autoNotifyPolicy { AutoNotifyPolicy::UPDATED },
200                 m_setRequestHandlerPolicy { SetRequestHandlerPolicy::NEVER },
201                 m_attributeUpdatedListeners{ },
202                 m_lockOwner{ },
203                 m_mutex{ },
204                 m_mutexAttributeUpdatedListeners{ }
205         {
206             m_lockOwner.reset(new AtomicThreadId);
207         }
208
209         RCSResourceObject::~RCSResourceObject()
210         {
211             if (m_resourceHandle)
212             {
213                 try
214                 {
215                     OC::OCPlatform::unregisterResource(m_resourceHandle);
216                 }
217                 catch (...)
218                 {
219                     OC_LOG(WARNING, LOG_TAG, "Failed to unregister resource.");
220                 }
221             }
222         }
223
224         template< typename K, typename V >
225         void RCSResourceObject::setAttributeInternal(K&& key, V&& value)
226         {
227             bool needToNotify = false;
228             bool valueUpdated = false;
229
230             {
231                 WeakGuard lock(*this);
232
233                 if (lock.hasLocked())
234                 {
235                     needToNotify = true;
236                     valueUpdated = testValueUpdated(key, value);
237                 }
238
239                 m_resourceAttributes[std::forward< K >(key)] = std::forward< V >(value);
240             }
241
242             if (needToNotify) autoNotify(valueUpdated);
243         }
244         void RCSResourceObject::setAttribute(const std::string& key,
245                 const RCSResourceAttributes::Value& value)
246         {
247             setAttributeInternal(key, value);
248         }
249
250         void RCSResourceObject::setAttribute(const std::string& key,
251                 RCSResourceAttributes::Value&& value)
252         {
253             setAttributeInternal(key, std::move(value));
254         }
255
256         void RCSResourceObject::setAttribute(std::string&& key,
257                 const RCSResourceAttributes::Value& value)
258         {
259             setAttributeInternal(std::move(key), value);
260         }
261
262         void RCSResourceObject::setAttribute(std::string&& key,
263                 RCSResourceAttributes::Value&& value)
264         {
265             setAttributeInternal(std::move(key), std::move(value));
266         }
267
268         RCSResourceAttributes::Value RCSResourceObject::getAttributeValue(
269                 const std::string& key) const
270         {
271             WeakGuard lock(*this);
272             return m_resourceAttributes.at(key);
273         }
274
275         bool RCSResourceObject::removeAttribute(const std::string& key)
276         {
277             bool needToNotify = false;
278             bool erased = false;
279             {
280                 WeakGuard lock(*this);
281
282                 if (m_resourceAttributes.erase(key))
283                 {
284                     erased = true;
285                     needToNotify = lock.hasLocked();
286                 }
287             }
288
289             if (needToNotify) autoNotify(true);
290
291             return erased;
292         }
293
294         bool RCSResourceObject::containsAttribute(const std::string& key) const
295         {
296             WeakGuard lock(*this);
297             return m_resourceAttributes.contains(key);
298         }
299
300         RCSResourceAttributes& RCSResourceObject::getAttributes()
301         {
302             expectOwnLock();
303             return m_resourceAttributes;
304         }
305
306         const RCSResourceAttributes& RCSResourceObject::getAttributes() const
307         {
308             expectOwnLock();
309             return m_resourceAttributes;
310         }
311
312         void RCSResourceObject::expectOwnLock() const
313         {
314             if (getLockOwner() != std::this_thread::get_id())
315             {
316                 throw NoLockException{ "Must acquire the lock first using LockGuard." };
317             }
318         }
319
320         std::thread::id RCSResourceObject::getLockOwner() const noexcept
321         {
322             return *m_lockOwner;
323         }
324
325         void RCSResourceObject::setLockOwner(std::thread::id&& id) const noexcept
326         {
327             m_lockOwner->store(std::move(id));
328         }
329
330         bool RCSResourceObject::isObservable() const
331         {
332             return ::hasProperty(m_properties, OC_OBSERVABLE);
333         }
334
335         bool RCSResourceObject::isDiscoverable() const
336         {
337             return ::hasProperty(m_properties, OC_DISCOVERABLE);
338         }
339
340         void RCSResourceObject::setGetRequestHandler(GetRequestHandler h)
341         {
342             m_getRequestHandler = std::make_shared< GetRequestHandler >(std::move(h));
343         }
344
345         void RCSResourceObject::setSetRequestHandler(SetRequestHandler h)
346         {
347             m_setRequestHandler = std::make_shared< SetRequestHandler >(std::move(h));
348         }
349
350         void RCSResourceObject::notify() const
351         {
352             typedef OCStackResult (*NotifyAllObservers)(OCResourceHandle);
353
354             invokeOCFuncWithResultExpect({ OC_STACK_OK, OC_STACK_NO_OBSERVERS },
355                     static_cast< NotifyAllObservers >(OC::OCPlatform::notifyAllObservers),
356                     m_resourceHandle);
357         }
358
359         void RCSResourceObject::addAttributeUpdatedListener(const std::string& key,
360                 AttributeUpdatedListener h)
361         {
362             std::lock_guard< std::mutex > lock(m_mutexAttributeUpdatedListeners);
363
364             m_attributeUpdatedListeners[key] =
365                     std::make_shared< AttributeUpdatedListener >(std::move(h));
366         }
367
368         void RCSResourceObject::addAttributeUpdatedListener(std::string&& key,
369                 AttributeUpdatedListener h)
370         {
371             std::lock_guard< std::mutex > lock(m_mutexAttributeUpdatedListeners);
372
373             m_attributeUpdatedListeners[std::move(key)] =
374                     std::make_shared< AttributeUpdatedListener >(std::move(h));
375         }
376
377         bool RCSResourceObject::removeAttributeUpdatedListener(const std::string& key)
378         {
379             std::lock_guard< std::mutex > lock(m_mutexAttributeUpdatedListeners);
380
381             return m_attributeUpdatedListeners.erase(key) != 0;
382         }
383
384         bool RCSResourceObject::testValueUpdated(const std::string& key,
385                 const RCSResourceAttributes::Value& value) const
386         {
387             return m_resourceAttributes.contains(key) == false
388                     || m_resourceAttributes.at(key) != value;
389         }
390
391         void RCSResourceObject::setAutoNotifyPolicy(AutoNotifyPolicy policy)
392         {
393             m_autoNotifyPolicy = policy;
394         }
395
396         RCSResourceObject::AutoNotifyPolicy RCSResourceObject::getAutoNotifyPolicy() const
397         {
398             return m_autoNotifyPolicy;
399         }
400
401         void RCSResourceObject::setSetRequestHandlerPolicy(SetRequestHandlerPolicy policy)
402         {
403             m_setRequestHandlerPolicy = policy;
404         }
405
406         auto RCSResourceObject::getSetRequestHandlerPolicy() const -> SetRequestHandlerPolicy
407         {
408             return m_setRequestHandlerPolicy;
409         }
410
411         void RCSResourceObject::autoNotify(bool isAttributesChanged) const
412         {
413             autoNotify(isAttributesChanged, m_autoNotifyPolicy);
414         }
415
416         void RCSResourceObject::autoNotify(
417                         bool isAttributesChanged, AutoNotifyPolicy autoNotifyPolicy) const
418         {
419             if(autoNotifyPolicy == AutoNotifyPolicy::NEVER) return;
420             if(autoNotifyPolicy == AutoNotifyPolicy::UPDATED &&
421                     isAttributesChanged == false) return;
422
423             notify();
424         }
425
426         OCEntityHandlerResult RCSResourceObject::entityHandler(
427                 const std::shared_ptr< OC::OCResourceRequest >& request)
428         {
429             OC_LOG(WARNING, LOG_TAG, "entityHandler");
430             if (!request)
431             {
432                 return OC_EH_ERROR;
433             }
434
435             try
436             {
437                 if (request->getRequestHandlerFlag() & OC::RequestHandlerFlag::RequestFlag)
438                 {
439                     return handleRequest(request);
440                 }
441
442                 if (request->getRequestHandlerFlag() & OC::RequestHandlerFlag::ObserverFlag)
443                 {
444                     return handleObserve(request);
445                 }
446             }
447             catch (const std::exception& e)
448             {
449                 OC_LOG_V(WARNING, LOG_TAG, "Failed to handle request : %s", e.what());
450                 throw;
451             }
452             catch (...)
453             {
454                 OC_LOG(WARNING, LOG_TAG, "Failed to handle request.");
455                 throw;
456             }
457
458             return OC_EH_ERROR;
459         }
460
461         OCEntityHandlerResult RCSResourceObject::handleRequest(
462                 const std::shared_ptr< OC::OCResourceRequest >& request)
463         {
464             assert(request != nullptr);
465
466             if (request->getRequestType() == "GET")
467             {
468                 return handleRequestGet(request);
469             }
470
471             if (request->getRequestType() == "PUT")
472             {
473                 return handleRequestSet(request);
474             }
475
476             return OC_EH_ERROR;
477         }
478
479         OCEntityHandlerResult RCSResourceObject::handleRequestGet(
480                 const std::shared_ptr< OC::OCResourceRequest >& request)
481         {
482             assert(request != nullptr);
483
484             auto attrs = getAttributesFromOCRequest(request);
485             return sendResponse(*this, request, invokeHandler(attrs, request, m_getRequestHandler));
486         }
487
488         bool RCSResourceObject::applyAcceptanceMethod(const RCSSetResponse& response,
489                 const RCSResourceAttributes& requstAttrs)
490         {
491             auto requestHandler = response.getHandler();
492
493             assert(requestHandler != nullptr);
494
495             auto replaced = requestHandler->applyAcceptanceMethod(response.getAcceptanceMethod(),
496                     *this, requstAttrs);
497
498             OC_LOG_V(WARNING, LOG_TAG, "replaced num %zu", replaced.size());
499             for (const auto& attrKeyValPair : replaced)
500             {
501                 std::shared_ptr< AttributeUpdatedListener > foundListener;
502                 {
503                     std::lock_guard< std::mutex > lock(m_mutexAttributeUpdatedListeners);
504
505                     auto it = m_attributeUpdatedListeners.find(attrKeyValPair.first);
506                     if (it != m_attributeUpdatedListeners.end())
507                     {
508                         foundListener = it->second;
509                     }
510                 }
511
512                 if (foundListener)
513                 {
514                     (*foundListener)(attrKeyValPair.second, requstAttrs.at(attrKeyValPair.first));
515                 }
516             }
517
518             return !replaced.empty();
519         }
520
521         OCEntityHandlerResult RCSResourceObject::handleRequestSet(
522                 const std::shared_ptr< OC::OCResourceRequest >& request)
523         {
524             assert(request != nullptr);
525
526             auto attrs = getAttributesFromOCRequest(request);
527             auto response = invokeHandler(attrs, request, m_setRequestHandler);
528
529             auto attrsChanged = applyAcceptanceMethod(response, attrs);
530
531             try
532             {
533                 autoNotify(attrsChanged, m_autoNotifyPolicy);
534                 return sendResponse(*this, request, response);
535             } catch (const RCSPlatformException& e) {
536                 OC_LOG_V(ERROR, LOG_TAG, "Error : %s ", e.what());
537                 return OC_EH_ERROR;
538             }
539         }
540
541         OCEntityHandlerResult RCSResourceObject::handleObserve(
542                 const std::shared_ptr< OC::OCResourceRequest >&)
543         {
544             if (!isObservable())
545             {
546                 return OC_EH_ERROR;
547             }
548
549             return OC_EH_OK;
550         }
551
552         RCSResourceObject::LockGuard::LockGuard(const RCSResourceObject::Ptr ptr) :
553                 m_resourceObject(*ptr),
554                 m_autoNotifyPolicy{ ptr->getAutoNotifyPolicy() },
555                 m_isOwningLock{ false }
556         {
557             init();
558         }
559
560         RCSResourceObject::LockGuard::LockGuard(
561                 const RCSResourceObject& serverResource) :
562                 m_resourceObject(serverResource),
563                 m_autoNotifyPolicy{ serverResource.getAutoNotifyPolicy() },
564                 m_isOwningLock{ false }
565         {
566             init();
567         }
568
569         RCSResourceObject::LockGuard::LockGuard(
570                 const RCSResourceObject::Ptr ptr, AutoNotifyPolicy autoNotifyPolicy) :
571                 m_resourceObject(*ptr),
572                 m_autoNotifyPolicy { autoNotifyPolicy },
573                 m_isOwningLock{ false }
574         {
575             init();
576         }
577
578         RCSResourceObject::LockGuard::LockGuard(
579                 const RCSResourceObject& resourceObject, AutoNotifyPolicy autoNotifyPolicy) :
580                 m_resourceObject(resourceObject),
581                 m_autoNotifyPolicy { autoNotifyPolicy },
582                 m_isOwningLock{ false }
583         {
584             init();
585         }
586
587         RCSResourceObject::LockGuard::~LockGuard() noexcept(false)
588         {
589             if (!std::uncaught_exception() && m_autoNotifyFunc) m_autoNotifyFunc();
590
591             if (m_isOwningLock)
592             {
593                 m_resourceObject.setLockOwner(std::thread::id{ });
594                 m_resourceObject.m_mutex.unlock();
595             }
596         }
597
598         void RCSResourceObject::LockGuard::init()
599         {
600             if (m_resourceObject.getLockOwner() != std::this_thread::get_id())
601             {
602                 m_resourceObject.m_mutex.lock();
603                 m_resourceObject.setLockOwner(std::this_thread::get_id());
604                 m_isOwningLock = true;
605             }
606             m_autoNotifyFunc = ::createAutoNotifyInvoker(&RCSResourceObject::autoNotify,
607                     m_resourceObject, m_resourceObject.m_resourceAttributes, m_autoNotifyPolicy);
608         }
609
610         RCSResourceObject::WeakGuard::WeakGuard(
611                 const RCSResourceObject& resourceObject) :
612                 m_isOwningLock{ false },
613                 m_resourceObject(resourceObject)
614         {
615             if (m_resourceObject.getLockOwner() != std::this_thread::get_id())
616             {
617                 m_resourceObject.m_mutex.lock();
618                 m_resourceObject.setLockOwner(std::this_thread::get_id());
619                 m_isOwningLock = true;
620             }
621         }
622
623         RCSResourceObject::WeakGuard::~WeakGuard()
624         {
625             if (m_isOwningLock)
626             {
627                 m_resourceObject.setLockOwner(std::thread::id{ });
628                 m_resourceObject.m_mutex.unlock();
629             }
630         }
631
632         bool RCSResourceObject::WeakGuard::hasLocked() const
633         {
634             return m_isOwningLock;
635         }
636
637     }
638 }