Changeset - 71f0379b39de
[Not reviewed]
tip default
0 6 0
Nathan Brink (binki) - 15 years ago 2010-10-09 11:29:35
ohnobinki@ohnopublishing.net
Renice execio's newly spawned processes. Fixes bug 8.
6 files changed with 30 insertions and 12 deletions:
0 comments (0 inline, 0 general)
configure.ac
Show inline comments
 
# Copyright 2010 Nathan Phillip Brink, Ethan Zonca
 
#
 
# This file is a part of DistRen.
 
#
 
# Distren is free software: you can redistribute it and/or modify
 
# it under the terms of the GNU Affero General Public License as published by
 
# the Free Software Foundation, either version 3 of the License, or
 
# (at your option) any later version.
 
#
 
# DistRen is distributed in the hope that it will be useful,
 
# but WITHOUT ANY WARRANTY; without even the implied warranty of
 
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 
# GNU Affero General Public License for more details.
 
#
 
# You should have received a copy of the GNU Affero General Public License
 
# along with DistRen.  If not, see <http://www.gnu.org/licenses/>.
 

	
 
AC_PREREQ(2.61)
 
AC_INIT([distren],[0.0],[http://bugs.ohnopub.net/], [], [http://ohnopub.net/distren/])
 
AC_CONFIG_HEADERS([src/common/config.h])
 
AC_CONFIG_SRCDIR([src/server/distrend.c])
 
AC_CONFIG_MACRO_DIR([m4])
 

	
 
AC_PROG_CC
 
AC_PROG_LIBTOOL
 

	
 
AM_INIT_AUTOMAKE([gnu dist-bzip2 subdir-objects -Wall])
 
AM_PROG_CC_C_O
 

	
 
dnl these macros force the refered to types to be available without me
 
dnl writing my own magic :-)
 
AC_TYPE_PID_T
 
AC_TYPE_SIZE_T
 

	
 
AC_TYPE_UINT8_T
 
AC_TYPE_UINT16_T
 
AC_TYPE_UINT32_T
 

	
 
dnl execio has a nice() call but it's not vital to our operation
 
AC_CHECK_FUNCS([nice])
 

	
 
dnl selective compilation
 
dnl For now, this is only left for when the C-based client is
 
dnl reintroducded.
 
AC_ARG_ENABLE([server],
 
	[AS_HELP_STRING([--disable-server],[Don't build the distren server])],
 
	[enable_server=$enableval],
 
	[enable_server=yes])
 
AM_CONDITIONAL([ENABLE_SERVER],
 
	[test "x$enable_server" = "xyes"])
 

	
 
dnl package dependencies:
 

	
 
DISTLIBS_MODULES="libconfuse >= 2.5 libcurl libxml-2.0 liblist >= 2.3.1 libarchive >= 2.8.0 libcrypto"
 
AC_SUBST([DISTLIBS_MODULES])
 
PKG_CHECK_MODULES([DISTLIBS], [$DISTLIBS_MODULES])
 
AX_LIB_MYSQL
 
AS_IF( [test "x${MYSQL_VERSION}" = "x"],
 
	[ AC_MSG_ERROR([I need mysql]) ] )
 

	
 
LIBS_save="$LIBS"
 
CFLAGS_save="$CFLAGS"
 
LIBS="$LIBS $DISTLIBS_LIBS"
 
CFLAGS="$CFLAGS $DISTLIBS_CFLAGS"
 
AC_LINK_IFELSE([AC_LANG_PROGRAM([#include <list.h>
 
	#include <stdio.h>
 
	], [printf(stderr, "%s", list_brag);
 
	return 0;])], [AC_DEFINE([HAVE_LIST_BRAG], [], [Define if liblist has list_brag.])], [])
 
LIBS="$LIBS_save"
 
CFLAGS="$CFLAGS_save"
 

	
 
PKG_CHECK_MODULES([CHECK], [check >= 0.9.3])
 

	
 
dnl define paths for configuration files until a better arrangement is
 
dnl made:
 

	
 
AC_DEFINE_DIR([LOCALSTATEDIR], [localstatedir], [Default directory for storing state information])
 
AC_DEFINE_DIR([RUNSTATEDIR], [localstatedir/run], [Default directory for registering runtime information like pid-files])
 

	
 
AC_CONFIG_FILES([Makefile
 
	libdistren.pc
 
	etc/distrendaemon.conf
 
	etc/distrenslave.conf
 
])
 

	
 
AC_OUTPUT
src/common/execio.c
Show inline comments
 
/*
 
  Copyright 2008 Nathan Phillip Brink, Ethan Zonca
 

	
 
  This file is a part of DistRen.
 

	
 
  DistRen is free software: you can redistribute it and/or modify
 
  it under the terms of the GNU Affero General Public License as published by
 
  the Free Software Foundation, either version 3 of the License, or
 
  (at your option) any later version.
 

	
 
  DistRen is distributed in the hope that it will be useful,
 
  but WITHOUT ANY WARRANTY; without even the implied warranty of
 
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 
  GNU Affero General Public License for more details.
 

	
 
  You should have received a copy of the GNU Affero General Public License
 
  along with DistRen.  If not, see <http://www.gnu.org/licenses/>.
 
*/
 

	
 
#include "common/config.h"
 

	
 
#include "common/execio.h"
 

	
 
#include <unistd.h>
 
#include <sys/types.h>
 
#ifndef _WIN32
 
#include <sys/wait.h>
 
#endif
 
#include <signal.h>
 
#include <fcntl.h>
 
#include <stdio.h>
 
#include <stdlib.h>
 
#include <errno.h>
 

	
 
int execio_open(struct execio **rem, const char *progname, char *const argv[])
 
int execio_open(struct execio **rem, const char *progname, char *const argv[], int nice_incr)
 
{
 
  /* pipe used to write to child */
 
  int pipe_write[2];
 
  /* pipe used to read from child */
 
  int pipe_read[2];
 

	
 
  pid_t child;
 

	
 
  /* for wait(2) if needed */
 
  int childstatus;
 
  
 
  int counter;
 
  int counter2;
 
  int maxfds;
 

	
 
  /* create two pipes to facilitate communication with child */
 
  if(pipe(pipe_write))
 
    return 1;
 
  if(pipe(pipe_read))
 
    {
 
      close(pipe_write[0]);
 
      close(pipe_write[1]);
 
      return 1;
 
    }
 
  
 
  /* parent */
 
  child = fork();
 
  if(child == -1)
 
    {
 
      close(pipe_write[0]);
 
      close(pipe_write[1]);
 
      close(pipe_read[0]);
 
      close(pipe_read[1]);
 
      return 1;
 
    }
 
  if(child)
 
    /* the parent proc: */
 
    {
 
      /* close sides of pipe we won't use */
 
      close(pipe_write[0]);
 
      close(pipe_read[1]);
 
      
 
      /* setup execio struct */
 
      (*rem) = malloc(sizeof(struct execio));
 
      if(!(*rem))
 
	{
 
	  /* we should tell the child we're dead - use wait and close our end of the pipes! */
 
	  close(pipe_write[1]);
 
	  close(pipe_read[0]);
 
	  /* we should probably pass of the wait() call to a thread that just does boring things like that. Especially for when the server tries to connect to other servers... */
 
	  /* maybe we should just kill instead of term the child */
 
	  kill(child, SIGTERM);
 
	  /* the waitpid(2) seems to indicate that only when the child is terminated will this wait return. */
 
	  waitpid(child, &childstatus, 0); 
 
	}
 
      (*rem)->pipe_write = pipe_write[1];
 
      (*rem)->pipe_read = pipe_read[0];
 
      (*rem)->state = 0;
 
      (*rem)->child = child;
 
      
 
      return 0;
 
    }
 
  
 
  /* child */
 
  else
 
    {
 
#ifdef HAVE_NICE
 
      /* lower the nice value */
 
      nice(nice_incr);
 
#endif
 

	
 
      /* close unused pipes */
 
      close(pipe_write[1]);
 
      close(pipe_read[0]);
 

	
 
      /*
 
	reset stdin, stdout, and stderr to the appropriate files. OK, not stderr :-) 
 
      */
 
      dup2(pipe_read[1], STDOUT_FILENO);
 
      dup2(pipe_write[0], STDIN_FILENO);
 
      /*
 
	close the fds that were dup'd
 
       */
 
      close(pipe_read[1]);
 
      close(pipe_write[0]);
 

	
 
      /* 
 
	 close all other file descriptors. We want to keep 0, 1, and 2 open. We don't know that the last open() or pipe() always gives the highest fd number. However, I will assume that it does. Maybe this is a bad idea:
 
       */
 
      counter = pipe_write[0];
 
      if(counter < pipe_write[1])
 
	counter = pipe_write[1];
 
      if(counter < pipe_read[0])
 
	counter = pipe_read[0];
 
      if(counter < pipe_read[1])
 
	counter = pipe_read[1];
 
      counter2 = 0;
 
      maxfds = counter;
 
      while(counter > 2)
 
	{
 
	  if(!close(counter))
 
	    counter2 ++; /* record how many descriptors we still had open :-) */
 
	  counter --;
 
	}
 
      
 
      /*
 
	now exec: execvp uses interpreter to find the file to exec
 
       */
 
      execvp(progname, argv);
 

	
 
      fprintf(stderr, "uh-oh, ``%s'' didn't start for execio\n", progname);
 
      exit(1);
 
    }
 
}
 

	
 
/*
 
  returns 1 if child has exited, 
 
  returns 0 if child is still alive
 
 */
 
int _execio_checkpid(struct execio *eio)
 
{
 
  int childstatus;
 
  
 
#ifdef _WIN32
 
  waitpid(eio->child, &childstatus, 0);
 
#else
 
  waitpid(eio->child, &childstatus, WNOHANG);
 
#endif
 
  /* perror()? */
 

	
 
  return WIFEXITED(childstatus);
 
}
 

	
 

	
 
int execio_read(struct execio *eio, const void *buf, size_t len, size_t *bytesread)
 
int execio_read(struct execio *eio, void *buf, size_t len, size_t *bytesread)
 
{
 
  ssize_t ret;
 
  /*
 
    TODO: detect NULL eio? 
 
    TODO: errno?
 
    update status of eio for execio_status/to be able to cleanup subproc??
 

	
 
    whenever read() returns 0, it means EOF
 
   */
 
  
 
  ret = read(eio->pipe_read, buf, len);
 
  if(ret == -1)
 
    {
 
      (*bytesread) = 0;
 
      perror("read");
 
      switch(errno)
 
	{
 
	case EAGAIN:
 
	case EINTR:
 
	  return 0;
 
	  break;
 
	default:
 
	  return 1;
 
	}
 
    }
 

	
 
  (*bytesread) = (size_t)ret;
 
  if(!ret)
 
    {
 
      /* should also be able to figure out if is bad fd and should set EXECIO_STATE_ERROR instead of _EOF */
 
      eio->state = EXECIO_STATE_EOF;
 
      return 1;
 
    }
 

	
 
  return 0;
 
}
 

	
 
int execio_write(struct execio *eio, const void *buf, size_t len, size_t *bytesread)
 
{
 
  errno = 0;
 
  (*bytesread) = write(eio->pipe_write, buf, len);
 
  if(!*bytesread)
 
    {
 
      switch(errno)
 
	{
 
	case EPIPE:
 
	  /* 
 
	     the program closed the pipe (died)
 
	  */
 
	  fprintf(stderr, "execio_write: the child program closed its stdin pipe\n");
 
	  eio->state = EXECIO_STATE_EOF;
 
	  break;
 
	
 
	default:
 
	  fprintf(stderr, "execio_write: unhandled error writing to an fd: \n");
 
	  perror("write");
 
	  eio->state = EXECIO_STATE_ERROR;
 
	  break;
 
	  
 
	}
 
      
 
      return 1;
 
    }
 

	
 
  return 0;
 
}
 

	
 

	
 
enum execio_state execio_state(struct execio *eio)
 
{
 
  return eio->state;
 
}
 

	
 

	
 
int execio_close(struct execio *eio)
 
{
 
  int childstatus;
 

	
 
  close(eio->pipe_read);
 
  close(eio->pipe_write);
 

	
 
  /* maybe we should just kill rather than term the child */
 
  kill(eio->child, SIGTERM);
 
  /* 
 
     the waitpid(2) seems to indicate that only when the child is terminated will this wait return. 
 
     This are of code will probably need improving - the ability to seng SIGKILL after a timeout? So we'll output a debug line before running waitpid
 
  */
 
  waitpid(eio->child, &childstatus, 0);
 

	
 
  free(eio);
 
  
 
  return 0;
 
}
 

	
src/common/execio.h
Show inline comments
 
/*
 
  Copyright 2010 Nathan Phillip Brink, Ethan Zonca
 

	
 
  This file is a part of DistRen.
 

	
 
  DistRen is free software: you can redistribute it and/or modify
 
  it under the terms of the GNU Affero General Public License as published by
 
  the Free Software Foundation, either version 3 of the License, or
 
  (at your option) any later version.
 

	
 
  DistRen is distributed in the hope that it will be useful,
 
  but WITHOUT ANY WARRANTY; without even the implied warranty of
 
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 
  GNU Affero General Public License for more details.
 

	
 
  You should have received a copy of the GNU Affero General Public License
 
  along with DistRen.  If not, see <http://www.gnu.org/licenses/>.
 
*/
 

	
 
#ifndef _DISTREN_EXECIO_H
 
#define _DISTREN_EXECIO_H
 

	
 
/*
 
  This file tries to abstract away getting a socket/fd that talks to a spawned program
 
 */
 

	
 
#include <unistd.h>
 

	
 
enum execio_state
 
  {
 
    EXECIO_STATE_ERROR,
 
    EXECIO_STATE_EOF
 
  };
 

	
 

	
 
struct execio
 
{
 
  int pipe_write;
 
  int pipe_read;
 

	
 
  enum execio_state state;
 

	
 
  pid_t child;
 
};
 

	
 
/**
 
  runs progname with the arguments in argv. argv must be null terminated!!!!!!!!!
 

	
 
  returns nonzero return on error
 
 * \brief
 
 *   runs progname with the arguments in argv. argv must be null terminated!!!!!!!!!
 
 *
 
 * \param eio
 
 *   Where to store the pointer to the execio handle.
 
 * \param progname
 
 *   The name of the program to execute at the system's shell.
 
 * \param argv
 
 *   The NULL-terminated list of arguments to send to the subcommand.
 
 * \param nice_incr
 
 *   The amount to increase the subprogram's nice value by. See nice(3p).
 
 * \return
 
 *   nonzero return on error
 
*/
 
int execio_open(struct execio **eio, const char *progname, char *const argv[]);
 
int execio_open(struct execio **eio, const char *progname, char *const argv[], int nice_incr);
 

	
 
/**
 
   doesn't block,
 
   returns 0 on success, 1 on failure
 
*/
 
int execio_read(struct execio *eio, const void *buf, size_t len, size_t *bytesread);
 
int execio_read(struct execio *eio, void *buf, size_t len, size_t *bytesread);
 
int execio_write(struct execio *eio, const void *buf, size_t len, size_t *byteswritten);
 

	
 
/**
 
  use this function to determine if the using program should keep trying to read/write
 

	
 
  @todo is this function good enough/necessary?
 
 */
 
enum execio_state execio_state(struct execio *eio);
 

	
 
/**
 
   Closes an execio session.
 
   @return nonzero on error 
 
*/
 
int execio_close(struct execio *eio);
 

	
 
#endif
 

	
src/common/remoteio.c
Show inline comments
 
@@ -406,385 +406,385 @@ int remoteio_write(struct remoteio *rem,
 
      poll(&pollfd, 1, 0);
 
      if(pollfd.events & POLLOUT)
 
	{
 
	  err = funcmap[rem->method].write_func(rem, buf, len, &bytes_written);
 
	  if(bytes_written > 0)
 
	    {
 
	      len -= bytes_written;
 
	      buf += bytes_written;
 
	    }
 
	}
 
    }
 

	
 
  /**
 
   * zero length is easy... and might be possible if the above
 
   * optimization works ;-)
 
   */
 
  if(!len)
 
    return 0;
 

	
 
  packet = malloc(sizeof(struct remoteio_packet));
 
  if(!packet)
 
    {
 
      fprintf(stderr, "OOM\n");
 
      return 1;
 
    }
 

	
 
  packet->len = len;
 
  packet->data = malloc(len);
 
  if(!packet->data)
 
    {
 
      free(packet);
 
      fprintf(stderr, "OOM\n");
 
      return 1;
 
    }
 

	
 
  memcpy(packet->data, buf, len);
 

	
 
  q_enqueue(rem->outmsgs, packet, 0);
 
  multiio_socket_event_enable(rem->opts->multiio, rem->sock, POLLOUT);
 

	
 
  return 0;
 
}
 

	
 
int _remoteio_handle_write(multiio_context_t multiio,
 
			   int fd,
 
			   short revent,
 
			   struct remoteio_opts *opts,
 
			   struct remoteio *rem)
 
{
 
  struct remoteio_packet *packet;
 
  size_t written_amount;
 

	
 
  int tmp;
 

	
 
  /*
 
   * check if we're out of stuff to write.
 
   */
 
  if(q_empty(rem->outmsgs))
 
    {
 
      multiio_socket_event_disable(multiio, fd, POLLOUT);
 
      return 0;
 
    }
 

	
 
  packet = q_front(rem->outmsgs);
 
  tmp = funcmap[rem->method].write_func(rem, packet->data, packet->len, &written_amount);
 

	
 
  /**
 
     Disconnect in case of write error.
 
  */
 
  if(tmp)
 
    {
 
      fprintf(stderr, __FILE__ ":%d: error handling for write() needs to be inserted into remoteio.... perhaps.. ;-)\n", __LINE__);
 
    }
 
  if(packet->len == written_amount)
 
    {
 
      q_dequeue(rem->outmsgs);
 
      remoteio_packet_free(packet);
 

	
 
      if(q_empty(rem->outmsgs))
 
	multiio_socket_event_disable(multiio, fd, POLLOUT);
 
    }
 
  else
 
    {
 
      /**
 
       * shifting seems the simplest solution.
 
       */
 
      packet->len -= written_amount;
 
      memmove(packet->data, packet->data + written_amount, packet->len);
 
    }
 

	
 
  return 0;
 
}
 

	
 

	
 
int remoteio_close(struct remoteio *rem)
 
{
 
  int rtn;
 
  
 
  /**
 
   * See careful_free's and _remoteio_handle_read()'s docs.  If
 
   * careful_free is nonzero, then we shouldn't free it here because
 
   * such a free would cause a segfault. However, whoever set
 
   * rem->careful_free to nonzero will handle resetting
 
   * rem->careful_free to zero and calling remoteio_close() if
 
   * necessary.
 
   */
 
  if(rem->careful_free)
 
    {
 
      rem->careful_free = 2;
 
      return 0;
 
    }
 

	
 
  /* call close handler */
 
  if(rem->close_handler)
 
    (*rem->close_handler)(rem->opts->generic_handler_data, rem->read_handler_data);
 

	
 
  /* cleanup multiiio stuff */
 
  multiio_socket_del(rem->opts->multiio, rem->sock);
 

	
 
  /* backend-specific cleanup */
 
  rtn = funcmap[rem->method].close_func(rem);
 

	
 
  /* this part is normal ;-) */
 
  free(rem->inbuf.data);
 
  q_free(rem->outmsgs, (list_dealloc_func_t)remoteio_packet_free);
 

	
 
  free(rem);
 

	
 
  return rtn;
 
}
 

	
 
/**
 
 * Frees an entire packet, including the passed pointer. If you just
 
 * want the contents of the packet free()ed, just do
 
 * free(packet.data);
 
 */
 
void remoteio_packet_free(struct remoteio_packet *packet)
 
{
 
  free(packet->data);
 
  free(packet); 
 
}
 

	
 

	
 
int _remoteio_getserver_traverse(char *servername, struct remoteio_server *aserver)
 
{
 
  if(!strcmp(aserver->name, servername))
 
    return FALSE; /* stop traversal */
 

	
 
  return TRUE;
 
}
 

	
 
struct remoteio_server *remoteio_getserver(const struct remoteio_opts *opts, const char *servername)
 
{
 
  int traversal_result;
 
  char *dispensible_servername;
 

	
 
  dispensible_servername = strdup(servername); /* for the sake of constness... */
 
  traversal_result = list_traverse(opts->servers, dispensible_servername, (list_traverse_func_t)&_remoteio_getserver_traverse, LIST_FRNT | LIST_ALTR);
 
  free(dispensible_servername);
 

	
 
  if(traversal_result == LIST_OK)
 
    return (struct remoteio_server *)list_curr(opts->servers);
 

	
 
  return (struct remoteio_server *)NULL;
 
}
 

	
 
size_t remoteio_sendq_len(const struct remoteio *rem)
 
{
 
  return (size_t)q_size(rem->outmsgs);
 
}
 

	
 
/**
 
   different remoteio methods' implementations:
 
 */
 

	
 
/*
 
  SSH, via execio
 
*/
 

	
 
int _remoteio_ssh_open(struct remoteio *rem, struct remoteio_server *server)
 
{
 
  char *userhost;
 
  char *sshargs[] = {rem->opts->ssh_command, NULL /* userhost */, "distrend", "-d", (char *)NULL};
 

	
 
  int rtn;
 

	
 
  if(server->username)
 
    _distren_asprintf(&userhost, "%s@%s", server->username, server->hostname);
 
  else
 
    userhost = strdup(server->hostname);
 
  sshargs[1] = userhost;
 

	
 
  rtn = execio_open( &rem->execio, "ssh", sshargs);
 
  rtn = execio_open( &rem->execio, "ssh", sshargs, 0);
 
  if(rtn)
 
    {
 
      fprintf(stderr, "error opening remoteio channel to ssh userhost ``%s''\n" , userhost);
 
      free(userhost);
 
      return 1;
 
    }
 
  free(userhost);
 
  
 
  return 0;
 
}
 

	
 
int _remoteio_ssh_read(struct remoteio *rem, void *buf, size_t len, size_t *bytesread)
 
{
 
  return execio_read(rem->execio, buf, len, bytesread);
 
}
 

	
 
int _remoteio_ssh_write(struct remoteio *rem, const void *buf, size_t len, size_t *byteswritten)
 
{
 
  return execio_write(rem->execio, buf, len, byteswritten);
 
}
 

	
 
int _remoteio_ssh_close(struct remoteio *rem)
 
{
 
  int rtn;
 
  
 
  rtn = execio_close(rem->execio);
 
  if(rtn)
 
    fprintf(stderr, "%s:%d: error closing execio\n", __FILE__, __LINE__);
 
  
 
  return rtn;
 
}
 

	
 
#ifndef _WIN32
 
/*
 
  local sockets implementation (``named pipes''), unix-only
 
 */
 
int _remoteio_sock_open(struct remoteio *rem, struct remoteio_server *server)
 
{
 
  int sock;
 
  struct sockaddr_un sockaddr;
 

	
 
  /*
 
    The POSIX docs pretty much say that I can't depend on sockpath being able to be longer than 
 
    some proprietary length. So, if the compiler specifies a long path for RUNSTATEDIR, it could
 
    cause a buffer overflow.
 
   */
 
  char *sockpath = RUNSTATEDIR "/distrend.sock";
 
  unsigned int sockaddr_len;
 

	
 
  sock = socket(AF_UNIX, SOCK_STREAM, 0);
 
  if(sock == -1)
 
    {
 
      perror("socket");
 
      return 1;
 
    }
 

	
 
  sockaddr.sun_family = AF_UNIX;
 
  /*
 
    The terminating NULL should not be included in what's copied to sun_path,
 
    although it won't hurt as long as strlen(sockpath) < max socket length
 
   */
 
  for(sockaddr_len = 0; sockpath[sockaddr_len]; sockaddr_len ++)
 
    sockaddr.sun_path[sockaddr_len] = sockpath[sockaddr_len];
 

	
 
  if(connect(sock, (struct sockaddr *)&sockaddr, sockaddr_len) == -1)
 
    {
 
      perror("connect");
 
      close(sock);
 
      return 1;
 
    }
 

	
 
  rem->sock = sock;
 

	
 
  return 0;
 
}
 

	
 
#endif /* _WIN32 */
 

	
 
int _remoteio_sock_close(struct remoteio *rem)
 
{
 
  close(rem->sock);
 

	
 
  return 0;
 
}
 

	
 
int _remoteio_sock_read(struct remoteio *rem, void *buf, size_t len, size_t *bytesread)
 
{
 
  ssize_t readrtn;
 

	
 
  *bytesread = 0;
 
  readrtn = read(rem->sock, buf, len);
 
  /*
 
    The following is valid for blocking sockets:
 
   */
 
  if(readrtn == -1)
 
    {
 
      /*
 
	in this case, we may have been interrupted by a signal and errno == EINTR
 
	or the connection was reset and errno = ECONNRESET
 

	
 
	Some of these are not error conditions:
 
       */
 
      perror("read");
 

	
 
      if(errno != EINTR)
 
	{
 
	  fprintf(stderr, "error reading socket in remoteio_sock_read\n");
 
	  return 1;
 
	}
 

	
 
      return 0;
 
    }
 

	
 
  *bytesread = readrtn;
 
  if(!readrtn)
 
    {
 
      /*
 
	means EOF except when FD is in ``message-nondiscard'' or ``message-discard''
 
	modes.
 
       */
 
      return 1;
 
    }
 

	
 
  return 0;
 
}
 

	
 
int _remoteio_sock_write(struct remoteio *rem, const void *buf, size_t len, size_t *byteswritten)
 
{
 
  ssize_t writertn;
 

	
 
  writertn = write(rem->sock, buf, len);
 

	
 
  if(writertn == -1)
 
    {
 
      perror("write");
 
      if(errno != EINTR)
 
	{
 
	  fprintf(stderr, "error writing to socket in remoteio_sock_write()\n");
 
	  return 1;
 
	}
 
    }
 

	
 
  *byteswritten = writertn;
 
  if(!writertn)
 
    {
 
      /*
 
	should we consider this an error? I'm pretty
 
	sure we should :-/
 
       */
 
      fprintf(stderr, "write() returned 0 in remoteio_sock_write()\n");
 
      return 1;
 
    }
 

	
 
  return 0;
 
}
 

	
 
/**
 
   TCP, taking advantage of the two generic socks read/write functions:
 
 */
 
int _remoteio_tcp_open(struct remoteio *rem, struct remoteio_server *server)
 
{
 
  int tmp;
 
  int tmp2;
 

	
 
  int sock;
 

	
 
  char *hostname;
 
  char *port;
 

	
 
  struct addrinfo addrinfo_hints;
 
  struct addrinfo *addrinfo_res;
 

	
 
  static char *default_port = REMOTEIO_DEFAULT_PORT;
 

	
 
  /**
 
     only hostname should be free()-ed, not port,
 
     because both are from the same block of malloc()-ed
 
     memory
 
   */
 
  hostname = strdup(server->hostname);
 
  for(port = hostname;
 
      *port && *port != ':';
 
      port ++)
 
    ;
 
  if(*port)
 
    {
 
      *port = '\0';
 
      port ++;
 
    }
 
  else
 
    port = default_port;
 

	
src/server/slavefuncs.c
Show inline comments
 
@@ -110,385 +110,385 @@ size_t curl_writetodisk(void *ptr, size_
 
    return fwrite(ptr, size, nmemb, stream);
 
  }
 

	
 
/** Helper function for cURL's progress display */
 
int curl_progress(char *Bar, double t, double d, double ultotal, double ulnow)
 
{
 
fprintf(stderr,"Downloading: %f%% complete\r",d/t*100);
 
return 0;
 
}
 

	
 
/** Retrieves a URL with cURL and saves it to disk */
 
CURLcode curlget(char *url, char *out){
 
  fprintf(stderr,"Preparing to download %s\n",url);
 
  double *Bar; // Stores cURL progress display info
 
  CURL *curl;
 
  CURLcode res;
 
  FILE *outfile;
 

	
 
  res = CURLE_FAILED_INIT;
 
  curl = curl_easy_init();
 
  if(curl)
 
    {
 
    outfile = fopen(out, "w"); // Open where we're writing to
 
    if(outfile == NULL)
 
      return 2; // Output dir doesn't exist
 
    curl_easy_setopt(curl, CURLOPT_URL, url);
 
    curl_easy_setopt(curl, CURLOPT_WRITEDATA, outfile);
 
    curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, curl_writetodisk); // this MUST be set for win32 compat.
 
    curl_easy_setopt(curl, CURLOPT_NOPROGRESS, 0);
 
    curl_easy_setopt(curl, CURLOPT_PROGRESSFUNCTION, (curl_progress_callback)&curl_progress);
 
    curl_easy_setopt(curl, CURLOPT_PROGRESSDATA, &Bar);
 
    res = curl_easy_perform(curl);
 
    curl_easy_cleanup(curl);
 
    fclose(outfile);
 
  }
 
  fprintf(stderr,"\n"); // Clears out he progressbar's carriage return
 
  return res; // 0 is OK, 1 is 404 or other error
 
}
 

	
 
/** Posts a file to a url with cUrl */
 
CURLcode curlpost(char *filename, char *url, int jobnum, int framenum, int slavekey)
 
{
 
  char *targetname = "uploadedfile"; // Name of the target in the php file on the server (Don't change me unless you have different PHP code)
 
  CURL *curl;
 
  CURLcode res;
 
  struct curl_httppost *formpost=NULL;
 
  struct curl_httppost *lastptr=NULL;
 
  struct curl_slist *headerlist=NULL;
 
  static const char buf[] = "Expect:";
 

	
 
  char *sjobnum;
 
  char *sframenum;
 
  char *sslavekey;
 

	
 
  if(DEBUG)
 
    fprintf(stderr,"Uploading to %s\n", url);
 

	
 
  _distren_asprintf(&sjobnum,"%d",jobnum);
 
  _distren_asprintf(&sframenum,"%d",framenum);
 
  _distren_asprintf(&sslavekey,"%d",slavekey);
 

	
 
  curl_global_init(CURL_GLOBAL_ALL);
 

	
 
  /* jobnum field... */
 
   curl_formadd(&formpost,
 
                &lastptr,
 
                CURLFORM_COPYNAME, "jobnum",
 
                CURLFORM_COPYCONTENTS, sjobnum, CURLFORM_END);
 
  /* framenum field... */
 
  curl_formadd(&formpost,
 
               &lastptr,
 
               CURLFORM_COPYNAME, "framenum",
 
               CURLFORM_COPYCONTENTS, sframenum, CURLFORM_END);
 
  /* slavekey field... */
 
  curl_formadd(&formpost,
 
               &lastptr,
 
               CURLFORM_COPYNAME, "slavekey",
 
               CURLFORM_COPYCONTENTS, sslavekey, CURLFORM_END);
 
  /* upload field... */
 
  curl_formadd(&formpost,
 
               &lastptr,
 
               CURLFORM_COPYNAME, targetname,
 
               CURLFORM_FILE, filename,
 
               CURLFORM_END);
 
  /* filename field... */
 
  curl_formadd(&formpost,
 
               &lastptr,
 
               CURLFORM_COPYNAME, "filename",
 
               CURLFORM_COPYCONTENTS, filename,
 
               CURLFORM_END);
 
  /* submit field, not usually needed, just in case... */
 
  curl_formadd(&formpost,
 
               &lastptr,
 
               CURLFORM_COPYNAME, "submit",
 
               CURLFORM_COPYCONTENTS, "send",
 
               CURLFORM_END);
 

	
 
  res = CURLE_FAILED_INIT;
 
  curl = curl_easy_init();
 
  headerlist = curl_slist_append(headerlist, buf);
 
  if(curl)
 
    {
 
    /* Setting the URL to get the post, and the contents of the post */
 
    curl_easy_setopt(curl, CURLOPT_URL, url);
 
    curl_easy_setopt(curl, CURLOPT_HTTPPOST, formpost);
 
    res = curl_easy_perform(curl);
 

	
 
    curl_easy_cleanup(curl);
 
    /* cleanup the formpost junk */
 
    curl_formfree(formpost);
 
    curl_slist_free_all (headerlist);
 
    free(sjobnum);
 
    free(sframenum);
 
    free(sslavekey);
 
    }
 
  return res;
 
}
 

	
 
/** Replaces wordtoreplace with replacewith in conffile (relative to SYSCONFDIR) */
 
int conf_replace(char *conffile, char *wordtoreplace, char *replacewith){
 
  int maxlinelen = 120;
 
  char *fileOrig;
 
  char *fileRepl;
 
  _distren_asprintf(&fileOrig, "%s/%s", SYSCONFDIR, conffile);
 
  _distren_asprintf(&fileRepl, "%s%s.edited", SYSCONFDIR, conffile);
 
  char buffer[maxlinelen+2];
 
  char *buff_ptr, *find_ptr;
 
  FILE *fp1, *fp2;
 
  size_t find_len = strlen(wordtoreplace);
 
  fp1 = fopen(fileOrig,"r");
 
  fp2 = fopen(fileRepl,"w");
 
  if (fp1 ==NULL){
 
    fprintf(stderr, "%s doesn't exist\n",fileOrig);
 
    return 0;
 
  }
 
  else if(fp2 ==NULL){
 
    fprintf(stderr, "Can't write a file to disk! Check permissions.\n");
 
    return 0;
 
  }
 
  else{
 
    while(fgets(buffer,maxlinelen+2,fp1))
 
      {
 
        buff_ptr = buffer;
 
        while ((find_ptr = strstr(buff_ptr,wordtoreplace)))
 
        {
 
           while(buff_ptr < find_ptr)
 
             fputc((int)*buff_ptr++,fp2);
 
           fputs(replacewith,fp2);
 
           buff_ptr += find_len;
 
         }
 
         fputs(buff_ptr,fp2);
 
      }
 
    rename(fileRepl, fileOrig);
 
  }
 
  fclose(fp2);
 
  fclose(fp1);
 
  fprintf(stderr,"Wrote conf file...\n");
 
return 1; // Success
 
}
 

	
 

	
 
/* Executors */
 

	
 
/** Executor function for Blender operations */
 
int exec_blender(char *input, char *output, char *outputExt, int xres, int yres, int frame)
 
{
 
  int ret;
 

	
 
  stringToUpper(outputExt);
 

	
 
  char *frame_str;
 
  _distren_asprintf(&frame_str, "%i", frame);
 

	
 
  char *xres_str;
 
  _distren_asprintf(&xres_str, "%i", xres);
 

	
 
  char *yres_str;
 
  _distren_asprintf(&yres_str, "%i", yres);
 

	
 
  char *command = "blender"; // @TODO: We currently expect this to be in PATH
 
  char *cmd[] = { command, "-b", input, "-o", output, "-F", outputExt, "-f", frame_str, "-t", "0", (char *)NULL }; // arguments for blender
 

	
 
  if(DEBUG)
 
    fprintf(stderr,"Preparing to execute command: %s -b %s -o %s -f %s\n", command, input, output, frame_str);
 

	
 
  char buf[20];
 
  struct execio *testrem;
 
  size_t readlen;
 

	
 
  if(DEBUG)
 
    fprintf(stderr,"Executing: %s\n", frame_str);
 

	
 
  ret = execio_open(&testrem, command, cmd);
 
  ret = execio_open(&testrem, command, cmd, 10);
 
  if(ret)
 
    {
 
      fprintf(stderr, "Error running blender\n");
 
      return 1;
 
    }
 
  buf[19] = '\0';
 
  while(!execio_read(testrem, buf, 19, &readlen))
 
    {
 
       buf[readlen] = '\0';
 
       if(DEBUG)
 
         fprintf(stderr, "read \"%s\"\n", buf);
 
    }
 
  execio_close(testrem);
 
  free(frame_str);
 
  return ret;
 
}
 

	
 
void xmlinit()
 
{
 
  xmlInitParser();
 
  xmlXPathInit();
 
}
 

	
 
void xmlcleanup()
 
{
 
  xmlCleanupParser();
 
}
 

	
 

	
 
/** Creates directories recursively */
 
int distren_mkdir_recurse(const char *dirname)
 
{
 
  size_t counter;
 
  char *nextdir;
 
  int ret;
 

	
 
  nextdir = strdup(dirname);
 
  /* skip preficing slashes */
 
  for(counter = 0; nextdir[counter] == '/'; counter ++)
 
    ;
 
  for(; nextdir[counter]; counter ++)
 
    {
 
      /** @TODO OS-portabalize the path-separators */
 
      if(nextdir[counter] == '/')
 
        {
 
          nextdir[counter] = '\0';
 
          ret = mkdir(nextdir, S_IRWXU | S_IRGRP | S_IROTH);
 
	  if(ret == -1
 
	     && errno != EEXIST)
 
	    {
 
	      perror("mkdir");
 
	      free(nextdir);
 
	      return 1;
 
	    }
 
          nextdir[counter] = '/';
 
        }
 
    }
 
  ret = mkdir(nextdir, S_IRWXU | S_IRGRP | S_IROTH);
 
  if(ret == -1
 
     && errno != EEXIST)
 
    {
 
      perror("mkdir");
 
      free(nextdir);
 
      return 1;
 
    }
 
  free(nextdir);
 

	
 
  return 0;
 
}
 

	
 
/**
 
 @TODO: Use for constructing path to job data locally and/or on data.distren.org
 
 */
 
int job_build_path(char *filename, unsigned int jobnum)
 
{
 
  return 0;
 
}
 

	
 

	
 
int downloadTar(char *url, char *destinationPath){
 
  // Prepare to download the job tar if it isn't  present
 
  struct stat buffer;
 
  int fstatus = stat(destinationPath, &buffer);
 
  if(fstatus == -1)
 
    {
 
      // Download the Tar
 
      int ret = curlget(url, destinationPath);
 
      if(ret == 0){
 
        fprintf(stderr, "Job data retrieved successfully\n");
 
        // free(url); @FIXME: causes doublefree! Curl must free the url?
 
        return 0;
 
      }
 
      else if(ret == 1){
 
        fprintf(stderr, "Downloading job data from %s failed. Check your network connection.\n",url);
 
        free(url);
 
        return 1; // Eventually make a retry loop
 
      }
 
    }
 
  if(DEBUG)
 
    fprintf(stderr, "Tar at %s already exists! Download cancelled.\n", destinationPath);
 
  return 2;
 
}
 

	
 

	
 
int uploadOutput(char *pathtoOutput, char *urltoOutput, int jobnum, int framenum, int slavekey){
 
  //fprintf(stderr,"Uploading output %s to url %s for job %d and frame %d for slavekey %d", pathtoOutput, urltoOutput, jobnum, framenum, slavekey);
 
  if( !curlpost(pathtoOutput, urltoOutput, jobnum, framenum, slavekey)) // Uploads output
 
    {
 
      if(DEBUG)
 
        fprintf(stderr,"Upload successful, removing old output...\n");
 
      else
 
        fprintf(stderr,"Uploaded.\n");
 

	
 
      remove(pathtoOutput); // Delete the file after its uploaded
 
      return 0;
 
    }
 
  else
 
    {
 
      fprintf(stderr,"Upload failed. Check your network connection. Retrying upload...\n");
 
      int tries=1;
 
      while(tries<=10 && curlpost(pathtoOutput, urltoOutput, jobnum, framenum, slavekey))
 
        {
 
          fprintf(stderr, "Upload failed. Trying again in 10 seconds... (attempt %d of 10)\n", tries);
 
          tries++;
 
          sleep(10);
 
        }
 
      return 1; // Upload failed after multiple tries
 
      // @FUTURE: Keep track of files that we were unable to upload, and upload them later
 
    }
 
}
 

	
 
void prepareJobPaths(int jobnum, int framenum, char *outputExt, char *datadir, char **urltoTar,char **pathtoTar,char **pathtoTardir,char **pathtoJob, char **pathtoJobfile, char **urltoJobfile, char **urltoOutput,char **pathtoOutput, char **pathtoRenderOutput, char **pathtoOutdir)
 
{
 
  // Variable Preparation
 
  char *jobdatapath;
 
   _distren_asprintf(&jobdatapath, "job%d", jobnum);
 
   _distren_asprintf(urltoTar, "http://data.distren.org/job%d/job.tar.gz", jobnum, jobnum); // Prepares URL to download from
 
   _distren_asprintf(urltoJobfile, "http://data.distren.org/job%d/job.blend", jobnum); // Prepares URL to download from
 

	
 
   _distren_asprintf(pathtoTar, "%s/%s/job.tar.gz", datadir, jobdatapath, jobnum); // Prepares destination to save to
 

	
 
   _distren_asprintf(pathtoTardir, "%s/%s/", datadir, jobdatapath); // Prepares destination to save to
 

	
 
   _distren_asprintf(pathtoJob, "%s/%s/", datadir, jobdatapath);
 

	
 
   _distren_asprintf(pathtoJobfile, "%s/%s/job.blend", datadir, jobdatapath ); // Prepares the path to the jobfile
 
   _distren_asprintf(urltoOutput, "http://distren.org/slaveUpload.php?jobkey=%d&framekey=%d",jobnum,framenum); // Prepares the URL where output is posted
 

	
 
   _distren_asprintf(pathtoRenderOutput, "%s/%s/output/job%d-frame#.%s", datadir, jobdatapath, jobnum, outputExt ); // Note: the # is for blender to put in framenum in output file
 
   _distren_asprintf(pathtoOutput, "%s/%s/output/job%d-frame%d.%s", datadir, jobdatapath, jobnum, framenum, outputExt ); // Note: the # is for blender to put in framenum in output file
 

	
 
   _distren_asprintf(pathtoOutdir, "%s/%s/output", datadir, jobdatapath);
 
   free(jobdatapath);
 
}
 

	
 
int checkUsername(char *username)
 
{
 
  if(username == NULL || strcmp(username, "!username") == 0 )
 
    {
 
     fprintf(stderr, "\nPlease ensure that your slave ID is present in distrenslave.conf, or use the -u flag to set a slave ID.\n");
 
     return 1;
 
   }
 
   else
 
     if( username != NULL || strcmp(username, "!username") != 0 )
 
       {
 
         // Log in the user
 
         if(login_user(username) == 1){
 
           // Logged in OK
 
           return 0;
 
         }
 
         else
 
           {
 
             fprintf(stderr, "Login failed, please check your username. If you have not registered, please do so on the DistRen website.\n");
 
             return 1;
 
           }
 
       }
 
     else
 
       {
 
         fprintf(stderr, "Please check your distrenslave.conf, it appears to be incorrectly formatted.\n");
 
         return 1;
 
       }
 
}
 

	
 
void slaveTest(char *datadir)
 
{
 
  int command;
 
  int test = 1;
 
  int jobnum = 0;
 
  int framenum = 0;
 
  int slavekey = 0;
 
  fprintf(stderr,"Hello!\n");
 
  char tmpString1[100] = "";
 
@@ -538,453 +538,453 @@ void slaveTest(char *datadir)
 
       fprintf(stderr,"Path to compressed data: ");
 
       scanf("%s", tmpString2);
 
       unpackJob(datadir, tmpString1);
 
       break;
 
     case 5:
 
       test = 0;
 
       break;
 
     default:
 
       fprintf(stderr, "Invalid input, please try again.\n");
 
       break;
 
     }
 
   }
 
}
 

	
 
/*
 
int runBenchmark(int slavekey, char *datadir){
 
  // Execute blender
 

	
 
  if(exec_blender(pathtoJobfile, pathtoOutput, framenum))
 
    {
 
      fprintf(stderr,"Error running Blender. Check your installation and/or your PATH.\n");
 
      _web_resetframe(slavekey, password, jobnum, framenum);  // Unassign the frame on the server so other slaves can render it
 
      return 1;
 
    }
 
  free(pathtoJobfile);
 

	
 
  struct stat buffer;
 
  int fstatus = stat(pathtoOutput, &buffer);
 
  if(fstatus == -1){
 
    fprintf(stderr,"*** Frame was not rendered correctly! Scene may not have camera, or your blender installation is not working.\n");
 
    _web_resetframe(slavekey, password, jobnum, framenum);  // Unassign the frame on the server so other slaves can render it
 
    return 1;
 
  }
 

	
 
}
 
*/
 

	
 
/* simpleSlave functions */
 

	
 
/** Memory struct for curl */
 
struct _web_memorystruct {
 
  char *memory;
 
  size_t size;
 
};
 

	
 
void *_web_myrealloc(void *ptr, size_t size);
 

	
 
void *_web_myrealloc(void *ptr, size_t size)
 
{
 
  /* There might be a realloc() out there that doesn't like reallocing
 
     NULL pointers, so we take care of it here */
 
  if(ptr)
 
    return realloc(ptr, size);
 
  else
 
    return malloc(size);
 
}
 

	
 
size_t _web_writememorycallback(void *ptr, size_t size, size_t nmemb, void *data)
 
{
 
  size_t realsize = size * nmemb;
 
  struct _web_memorystruct *mem = (struct _web_memorystruct *)data;
 

	
 
  mem->memory = _web_myrealloc(mem->memory, mem->size + realsize + 1);
 
  if (mem->memory) {
 
    memcpy(&(mem->memory[mem->size]), ptr, realsize);
 
    mem->size += realsize;
 
    mem->memory[mem->size] = 0;
 
  }
 
  return realsize;
 
}
 

	
 
struct _web_memorystruct _web_getrequest(char *url){
 
  // fprintf(stderr,"Preparing to get request at %s",url);
 

	
 
  CURL *curl;
 
  CURLcode res;
 
  struct _web_memorystruct chunk;
 

	
 
  chunk.memory=NULL; /* we expect realloc(NULL, size) to work */
 
  chunk.size = 0;    /* no data at this point */
 

	
 
  curl = curl_easy_init();
 
  if(curl) {
 
    curl_easy_setopt(curl, CURLOPT_URL, url);
 
    curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, _web_writememorycallback);
 
    curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void *)&chunk);
 
    curl_easy_setopt(curl, CURLOPT_USERAGENT, "libcurl-agent/1.0");
 

	
 
    res = curl_easy_perform(curl);
 
    curl_easy_cleanup(curl);
 
  }
 

	
 
  /* we're done with libcurl, so clean it up */
 
  curl_global_cleanup();
 
  return chunk; // 0 is OK, 1 is 404 or other error
 
}
 

	
 
