source: trunk/FACT++/src/DimServiceInfoList.cc @ 10492

Last change on this file since 10492 was 10492, checked in by tbretz, 9 years ago
Return more info about statet which were not found in GetState.
File size: 23.2 KB
Line 
1// **************************************************************************
2/** @class DimServiceInfoList
3
4@brief Maintains a list of all services available in the Dim network
5
6The idea of this class is to maintain a list of services available
7in the Dim network as well as state descriptions if available.
8
9Therefore, it subscribes to the SERVICE_LIST, SERVICE_DESC and STATE_LIST
10services of all servers.
11
12To maintain the list it derives from DimServerList which maintains
13a list of all servers.
14
15To maintain the subscriptions it overwrites:
16
17- void DimServerList::AddServer(const std::string &s)
18- void DimServerList::RemoveServer(const std::string &s)
19- void DimServerList::RemoveAllServers()
20
21If a derived class also overwrites these functions it must be ensured that
22the member functions of DimServiceInfoList are still called properly.
23
24Whenever a service is added or removed, or all services of one server
25is removed the following virtual functions are called:
26
27- virtual void AddService(const std::string &server, const std::string &service, const std::string &fmt, bool iscmd)
28- virtual void RemoveService(const std::string &server, const std::string &service, bool iscmd)
29- virtual void RemoveAllServices(const std::string &server)
30
31Note, that these functions are not called from the RemoveServer() and
32RemoveAllServer() functions. It might be a difference whether all services
33were removed but the server is still online or the server went offline.
34
35If a description or a state was added, this is signaled though:
36
37- virtual void AddDescription(const std::string &server, const std::string &service, const std::vector<Description> &vec)
38- virtual void AddStates(const std::string &server, const std::vector<State> &vec)
39
40Note, that Descriptions and States are never removed except a service or
41server goes offline. It is expected that if a service comes online also
42the list of descritions is sent again.
43
44*/
45// **************************************************************************
46#include "DimServiceInfoList.h"
47
48#include <sstream>
49
50#include "WindowLog.h"
51#include "Converter.h"
52
53#include "tools.h"
54#include "Time.h"
55
56using namespace std;
57
58// --------------------------------------------------------------------------
59//
60//! A helper to shorten the call to create a DimInfo.
61//!
62//! @param str
63//!    name of the server to which we want to subscribe
64//!
65//! @param svc
66//!    name of the servic on the server to which we want to subscribe
67//!
68//! @returns
69//!    a pointer to the newly created DimInfo
70//!
71DimInfo *DimServiceInfoList::CreateDimInfo(const string &str, const string &svc) const
72{
73    return new DimInfo((str+'/'+svc).c_str(),
74                       const_cast<char*>(""),
75                       const_cast<DimServiceInfoList*>(this));
76}
77
78// --------------------------------------------------------------------------
79//
80//! Adds the service subscription for SERVICE_LIST, SERVICE_DESC and
81//! STATE_LIST for the given server. Don't forget to call this function
82//! if it is overwritten in a derived class.
83//!
84//! @param s
85//!     server which should be added
86//!
87//! @throws
88//!     a runtime_error is the server is already in the list
89//
90void DimServiceInfoList::AddServer(const string &s)
91{
92    // Check if this server is already in the list.
93    // This should never happen if Dim works reliable
94    const ServiceInfoList::iterator v = fServiceInfoList.find(s);
95    if (v!=fServiceInfoList.end())
96    {
97        stringstream err;
98        err << "Server '" << s << "' in list not as it ought to be.";
99        throw runtime_error(err.str());
100    }
101
102    fServiceInfoList[s].push_back(CreateSL(s));
103    fServiceInfoList[s].push_back(CreateFMT(s));
104    fServiceInfoList[s].push_back(CreateDS(s));
105}
106
107// --------------------------------------------------------------------------
108//
109//! Removes the service subscription for SERVICE_LIST, SERVICE_DESC and
110//! STATE_LIST for the given server, as well as the stored informations.
111//! Don't forget to call this function if it is overwritten in a derived
112//! class.
113//!
114//! @param s
115//!     server which should be removed
116//!
117//! @throws
118//!     a runtime_error is the server to be removed is not in the list
119//
120void DimServiceInfoList::RemoveServer(const string &s)
121{
122    const ServiceInfoList::iterator v = fServiceInfoList.find(s);
123    if (v==fServiceInfoList.end())
124    {
125        stringstream err;
126        err << "Server '" << s << "' not in list as it ought to be.";
127        throw runtime_error(err.str());
128    }
129
130    // Remove the server from the server list
131    delete v->second[0];
132    delete v->second[1];
133    delete v->second[2];
134
135    fServiceInfoList.erase(v);
136    fServiceList.erase(fServiceList.find(s));
137}
138
139// --------------------------------------------------------------------------
140//
141//! Removes the service subscription for SERVICE_LIST, SERVICE_DESC and
142//! STATE_LIST for all servers, as well as all stored informations.
143//! Don't forget to call this function if it is overwritten in a derived
144//! class.
145//!
146void DimServiceInfoList::RemoveAllServers()
147{
148    for (ServiceInfoList::iterator i=fServiceInfoList.begin();
149         i!=fServiceInfoList.end(); i++)
150    {
151        delete i->second[0];
152        delete i->second[1];
153        delete i->second[2];
154    }
155
156    fServiceInfoList.clear();
157    fServiceList.clear();
158}
159
160
161// --------------------------------------------------------------------------
162//
163//! This function processes the update of the SERVICE_LIST, SERVICE_DESC,
164//! and STATE_LIST updates.
165//!
166//! Whenever a service is added or removed or all services of a server are
167//! removed (the list is newly sent completely) the virtual functions
168//! AddService(), RemoveService() and RemoveAllServices() aee called.
169//!
170//! If a new description or a new state is added, the virtual functions
171//! AddDescription() and AddStates() respectively are called.
172//
173void DimServiceInfoList::infoHandler()
174{
175    // Get the name of the service
176    const string svc = getInfo()->getName();
177
178    // Get the server name from the service name
179    const string server  = svc.substr(0, svc.find_first_of('/'));
180    const string service = svc.substr(svc.find_first_of('/')+1);
181
182    if (service=="SERVICE_LIST")
183    {
184        // For easy and fast access get the corresponding reference
185        TypeList &list = fServiceList[server].first;
186
187        const string str = getInfo()->getString();
188
189        // WHAT's THIS???
190        if (str.length()==0)
191            return;
192
193        // Initialize the entry with an empty list
194        if (str[0]!='+' && str[0]!='-')
195        {
196            RemoveAllServices(server);
197            list.clear();
198        }
199
200        string buffer;
201
202        // Tokenize the stream into lines
203        stringstream stream(str);
204        while (getline(stream, buffer, '\n'))
205        {
206            if (buffer.empty())
207                continue;
208
209            // Get the type and compare it with fType
210            const string type = buffer.substr(buffer.find_last_of('|')+1);
211
212            /*
213            const bool iscmd = type=="CMD";
214            if (type!=fType && fType!="*")
215                continue;
216                */
217
218            // Get format, name and command name
219            const string fmt  = buffer.substr(buffer.find_first_of('|')+1, buffer.find_last_of('|')-buffer.find_first_of('|')-1);
220            const string name = buffer.substr(buffer.find_first_of('/')+1, buffer.find_first_of('|')-buffer.find_first_of('/')-1);
221            //const string cmd  = buffer.substr(0, buffer.find_first_of('|'));
222
223            const bool iscmd = type=="CMD";
224
225            // FIXME: Do we need to check that the buffer starts with SERVER ?
226
227            if (buffer[0]=='-')
228            {
229                // Check if this server is not found in the list.
230                // This should never happen if Dim works reliable
231                const TypeList::iterator v = list.find(name);
232                if (v==list.end())
233                {
234                    stringstream err;
235                    err << "Service '" << server << "/" << name << "' not in list as it ought to be.";
236                    throw runtime_error(err.str());
237                }
238
239                RemoveService(server, name, iscmd);
240                list.erase(v);
241
242                continue;
243            }
244
245            if (buffer[0]=='+')
246            {
247                // Check if this server is not found in the list.
248                // This should never happen if Dim works reliable
249                const TypeList::iterator v = list.find(name);
250                if (v!=list.end())
251                {
252                    stringstream err;
253                    err << "Service '" << server << "/" << name << "' already in list not as it ought to be.";
254                    throw runtime_error(err.str());
255                }
256
257                list[name] = make_pair(fmt, iscmd);
258                AddService(server, name, fmt, iscmd);
259
260                continue;
261            }
262
263            // Add name the the list
264            list[name] = make_pair(fmt, iscmd);
265            AddService(server, name, fmt, iscmd);
266        }
267
268        return;
269    }
270
271    if (service=="SERVICE_DESC")
272    {
273        // For easy and fast access get the corresponding reference
274        DescriptionList &list = fServiceList[server].second;
275
276        list.clear();
277
278        string buffer;
279
280        stringstream stream(getInfo()->getString());
281        while (getline(stream, buffer, '\n'))
282        {
283            if (buffer.empty())
284                continue;
285
286            const vector<Description> v = Description::SplitDescription(buffer);
287
288            const string name    = v[0].name.substr(v[0].name.find_first_of('/')+1);
289            const string comment = v[0].comment;
290
291            list[name] = make_pair(comment, vector<Description>(v.begin()+1, v.end()));
292
293            AddDescription(server, name, v);
294        }
295
296        return;
297    }
298
299    if (service=="STATE_LIST")
300    {
301        vector<State> &vec = fServiceList[server].third;
302        vec = State::SplitStates(getInfo()->getString());
303        AddStates(server, vec);
304
305        return;
306    }
307
308    DimServerList::infoHandler();
309}
310
311// --------------------------------------------------------------------------
312//
313//! Returns a list of all services available for the given server.
314//! Depending on iscmd either only services or only commands are returned.
315//!
316//! @param server
317//!     server for which the list should be returned
318//!
319//! @param iscmd
320//!     true if only commands should be returned, false for services
321//!
322//! @returns
323//!     a vector<string> which contains all the service or command names for
324//!     the given server. The names returned are always SERVER/SERVICE
325//!     If the server was not fund an empty vector is returned.
326//
327vector<string> DimServiceInfoList::GetServiceList(const std::string &server, bool iscmd) const
328{
329    const ServiceList::const_iterator m = fServiceList.find(server);
330    if (m==fServiceList.end())
331        return vector<string>();
332
333    const TypeList &list = m->second.first;
334
335    vector<string> vec;
336    for (TypeList::const_iterator i=list.begin(); i!=list.end(); i++)
337        if (i->second.second==iscmd)
338            vec.push_back(server+'/'+i->first);
339
340    return vec;
341}
342
343// --------------------------------------------------------------------------
344//
345//! Returns a list of all services available in the network.
346//! Depending on iscmd either only services or only commands are returned.
347//!
348//! @param iscmd
349//!     true if only commands should be returned, false for services
350//!
351//! @returns
352//!     a vector<string> which contains all the service or command names in
353//!     the network. The names returned are always SERVER/SERVICE
354//
355vector<string> DimServiceInfoList::GetServiceList(bool iscmd) const
356{
357    vector<string> vec;
358    for (ServiceList::const_iterator m=fServiceList.begin(); m!=fServiceList.end(); m++)
359    {
360        const TypeList &list = m->second.first;
361
362        for (TypeList::const_iterator i=list.begin(); i!=list.end(); i++)
363            if (i->second.second==iscmd)
364                vec.push_back(m->first+'/'+i->first);
365    }
366
367    return vec;
368}
369
370// --------------------------------------------------------------------------
371//
372//! Returns a list of all descriptions for the given service on the
373//! given server. Service in this context can also be a command.
374//!
375//! @param server
376//!     Server name to look for
377//!
378//! @param service
379//!     Service/command name to look for
380//!
381//! @returns
382//!     a vector<Description> which contains all argument descriptions for
383//!     the given service or command. The first entry contains the name
384//!     and the general description for the given service. If the server
385//!     or service was not found an empty vector is returned.
386//
387std::vector<Description> DimServiceInfoList::GetDescription(const std::string &server, const std::string &service) const
388{
389    const ServiceList::const_iterator s = fServiceList.find(server);
390    if (s==fServiceList.end())
391        return vector<Description>();
392
393    const DescriptionList &descs = s->second.second;
394
395    const DescriptionList::const_iterator d = descs.find(service);
396    if (d==descs.end())
397        return vector<Description>();
398
399    vector<Description> vec;
400    vec.push_back(Description(service, d->second.first));
401    vec.insert(vec.end(), d->second.second.begin(), d->second.second.end());
402
403    return vec;
404}
405
406// --------------------------------------------------------------------------
407//
408//! Returns a list of all states associated with the given server.
409//!
410//! @param server
411//!     Server name to look for
412//!
413//! @returns
414//!     a vector<State> which contains all state descriptions for
415//!     the given server. If the server or service was not found an
416//!     empty vector is returned.
417//
418vector<State> DimServiceInfoList::GetStates(const std::string &server) const
419{
420    const ServiceList::const_iterator s = fServiceList.find(server);
421    if (s==fServiceList.end())
422        return vector<State>();
423
424    return s->second.third;
425}
426
427// --------------------------------------------------------------------------
428//
429//! Returns the Description of the state as defined by the arguments.
430//! given server. Service in this context can also be a command.
431//!
432//! @param server
433//!     Server name to look for
434//!
435//! @param state
436//!     The state index to look for (e.g. 1)
437//!
438//! @returns
439//!     The State object containing the description. If the server was
440//!     not found the State object will contain the index -3, if the
441//!     state was not found -2.
442//
443State DimServiceInfoList::GetState(const std::string &server, int state) const
444{
445    const ServiceList::const_iterator s = fServiceList.find(server);
446    if (s==fServiceList.end())
447    {
448        stringstream str;
449        str << "DimServiceInfoList::GetState: Searching for state #" << state << " server " << server << " not found.";
450        return State(-3, "Server not found", str.str());
451    }
452
453    const std::vector<State> &v = s->second.third;
454
455    for (vector<State>::const_iterator i=v.begin(); i!=v.end(); i++)
456        if (i->index==state)
457            return *i;
458
459    stringstream str;
460    str << "DimServiceInfoList::GetState: State #" << state << " not found on server " << server << ".";
461    return State(-2, "State not found", str.str());
462}
463
464// --------------------------------------------------------------------------
465//
466//! Returns whether the given service on the given server is a command
467//! or not.
468//!
469//! @param server
470//!     Server name to look for
471//!
472//! @param service
473//!     The service name to look for
474//!
475//! @returns
476//!     1 if it is a command, 0 if it is a service, -1 if the service
477//!     was not found on the server, -2 if the server was not found.
478//
479int DimServiceInfoList::IsCommand(const std::string &server, const std::string &service) const
480{
481    const ServiceList::const_iterator s = fServiceList.find(server);
482    if (s==fServiceList.end())
483        return -2;
484
485    const TypeList &list = s->second.first;
486
487    const TypeList::const_iterator t = list.find(service);
488    if (t==list.end())
489        return -1;
490
491    return t->second.second;
492}
493
494
495// --------------------------------------------------------------------------
496//
497//! Print the full available documentation (description) of all available
498//! services or comments to the the given stream.
499//!
500//! @param out
501//!    ostream to which the output is send.
502//!
503//! @param iscmd
504//!   true if all commands should be printed, false for services.
505//!
506//! @param serv
507//!    if a server is given, only the information for this server is printed
508//!
509//! @param service
510//!    if a service is given, only information for this service is printed
511//!
512//! @returns
513//!    the number of descriptions found
514//
515int DimServiceInfoList::PrintDescription(std::ostream &out, bool iscmd, const string &serv, const string &service) const
516{
517    int rc = 0;
518    for (ServiceList::const_iterator i=fServiceList.begin(); i!=fServiceList.end(); i++)
519    {
520        const string &server = i->first;
521
522        if (!serv.empty() && server!=serv)
523            continue;
524
525        out << kRed << "----- " << server << " -----" << endl;
526
527        const TypeList        &types = i->second.first;
528        const DescriptionList &descs = i->second.second;
529
530        for (TypeList::const_iterator t=types.begin(); t!=types.end(); t++)
531        {
532            if (!service.empty() && t->first!=service)
533                continue;
534
535            if (t->second.second!=iscmd)
536                continue;
537
538            rc++;
539
540            out << " " << t->first;
541
542            // Check t->second->first for command or service
543            const string fmt = t->second.first;
544            if (!fmt.empty())
545                out << '[' << fmt << ']';
546
547            const DescriptionList::const_iterator d = descs.find(t->first);
548            if (d==descs.end())
549            {
550                out << endl;
551                continue;
552            }
553
554            const string comment         = d->second.first;
555            const vector<Description> &v = d->second.second;
556
557            for (vector<Description>::const_iterator j=v.begin(); j!=v.end(); j++)
558                out << " <" << j->name << ">";
559            out << endl;
560
561            if (!comment.empty())
562                out << "    " << comment << endl;
563
564            for (vector<Description>::const_iterator j=v.begin(); j!=v.end(); j++)
565            {
566                out << "    " << kGreen << j->name;
567                if (!j->comment.empty())
568                    out << kReset << ": " << kBlue << j->comment;
569                if (!j->unit.empty())
570                    out << kYellow << " [" << j->unit << "]";
571                out << endl;
572            }
573        }
574        out << endl;
575    }
576
577    return rc;
578}
579
580// --------------------------------------------------------------------------
581//
582//! Print the full list of stated for the given server.
583//!
584//! @param out
585//!    ostream to which the output is send.
586//!
587//! @param serv
588//!    if a server is given, only the information for this server is printed
589//!
590//! @returns
591//!    the number of states found
592//
593int DimServiceInfoList::PrintStates(std::ostream &out, const string &serv) const
594{
595    int rc = 0;
596    for (ServiceList::const_iterator i=fServiceList.begin(); i!=fServiceList.end(); i++)
597    {
598        const string &server = i->first;
599
600        if (!serv.empty() && server!=serv)
601            continue;
602
603        out << kRed << "----- " << server << " -----" << endl;
604
605        const vector<State> &v = i->second.third;
606
607        if (v.size()==0)
608            out << "   <no states>" << endl;
609        else
610            rc++;
611
612        for (vector<State>::const_iterator s=v.begin(); s!=v.end(); s++)
613        {
614            out << kBold   << setw(5) << s->index << kReset << ": ";
615            out << kYellow << s->name;
616            out << kBlue   << " (" << s->comment << ")" << endl;
617        }
618        out << endl;
619    }
620
621    return rc;
622}
623
624
625// --------------------------------------------------------------------------
626//
627//! Tries to send a dim command according to the arguments.
628//! The command given is evaluated according to the available format string.
629//!
630//! @param server
631//!    The name of the server to which the command should be send, e.g. DRIVE
632//!
633//! @param str
634//!    Command and data, eg "TRACK 12.5 13.8"
635//!
636//! @param lout
637//!    the ostream to which errors and debug output is redirected
638//!
639//! @throws
640//!    runtime_error if the server or command was not found, or if the
641//!    format associated with the command could not be properly parsed,
642//!    or if the command could not successfully be emitted.
643//!
644void DimServiceInfoList::SendDimCommand(const string &server, string str, ostream &lout) const
645{
646    str = Tools::Trim(str);
647
648    // Find the delimiter between the command name and the data
649    size_t p0 = str.find_first_of(' ');
650    if (p0==string::npos)
651        p0 = str.length();
652
653    // Get just the command name separated from the data
654    const string name = str.substr(0, p0);
655
656    // Compile the command which will be sent to the state-machine
657    const string cmd = server + '/' + name;
658
659    const ServiceList::const_iterator m = fServiceList.find(server);
660    if (m==fServiceList.end())
661        throw runtime_error("Unkown server '"+server+"'");
662
663    const TypeList &services = m->second.first;
664
665    const TypeList::const_iterator t = services.find(name);
666    if (t==services.end())
667        throw runtime_error("Command '"+name+"' not known on server '"+server+"'");
668
669    if (!t->second.second)
670        throw runtime_error("'"+server+"/"+name+" not a command.");
671
672    // Get the format of the event data
673    const string fmt = t->second.first;
674
675    // Convert the user entered data according to the format string
676    // into a data block which will be attached to the event
677    const Converter conv(lout, fmt, false);
678    if (!conv)
679        throw runtime_error("Couldn't properly parse the format... ignored.");
680
681    lout << kBlue << cmd;
682    const vector<char> v = conv.GetVector(str.substr(p0));
683    lout << endl;
684
685    const int rc = DimClient::sendCommand(cmd.c_str(), (void*)v.data(), v.size());
686    if (!rc)
687        throw runtime_error("ERROR - Sending command "+cmd+" failed.");
688}
689
690// --------------------------------------------------------------------------
691//
692//! Catches the runtime_erros thrown by
693//!    SendDimCommand(const string &, string, ostream &)
694//! and redirects the error message to the output stream.
695//!
696//! @param lout
697//!    the ostream to which errors and debug output is redirected
698//!
699//! @param server
700//!    The name of the server to which the command should be send, e.g. DRIVE
701//!
702//! @param str
703//!    Command and data, eg "TRACK 12.5 13.8"
704//!
705//! @returns
706//!    true if SendDimComment didn't throw an exception, false otherwise
707//!
708bool DimServiceInfoList::SendDimCommand(ostream &lout, const string &server, const string &str) const
709{
710    try
711    {
712        SendDimCommand(server, str, lout);
713        lout << kGreen << "Command emitted successfully to " << server << "." << endl;
714        return true;
715    }
716    catch (const runtime_error &e)
717    {
718        lout << kRed << e.what() << endl;
719        return false;
720    }
721}
722
723// --------------------------------------------------------------------------
724//
725//! Calls SendDimCommand(const string &, string, ostream &) and dumps
726//! the output.
727//!
728//! @param server
729//!    The name of the server to which the command should be send, e.g. DRIVE
730//!
731//! @param str
732//!    Command and data, eg "TRACK 12.5 13.8"
733//!
734//! @throws
735//!    see SendDimCommand(const string &, string, ostream &)
736//
737void DimServiceInfoList::SendDimCommand(const std::string &server, const std::string &str) const
738{
739    ostringstream dummy;
740    SendDimCommand(server, str, dummy);
741}
Note: See TracBrowser for help on using the repository browser.