Esempio n. 1
0
void mscb_define(char *submaster, char *equipment, char *devname, DEVICE_DRIVER *driver,
                 int address, unsigned char var_index, char *name, double threshold)
{
   int i, dev_index, chn_index, chn_total;
   char str[256];
   float f_threshold;
   HNDLE hDB;

   cm_get_experiment_database(&hDB, NULL);
//printf(hDB+"\n");
   if (submaster && submaster[0]) {
      sprintf(str, "/Equipment/%s/Settings/Devices/%s/Device", equipment, devname);
      db_set_value(hDB, 0, str, submaster, 32, 1, TID_STRING);
      sprintf(str, "/Equipment/%s/Settings/Devices/%s/Pwd", equipment, devname);
      db_set_value(hDB, 0, str, "mscb174", 32, 1, TID_STRING);
   }

   /* find device in device driver */
   for (dev_index=0 ; driver[dev_index].name[0] ; dev_index++)
      if (equal_ustring(driver[dev_index].name, devname))
         break;

   if (!driver[dev_index].name[0]) {
      cm_msg(MERROR, "Device \"%s\" not present in device driver list", devname);
      return;
   }

   /* count total number of channels */
   for (i=chn_total=0 ; i<=dev_index ; i++)
      chn_total += driver[i].channels;

   chn_index = driver[dev_index].channels;
   sprintf(str, "/Equipment/%s/Settings/Devices/%s/MSCB Address", equipment, devname);
   db_set_value_index(hDB, 0, str, &address, sizeof(int), chn_index, TID_INT, TRUE);
   sprintf(str, "/Equipment/%s/Settings/Devices/%s/MSCB Index", equipment, devname);
   db_set_value_index(hDB, 0, str, &var_index, sizeof(char), chn_index, TID_BYTE, TRUE);

   if (threshold != -1) {
     sprintf(str, "/Equipment/%s/Settings/Update Threshold", equipment);
     f_threshold = (float) threshold;
     db_set_value_index(hDB, 0, str, &f_threshold, sizeof(float), chn_total, TID_FLOAT, TRUE);
   }

   if (name && name[0]) {
      sprintf(str, "/Equipment/%s/Settings/Names Input", equipment);
      db_set_value_index(hDB, 0, str, name, 32, chn_total, TID_STRING, TRUE);
   }

   /* increment number of channels for this driver */
   driver[dev_index].channels++;
}
Esempio n. 2
0
File: cd_fgd.c Progetto: cjpl/midas
INT fgd_init(EQUIPMENT * pequipment)
{
   int status, size, i, j, index, offset;
   char str[256];
   HNDLE hDB, hKey, hNames, hThreshold;
   FGD_INFO *fgd_info;

   /* allocate private data */
   pequipment->cd_info = calloc(1, sizeof(FGD_INFO));
   fgd_info = (FGD_INFO *) pequipment->cd_info;

   /* get class driver root key */
   cm_get_experiment_database(&hDB, NULL);
   sprintf(str, "/Equipment/%s", pequipment->name);
   db_create_key(hDB, 0, str, TID_KEY);
   db_find_key(hDB, 0, str, &fgd_info->hKeyRoot);

   /* save event format */
   size = sizeof(str);
   db_get_value(hDB, fgd_info->hKeyRoot, "Common/Format", str, &size, TID_STRING, TRUE);

   if (equal_ustring(str, "Fixed"))
      fgd_info->format = FORMAT_FIXED;
   else if (equal_ustring(str, "MIDAS"))
      fgd_info->format = FORMAT_MIDAS;
   else if (equal_ustring(str, "YBOS"))
      fgd_info->format = FORMAT_YBOS;

   /* count total number of channels */
   for (i = 0, fgd_info->num_channels = 0; pequipment->driver[i].name[0]; i++) {
      if (pequipment->driver[i].channels == 0) {
         cm_msg(MERROR, "fgd_init", "Driver with zero channels not allowed");
         return FE_ERR_ODB;
      }

      fgd_info->num_channels += pequipment->driver[i].channels;
   }

   if (fgd_info->num_channels == 0) {
      cm_msg(MERROR, "fgd_init", "No channels found in device driver list");
      return FE_ERR_ODB;
   }

   /* Allocate memory for buffers */
   fgd_info->names = (char *) calloc(fgd_info->num_channels, NAME_LENGTH);

   fgd_info->demand = (float *) calloc(fgd_info->num_channels, sizeof(float));
   fgd_info->measured = (float *) calloc(fgd_info->num_channels, sizeof(float));

   fgd_info->temp1 = (float *) calloc(fgd_info->num_channels, sizeof(float));
   fgd_info->temp2 = (float *) calloc(fgd_info->num_channels, sizeof(float));
   fgd_info->temp3 = (float *) calloc(fgd_info->num_channels, sizeof(float));

   fgd_info->update_threshold = (float *) calloc(fgd_info->num_channels, sizeof(float));

   fgd_info->demand_mirror = (float *) calloc(fgd_info->num_channels, sizeof(float));
   fgd_info->measured_mirror = (float *) calloc(fgd_info->num_channels, sizeof(float));

   fgd_info->channel_offset = (INT *) calloc(fgd_info->num_channels, sizeof(INT));
   fgd_info->driver = (void *) calloc(fgd_info->num_channels, sizeof(void *));

   if (!fgd_info->driver) {
      cm_msg(MERROR, "hv_init", "Not enough memory");
      return FE_ERR_ODB;
   }

   /*---- Initialize device drivers ----*/

   /* call init method */
   for (i = 0; pequipment->driver[i].name[0]; i++) {
      sprintf(str, "Settings/Devices/%s", pequipment->driver[i].name);
      status = db_find_key(hDB, fgd_info->hKeyRoot, str, &hKey);
      if (status != DB_SUCCESS) {
         db_create_key(hDB, fgd_info->hKeyRoot, str, TID_KEY);
         status = db_find_key(hDB, fgd_info->hKeyRoot, str, &hKey);
         if (status != DB_SUCCESS) {
            cm_msg(MERROR, "hv_init", "Cannot create %s entry in online database", str);
            free_mem(fgd_info);
            return FE_ERR_ODB;
         }
      }

      status = device_driver(&pequipment->driver[i], CMD_INIT, hKey);
      if (status != FE_SUCCESS) {
         free_mem(fgd_info);
         return status;
      }
   }

   /* compose device driver channel assignment */
   for (i = 0, j = 0, index = 0, offset = 0; i < fgd_info->num_channels; i++, j++) {
      while (j >= pequipment->driver[index].channels && pequipment->driver[index].name[0]) {
         offset += j;
         index++;
         j = 0;
      }

      fgd_info->driver[i] = &pequipment->driver[index];
      fgd_info->channel_offset[i] = offset;
   }

   /*---- create demand variables ----*/
   /* get demand from ODB */
   status =
       db_find_key(hDB, fgd_info->hKeyRoot, "Variables/Demand", &fgd_info->hKeyDemand);
   if (status == DB_SUCCESS) {
      size = sizeof(float) * fgd_info->num_channels;
      db_get_data(hDB, fgd_info->hKeyDemand, fgd_info->demand, &size, TID_FLOAT);
   }
   /* let device driver overwrite demand values, if it supports it */
   for (i = 0; i < fgd_info->num_channels; i++) {
      if (fgd_info->driver[i]->flags & DF_PRIO_DEVICE) {
         device_driver(fgd_info->driver[i], CMD_GET_DEMAND,
                       i - fgd_info->channel_offset[i], &fgd_info->demand[i]);
         fgd_info->demand_mirror[i] = fgd_info->demand[i];
      } else
         fgd_info->demand_mirror[i] = -12345.f; /* use -12345 as invalid value */
   }
   /* write back demand values */
   status =
       db_find_key(hDB, fgd_info->hKeyRoot, "Variables/Demand", &fgd_info->hKeyDemand);
   if (status != DB_SUCCESS) {
      db_create_key(hDB, fgd_info->hKeyRoot, "Variables/Demand", TID_FLOAT);
      db_find_key(hDB, fgd_info->hKeyRoot, "Variables/Demand", &fgd_info->hKeyDemand);
   }
   size = sizeof(float) * fgd_info->num_channels;
   db_set_data(hDB, fgd_info->hKeyDemand, fgd_info->demand, size,
               fgd_info->num_channels, TID_FLOAT);
   db_open_record(hDB, fgd_info->hKeyDemand, fgd_info->demand,
                  fgd_info->num_channels * sizeof(float), MODE_READ, fgd_demand,
                  pequipment);

   /*---- create measured variables ----*/
   db_merge_data(hDB, fgd_info->hKeyRoot, "Variables/Current Measured",
                 fgd_info->measured, sizeof(float) * fgd_info->num_channels,
                 fgd_info->num_channels, TID_FLOAT);
   db_find_key(hDB, fgd_info->hKeyRoot, "Variables/Current Measured", &fgd_info->hKeyMeasured);
   memcpy(fgd_info->measured_mirror, fgd_info->measured,
          fgd_info->num_channels * sizeof(float));

   /*---- create Temp1 measured variables ----*/
   db_merge_data(hDB, fgd_info->hKeyRoot, "Variables/Temp1",
                 fgd_info->temp1, sizeof(float) * fgd_info->num_channels,
                 fgd_info->num_channels, TID_FLOAT);
   db_find_key(hDB, fgd_info->hKeyRoot, "Variables/Temp1", &fgd_info->hKeyTemp1);

   /*---- create Temp2 measured variables ----*/
   db_merge_data(hDB, fgd_info->hKeyRoot, "Variables/Temp2",
                 fgd_info->temp2, sizeof(float) * fgd_info->num_channels,
                 fgd_info->num_channels, TID_FLOAT);
   db_find_key(hDB, fgd_info->hKeyRoot, "Variables/Temp2", &fgd_info->hKeyTemp2);

   /*---- create Temp3 measured variables ----*/
   db_merge_data(hDB, fgd_info->hKeyRoot, "Variables/Temp3",
                 fgd_info->temp3, sizeof(float) * fgd_info->num_channels,
                 fgd_info->num_channels, TID_FLOAT);
   db_find_key(hDB, fgd_info->hKeyRoot, "Variables/Temp3", &fgd_info->hKeyTemp3);

   /*---- get default names from device driver ----*/
   for (i = 0; i < fgd_info->num_channels; i++) {
      sprintf(fgd_info->names + NAME_LENGTH * i, "Default%%CH %d", i);
      device_driver(fgd_info->driver[i], CMD_GET_LABEL,
                    i - fgd_info->channel_offset[i], fgd_info->names + NAME_LENGTH * i);
   }
   db_merge_data(hDB, fgd_info->hKeyRoot, "Settings/Names",
                 fgd_info->names, NAME_LENGTH * fgd_info->num_channels,
                 fgd_info->num_channels, TID_STRING);

   /*---- set labels form midas SC names ----*/
   for (i = 0; i < fgd_info->num_channels; i++) {
      fgd_info = (FGD_INFO *) pequipment->cd_info;
      device_driver(fgd_info->driver[i], CMD_SET_LABEL,
                    i - fgd_info->channel_offset[i], fgd_info->names + NAME_LENGTH * i);
   }

   /* open hotlink on channel names */
   if (db_find_key(hDB, fgd_info->hKeyRoot, "Settings/Names", &hNames) == DB_SUCCESS)
      db_open_record(hDB, hNames, fgd_info->names, NAME_LENGTH*fgd_info->num_channels,
                     MODE_READ, fgd_update_label, pequipment);

   /*---- get default update threshold from device driver ----*/
   for (i = 0; i < fgd_info->num_channels; i++) {
      fgd_info->update_threshold[i] = 1.f;      /* default 1 unit */
      device_driver(fgd_info->driver[i], CMD_GET_THRESHOLD,
                    i - fgd_info->channel_offset[i], &fgd_info->update_threshold[i]);
   }
   db_merge_data(hDB, fgd_info->hKeyRoot, "Settings/Update Threshold Measured",
                 fgd_info->update_threshold, sizeof(float)*fgd_info->num_channels,
                 fgd_info->num_channels, TID_FLOAT);

   /* open hotlink on update threshold */
   if (db_find_key(hDB, fgd_info->hKeyRoot, "Settings/Update Threshold Measured", &hThreshold) == DB_SUCCESS)
     db_open_record(hDB, hThreshold, fgd_info->update_threshold, sizeof(float)*fgd_info->num_channels,
		    MODE_READ, NULL, NULL);
   
   /*---- set initial demand values ----*/
   // fgd_demand(hDB, fgd_info->hKeyDemand, pequipment);

   /* initially read all channels */
   for (i = 0; i < fgd_info->num_channels; i++)
      fgd_read(pequipment, i);

   return FE_SUCCESS;
}
Esempio n. 3
0
INT submit_elog(char *host, int port, int ssl, char *subdir, char *experiment,
                char *uname, char *upwd,
                int reply,
                int quote_on_reply,
                int edit,
                int download,
                int suppress,
                int encoding,
                char attrib_name[MAX_N_ATTR][NAME_LENGTH],
                char attrib[MAX_N_ATTR][NAME_LENGTH],
                int n_attr,
                char *text, char afilename[MAX_ATTACHMENTS][256],
                char *buffer[MAX_ATTACHMENTS], INT buffer_size[MAX_ATTACHMENTS])