void _web_finishframe(int slavekey, char *slavepass, int jobnum, int framenum){
 
  char *url;
 
  _distren_asprintf(&url,"http://distren.org/slave/act.php?mode=finishframe&slavekey=%d&slavepass=%s&jobnum=%d&framenum=%d", slavekey, slavepass, jobnum, framenum);
 
  struct _web_memorystruct data = _web_getrequest(url);
 
  free(url);
 

	
 
  if(DEBUG)
 
    fprintf(stderr,"%s\n", data.memory);
 
  if(data.memory)
 
    free(data.memory);
 
}
 

	
 
void _web_resetframe(int slavekey, char *slavepass, int jobnum, int framenum){
 
  fprintf(stderr,"Resetting frame %d in job %d on server... ",framenum,jobnum);
 
  char *url;
 
  _distren_asprintf(&url,"http://distren.org/slave/act.php?mode=resetframe&slavekey=%d&slavepass=%s&jobnum=%d&framenum=%d", slavekey, slavepass, jobnum, framenum);
 
  struct _web_memorystruct data = _web_getrequest(url);
 
  free(url);
 

	
 
  if(DEBUG)
 
    fprintf(stderr,"%s\n", data.memory);
 
  if(data.memory)
 
    free(data.memory);
 
}
 

	
 
void _web_startframe(int slavekey, char *slavepass, int jobnum, int framenum){
 
  if(DEBUG)
 
    fprintf(stderr,"Marking frame %d started on server... ",framenum);
 
  char *url;
 
  _distren_asprintf(&url,"http://distren.org/slave/act.php?mode=startframe&slavekey=%d&slavepass=%s&jobnum=%d&framenum=%d", slavekey, slavepass, jobnum, framenum);
 
  struct _web_memorystruct data = _web_getrequest(url);
 
  free(url);
 

	
 
  if(DEBUG)
 
    fprintf(stderr,"%s\n", data.memory);
 
  if(data.memory)
 
    free(data.memory);
 
}
 

	
 
/** @TODO: Needs to get xres, yres, outpuext */
 
int _web_getwork(int slavekey, char *slavepass, int *jobnum, int *framenum, int *xres, int *yres, char **outputext)
 
{
 
  char *url;
 
  _distren_asprintf(&url,"http://distren.org/slave/act.php?mode=getwork&slavekey=%d&slavepass=%s", slavekey, slavepass);
 
  struct _web_memorystruct data = _web_getrequest(url);
 
  free(url);
 

	
 
  if(!data.memory || !strcmp(data.memory,",")){
 
    fprintf(stderr,"*** No work available on server! In other news, really weird things are happening. Check it out. You shouldn't be seeing this.\n");
 
    return 0;
 
  }
 
  else if(!strcmp(data.memory, "ERROR_BADKEY")){
 
    fprintf(stderr,"*** Slave %d does not exist! Check your slave ID, or register your slave on distren.org\n",slavekey);
 
    free(data.memory);
 
    return 0;
 
  }
 
  else if(!strcmp(data.memory, "ERROR_NORENDERPOWER")){
 
    fprintf(stderr,"*** Render power not set! Please invoke distrensimpleslave -r to run the benchmark!\n");
 
    free(data.memory);
 
    return 0;
 
  }
 
  // Compare to PACKAGE_VERSION
 
  else{
 
    char *tmp;
 
    char *serverversion;
 

	
 
    tmp = strtok (data.memory,",,");
 
    if(tmp != NULL) { // make sure work is available
 
      *jobnum = atoi(tmp); // Grab jobnum
 

	
 
      tmp = strtok (NULL, ",");
 
      if(tmp == NULL)
 
        return 0; // no work
 
      *framenum = atoi(tmp); // Grab framenum
 

	
 
      tmp = strtok (NULL, ",");
 
      if(tmp == NULL)
 
        return 0; // no work
 
      serverversion = tmp;
 

	
 
      tmp = strtok (NULL, ",");
 
      if(tmp == NULL)
 
        return 0; // no work
 
      *xres = atoi(tmp);
 

	
 
      tmp = strtok (NULL, ",");
 
      if(tmp == NULL)
 
        return 0; // no work
 
      *yres = atoi(tmp);
 

	
 
      tmp = strtok (NULL, ",");
 
      if(tmp == NULL)
 
        return 0; // no work
 
      *outputext = strdup(tmp);
 
      if(DEBUG)
 
        fprintf(stderr,"GETWORK Debug output - Job: %d | Frame: %d | Xres: %d | Yres: %d | Outformat: %s\n", *jobnum, *framenum, *xres, *yres, outputext);
 
        fprintf(stderr,"GETWORK Debug output - Job: %d | Frame: %d | Xres: %d | Yres: %d | Outformat: %s\n", *jobnum, *framenum, *xres, *yres, *outputext);
 

	
 
      // @FIXME: Setting outputext and serverversion = temp; will this cause issues as these are pointers to parts of the original temp var?
 

	
 
      // @TODO: This should be called every time, not just on fail.
 
      if(strcmp(PACKAGE_VERSION,serverversion)){
 
        fprintf(stderr,"Your distren package is out of date! Please acquire a newer version. (%s local vs %s remote)\n", PACKAGE_VERSION, serverversion);
 
        return 0;
 
      }
 
      if(DEBUG)
 
        fprintf(stderr,"Software versions: %s local vs %s remote\n", PACKAGE_VERSION, serverversion);
 

	
 

	
 
      free(data.memory);
 
      return 1;
 
    }
 
    else
 
      return 0; // error
 
  }
 
}
 

	
 