/********************************************************************\

  Routine: submit_elog

  Purpose: Submit an ELog entry

  Input:
    char   *host            Host name where ELog server runs
    in     port             ELog server port number
    int    ssl              SSL flag
    char   *subdir          Subdirectoy to elog server
    char   *uname           User name
    char   *upwd            User password
    int    reply            Reply to existing message
    int    edit             Edit existing message
    int    download         Download existing message
    int    suppress         Suppress Email notification
    int    encoding         0:ELCode,1:plain,2:HTML
    char   *attrib_name     Attribute names
    char   *attrib          Attribute values
    char   *text            Message text

    char   afilename[]      File names of attachments
    char   *buffer[]        Attachment contents
    INT    buffer_size[]    Size of buffer in bytes

  Function value:
    EL_SUCCESS              Successful completion

\********************************************************************/
{
   int status, sock, i, n, header_length, content_length, index;
   char host_name[256], boundary[80], str[80], encrypted_passwd[256], *p, *old_encoding;
   char old_attrib_name[MAX_N_ATTR+1][NAME_LENGTH], old_attrib[MAX_N_ATTR+1][NAME_LENGTH];
   struct hostent *phe;
#ifdef HAVE_SSL
   SSL *ssl_con = NULL;
#endif

   /* get local host name */
   gethostname(host_name, sizeof(host_name));

   phe = gethostbyname(host_name);
   if (phe == NULL) {
      perror("Cannot retrieve host name");
      return -1;
   }
   phe = gethostbyaddr(phe->h_addr, sizeof(int), AF_INET);
   if (phe == NULL) {
      perror("Cannot retrieve host name");
      return -1;
   }

   /* if domain name is not in host name, hope to get it from phe */
   if (strchr(host_name, '.') == NULL)
      strcpy(host_name, phe->h_name);

   if (edit || download) {
      if (edit)
         status = retrieve_elog(host, port, subdir, ssl, experiment, uname, upwd, edit,
                                old_attrib_name, old_attrib, old_text);
      else
         status = retrieve_elog(host, port, subdir, ssl, experiment, uname, upwd, download,
                                old_attrib_name, old_attrib, old_text);

      if (status != 1)
         return status;

      /* update attributes */
      for (index = 0; index < n_attr; index++) {
         for (i = 0; i < MAX_N_ATTR && old_attrib_name[i][0]; i++)
            if (equal_ustring(attrib_name[index], old_attrib_name[i]))
               break;

         if (old_attrib_name[i][0])
            strlcpy(old_attrib[i], attrib[index], NAME_LENGTH);
      }

      /* copy attributes */
      for (i = 0; i < MAX_N_ATTR && old_attrib_name[i][0]; i++) {
         strlcpy(attrib_name[i], old_attrib_name[i], NAME_LENGTH);
         strlcpy(attrib[i], old_attrib[i], NAME_LENGTH);
      }

      n_attr = i;

      if (text[0] == 0)
         strlcpy(text, old_text, TEXT_SIZE);
   }
   
   if (download) {
      if (strstr(response, "$@MID@$:"))
         printf("%s", strstr(response, "$@MID@$:"));
      else
         printf("%s", response);
      return 1;
   }

   if (reply) {
      status =
          retrieve_elog(host, port, subdir, ssl, experiment, uname, upwd, reply,
                        old_attrib_name, old_attrib, old_text);

      if (status != 1)
         return status;

      /* update attributes */
      for (index = 0; index < n_attr; index++) {
         for (i = 0; i < MAX_N_ATTR && old_attrib_name[i][0]; i++)
            if (equal_ustring(attrib_name[index], old_attrib_name[i]))
               break;

         if (old_attrib_name[i][0])
            strlcpy(old_attrib[i], attrib[index], NAME_LENGTH);
      }

      /* copy attributes */
      for (i = 0; i < MAX_N_ATTR && old_attrib_name[i][0]; i++) {
         if (equal_ustring(old_attrib_name[i], "Reply to") || equal_ustring(old_attrib_name[i], "Date")) {
            attrib_name[i][0] = 0;
            attrib[i][0] = 0;
         } else {
            strlcpy(attrib_name[i], old_attrib_name[i], NAME_LENGTH);
            strlcpy(attrib[i], old_attrib[i], NAME_LENGTH);
         }
      }

      n_attr = i;

      /* check encoding */
      old_encoding = "plain";

      for (i = 0; i < n_attr; i++)
         if (equal_ustring(attrib_name[i], "encoding"))
            break;

      if (i < n_attr)
         old_encoding = attrib[i];

      if (quote_on_reply) {
         strlcpy(new_text, text, sizeof(new_text));

         /* precede old text with "> " */
         text[0] = 0;
         p = old_text;

         do {
            if (strchr(p, '\n')) {
               *strchr(p, '\n') = 0;

               if (old_encoding[0] == 'H') {
                  strlcat(text, "> ", TEXT_SIZE);
                  strlcat(text, p, TEXT_SIZE);
                  strlcat(text, "<br>\n", TEXT_SIZE);
               } else {
                  strlcat(text, "> ", TEXT_SIZE);
                  strlcat(text, p, TEXT_SIZE);
                  strlcat(text, "\n", TEXT_SIZE);
               }

               p += strlen(p) + 1;
               if (*p == '\n')
                  p++;
            } else {
               if (old_encoding[0] == 'H') {
                  strlcat(text, "> ", TEXT_SIZE);
                  strlcat(text, p, TEXT_SIZE);
                  strlcat(text, "<p>\n", TEXT_SIZE);
               } else {
                  strlcat(text, "> ", TEXT_SIZE);
                  strlcat(text, p, TEXT_SIZE);
                  strlcat(text, "\n\n", TEXT_SIZE);
               }

               break;
            }

         } while (1);

         strlcat(text, new_text, TEXT_SIZE);
      }
   }

   sock = elog_connect(host, port);
   if (sock < 0)
      return sock;

#ifdef HAVE_SSL
   if (ssl)
      if (ssl_connect(sock, &ssl_con) < 0) {
         printf("elogd server does not run SSL protocol\n");
         return -1;
      }
#endif

   content_length = 100000;
   for (i = 0; i < MAX_ATTACHMENTS; i++)
      if (afilename[i][0])
         content_length += buffer_size[i];
   content = (char *)malloc(content_length);
   if (content == NULL) {
      printf("Not enough memory\n");
      return -1;
   }

   /* compose content */
   srand((unsigned) time(NULL));
   sprintf(boundary, "---------------------------%04X%04X%04X", rand(), rand(), rand());
   strcpy(content, boundary);
   strcat(content, "\r\nContent-Disposition: form-data; name=\"cmd\"\r\n\r\nSubmit\r\n");

   if (uname[0])
      sprintf(content + strlen(content),
              "%s\r\nContent-Disposition: form-data; name=\"unm\"\r\n\r\n%s\r\n", boundary, uname);

   if (upwd[0]) {
      do_crypt(upwd, encrypted_passwd, sizeof(encrypted_passwd));
      sprintf(content + strlen(content),
              "%s\r\nContent-Disposition: form-data; name=\"upwd\"\r\n\r\n%s\r\n", boundary,
              encrypted_passwd);
   }

   if (experiment[0])
      sprintf(content + strlen(content),
              "%s\r\nContent-Disposition: form-data; name=\"exp\"\r\n\r\n%s\r\n", boundary, experiment);

   if (reply)
      sprintf(content + strlen(content),
              "%s\r\nContent-Disposition: form-data; name=\"reply_to\"\r\n\r\n%d\r\n", boundary, reply);

   if (edit) {
      sprintf(content + strlen(content),
              "%s\r\nContent-Disposition: form-data; name=\"edit_id\"\r\n\r\n%d\r\n", boundary, edit);
      sprintf(content + strlen(content),
              "%s\r\nContent-Disposition: form-data; name=\"skiplock\"\r\n\r\n1\r\n", boundary);
   }

   if (suppress)
      sprintf(content + strlen(content),
              "%s\r\nContent-Disposition: form-data; name=\"suppress\"\r\n\r\n1\r\n", boundary);

   if (encoding == 0)
      sprintf(content + strlen(content),
              "%s\r\nContent-Disposition: form-data; name=\"encoding\"\r\n\r\nELCode\r\n", boundary);
   else if (encoding == 1)
      sprintf(content + strlen(content),
              "%s\r\nContent-Disposition: form-data; name=\"encoding\"\r\n\r\nplain\r\n", boundary);
   else if (encoding == 2)
      sprintf(content + strlen(content),
              "%s\r\nContent-Disposition: form-data; name=\"encoding\"\r\n\r\nHTML\r\n", boundary);

   for (i = 0; i < n_attr; i++) {
      strcpy(str, attrib_name[i]);
      if (str[0]) {
         stou(str);
         sprintf(content + strlen(content),
                 "%s\r\nContent-Disposition: form-data; name=\"%s\"\r\n\r\n%s\r\n", boundary, str, attrib[i]);
      }
   }

   if (text[0])
      sprintf(content + strlen(content),
              "%s\r\nContent-Disposition: form-data; name=\"Text\"\r\n\r\n%s\r\n%s\r\n",
              boundary, text, boundary);

   content_length = strlen(content);
   p = content + content_length;

   for (i = 0; i < MAX_ATTACHMENTS; i++)
      if (afilename[i][0]) {
         sprintf(p,
                 "Content-Disposition: form-data; name=\"attfile%d\"; filename=\"%s\"\r\n\r\n",
                 i + 1, afilename[i]);

         content_length += strlen(p);
         p += strlen(p);
         memcpy(p, buffer[i], buffer_size[i]);
         p += buffer_size[i];
         strcpy(p, boundary);
         strcat(p, "\r\n");

         content_length += buffer_size[i] + strlen(p);
         p += strlen(p);
      }

   /* compose request */
   strcpy(request, "POST /");
   if (subdir[0])
      sprintf(request + strlen(request), "%s/", subdir);
   if (experiment[0]) {
      strcpy(str, experiment);
      url_encode(str, sizeof(str));
      sprintf(request + strlen(request), "%s/", str);
   }
   strcat(request, " HTTP/1.0\r\n");

   sprintf(request + strlen(request), "Content-Type: multipart/form-data; boundary=%s\r\n", boundary);
   if (port != 80)
      sprintf(str, "%s:%d", host, port);
   else
      sprintf(str, "%s", host);
   sprintf(request + strlen(request), "Host: %s\r\n", str);
   sprintf(request + strlen(request), "User-Agent: ELOG\r\n");
   sprintf(request + strlen(request), "Content-Length: %d\r\n", content_length);

   strcat(request, "\r\n");

   header_length = strlen(request);

   /*
      {
      FILE *f;
      f = fopen("elog.log", "w");
      fwrite(request, header_length+content_length, 1, f);
      fclose(f);
      }
    */

   /* send request */
#ifdef HAVE_SSL
   if (ssl)
      SSL_write(ssl_con, request, header_length);
   else
#endif
      send(sock, request, header_length, 0);
   if (verbose) {
      printf("Request sent to host:\n");
      puts(request);
   }

   /* send content */
#ifdef HAVE_SSL
   if (ssl)
      SSL_write(ssl_con, content, content_length);
   else
#endif
      send(sock, content, content_length, 0);
   if (verbose) {
      printf("Content sent to host:\n");
      puts(content);
   }

   /* receive response */
   memset(response, 0, sizeof(response));
#ifdef HAVE_SSL
   if (ssl)
      i = SSL_read(ssl_con, response, sizeof(response) - 1);
   else
#endif
      i = recv(sock, response, sizeof(response) - 1, 0);
   if (i < 0) {
      perror("Cannot receive response");
      return -1;
   }

   /* discard remainder of response */
   n = i;
   while (i > 0) {
#ifdef HAVE_SSL
      if (ssl)
         i = SSL_read(ssl_con, response + n, sizeof(response) - 1 - n);
      else
#endif
         i = recv(sock, response + n, sizeof(response) - 1 - n, 0);
      if (i > 0)
         n += i;
   }
   response[n] = 0;

#ifdef HAVE_SSL
   if (ssl) {
      SSL_shutdown(ssl_con);
      SSL_free(ssl_con);
   }
#endif

   closesocket(sock);

   if (verbose) {
      printf("Response received:\n");
      puts(response);
   }

   /* check response status */
   if (strstr(response, "302 Found")) {
      if (strstr(response, "Location:")) {
         if (strstr(response, "has moved"))
            printf("Error: elogd server has moved to another location\n");
         else if (strstr(response, "fail"))
            printf("Error: Invalid user name or password\n");
         else {
            strncpy(str, strstr(response, "Location:") + 10, sizeof(str));
            if (strchr(str, '?'))
               *strchr(str, '?') = 0;
            if (strchr(str, '\n'))
               *strchr(str, '\n') = 0;
            if (strchr(str, '\r'))
               *strchr(str, '\r') = 0;

            if (strrchr(str, '/'))
               printf("Message successfully transmitted, ID=%s\n", strrchr(str, '/') + 1);
            else
               printf("Message successfully transmitted, ID=%s\n", str);
         }
      } else
         printf("Message successfully transmitted\n");
   } else if (strstr(response, "Logbook Selection"))
      printf("Error: No logbook specified\n");
   else if (strstr(response, "enter password"))
      printf("Error: Missing or invalid password\n");
   else if (strstr(response, "form name=form1"))
      printf("Error: Missing or invalid user name/password\n");
   else if (strstr(response, "Error: Attribute")) {
      if (strstr(response, "not existing")) {
         strncpy(str, strstr(response, "Error: Attribute") + 27, sizeof(str));
         if (strchr(str, '<'))
            *strchr(str, '<') = 0;
         printf("Error: Non existing attribute option \"%s\"\n", str);
      } else {
         strncpy(str, strstr(response, "Error: Attribute") + 20, sizeof(str));
         if (strchr(str, '<'))
            *strchr(str, '<') = 0;
         printf("Error: Missing required attribute \"%s\"\n", str);
      }
   } else
      printf("Error transmitting message\n");

   return 1;
}
Esempio n. 4
0
INT multi_init(EQUIPMENT * pequipment)
{
   int status, size, i, j, index, ch_offset;
   char str[256];
   HNDLE hDB, hKey, hNamesIn, hNamesOut;
   MULTI_INFO *m_info;
   BOOL partially_disabled;

   /* allocate private data */
   pequipment->cd_info = calloc(1, sizeof(MULTI_INFO));
   m_info = (MULTI_INFO *) pequipment->cd_info;

   /* get class driver root key */
   cm_get_experiment_database(&hDB, NULL);
   sprintf(str, "/Equipment/%s", pequipment->name);
   db_create_key(hDB, 0, str, TID_KEY);
   db_find_key(hDB, 0, str, &m_info->hKeyRoot);

   /* save event format */
   size = sizeof(str);
   db_get_value(hDB, m_info->hKeyRoot, "Common/Format", str, &size, TID_STRING, TRUE);

   if (equal_ustring(str, "Fixed"))
      m_info->format = FORMAT_FIXED;
   else if (equal_ustring(str, "MIDAS"))
      m_info->format = FORMAT_MIDAS;
   else if (equal_ustring(str, "YBOS"))
      m_info->format = FORMAT_YBOS;

   /* count total number of channels */
   for (i = m_info->num_channels_input = m_info->num_channels_output = 0;
        pequipment->driver[i].name[0]; i++) {
      if (pequipment->driver[i].flags & DF_INPUT)
         m_info->num_channels_input += pequipment->driver[i].channels;
      if (pequipment->driver[i].flags & DF_OUTPUT)
         m_info->num_channels_output += pequipment->driver[i].channels;
   }

   if (m_info->num_channels_input == 0 && m_info->num_channels_output == 0) {
      cm_msg(MERROR, "multi_init", "No channels found in device driver list");
      return FE_ERR_ODB;
   }

   /* Allocate memory for buffers */
   if (m_info->num_channels_input) {
      m_info->names_input = (char *) calloc(m_info->num_channels_input, NAME_LENGTH);
      m_info->var_input = (float *) calloc(m_info->num_channels_input, sizeof(float));
      m_info->update_threshold = (float *) calloc(m_info->num_channels_input, sizeof(float));
      m_info->offset_input = (float *) calloc(m_info->num_channels_input, sizeof(float));
      m_info->factor_input = (float *) calloc(m_info->num_channels_input, sizeof(float));
      m_info->input_mirror = (float *) calloc(m_info->num_channels_input, sizeof(float));
      m_info->channel_offset_input = (INT *) calloc(m_info->num_channels_input, sizeof(INT));
      m_info->driver_input = (void *) calloc(m_info->num_channels_input, sizeof(void *));
   }
   
   if (m_info->num_channels_output) {
      m_info->names_output = (char *) calloc(m_info->num_channels_output, NAME_LENGTH);
      m_info->var_output = (float *) calloc(m_info->num_channels_output, sizeof(float));
      m_info->offset_output = (float *) calloc(m_info->num_channels_output, sizeof(float));
      m_info->factor_output = (float *) calloc(m_info->num_channels_output, sizeof(float));
      m_info->output_mirror = (float *) calloc(m_info->num_channels_output, sizeof(float));
      m_info->channel_offset_output = (INT *) calloc(m_info->num_channels_output, sizeof(DWORD));
      m_info->driver_output = (void *) calloc(m_info->num_channels_output, sizeof(void *));
   }
 
   /*---- Create/Read settings ----*/

   if (m_info->num_channels_input) {
      /* Update threshold */
      for (i = 0; i < m_info->num_channels_input; i++)
         m_info->update_threshold[i] = 0.1f;       /* default 0.1 */
      db_merge_data(hDB, m_info->hKeyRoot, "Settings/Update Threshold",
                    m_info->update_threshold, m_info->num_channels_input * sizeof(float),
                    m_info->num_channels_input, TID_FLOAT);
      db_find_key(hDB, m_info->hKeyRoot, "Settings/Update Threshold", &hKey);
      db_open_record(hDB, hKey, m_info->update_threshold,
                     m_info->num_channels_input * sizeof(float), MODE_READ, NULL, NULL);

      /* Offset */
      for (i = 0; i < m_info->num_channels_input; i++)
         m_info->offset_input[i] = 0.f;    /* default 0 */
      db_merge_data(hDB, m_info->hKeyRoot, "Settings/Input Offset",
                    m_info->offset_input, m_info->num_channels_input * sizeof(float),
                    m_info->num_channels_input, TID_FLOAT);
      db_find_key(hDB, m_info->hKeyRoot, "Settings/Input Offset", &hKey);
      db_open_record(hDB, hKey, m_info->offset_input,
                     m_info->num_channels_input * sizeof(float), MODE_READ, NULL, NULL);
   }

   for (i = 0; i < m_info->num_channels_output; i++)
      m_info->offset_output[i] = 0.f;

   if (m_info->num_channels_output) {
      db_merge_data(hDB, m_info->hKeyRoot, "Settings/Output Offset",
                    m_info->offset_output, m_info->num_channels_output * sizeof(float),
                    m_info->num_channels_output, TID_FLOAT);
      db_find_key(hDB, m_info->hKeyRoot, "Settings/Output Offset", &hKey);
      db_open_record(hDB, hKey, m_info->offset_output,
                     m_info->num_channels_output * sizeof(float), MODE_READ, NULL, NULL);
   }

   /* Factor */
   for (i = 0; i < m_info->num_channels_input; i++)
      m_info->factor_input[i] = 1.f;    /* default 1 */

   if (m_info->num_channels_input) {
      db_merge_data(hDB, m_info->hKeyRoot, "Settings/Input Factor",
                    m_info->factor_input, m_info->num_channels_input * sizeof(float),
                    m_info->num_channels_input, TID_FLOAT);
      db_find_key(hDB, m_info->hKeyRoot, "Settings/Input factor", &hKey);
      db_open_record(hDB, hKey, m_info->factor_input,
                     m_info->num_channels_input * sizeof(float), MODE_READ, NULL, NULL);
   }

   if (m_info->num_channels_output) {
      for (i = 0; i < m_info->num_channels_output; i++)
         m_info->factor_output[i] = 1.f;
      db_merge_data(hDB, m_info->hKeyRoot, "Settings/Output Factor",
                    m_info->factor_output, m_info->num_channels_output * sizeof(float),
                    m_info->num_channels_output, TID_FLOAT);
      db_find_key(hDB, m_info->hKeyRoot, "Settings/Output factor", &hKey);
      db_open_record(hDB, hKey, m_info->factor_output,
                     m_info->num_channels_output * sizeof(float), MODE_READ, NULL, NULL);
   }

   /*---- Create/Read variables ----*/

   /* Input */
   if (m_info->num_channels_input) {
      db_merge_data(hDB, m_info->hKeyRoot, "Variables/Input",
                    m_info->var_input, m_info->num_channels_input * sizeof(float),
                    m_info->num_channels_input, TID_FLOAT);
      db_find_key(hDB, m_info->hKeyRoot, "Variables/Input", &m_info->hKeyInput);
      memcpy(m_info->input_mirror, m_info->var_input,
             m_info->num_channels_input * sizeof(float));
   }

   /* Output */
   if (m_info->num_channels_output) {
      db_merge_data(hDB, m_info->hKeyRoot, "Variables/Output",
                    m_info->var_output, m_info->num_channels_output * sizeof(float),
                    m_info->num_channels_output, TID_FLOAT);
      db_find_key(hDB, m_info->hKeyRoot, "Variables/Output", &m_info->hKeyOutput);
   }

   /*---- Initialize device drivers ----*/

   /* call init method */
   partially_disabled = FALSE;
   for (i = 0; pequipment->driver[i].name[0]; i++) {
      sprintf(str, "Settings/Devices/%s", pequipment->driver[i].name);
      status = db_find_key(hDB, m_info->hKeyRoot, str, &hKey);
      if (status != DB_SUCCESS) {
         db_create_key(hDB, m_info->hKeyRoot, str, TID_KEY);
         status = db_find_key(hDB, m_info->hKeyRoot, str, &hKey);
         if (status != DB_SUCCESS) {
            cm_msg(MERROR, "multi_init", "Cannot create %s entry in online database",
                   str);
            free_mem(m_info);
            return FE_ERR_ODB;
         }
      }

      /* check enabled flag */
      size = sizeof(pequipment->driver[i].enabled);
      pequipment->driver[i].enabled = 1;
      sprintf(str, "Settings/Devices/%s/Enabled", pequipment->driver[i].name);
      status = db_get_value(hDB, m_info->hKeyRoot, str, &pequipment->driver[i].enabled, &size, TID_BOOL, TRUE);
      if (status != DB_SUCCESS)
         return FE_ERR_ODB;

      if (pequipment->driver[i].enabled) {
         status = device_driver(&pequipment->driver[i], CMD_INIT, hKey);
         if (status != FE_SUCCESS) {
            free_mem(m_info);
            return status;
         }
      } else
         partially_disabled = TRUE;
   }

   /* compose device driver channel assignment */
   for (i = 0, j = 0, index = 0, ch_offset = 0; i < m_info->num_channels_input; i++, j++) {
      while (pequipment->driver[index].name[0] &&
             (j >= pequipment->driver[index].channels ||
              (pequipment->driver[index].flags & DF_INPUT) == 0)) {
         ch_offset += j;
         index++;
         j = 0;
      }

      m_info->driver_input[i] = &pequipment->driver[index];
      m_info->channel_offset_input[i] = ch_offset;
   }

   for (i = 0, j = 0, index = 0, ch_offset = 0; i < m_info->num_channels_output; i++, j++) {
      while (pequipment->driver[index].name[0] &&
             (j >= pequipment->driver[index].channels ||
              (pequipment->driver[index].flags & DF_OUTPUT) == 0)) {
         ch_offset += j;
         index++;
         j = 0;
      }

      m_info->driver_output[i] = &pequipment->driver[index];
      m_info->channel_offset_output[i] = ch_offset;
   }

   /*---- get default names from device driver ----*/
   if (m_info->num_channels_input) {
      for (i = 0; i < m_info->num_channels_input; i++) {
         sprintf(m_info->names_input + NAME_LENGTH * i, "Input Channel %d", i);
         device_driver(m_info->driver_input[i], CMD_GET_LABEL,
                       i - m_info->channel_offset_input[i], 
                       m_info->names_input + NAME_LENGTH * i);

         /* merge existing names with labels from driver */
         status = db_find_key(hDB, m_info->hKeyRoot, "Settings/Names Input", &hKey);
         if (status != DB_SUCCESS) {
            db_create_key(hDB, m_info->hKeyRoot, "Settings/Names Input", TID_STRING);
            db_find_key(hDB, m_info->hKeyRoot, "Settings/Names Input", &hKey);
            db_set_data(hDB, hKey, m_info->names_input, NAME_LENGTH, 1, TID_STRING);
         } else {
            size = sizeof(str);
            db_get_data_index(hDB, hKey, str, &size, i, TID_STRING);
            if (!str[0])
               db_set_data_index(hDB, hKey, m_info->names_input+NAME_LENGTH*i, NAME_LENGTH, i, TID_STRING);
         }
      }
   }

   if (m_info->num_channels_output) {
      for (i = 0; i < m_info->num_channels_output; i++) {
         sprintf(m_info->names_output + NAME_LENGTH * i, "Output Channel %d", i);
         device_driver(m_info->driver_output[i], CMD_GET_LABEL, 
                       i - m_info->channel_offset_output[i], 
                       m_info->names_output + NAME_LENGTH * i);

         /* merge existing names with labels from driver */
         status = db_find_key(hDB, m_info->hKeyRoot, "Settings/Names Output", &hKey);
         if (status != DB_SUCCESS) {
            db_create_key(hDB, m_info->hKeyRoot, "Settings/Names Output", TID_STRING);
            db_find_key(hDB, m_info->hKeyRoot, "Settings/Names Output", &hKey);
            db_set_data(hDB, hKey, m_info->names_input, NAME_LENGTH, 1, TID_STRING);
         } else {
            size = sizeof(str);
            db_get_data_index(hDB, hKey, str, &size, i, TID_STRING);
            if (!str[0])
               db_set_data_index(hDB, hKey, m_info->names_input+NAME_LENGTH*i, NAME_LENGTH, i, TID_STRING);
         }

      }
   }

   /*---- set labels from midas SC names ----*/
   if (m_info->num_channels_input) {
      for (i = 0; i < m_info->num_channels_input; i++) {
         device_driver(m_info->driver_input[i], CMD_SET_LABEL,
                       i - m_info->channel_offset_input[i],
                       m_info->names_input + NAME_LENGTH * i);
      }

      /* open hotlink on input channel names */
      if (db_find_key(hDB, m_info->hKeyRoot, "Settings/Names Input", &hNamesIn) ==
          DB_SUCCESS)
         db_open_record(hDB, hNamesIn, m_info->names_input,
                        NAME_LENGTH * m_info->num_channels_input, MODE_READ,
                        multi_update_label, pequipment);
   }

   for (i = 0; i < m_info->num_channels_output; i++) {
      device_driver(m_info->driver_output[i], CMD_SET_LABEL,
                    i - m_info->channel_offset_output[i],
                    m_info->names_output + NAME_LENGTH * i);
   }

   /* open hotlink on output channel names */
   if (m_info->num_channels_output) {
      if (db_find_key(hDB, m_info->hKeyRoot, "Settings/Names Output", &hNamesOut) ==
          DB_SUCCESS)
         db_open_record(hDB, hNamesOut, m_info->names_output,
                        NAME_LENGTH * m_info->num_channels_output, MODE_READ,
                        multi_update_label, pequipment);

      /* open hot link to output record */
      db_open_record(hDB, m_info->hKeyOutput, m_info->var_output,
                     m_info->num_channels_output * sizeof(float),
                     MODE_READ, multi_output, pequipment);
   }

   /* set initial demand values */
   for (i = 0; i < m_info->num_channels_output; i++) {
      if (pequipment->driver[index].flags & DF_PRIO_DEVICE) {
         /* read default value directly from device bypassing multi-thread buffer */
         device_driver(m_info->driver_output[i], CMD_GET_DEMAND,
                       i - m_info->channel_offset_output[i],
                       &m_info->output_mirror[i]);
      } else {
         /* use default value from ODB */
         m_info->output_mirror[i] = m_info->var_output[i] * m_info->factor_output[i] -
             m_info->offset_output[i];

         device_driver(m_info->driver_output[i], CMD_SET,
                       i - m_info->channel_offset_output[i],
                       m_info->output_mirror[i]);
      }
   }

   if (m_info->num_channels_output)
      db_set_record(hDB, m_info->hKeyOutput, m_info->output_mirror,
                    m_info->num_channels_output * sizeof(float), 0);

   /* initially read all input channels */
   if (m_info->num_channels_input)
      multi_read(pequipment, -1);

   if (partially_disabled)
      return FE_PARTIALLY_DISABLED;
   
   return FE_SUCCESS;
}
Esempio n. 5
0
INT register_equipment(void)
{
   INT index, size, status;
   char str[256];
   EQUIPMENT_INFO *eq_info;
   EQUIPMENT_STATS *eq_stats;
   HNDLE hKey;

   /* get current ODB run state */
   size = sizeof(run_state);
   run_state = STATE_STOPPED;
   db_get_value(hDB, 0, "/Runinfo/State", &run_state, &size, TID_INT, TRUE);
   size = sizeof(run_number);
   run_number = 1;
   status = db_get_value(hDB, 0, "/Runinfo/Run number", &run_number, &size, TID_INT, TRUE);
   assert(status == SUCCESS);

   /* scan EQUIPMENT table from mevb.C */
   for (index = 0; equipment[index].name[0]; index++) {
      eq_info = &equipment[index].info;
      eq_stats = &equipment[index].stats;

      if (eq_info->event_id == 0) {
         printf("\nEvent ID 0 for %s not allowed\n", equipment[index].name);
         cm_disconnect_experiment();
         ss_sleep(5000);
         exit(0);
      }

      /* init status */
      equipment[index].status = EB_SUCCESS;

      sprintf(str, "/Equipment/%s/Common", equipment[index].name);

      /* get last event limit from ODB */
      if (eq_info->eq_type != EQ_SLOW) {
         db_find_key(hDB, 0, str, &hKey);
         size = sizeof(double);
         if (hKey)
            db_get_value(hDB, hKey, "Event limit", &eq_info->event_limit, &size, TID_DOUBLE, TRUE);
      }

      /* Create common subtree */
      status = db_check_record(hDB, 0, str, EQUIPMENT_COMMON_STR, TRUE);
      if (status != DB_SUCCESS) {
         printf("Cannot check equipment record, status = %d\n", status);
         ss_sleep(3000);
      }
      db_find_key(hDB, 0, str, &hKey);

      if (equal_ustring(eq_info->format, "FIXED"))
         equipment[index].format = FORMAT_FIXED;
      else                      /* default format is MIDAS */
         equipment[index].format = FORMAT_MIDAS;

      gethostname(eq_info->frontend_host, sizeof(eq_info->frontend_host));
      strcpy(eq_info->frontend_name, frontend_name);
      strcpy(eq_info->frontend_file_name, frontend_file_name);

      /* set record from equipment[] table in frontend.c */
      db_set_record(hDB, hKey, eq_info, sizeof(EQUIPMENT_INFO), 0);

      /* get record once at the start equipment info */
      size = sizeof(EQUIPMENT_INFO);
      db_get_record(hDB, hKey, eq_info, &size, 0);

    /*---- Create just the key , leave it empty ---------------------------------*/
      sprintf(str, "/Equipment/%s/Variables", equipment[index].name);
      db_create_key(hDB, 0, str, TID_KEY);
      db_find_key(hDB, 0, str, &hKey);
      equipment[index].hkey_variables = hKey;

    /*---- Create and initialize statistics tree -------------------*/
      sprintf(str, "/Equipment/%s/Statistics", equipment[index].name);

      status = db_check_record(hDB, 0, str, EQUIPMENT_STATISTICS_STR, TRUE);
      if (status != DB_SUCCESS) {
         printf("Cannot create/check statistics record, error %d\n", status);
         ss_sleep(3000);
      }

      status = db_find_key(hDB, 0, str, &hKey);
      if (status != DB_SUCCESS) {
         printf("Cannot find statistics record, error %d\n", status);
         ss_sleep(3000);
      }

      eq_stats->events_sent = 0;
      eq_stats->events_per_sec = 0;
      eq_stats->kbytes_per_sec = 0;

      /* open hot link to statistics tree */
      status = db_open_record(hDB, hKey, eq_stats, sizeof(EQUIPMENT_STATS)
                              , MODE_WRITE, NULL, NULL);
      if (status != DB_SUCCESS) {
         cm_msg(MERROR, "register_equipment",
                "Cannot open statistics record, error %d. Probably other FE is using it", status);
         ss_sleep(3000);
      }

    /*---- open event buffer ---------------------------------------*/
      if (eq_info->buffer[0]) {
         status = bm_open_buffer(eq_info->buffer, 2 * max_event_size, &equipment[index].buffer_handle);
         if (status != BM_SUCCESS && status != BM_CREATED) {
            cm_msg(MERROR, "register_equipment",
                   "Cannot open event buffer. Try to reduce EVENT_BUFFER_SIZE in midas.h \
          and rebuild the system.");
            return 0;
         }

	 if (1)
	   {
	     int level = 0;
	     bm_get_buffer_level(equipment[index].buffer_handle, &level);
	     printf("Buffer %s, level %d, info: \n", eq_info->buffer, level);
	   }

         /* set the default buffer cache size */
         bm_set_cache_size(equipment[index].buffer_handle, 0, SERVER_CACHE_SIZE);
      } else {
Esempio n. 6
0
/**
Scan ODB for alarms.
@return AL_SUCCESS
*/
INT al_check()
{
   if (rpc_is_remote())
      return rpc_call(RPC_AL_CHECK);

#ifdef LOCAL_ROUTINES
   {
   INT i, status, size, semaphore;
   HNDLE hDB, hkeyroot, hkey;
   KEY key;
   ALARM a;
   char str[256], value[256];
   time_t now;
   PROGRAM_INFO program_info;
   BOOL flag;
   
   ALARM_CLASS_STR(alarm_class_str);
   ALARM_ODB_STR(alarm_odb_str);
   ALARM_PERIODIC_STR(alarm_periodic_str);
   
   cm_get_experiment_database(&hDB, NULL);
   
   if (hDB == 0)
      return AL_SUCCESS;     /* called from server not yet connected */
   
   /* check online mode */
   flag = TRUE;
   size = sizeof(flag);
   db_get_value(hDB, 0, "/Runinfo/Online Mode", &flag, &size, TID_INT, TRUE);
   if (!flag)
      return AL_SUCCESS;
   
   /* check global alarm flag */
   flag = TRUE;
   size = sizeof(flag);
   db_get_value(hDB, 0, "/Alarms/Alarm system active", &flag, &size, TID_BOOL, TRUE);
   if (!flag)
      return AL_SUCCESS;
   
   /* request semaphore */
   cm_get_experiment_semaphore(&semaphore, NULL, NULL, NULL);
   status = ss_semaphore_wait_for(semaphore, 100);
   if (status == SS_TIMEOUT)
      return AL_SUCCESS;        /* someone else is doing alarm business */
   if (status != SS_SUCCESS) {
      printf("al_check: Something is wrong with our semaphore, ss_semaphore_wait_for() returned %d, aborting.\n", status);
      //abort(); // DOES NOT RETURN
      printf("al_check: Cannot abort - this will lock you out of odb. From this point, MIDAS will not work correctly. Please read the discussion at https://midas.triumf.ca/elog/Midas/945\n");
      // NOT REACHED
      return AL_SUCCESS;
   }
   
   /* check ODB alarms */
   db_find_key(hDB, 0, "/Alarms/Alarms", &hkeyroot);
   if (!hkeyroot) {
      /* create default ODB alarm */
      status = db_create_record(hDB, 0, "/Alarms/Alarms/Demo ODB", strcomb(alarm_odb_str));
      db_find_key(hDB, 0, "/Alarms/Alarms", &hkeyroot);
      if (!hkeyroot) {
         ss_semaphore_release(semaphore);
         return AL_SUCCESS;
      }
      
      status = db_create_record(hDB, 0, "/Alarms/Alarms/Demo periodic", strcomb(alarm_periodic_str));
      db_find_key(hDB, 0, "/Alarms/Alarms", &hkeyroot);
      if (!hkeyroot) {
         ss_semaphore_release(semaphore);
         return AL_SUCCESS;
      }
      
      /* create default alarm classes */
      status = db_create_record(hDB, 0, "/Alarms/Classes/Alarm", strcomb(alarm_class_str));
      status = db_create_record(hDB, 0, "/Alarms/Classes/Warning", strcomb(alarm_class_str));
      if (status != DB_SUCCESS) {
         ss_semaphore_release(semaphore);
         return AL_SUCCESS;
      }
   }
   
   for (i = 0;; i++) {
      status = db_enum_key(hDB, hkeyroot, i, &hkey);
      if (status == DB_NO_MORE_SUBKEYS)
         break;
      
      db_get_key(hDB, hkey, &key);
      
      size = sizeof(a);
      status = db_get_record(hDB, hkey, &a, &size, 0);
      if (status != DB_SUCCESS || a.type < 1 || a.type > AT_LAST) {
         /* make sure alarm record has right structure */
         db_check_record(hDB, hkey, "", strcomb(alarm_odb_str), TRUE);
         size = sizeof(a);
         status = db_get_record(hDB, hkey, &a, &size, 0);
         if (status != DB_SUCCESS || a.type < 1 || a.type > AT_LAST) {
            cm_msg(MERROR, "al_check", "Cannot get alarm record");
            continue;
         }
      }
      
      /* check periodic alarm only when active */
      if (a.active &&
          a.type == AT_PERIODIC &&
          a.check_interval > 0 && (INT) ss_time() - (INT) a.checked_last > a.check_interval) {
         /* if checked_last has not been set, set it to current time */
         if (a.checked_last == 0) {
            a.checked_last = ss_time();
            db_set_record(hDB, hkey, &a, size, 0);
         } else
            al_trigger_alarm(key.name, a.alarm_message, a.alarm_class, "", AT_PERIODIC);
      }
      
      /* check alarm only when active and not internal */
      if (a.active &&
          a.type == AT_EVALUATED &&
          a.check_interval > 0 && (INT) ss_time() - (INT) a.checked_last > a.check_interval) {
         /* if condition is true, trigger alarm */
         if (al_evaluate_condition(a.condition, value)) {
            sprintf(str, a.alarm_message, value);
            al_trigger_alarm(key.name, str, a.alarm_class, "", AT_EVALUATED);
         } else {
            a.checked_last = ss_time();
            status = db_set_value(hDB, hkey, "Checked last", &a.checked_last, sizeof(DWORD), 1, TID_DWORD);
            if (status != DB_SUCCESS) {
               cm_msg(MERROR, "al_check", "Cannot change alarm record");
               continue;
            }
         }
      }
   }
   
   /* check /programs alarms */
   db_find_key(hDB, 0, "/Programs", &hkeyroot);
   if (hkeyroot) {
      for (i = 0;; i++) {
         status = db_enum_key(hDB, hkeyroot, i, &hkey);
         if (status == DB_NO_MORE_SUBKEYS)
            break;
         
         db_get_key(hDB, hkey, &key);
         
         /* don't check "execute on xxx" */
         if (key.type != TID_KEY)
            continue;
         
         size = sizeof(program_info);
         status = db_get_record(hDB, hkey, &program_info, &size, 0);
         if (status != DB_SUCCESS) {
            cm_msg(MERROR, "al_check", "Cannot get program info record");
            continue;
         }
         
         now = ss_time();
         
         rpc_get_name(str);
         str[strlen(key.name)] = 0;
         if (!equal_ustring(str, key.name) && cm_exist(key.name, FALSE) == CM_NO_CLIENT) {
            if (program_info.first_failed == 0) {
               program_info.first_failed = (DWORD) now;
               db_set_record(hDB, hkey, &program_info, sizeof(program_info), 0);
            }
            
            /* fire alarm when not running for more than what specified in check interval */
            if (now - program_info.first_failed >= program_info.check_interval / 1000) {
               /* if not running and alarm calss defined, trigger alarm */
               if (program_info.alarm_class[0]) {
                  sprintf(str, "Program %s is not running", key.name);
                  al_trigger_alarm(key.name, str, program_info.alarm_class,
                                   "Program not running", AT_PROGRAM);
               }
               
               /* auto restart program */
               if (program_info.auto_restart && program_info.start_command[0]) {
                  ss_system(program_info.start_command);
                  program_info.first_failed = 0;
                  cm_msg(MTALK, "al_check", "Program %s restarted", key.name);
               }
            }
         } else {
            if (program_info.first_failed != 0) {
               program_info.first_failed = 0;
               db_set_record(hDB, hkey, &program_info, sizeof(program_info), 0);
            }
         }
      }
   }
   
   ss_semaphore_release(semaphore);
   }
#endif                          /* LOCAL_COUTINES */

   return SUCCESS;
}
Esempio n. 7
0
BOOL al_evaluate_condition(const char *condition, char *value)
{
   HNDLE hDB, hkey;
   int i, j, idx1, idx2, idx, size, state;
   KEY key;
   double value1, value2;
   char value1_str[256], value2_str[256], str[256], op[3], function[80];
   char data[10000];
   DWORD dtime;

   strcpy(str, condition);
   op[1] = op[2] = 0;
   value1 = value2 = 0;
   idx1 = idx2 = 0;

   /* find value and operator */
   for (i = strlen(str) - 1; i > 0; i--)
      if (strchr("<>=!&", str[i]) != NULL)
         break;
   op[0] = str[i];
   for (j = 1; str[i + j] == ' '; j++);
   strlcpy(value2_str, str + i + j, sizeof(value2_str));
   value2 = atof(value2_str);
   str[i] = 0;

   if (i > 0 && strchr("<>=!&", str[i - 1])) {
      op[1] = op[0];
      op[0] = str[--i];
      str[i] = 0;
   }

   i--;
   while (i > 0 && str[i] == ' ')
      i--;
   str[i + 1] = 0;

   /* check if function */
   function[0] = 0;
   if (str[i] == ')') {
      str[i--] = 0;
      if (strchr(str, '(')) {
         *strchr(str, '(') = 0;
         strcpy(function, str);
         for (i = strlen(str) + 1, j = 0; str[i]; i++, j++)
            str[j] = str[i];
         str[j] = 0;
         i = j - 1;
      }
   }

   /* find key */
   if (str[i] == ']') {
      str[i--] = 0;
      if (str[i] == '*') {
         idx1 = -1;
         while (i > 0 && str[i] != '[')
            i--;
         str[i] = 0;
      } else if (strchr(str, '[') &&
                 strchr(strchr(str, '['), '-')) {
         while (i > 0 && isdigit(str[i]))
            i--;
         idx2 = atoi(str + i + 1);
         while (i > 0 && str[i] != '[')
            i--;
         idx1 = atoi(str + i + 1);
         str[i] = 0;
      } else {
         while (i > 0 && isdigit(str[i]))
            i--;
         idx1 = idx2 = atoi(str + i + 1);
         str[i] = 0;
      }
   }

   cm_get_experiment_database(&hDB, NULL);
   db_find_key(hDB, 0, str, &hkey);
   if (!hkey) {
      cm_msg(MERROR, "al_evaluate_condition", "Cannot find key %s to evaluate alarm condition", str);
      if (value)
         strcpy(value, "unknown");
      return FALSE;
   }
   db_get_key(hDB, hkey, &key);

   if (idx1 < 0) {
      idx1 = 0;
      idx2 = key.num_values-1;
   }

   for (idx=idx1; idx<=idx2 ; idx++) {
      
      if (equal_ustring(function, "access")) {
         /* check key access time */
         db_get_key_time(hDB, hkey, &dtime);
         sprintf(value1_str, "%d", dtime);
         value1 = atof(value1_str);
      } else if (equal_ustring(function, "access_running")) {
         /* check key access time if running */
         db_get_key_time(hDB, hkey, &dtime);
         sprintf(value1_str, "%d", dtime);
         size = sizeof(state);
         db_get_value(hDB, 0, "/Runinfo/State", &state, &size, TID_INT, FALSE);
         if (state != STATE_RUNNING)
            strcpy(value1_str, "0");
         value1 = atof(value1_str);
      } else {
         /* get key data and convert to double */
         db_get_key(hDB, hkey, &key);
         size = sizeof(data);
         db_get_data_index(hDB, hkey, data, &size, idx, key.type);
         db_sprintf(value1_str, data, size, 0, key.type);
         value1 = atof(value1_str);
      }

      /* convert boolean values to integers */
      if (key.type == TID_BOOL) {
         value1 = (value1_str[0] == 'Y' || value1_str[0] == 'y' || value1_str[0] == '1');
         value2 = (value2_str[0] == 'Y' || value2_str[0] == 'y' || value2_str[0] == '1');
      }

      /* return value */
      if (value)
         strcpy(value, value1_str);

      /* now do logical operation */
      if (strcmp(op, "=") == 0)
         if (value1 == value2) return TRUE;
      if (strcmp(op, "==") == 0)
         if (value1 == value2) return TRUE;
      if (strcmp(op, "!=") == 0)
         if (value1 != value2) return TRUE;
      if (strcmp(op, "<") == 0)
         if (value1 < value2) return TRUE;
      if (strcmp(op, ">") == 0)
         if (value1 > value2) return TRUE;
      if (strcmp(op, "<=") == 0)
         if (value1 <= value2) return TRUE;
      if (strcmp(op, ">=") == 0)
         if (value1 >= value2) return TRUE;
      if (strcmp(op, "&") == 0)
         if (((unsigned int)value1 & (unsigned int)value2) > 0) return TRUE;
   }

   return FALSE;
}
Esempio n. 8
0
INT al_trigger_class(const char *alarm_class, const char *alarm_message, BOOL first)
/********************************************************************\

  Routine: al_trigger_class

  Purpose: Trigger a certain alarm class

  Input:
    char   *alarm_class     Alarm class, must be defined in
                            /alarms/classes
    char   *alarm_message   Optional message which goes with alarm
    BOOL   first            TRUE if alarm is triggered first time
                            (used for elog)

  Output:

  Function value:
    AL_INVALID_NAME         Alarm class not defined
    AL_SUCCESS              Successful completion

\********************************************************************/
{
   int status, size, state;
   HNDLE hDB, hkeyclass;
   char str[256], command[256], tag[32], url[256];
   ALARM_CLASS ac;
   DWORD now = ss_time();

   tag[0] = 0;

   cm_get_experiment_database(&hDB, NULL);

   /* get alarm class */
   sprintf(str, "/Alarms/Classes/%s", alarm_class);
   db_find_key(hDB, 0, str, &hkeyclass);
   if (!hkeyclass) {
      cm_msg(MERROR, "al_trigger_class", "Alarm class %s not found in ODB", alarm_class);
      return AL_INVALID_NAME;
   }

   size = sizeof(ac);
   status = db_get_record(hDB, hkeyclass, &ac, &size, 0);
   if (status != DB_SUCCESS) {
      cm_msg(MERROR, "al_trigger_class", "Cannot get alarm class record");
      return AL_ERROR_ODB;
   }

   /* write system message */
   if (ac.write_system_message && (now - ac.system_message_last >= (DWORD)ac.system_message_interval)) {
      if (equal_ustring(alarm_class, "All"))
         sprintf(str, "General alarm: %s", alarm_message);
      else
         sprintf(str, "%s: %s", alarm_class, alarm_message);
      cm_msg(MTALK, "al_trigger_class", "%s", str);
      ac.system_message_last = now;
   }

   /* write elog message on first trigger if using internal ELOG */
   size = sizeof(url);
   if (ac.write_elog_message && first &&
       db_get_value(hDB, 0, "/Elog/URL", url, &size, TID_STRING, FALSE) != DB_SUCCESS)
      el_submit(0, "Alarm system", "Alarm", "General", alarm_class, str,
                "", "plain", "", "", 0, "", "", 0, "", "", 0, tag, sizeof(tag));

   /* execute command */
   if (ac.execute_command[0] &&
       ac.execute_interval > 0 && (INT) ss_time() - (INT) ac.execute_last > ac.execute_interval) {
      if (equal_ustring(alarm_class, "All"))
         sprintf(str, "General alarm: %s", alarm_message);
      else
         sprintf(str, "%s: %s", alarm_class, alarm_message);
      sprintf(command, ac.execute_command, str);
      cm_msg(MINFO, "al_trigger_class", "Execute: %s", command);
      ss_system(command);
      ac.execute_last = ss_time();
   }

   /* stop run */
   if (ac.stop_run) {
      state = STATE_STOPPED;
      size = sizeof(state);
      db_get_value(hDB, 0, "/Runinfo/State", &state, &size, TID_INT, TRUE);
      if (state != STATE_STOPPED) {
         cm_msg(MINFO, "al_trigger_class", "Stopping the run from alarm class \'%s\', message \'%s\'", alarm_class, alarm_message);
         cm_transition(TR_STOP, 0, NULL, 0, TR_DETACH, FALSE);
      }
   }

   status = db_set_record(hDB, hkeyclass, &ac, sizeof(ac), 0);
   if (status != DB_SUCCESS) {
      cm_msg(MERROR, "al_trigger_class", "Cannot update alarm class record");
      return AL_ERROR_ODB;
   }

   return AL_SUCCESS;
}