void _web_setrenderpower(int slavekey, char *slavepass, int renderpower){
 
  fprintf(stderr,"Setting render power on server... ");
 
  char *url;
 
  _distren_asprintf(&url,"http://distren.org/slave/act.php?mode=setrenderpower&slavekey=%d&slavepass=%s&renderpower=%d", slavekey, slavepass, renderpower);
 
  struct _web_memorystruct data = _web_getrequest(url);
 
  free(url);
 

	
 
  if(DEBUG)
 
    fprintf(stderr,"%s\n", data.memory);
 
  if(data.memory)
 
    free(data.memory);
 
}
 

	
 
int slaveBenchmark(char *datadir, int *benchmarkTime, int *renderPower){
 
  int ret;
 
  int frameToRender = 1;
 
  char *frame_str;
 
  _distren_asprintf(&frame_str, "%d", frameToRender); // Render frame 1
 

	
 
  char *output;
 
  _distren_asprintf(&output, "%s/benchmark#.jpg", datadir); // Where to save benchmark output
 

	
 
  char *realOutput;
 
  _distren_asprintf(&realOutput, "%s/benchmark%d.jpg", datadir, frameToRender); // Where to save benchmark output
 

	
 

	
 
  char *input;
 
  _distren_asprintf(&input, "%s/benchmark.blend", datadir); // Input file
 

	
 
  fprintf(stderr,"Downloading benchmark data...\n");
 
  curlget("http://data.distren.org/benchmark.blend", input); // Download to input file location
 

	
 
  char *command = "blender"; // @TODO: We currently expect this to be in PATH
 
  char *cmd[] = { command, "-b", input, "-o", output, "-f", frame_str, "-t", "0", (char *)NULL }; // arguments for blender
 

	
 
  // fprintf(stderr,"Preparing to execute command: %s -b %s -o %s -f %s\n", command, input, output, frame_str);
 
  fprintf(stderr,"Running benchmark...\n");
 

	
 
  long startTime;
 
  long endTime;
 

	
 
  time(&startTime);
 

	
 
  char buf[20];
 
  struct execio *testrem;
 
  size_t readlen;
 

	
 
  ret = execio_open(&testrem, command, cmd);
 
  ret = execio_open(&testrem, command, cmd, 10);
 
  if(ret)
 
    {
 
      fprintf(stderr, "Error executing blender\n");
 
      return 1;
 
    }
 

	
 
  buf[19] = '\0';
 
  while(!execio_read(testrem, buf, 19, &readlen))
 
    {
 
       buf[readlen] = '\0';
 
       fprintf(stderr, "read \"%s\"\n", buf);
 
    }
 
  execio_close(testrem);
 

	
 
  time(&endTime);
 

	
 
  struct stat buffer;
 
  int ostatus = stat(realOutput, &buffer);
 
  if(ostatus == -1){
 
    ret = 1; // Return error if output wasn't generated
 
  }
 
  else
 
    remove(output);
 

	
 
  *benchmarkTime = abs(difftime(startTime,endTime));
 
  float tmp = *benchmarkTime;
 
  tmp = (1/tmp) * 50000;
 
  *renderPower = (int)tmp;
 
  
 
free(realOutput);
 
  free(frame_str);
 
  free(input);
 
  free(output);
 
  return ret;
 
}
 

	
 

	
 

	
 
/** *********************************************************************************************************/
 
/** Why hello ohnobinki! Normaldotcom has graciously prepared this portion of code for you to work on! Yay! */
 
/** *********************************************************************************************************/
 

	
 

	
 
/**
 
   Extracts archive to the specified directory, creating this directory
 
   if necessary (but this directory will not be recursively created).
 
   @param outdir output directory
 
   @param pathtoTar filename of the archive to extract
 

	
 
   ohnobinki: please make me work :-\
 
 */
 
int unpackJob(char *outdir, char *pathtoTar)
 
{
 
  int ret;
 

	
 
  struct archive *a;
 
  struct archive_entry *ae;
 
  int astatus;
 

	
 
  /* ignore return because directory may exist already */
 
  mkdir(outdir, 0700);
 
  ret = chdir(outdir);
 
  if(ret == -1)
 
    {
 
      perror("chdir");
 
      return 1;
 
    }
 

	
 
  a = archive_read_new();
 
  ae = archive_entry_new();
 

	
 
  if(!a
 
     || !ae)
 
    {
 
      if(a)
 
	archive_read_finish(a);
 
      if(ae)
 
	archive_entry_free(ae);
 
      return 1;
 
    }
 

	
 
  fprintf(stderr, "Trying to unpack %s into %s\n", pathtoTar, outdir);
 

	
 
  archive_read_support_compression_all(a);
 
  archive_read_support_format_all(a);
 
  astatus = archive_read_open_filename(a, pathtoTar, 1);
 
  if (astatus != ARCHIVE_OK)
 
    {
 
      fprintf(stderr, "Error opening archive!\n");
 
      archive_read_finish(a);
 
      archive_entry_free(ae);
 
      return 1;
 
    }
 

	
 
  while((astatus = archive_read_next_header2(a, ae)) == ARCHIVE_OK)
 
    {
 
      astatus = archive_read_extract(a, ae,
 
				     ARCHIVE_EXTRACT_NO_OVERWRITE
 
				     | ARCHIVE_EXTRACT_SECURE_SYMLINKS
 
				     | ARCHIVE_EXTRACT_SECURE_NODOTDOT);
 
      if(astatus != ARCHIVE_OK)
 
	fprintf(stderr, "Encountered error or warning when attempting to extract file: %s\n",
 
		archive_entry_pathname(ae));
 
    }
 
  archive_entry_free(ae);
 
  archive_read_finish(a);
 

	
 
  if(astatus != ARCHIVE_EOF)
 
    {
 
      fprintf(stderr, "Error reading archive!\n");
 
      return 1;
 
    }
 

	
 
  return 0;
 
}
 

	
 

	
 
/** Logs the user into the server after ensuring that keys exist
 
    ohnobinki: I assume you could use this for remoteio, or just kill it
 
*/
 
int login_user(char *username)
 
{
 
  // @TODO: Put some telnet-style auth code here unless this is obselete
 
  return 1; // success
 
}
 

	
 
/**
 
 * Sends the server a single request (see protocol.h)
 
 * ohnobinki: This should hopefully work, maybe ;D
 
 *
 
 * @deprecated THIS FUNCTION SHOULD DIE VERY, VERY SOON!
 
 * (and painfully :-p)
 
*/
 
int sendSignal(struct remoteio *rem, char signal)
 
{
 

	
 
  fprintf(stderr, __FILE__ ":%d: Ignoring call to DEPRECATED and WRONG sendSignal() function. See similar message for sendExtSignal() for details\n", __LINE__);
 
  return 1;
 
  remoteio_write(rem, &signal, 1);
 

	
 
  /**
 
     if remoteio_write returned 1, the connection
 
     is probably dead or there was a real error
 
   */
 
  return 1;
 
}
 

	
 
/**
 
 * Sends the server an extended signal (request + data)
 
 * ohnobinki: I have no clue how you really want to handle this. Please clarify/edit
 
 * normaldotcom: I see more and more how clueless you are, I hope to get to his soon ;-)
 
 *
 
 * @deprecated lol
 
 */
 
int sendExtSignal(struct remoteio *rem, char signal, char *data)
 
{
 
  size_t len;
 
  char *ssignal;
 

	
 
  fprintf(stderr, __FILE__ ":%d: Ignoring call to DEPRECATED and WRONG sendExtSignal() function. First of all, this function's name is camelCase. Secondly, it doesn't use protocol.h properly. I'll show how later. Thirdly, when protocol.h and request.h (still being written) are used properly, you don't need sendExtSignal() at all.\n", __LINE__);
 
  return 1;
 

	
 
  /**
 
   * Just append the data FIXME: We should do this differently
 
   */
 
  _distren_asprintf(&ssignal, "%c%s", signal, data);
 
  len = strlen(ssignal);
 
  remoteio_write(rem, ssignal, len);
 

	
 
  return 0;
 
}
 

	
 

	
 
/* Port of web functions for standard code
 

	
 
   Currently, most functions are stubs due to lack
 
   of socket reading code
 

	
 
   ohnobinki: I can take care of a fair amount of this, but the remotio reading and writing is where you should really lay down some code.
 
*/
 

	
 
/** marks frame finished on server */
 
void finishframe(struct remoteio *rem, int jobnum, int framenum){
 
  char* data;
 
  _distren_asprintf(&data, "%d%d", jobnum, framenum);
 
  sendExtSignal(rem, DISTREN_REQUEST_STATUS, data);
 
}
 

	
 
/** resets frame to unassigned on server */
 
void resetframe(struct remoteio *rem, int jobnum, int framenum){
 
  fprintf(stderr,"Resetting frame %d in job %d on server... ",framenum,jobnum);
 
  char* data;
test/check_execio.c
Show inline comments
 
/*
 
 * Copyright 2010 Nathan Phillip Brink, Ethan Zonca
 
 *
 
 * This file is a part of DistRen.
 
 *
 
 * DistRen is free software: you can redistribute it and/or modify
 
 * it under the terms of the GNU Affero General Public License as published by
 
 * the Free Software Foundation, either version 3 of the License, or
 
 * (at your option) any later version.
 
 *
 
 * DistRen is distributed in the hope that it will be useful,
 
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 
 * GNU Affero General Public License for more details.
 
 *
 
 * You should have received a copy of the GNU Affero General Public License
 
 * along with DistRen.  If not, see <http://www.gnu.org/licenses/>.
 
 */
 

	
 
#include "check_execio.h"
 

	
 
#include "common/execio.h"
 

	
 
#include <check.h>
 
#include <string.h>
 

	
 
START_TEST (check_execio)
 
{
 
  struct execio *eio;
 
  char *echoargv[] = 
 
    {
 
      "echo",
 
      "test"
 
    };
 

	
 
  char inbuf[20];
 
  size_t bytesread;
 
  size_t pos;
 

	
 
  pos = 1;
 

	
 
  fail_unless(execio_open(&eio, echoargv[0], echoargv) == 0,
 
  fail_unless(execio_open(&eio, echoargv[0], echoargv, 0) == 0,
 
	      "execio_open failed");
 
  
 
  fail_unless(execio_read(eio, inbuf, sizeof(inbuf) - 1, &bytesread) == 0,
 
	      "error using execio_read\n");
 
  pos += bytesread;
 

	
 
  while (bytesread && pos < (sizeof(inbuf) - 1))
 
    {
 
      execio_read(eio, &inbuf[pos], sizeof(inbuf) - 1 - pos, &bytesread);
 
      pos += bytesread;
 
    }
 

	
 
  fail_if (pos > 10,
 
	   "I read more than 10 bytes from the command ``echo test'' when I expected only 5 or 6 bytes");
 

	
 
  inbuf[sizeof(inbuf) - 1] = '\0';
 
  fail_if (strncmp(inbuf, "test", 4),
 
	   "Expecting ``test''; got ``%s''",
 
	   inbuf);
 

	
 
  fail_unless(execio_close(eio) == 0,
 
	      "error using execio_close\n");
 
}
 
END_TEST
 

	
 
Suite *execio_suite()
 
{
 
  Suite *s;
 
  TCase *tc;
 

	
 
  s = suite_create("execio");
 

	
 
  tc = tcase_create("core");
 
  tcase_add_test(tc, check_execio);
 
  suite_add_tcase(s, tc);
 

	
 
  return s;
 
}
0 comments (0 inline, 0 general)