Esempio n. 1
0
inline Result<IPNetwork> IPNetwork::fromLinkDevice(
    const std::string& name,
    int family)
{
#if !defined(__linux__) && !defined(__APPLE__)
  return Error("Not implemented");
#else
  if (family != AF_INET) {
    return Error("Unsupported family type: " + stringify(family));
  }

  struct ifaddrs* ifaddr = NULL;
  if (getifaddrs(&ifaddr) == -1) {
    return ErrnoError();
  }

  // Indicates whether the link device is found or not.
  bool found = false;

  for (struct ifaddrs* ifa = ifaddr; ifa != NULL; ifa = ifa->ifa_next) {
    if (ifa->ifa_name != NULL && !strcmp(ifa->ifa_name, name.c_str())) {
      found = true;

      if (ifa->ifa_addr != NULL && ifa->ifa_addr->sa_family == family) {
        IP address = IP::create(*ifa->ifa_addr).get();

        if (ifa->ifa_netmask != NULL &&
            ifa->ifa_netmask->sa_family == family) {
          IP netmask = IP::create(*ifa->ifa_netmask).get();

          freeifaddrs(ifaddr);

          Try<IPNetwork> network = IPNetwork::create(address, netmask);
          if (network.isError()) {
            return Error(network.error());
          }

          return network.get();
        }

        freeifaddrs(ifaddr);

        // Note that this is the case where netmask is not specified.
        // We've seen such cases when VPN is used. In that case, a
        // default /32 prefix is used.
        Try<IPNetwork> network = IPNetwork::create(address, 32);
        if (network.isError()) {
          return Error(network.error());
        }

        return network.get();
      }
    }
  }

  freeifaddrs(ifaddr);

  if (!found) {
    return Error("Cannot find the link device");
  }

  return None();
#endif
}
Esempio n. 2
0
void execute(const string& script)
{
  // Create a temporary directory for the test.
  Try<string> directory = environment->mkdtemp();

  CHECK_SOME(directory) << "Failed to create temporary directory";

  if (flags.verbose) {
    std::cerr << "Using temporary directory '"
              << directory.get() << "'" << std::endl;
  }

  // Determine the path for the script.
  Result<string> path = os::realpath(getTestScriptPath(script));

  if (!path.isSome()) {
    FAIL() << "Failed to locate script "
           << script << ": "
           << (path.isError() ? path.error() : "No such file or directory");
  }

  // Fork a process to change directory and run the test.
  pid_t pid;
  if ((pid = fork()) == -1) {
    FAIL() << "Failed to fork to launch script";
  }

  if (pid > 0) {
    // In parent process.
    int status;
    while (wait(&status) != pid || WIFSTOPPED(status));
    CHECK(WIFEXITED(status) || WIFSIGNALED(status));

    if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) {
      FAIL() << script << " " << WSTRINGIFY(status);
    }
  } else {
    // In child process. DO NOT USE GLOG!

    // Start by cd'ing into the temporary directory.
    Try<Nothing> chdir = os::chdir(directory.get());
    if (chdir.isError()) {
      std::cerr << "Failed to chdir to '" << directory.get() << "': "
                << chdir.error() << std::endl;
      abort();
    }

    // Redirect output to /dev/null unless the test is verbose.
    if (!flags.verbose) {
      if (freopen("/dev/null", "w", stdout) == NULL ||
          freopen("/dev/null", "w", stderr) == NULL) {
        std::cerr << "Failed to redirect stdout/stderr to /dev/null:"
                  << os::strerror(errno) << std::endl;
        abort();
      }
    }

    // Set up the environment for executing the script. We might be running from
    // the Mesos source tree or from an installed version of the tests. In the
    // latter case, all of the variables below are swizzled to point to the
    // installed locations, except MESOS_SOURCE_DIR. Scripts that make use of
    // MESOS_SOURCE_DIR are expected to gracefully degrade if the Mesos source
    // is no longer present.
    os::setenv("MESOS_BUILD_DIR", flags.build_dir);
    os::setenv("MESOS_HELPER_DIR", getTestHelperDir());
    os::setenv("MESOS_LAUNCHER_DIR", getLauncherDir());
    os::setenv("MESOS_SBIN_DIR", getSbinDir());
    os::setenv("MESOS_SOURCE_DIR", flags.source_dir);
    os::setenv("MESOS_WEBUI_DIR", getWebUIDir());

    // Enable replicated log based registry.
    os::setenv("MESOS_REGISTRY", "replicated_log");

    // Enable authentication.
    os::setenv("MESOS_AUTHENTICATE_FRAMEWORKS", "true");

    // Create test credentials.
    const string& credentials =
      DEFAULT_CREDENTIAL.principal() + " " + DEFAULT_CREDENTIAL.secret();

    const string& credentialsPath =
      path::join(directory.get(), "credentials");

    CHECK_SOME(os::write(credentialsPath, credentials))
      << "Failed to write credentials to '" << credentialsPath << "'";

    os::setenv("MESOS_CREDENTIALS", "file://" + credentialsPath);

    // We set test credentials here for example frameworks to use.
    os::setenv("DEFAULT_PRINCIPAL", DEFAULT_CREDENTIAL.principal());
    os::setenv("DEFAULT_SECRET", DEFAULT_CREDENTIAL.secret());

    // TODO(bmahler): Update the example frameworks to use flags and
    // remove the special DEFAULT_* environment variables above.
    os::setenv("MESOS_PRINCIPAL", DEFAULT_CREDENTIAL.principal());
    os::setenv("MESOS_SECRET", DEFAULT_CREDENTIAL.secret());

    // Create test ACLs.
    ACLs acls;
    acls.set_permissive(false);

    mesos::ACL::RunTask* run = acls.add_run_tasks();
    run->mutable_principals()->add_values(DEFAULT_CREDENTIAL.principal());

    Result<string> user = os::user();
    CHECK_SOME(user) << "Failed to get current user name";
    run->mutable_users()->add_values(user.get());

    mesos::ACL::RegisterFramework* register_ = acls.add_register_frameworks();
    register_->mutable_principals()->add_values(DEFAULT_CREDENTIAL.principal());
    register_->mutable_roles()->add_values("*");

    const string& aclsPath = path::join(directory.get(), "acls");

    CHECK_SOME(os::write(aclsPath, stringify(JSON::protobuf(acls))))
      << "Failed to write ACLs to '" << aclsPath << "'";

    os::setenv("MESOS_ACLS", "file://" + aclsPath);

    // Now execute the script.
    execl(path.get().c_str(), path.get().c_str(), (char*) NULL);

    std::cerr << "Failed to execute '" << script << "': "
              << os::strerror(errno) << std::endl;
    abort();
  }
}
Esempio n. 3
0
void FlagsBase::add(
    T1 Flags::*t1,
    const std::string& name,
    const std::string& help,
    const T2& t2,
    F validate)
{
  // Don't bother adding anything if the pointer is NULL.
  if (t1 == NULL) {
    return;
  }

  Flags* flags = dynamic_cast<Flags*>(this);
  if (flags == NULL) {
    ABORT("Attempted to add flag '" + name + "' with incompatible type");
  } else {
    flags->*t1 = t2; // Set the default.
  }

  Flag flag;
  flag.name = name;
  flag.help = help;
  flag.boolean = typeid(T1) == typeid(bool);

  // NOTE: We need to take FlagsBase* (or const FlagsBase&) as the
  // first argument to 'load', 'stringify', and 'validate' so that we
  // use the correct instance of FlagsBase. In other words, we can't
  // capture 'this' here because it's possible that the FlagsBase
  // object that we're working with when we invoke FlagsBase::add is
  // not the same instance as 'this' when the these lambdas get
  // invoked.

  flag.load = [t1](FlagsBase* base, const std::string& value) -> Try<Nothing> {
    Flags* flags = dynamic_cast<Flags*>(base);
    if (base != NULL) {
      // NOTE: 'fetch' "retrieves" the value if necessary and then
      // invokes 'parse'. See 'fetch' for more details.
      Try<T1> t = fetch<T1>(value);
      if (t.isSome()) {
        flags->*t1 = t.get();
      } else {
        return Error("Failed to load value '" + value + "': " + t.error());
      }
    }
    return Nothing();
  };

  flag.stringify = [t1](const FlagsBase& base) -> Option<std::string> {
    const Flags* flags = dynamic_cast<const Flags*>(&base);
    if (flags != NULL) {
      return stringify(flags->*t1);
    }
    return None();
  };

  flag.validate = [t1, validate](const FlagsBase& base) -> Option<Error> {
    const Flags* flags = dynamic_cast<const Flags*>(&base);
    if (flags != NULL) {
      return validate(flags->*t1);
    }
    return None();
  };

  // Update the help string to include the default value.
  flag.help += help.size() > 0 && help.find_last_of("\n\r") != help.size() - 1
    ? " (default: " // On same line, add space.
    : "(default: "; // On newline.
  flag.help += stringify(t2);
  flag.help += ")";

  add(flag);
}
Esempio n. 4
0
ECRESULT ECUserStoreTable::Load() {
	ECRESULT er = erSuccess;
	ECListIntIterator i;
    ECDatabase *lpDatabase = NULL;
    DB_RESULT 	lpDBResult = NULL;
    DB_ROW		lpDBRow = NULL;
    DB_LENGTHS	lpDBLength = NULL;
	std::string strQuery;
    std::list<unsigned int> lstObjIds;
	ECUserStore sUserStore;
	int iRowId;
	ECUserManagement *lpUserManagement = lpSession->GetUserManagement();
	ECSecurity *lpSecurity = lpSession->GetSecurity();
	objectdetails_t sUserDetails;
	GUID sZeroGuid = {0};
	objectclass_t objclass;
	objectdetails_t sDetails;

	enum cols { USERID = 0, EXTERNID, OBJCLASS, UCOMPANY, STOREGUID, STORETYPE, USERNAME, SCOMPANY, HIERARCHYID, STORESIZE, MODTIME_HI, MODTIME_LO };

	er = lpSession->GetDatabase(&lpDatabase);
	if (er != erSuccess)
		goto exit;

    Clear();

	/*
	 * The next query will first get the list of all users with their primary store details or NULL if
	 * no primary store was found. Secondly it will get the list of all stores with their owner or NULL
	 * if they're detached.
	 * The most important difference id that the first query will return no store for users without a
	 * primary store, even if they do have an archive store attached, while the second query will
	 * return all stores types.
	 */
	strQuery =
		" SELECT u.id, u.externid, u.objectclass, u.company, s.guid, s.type, s.user_name, s.company, s.hierarchy_id, p.val_longint, m.val_hi, m.val_lo FROM users AS u"
		"  LEFT JOIN stores AS s ON s.user_id=u.id AND s.type=" + stringify(ECSTORE_TYPE_PRIVATE) + " LEFT JOIN hierarchy AS h ON h.id=s.hierarchy_id"
		"  LEFT JOIN properties AS p ON p.hierarchyid=s.hierarchy_id and p.tag=0x0E08 and p.type=0x14"
		"  LEFT JOIN properties AS m ON m.hierarchyid=s.hierarchy_id and m.tag=0x66A2 and m.type=0x40"
		" UNION"
		" SELECT u.id, u.externid, u.objectclass, u.company, s.guid, s.type, s.user_name, s.company, s.hierarchy_id, p.val_longint, m.val_hi, m.val_lo FROM users AS u"
		"  RIGHT JOIN stores AS s ON s.user_id=u.id LEFT JOIN hierarchy AS h ON h.id=s.hierarchy_id"
		"  LEFT JOIN properties AS p ON p.hierarchyid=s.hierarchy_id and p.tag=0x0E08 and p.type=0x14"
		"  LEFT JOIN properties AS m ON m.hierarchyid=s.hierarchy_id and m.tag=0x66A2 and m.type=0x40";

	er = lpDatabase->DoSelect(strQuery, &lpDBResult);
	if(er != erSuccess)
		goto exit;

	iRowId = 0;
	while(1) {
		lpDBRow = lpDatabase->FetchRow(lpDBResult);

		if(lpDBRow == NULL)
			break;

		lpDBLength = lpDatabase->FetchRowLengths(lpDBResult);

		if (lpDBRow[OBJCLASS]) {
			objclass = (objectclass_t)atoi(lpDBRow[OBJCLASS]);
			if (objclass != ACTIVE_USER && objclass != NONACTIVE_USER &&
				objclass != NONACTIVE_ROOM && objclass != NONACTIVE_EQUIPMENT)
				continue;
		}

		if (lpDBRow[USERID]) {
			sUserStore.ulUserId = atoi(lpDBRow[USERID]);
			if (sUserStore.ulUserId == ZARAFA_UID_SYSTEM) // everyone already filtered by object type
				continue;
		} else {
			sUserStore.ulUserId = -1;
		}

		sUserStore.ulCompanyId = 0;
		if (lpDBRow[UCOMPANY])
			sUserStore.ulCompanyId = atoi(lpDBRow[UCOMPANY]);
		if (lpDBRow[SCOMPANY])
			sUserStore.ulCompanyId = atoi(lpDBRow[SCOMPANY]); // might override from user.company
		// check if we're admin over this company
		if (lpSecurity->IsAdminOverUserObject(sUserStore.ulCompanyId) != erSuccess)
			continue;

		if (lpDBRow[EXTERNID]) {
			sUserStore.sExternId.id.assign(lpDBRow[EXTERNID], lpDBLength[EXTERNID]);
			sUserStore.sExternId.objclass = objclass;
		} else {
			sUserStore.sExternId.id.clear();
			sUserStore.sExternId.objclass = OBJECTCLASS_UNKNOWN;
		}

		sUserStore.strUsername.clear();
		// find and override real username if possible
		if (sUserStore.ulUserId != -1 && lpUserManagement->GetObjectDetails(sUserStore.ulUserId, &sUserDetails) == erSuccess) {
			if (lpSession->GetSessionManager()->IsDistributedSupported()) {
				if (sUserDetails.GetPropString(OB_PROP_S_SERVERNAME).compare(lpSession->GetSessionManager()->GetConfig()->GetSetting("server_name")) != 0)
					continue;		// user not on this server
			}

			sUserStore.strUsername = sUserDetails.GetPropString(OB_PROP_S_LOGIN);
		}

		sUserStore.sGuid = sZeroGuid;
		if (lpDBRow[STOREGUID])
			memcpy(&sUserStore.sGuid, lpDBRow[STOREGUID], lpDBLength[STOREGUID]);

		if (lpDBRow[STORETYPE])
			sUserStore.ulStoreType = atoi(lpDBRow[STORETYPE]);
		else
			sUserStore.ulStoreType = ECSTORE_TYPE_PRIVATE; // or invalid value?
			
		if (lpDBRow[USERNAME])
			sUserStore.strGuessname = lpDBRow[USERNAME];
		else
			sUserStore.strGuessname.clear();

		if (sUserStore.ulCompanyId > 0 && lpUserManagement->GetObjectDetails(sUserStore.ulCompanyId, &sDetails) == erSuccess) {
			sUserStore.strCompanyName = sDetails.GetPropString(OB_PROP_S_LOGIN);
		}

		if(lpDBRow[HIERARCHYID])
			sUserStore.ulObjId = atoui(lpDBRow[HIERARCHYID]);
		else
			sUserStore.ulObjId = 0;

		sUserStore.tModTime = 0;
		if(lpDBRow[MODTIME_HI] && lpDBRow[MODTIME_LO]) {
			FILETIME ft;
			ft.dwHighDateTime = atoui(lpDBRow[MODTIME_HI]);
			ft.dwLowDateTime =  atoui(lpDBRow[MODTIME_LO]);
			sUserStore.tModTime = 0;
			FileTimeToUnixTime(ft, &sUserStore.tModTime);
		}

		if(lpDBRow[STORESIZE])
			sUserStore.ullStoreSize = atoll(lpDBRow[STORESIZE]);
		else
			sUserStore.ullStoreSize = 0;

		// add to table
		lstObjIds.push_back(iRowId);
		// remember details
		m_mapUserStoreData.insert(std::pair<unsigned int, ECUserStore>(iRowId++, sUserStore));
	}

	LoadRows(&lstObjIds, 0);

exit:	
	if (lpDBResult) {
		lpDatabase->FreeResult(lpDBResult);
		lpDBResult = NULL;
	}

	return er;
}
Esempio n. 5
0
void test_stringify() {
  char *h = stringify('h');
  assert_string_equals("h", h);
  free(h);
}
Esempio n. 6
0
ostream& operator<<(std::ostream& stream, const CapabilityInfo& capabilityInfo)
{
  return stream << stringify(JSON::protobuf(capabilityInfo));
}
Esempio n. 7
0
bool retro_load_game(const struct retro_game_info *info)
{
   quakeparms_t parms;

   extract_directory(g_rom_dir, info->path, sizeof(g_rom_dir));

   snprintf(g_pak_path, sizeof(g_pak_path), "%s", info->path);

   MEMSIZE_MB = DEFAULT_MEMSIZE_MB;

   if (strstr(info->path, "hipnotic") || strstr(info->path, "rogue")
         || strstr(info->path, "HIPNOTIC")
         || strstr(info->path, "ROGUE"))
   {
#if defined(HW_RVL) || defined(_XBOX1)
      MEMSIZE_MB = 16;
#endif
      extract_directory(g_rom_dir, g_rom_dir, sizeof(g_rom_dir));
   }

   memset(&parms, 0, sizeof(parms));

   COM_InitArgv(0, NULL);

   parms.argc = com_argc;
   parms.argv = com_argv;
   parms.basedir = g_rom_dir;
   parms.memsize = MEMSIZE_MB * 1024 * 1024;

   heap = (unsigned char*)malloc(parms.memsize);

   parms.membase = heap;

#ifdef NQ_HACK
   fprintf(stderr, "Quake Libretro -- TyrQuake Version %s\n", stringify(TYR_VERSION));
#endif
#ifdef QW_HACK
   fprintf(stderr, "QuakeWorld Libretro -- TyrQuake Version %s\n", stringify(TYR_VERSION));
#endif

   Sys_Init();
   Host_Init(&parms);

   Cvar_Set("cl_bob", "0.02");
   Cvar_Set("crosshair", "0");
   Cvar_Set("viewsize", "100");
   Cvar_Set("showram", "0");
   Cvar_Set("dither_filter", "1");
   Cvar_RegisterVariable(&framerate);
   Cvar_Set("framerate", "60");

   enum retro_pixel_format fmt = RETRO_PIXEL_FORMAT_RGB565;
   if (!environ_cb(RETRO_ENVIRONMENT_SET_PIXEL_FORMAT, &fmt))
   {
      fprintf(stderr, "RGB565 is not supported.\n");
      return false;
   }

   /* set keyboard callback */

   //struct retro_keyboard_callback cb = { keyboard_cb };
   //environ_cb(RETRO_ENVIRONMENT_SET_KEYBOARD_CALLBACK, &cb);

#ifdef NQ_HACK
   oldtime = Sys_DoubleTime() - 0.1;
#endif
#ifdef QW_HACK
   oldtime = Sys_DoubleTime();
#endif

   return true;
}
Esempio n. 8
0
/**
 * Resolve a user and return its username and entryid.
 *
 * @param[in]	strUser
 *					The user to resolve.
 * @param[out]	lpsEntryId
 *					Pointer to a entryid_t that will be populated with the entryid
 *					of the resovled user. This argument can be set to NULL if the entryid
 *					is not required.
 * @param[out]	lpstrFullname
 *					Pointer to a std::string that will be populated with the full name
 *					of the resolved user. This argument can be set to NULL if the full name
 *					is not required.
 * @param[out]	lpbAclCapable
 * 					Pointer to a boolean that will be set to true if the user is ACL capable.
 * 					This argument can be set to NULL if the active/non-active
 * 					information is not required.
 *
 * @return HRESULT
 */
HRESULT ArchiverSession::GetUserInfo(const tstring &strUser, abentryid_t *lpsEntryId, tstring *lpstrFullname, bool *lpbAclCapable)
{
	HRESULT hr = hrSuccess;
	MsgStorePtr ptrStore;
	ECServiceAdminPtr ptrServiceAdmin;
	ULONG cbEntryId = 0;
	EntryIdPtr ptrEntryId;

	hr = HrOpenDefaultStore(m_ptrSession, &ptrStore);
	if (hr != hrSuccess) {
		m_lpLogger->Log(EC_LOGLEVEL_INFO, "Failed to open default store (hr=%s)", stringify(hr, true).c_str());
		goto exit;
	}

	hr = ptrStore.QueryInterface(ptrServiceAdmin);
	if (hr != hrSuccess) {
		m_lpLogger->Log(EC_LOGLEVEL_INFO, "Failed to obtain the serviceadmin interface (hr=%s)", stringify(hr, true).c_str());
		goto exit;
	}

	hr = ptrServiceAdmin->ResolveUserName((LPCTSTR)strUser.c_str(), fMapiUnicode, &cbEntryId, &ptrEntryId);
	if (hr != hrSuccess) {
		m_lpLogger->Log(EC_LOGLEVEL_INFO, "Failed to resolve user '" TSTRING_PRINTF "' (hr=%s)", strUser.c_str(), stringify(hr, true).c_str());
		goto exit;
	}


	if (lpstrFullname || lpbAclCapable) {
		ULONG ulType = 0;
		MailUserPtr ptrUser;
		ULONG cValues = 0;
		SPropArrayPtr ptrUserProps;

		SizedSPropTagArray(2, sptaUserProps) = {2, {PR_DISPLAY_NAME, PR_DISPLAY_TYPE_EX}};
		enum {IDX_DISPLAY_NAME, IDX_DISPLAY_TYPE_EX};

		hr = m_ptrSession->OpenEntry(cbEntryId, ptrEntryId, &IID_IMailUser, 0, &ulType, &ptrUser);
		if (hr != hrSuccess) {
			m_lpLogger->Log(EC_LOGLEVEL_INFO, "Failed to open user object for user '" TSTRING_PRINTF "' (hr=%s)", strUser.c_str(), stringify(hr, true).c_str());
			goto exit;
		}

		hr = ptrUser->GetProps((LPSPropTagArray)&sptaUserProps, 0, &cValues, &ptrUserProps);
		if (FAILED(hr)) {
			m_lpLogger->Log(EC_LOGLEVEL_INFO, "Failed to obtain properties from user '" TSTRING_PRINTF "' (hr=0x%08x)", strUser.c_str(), hr);
			goto exit;
		}

		if (lpstrFullname) {
			if (ptrUserProps[IDX_DISPLAY_NAME].ulPropTag != PR_DISPLAY_NAME) {
				hr = ptrUserProps[IDX_DISPLAY_NAME].Value.err;
				m_lpLogger->Log(EC_LOGLEVEL_INFO, "Failed to obtain the display name for user '" TSTRING_PRINTF "' (hr=%s)", strUser.c_str(), stringify(hr, true).c_str());
				goto exit;
			}

			lpstrFullname->assign(ptrUserProps[IDX_DISPLAY_NAME].Value.LPSZ);
		}
		
		if (lpbAclCapable) {
			if (ptrUserProps[IDX_DISPLAY_TYPE_EX].ulPropTag != PR_DISPLAY_TYPE_EX) {
				hr = ptrUserProps[IDX_DISPLAY_TYPE_EX].Value.err;
				m_lpLogger->Log(EC_LOGLEVEL_INFO, "Failed to obtain the type for user '" TSTRING_PRINTF "' (hr=%s)", strUser.c_str(), stringify(hr, true).c_str());
				goto exit;
			}

			*lpbAclCapable = (ptrUserProps[IDX_DISPLAY_TYPE_EX].Value.ul & DTE_FLAG_ACL_CAPABLE);
		}
	}

	if (lpsEntryId)
		lpsEntryId->assign(cbEntryId, ptrEntryId);
	
exit:
	return hr;
}
Esempio n. 9
0
std::string ZooKeeperTestServer::connectString() const
{
    CHECK(port > 0) << "Illegal state, must call startNetwork first!";
    return "127.0.0.1:" + stringify(port);
}
Esempio n. 10
0
/*! \internal
  Stringifies \a variant.
 */
void JsonWriter::stringify(const QVariant &variant, int depth)
{
    if (variant.type() == QVariant::List || variant.type() == QVariant::StringList) {
        m_result += QLatin1Char('[');
        QVariantList list = variant.toList();
        for (int i = 0; i < list.count(); i++) {
            if (i != 0) {
                m_result += QLatin1Char(',');
                if (m_autoFormatting)
                    m_result += QLatin1Char(' ');
            }
            stringify(list[i], depth+1);
        }
        m_result += QLatin1Char(']');
    } else if (variant.type() == QVariant::Map) {
        QString indent = m_autoFormattingIndent.repeated(depth);
        QVariantMap map = variant.toMap();
        if (m_autoFormatting && depth != 0) {
            m_result += QLatin1Char('\n');
            m_result += indent;
            m_result += QLatin1String("{\n");
        } else {
            m_result += QLatin1Char('{');
        }
        for (QVariantMap::const_iterator it = map.constBegin(); it != map.constEnd(); ++it) {
            if (it != map.constBegin()) {
                m_result += QLatin1Char(',');
                if (m_autoFormatting)
                    m_result += QLatin1Char('\n');
            }
            if (m_autoFormatting)
                m_result += indent + QLatin1Char(' ');
            m_result += QLatin1Char('\"') + escape(it.key()) + QLatin1String("\":");
            stringify(it.value(), depth+1);
        }
        if (m_autoFormatting) {
            m_result += QLatin1Char('\n');
            m_result += indent;
        }
        m_result += QLatin1Char('}');
    } else if (variant.type() == QVariant::String || variant.type() == QVariant::ByteArray) {
        m_result += QLatin1Char('\"') + escape(variant) + QLatin1Char('\"');
    } else if (variant.type() == QVariant::Double || (int)variant.type() == (int)QMetaType::Float) {
        double d = variant.toDouble();
        if (qIsFinite(d))
            m_result += QString::number(variant.toDouble(), 'g', 15);
        else
            m_result += QLatin1String("null");
    } else if (variant.type() == QVariant::Bool) {
        m_result += variant.toBool() ? QLatin1String("true") : QLatin1String("false");
    } else if (variant.type() == QVariant::Invalid) {
        m_result += QLatin1String("null");
    } else if (variant.type() == QVariant::ULongLong) {
        m_result += QString::number(variant.toULongLong());
    } else if (variant.type() == QVariant::LongLong) {
        m_result += QString::number(variant.toLongLong());
    } else if (variant.type() == QVariant::Int) {
        m_result += QString::number(variant.toInt());
    } else if (variant.type() == QVariant::UInt) {
        m_result += QString::number(variant.toUInt());
    } else if (variant.type() == QVariant::Char) {
        QChar c = variant.toChar();
        if (c.unicode() > 127)
            m_result += QLatin1String("\"\\u") + QString::number(c.unicode(), 16).rightJustified(4, QLatin1Char('0')) + QLatin1Char('\"');
        else
            m_result += QLatin1Char('\"') + c + QLatin1Char('\"');
    } else if (variant.canConvert<qlonglong>()) {
        m_result += QString::number(variant.toLongLong());
    } else if (variant.canConvert<QString>()) {
        m_result += QLatin1Char('\"') + escape(variant) + QLatin1Char('\"');
    } else {
        if (!m_errorString.isEmpty())
            m_errorString.append(QLatin1Char('\n'));
        QString msg = QString::fromLatin1("Unsupported type %1 (id: %2)").arg(QString::fromUtf8(variant.typeName())).arg(variant.userType());
        m_errorString.append(msg);
        qWarning() << "JsonWriter::stringify - " << msg;
        m_result += QLatin1String("null");
    }
}
Esempio n. 11
0
/**
 * Open a message store with best access.
 *
 * @param[in]	sEntryId
 *					The entryid of the store to open.
 * @param[in]	ulFlags
 * 					Flags that are passed on to OpenMsgStore
 * @param[out]	lppMsgStore
 *					Pointer to a IMsgStore pointer that will be assigned the
 *					address of the returned message store.
 *
 * @return HRESULT
 */ 
HRESULT ArchiverSession::OpenStore(const entryid_t &sEntryId, ULONG ulFlags, LPMDB *lppMsgStore)
{
	HRESULT hr = hrSuccess;
	MsgStorePtr ptrUserStore;
	ArchiverSessionPtr ptrSession;
	
	if (sEntryId.isWrapped()) {
		entryid_t sTempEntryId = sEntryId;
		std::string	strPath;

		sTempEntryId.unwrap(&strPath);

		m_lpLogger->Log(EC_LOGLEVEL_DEBUG, "Archive store entryid is wrapped.");
		
		hr = CreateRemote(strPath.c_str(), m_lpLogger, &ptrSession);
		if (hr != hrSuccess) {
			m_lpLogger->Log(EC_LOGLEVEL_INFO, "Failed to create ArchiverSession on '%s' (hr=%s)", strPath.c_str(), stringify(hr, true).c_str());
			goto exit;
		}
		
		hr = ptrSession->OpenStore(sTempEntryId, ulFlags, lppMsgStore);		
	} else {	
		hr = m_ptrSession->OpenMsgStore(0, sEntryId.size(), sEntryId, &ptrUserStore.iid, ulFlags, &ptrUserStore);
		if (hr != hrSuccess) {
			m_lpLogger->Log(EC_LOGLEVEL_INFO, "Failed to open store. (entryid=%s, hr=%s)", sEntryId.tostring().c_str(), stringify(hr, true).c_str());
			goto exit;
		}
			
		hr = ptrUserStore->QueryInterface(IID_IMsgStore, (LPVOID*)lppMsgStore);
	}
	
exit:
	return hr;
}
Esempio n. 12
0
 /*! @brief Pointer constructor.
  *
  *  Constructs the StackLog using the given Logger and applies the given
  *  prefix to the logger.
  *
  *  @param logIn The Logger to manage.
  *  @param str The prefix to apply.
  */
 StackLog(Log* const logIn, const std::string& str)
     : logger(*logIn)
     , before(logger.prefix)
 {
     logger.prefix = stringify(str, ": ");
 }
Esempio n. 13
0
 /*! @brief Reference constructor.
  *
  *  Constructs the StackLog using the given Logger and applies the given
  *  prefix to the logger.
  *
  *  @param logIn The Logger to manage.
  *  @param str The prefix to apply.
  */
 StackLog(Log& logIn, std::string str)
     : logger(logIn)
     , before(logIn.prefix)
 {
     logger.prefix = stringify(str, ": ");
 }
Esempio n. 14
0
// Reads from /proc/cpuinfo and returns a list of CPUs.
inline Try<std::list<CPU> > cpus()
{
  std::list<CPU> results;

  std::ifstream file("/proc/cpuinfo");

  if (!file.is_open()) {
    return Error("Failed to open /proc/cpuinfo");
  }

  // Placeholders as we parse the file.
  Option<unsigned int> id;
  Option<unsigned int> core;
  Option<unsigned int> socket;

  std::string line;
  while (std::getline(file, line)) {
    if (line.find("processor") == 0 ||
        line.find("physical id") == 0 ||
        line.find("core id") == 0) {
      // Get out and parse the value.
      std::vector<std::string> tokens = strings::tokenize(line, ": ");

      if (tokens.size() < 2) {
        return Error("Unexpected format in /proc/cpuinfo: " +
                     stringify(tokens));
      }

      Try<unsigned int> value = numify<unsigned int>(tokens.back());
      if (value.isError()) {
        return Error(value.error());
      }

      // Now save the value.
      if (line.find("processor") == 0) {
        if (id.isSome()) {
          // The physical id and core id are not present in this case.
          results.push_back(CPU(id.get(), 0, 0));
        }
        id = value.get();
      } else if (line.find("physical id") == 0) {
        if (socket.isSome()) {
          return Error("Unexpected format in /proc/cpuinfo");
        }
        socket = value.get();
      } else if (line.find("core id") == 0) {
        if (core.isSome()) {
          return Error("Unexpected format in /proc/cpuinfo");
        }
        core = value.get();
      }

      // And finally create a CPU if we have all the information.
      if (id.isSome() && core.isSome() && socket.isSome()) {
        results.push_back(CPU(id.get(), core.get(), socket.get()));
        id = None();
        core = None();
        socket = None();
      }
    }
  }

  // Add the last processor if the physical id and core id were not present.
  if (id.isSome()) {
    // The physical id and core id are not present.
    results.push_back(CPU(id.get(), 0, 0));
  }

  if (file.fail() && !file.eof()) {
    file.close();
    return Error("Failed to read /proc/cpuinfo");
  }

  file.close();

  return results;
}
Esempio n. 15
0
 void DataFlow::display()
 {
   cout << stringify() << endl;
 }
Esempio n. 16
0
	void instance::on_end_turn(const Event& inEvt) {
    // validate: make sure the sender is the active puppet
    if (get_sender(inEvt)->get_puppet() != active_puppet_) {
      log_->errorStream()
        << get_sender(inEvt)->get_puppet()->getName()
        << " is trying to end his opponent's turn!";
      return;
    }

    // get up all the opponent units with summoning sickness
    for (auto unit : waiting_puppet_->getUnits())
      if (unit->hasSummoningSickness())
        unit->getUp();

		// is any of its units charging?
    if (!attackers_.empty()) {
      in_battle_ = true;
      nr_battle_acks_ = 0;
			// toggle into Charging state
			// and toggle opponent into Blocking state
      Event e(EventUID::StartBlockPhase);
      broadcast(e);
      return;
    }

		// otherwise, just start the opponent's turn
		log_->debugStream()
		<< "ending " << active_puppet_->getName() << "'s turn ";

    // find the next puppet
    waiting_puppet_ = active_puppet_;
    if (active_puppet_ == puppets_.back())
      active_puppet_ = puppets_.front();
    else {
      for (puppets_t::const_iterator puppet = puppets_.begin(); puppet != puppets_.end(); ++puppet) {
        if ((*puppet) == active_puppet_) {
          ++puppet;
          active_puppet_ = (*puppet);
          break;
        }
      }
      /*bool found = false;
      for (auto puppet : puppets_) {
        if (found)
          active_puppet_ = puppet;
          break;
        if (puppet == active_puppet_)
          found = true;
      }*/
    }

    waiting_player_ = active_player_;
    active_player_ = get_player(active_puppet_);

    // send to all players except the active one
    Event _turn_started(EventUID::TurnStarted);
    _turn_started.setProperty("P", stringify(active_puppet_->getUID()));
    for (auto player : players_) {
      if (player != active_player_) {
        log_->infoStream() << "\tinforming " <<
          player->get_puppet()->getName() <<
          player->get_puppet()->getUID() << " that their turn is not active";
        send(player, _turn_started);
      }
    }

		log_->debugStream()
		<< "starting " << active_puppet_->getName() << "'s turn ";

		Event evt(EventUID::StartTurn);
    send(active_player_, evt);
    this->draw_spells(active_puppet_);

		return;
	}
Esempio n. 17
0
    [0x07] = 0xf4,
    /* 7c08: jmp 0x7c07=0x7c0a-3 */
    [0x08] = 0xeb,
    [0x09] = LOW(-3),
    /* We mov 0xdead here: set value to make debugging easier */
    [SIGNATURE_OFFSET] = LOW(0xface),
    [SIGNATURE_OFFSET + 1] = HIGH(0xface),
    /* End of boot sector marker */
    [0x1FE] = 0x55,
    [0x1FF] = 0xAA,
};

static const char *disk = "tests/acpi-test-disk.raw";
static const char *data_dir = "tests/acpi-test-data";
#ifdef CONFIG_IASL
static const char *iasl = stringify(CONFIG_IASL);
#else
static const char *iasl;
#endif

static void free_test_data(test_data *data)
{
    AcpiSdtTable *temp;
    int i;

    if (data->rsdt_tables_addr) {
        g_free(data->rsdt_tables_addr);
    }

    for (i = 0; i < data->tables->len; ++i) {
        temp = &g_array_index(data->tables, AcpiSdtTable, i);
Esempio n. 18
0
/* ECMA-262 5.1 Edition    15.12.3 (abstract operation JO) */
static HRESULT stringify_object(stringify_ctx_t *ctx, jsdisp_t *obj)
{
    DISPID dispid = DISPID_STARTENUM;
    jsval_t val = jsval_undefined();
    unsigned prop_cnt = 0, i;
    size_t stepback;
    BSTR prop_name;
    HRESULT hres;

    if(is_on_stack(ctx, obj)) {
        FIXME("Found a cycle\n");
        return E_FAIL;
    }

    if(!stringify_push_obj(ctx, obj))
        return E_OUTOFMEMORY;

    if(!append_char(ctx, '{'))
        return E_OUTOFMEMORY;

    while((hres = IDispatchEx_GetNextDispID(&obj->IDispatchEx_iface, fdexEnumDefault, dispid, &dispid)) == S_OK) {
        jsval_release(val);
        hres = jsdisp_propget(obj, dispid, &val);
        if(FAILED(hres))
            return hres;

        if(is_undefined(val))
            continue;

        stepback = ctx->buf_len;

        if(prop_cnt && !append_char(ctx, ',')) {
            hres = E_OUTOFMEMORY;
            break;
        }

        if(*ctx->gap) {
            if(!append_char(ctx, '\n')) {
                hres = E_OUTOFMEMORY;
                break;
            }

            for(i=0; i < ctx->stack_top; i++) {
                if(!append_string(ctx, ctx->gap)) {
                    hres = E_OUTOFMEMORY;
                    break;
                }
            }
        }

        hres = IDispatchEx_GetMemberName(&obj->IDispatchEx_iface, dispid, &prop_name);
        if(FAILED(hres))
            break;

        hres = json_quote(ctx, prop_name, SysStringLen(prop_name));
        SysFreeString(prop_name);
        if(FAILED(hres))
            break;

        if(!append_char(ctx, ':') || (*ctx->gap && !append_char(ctx, ' '))) {
            hres = E_OUTOFMEMORY;
            break;
        }

        hres = stringify(ctx, val);
        if(FAILED(hres))
            break;

        if(hres == S_FALSE) {
            ctx->buf_len = stepback;
            continue;
        }

        prop_cnt++;
    }
    jsval_release(val);
    if(FAILED(hres))
        return hres;

    if(prop_cnt && *ctx->gap) {
        if(!append_char(ctx, '\n'))
            return E_OUTOFMEMORY;

        for(i=1; i < ctx->stack_top; i++) {
            if(!append_string(ctx, ctx->gap)) {
                hres = E_OUTOFMEMORY;
                break;
            }
        }
    }

    if(!append_char(ctx, '}'))
        return E_OUTOFMEMORY;

    stringify_pop_obj(ctx);
    return S_OK;
}
Esempio n. 19
0
ostream& operator<<(ostream& stream, const hashmap<string, string>& map)
{
  return stream << stringify(map);
}
Esempio n. 20
0
mesos::internal::master::Flags::Flags()
{
  add(&Flags::version,
      "version",
      "Show version and exit.",
      false);

  add(&Flags::hostname,
      "hostname",
      "The hostname the master should advertise in ZooKeeper.\n"
      "If left unset, the hostname is resolved from the IP address\n"
      "that the slave binds to; unless the user explicitly prevents\n"
      "that, using --no-hostname_lookup, in which case the IP itself\n"
      "is used.");

  add(&Flags::hostname_lookup,
      "hostname_lookup",
      "Whether we should execute a lookup to find out the server's hostname,\n"
      "if not explicitly set (via, e.g., `--hostname`).\n"
      "True by default; if set to 'false' it will cause Mesos\n"
      "to use the IP address, unless the hostname is explicitly set.",
      true);

  add(&Flags::root_submissions,
      "root_submissions",
      "Can root submit frameworks?",
      true);

  add(&Flags::work_dir,
      "work_dir",
      "Directory path to store the persistent information stored in the \n"
      "Registry. (example: /var/lib/mesos/master)");

  // TODO(bmahler): Consider removing 'in_memory' as it was only
  // used before 'replicated_log' was implemented.
  add(&Flags::registry,
      "registry",
      "Persistence strategy for the registry;\n"
      "available options are 'replicated_log', 'in_memory' (for testing).",
      "replicated_log");

  // TODO(vinod): Instead of specifying the quorum size consider
  // specifying the number of masters or the list of masters.
  add(&Flags::quorum,
      "quorum",
      "The size of the quorum of replicas when using 'replicated_log' based\n"
      "registry. It is imperative to set this value to be a majority of\n"
      "masters i.e., quorum > (number of masters)/2.");

  add(&Flags::zk_session_timeout,
      "zk_session_timeout",
      "ZooKeeper session timeout.",
      ZOOKEEPER_SESSION_TIMEOUT);

  // TODO(bmahler): Set the default to true in 0.20.0.
  add(&Flags::registry_strict,
      "registry_strict",
      "Whether the Master will take actions based on the persistent\n"
      "information stored in the Registry. Setting this to false means\n"
      "that the Registrar will never reject the admission, readmission,\n"
      "or removal of a slave. Consequently, 'false' can be used to\n"
      "bootstrap the persistent state on a running cluster.\n"
      "NOTE: This flag is *experimental* and should not be used in\n"
      "production yet.",
      false);

  add(&Flags::registry_fetch_timeout,
      "registry_fetch_timeout",
      "Duration of time to wait in order to fetch data from the registry\n"
      "after which the operation is considered a failure.",
      Seconds(60));

  add(&Flags::registry_store_timeout,
      "registry_store_timeout",
      "Duration of time to wait in order to store data in the registry\n"
      "after which the operation is considered a failure.",
      Seconds(5));

  add(&Flags::log_auto_initialize,
      "log_auto_initialize",
      "Whether to automatically initialize the replicated log used for the\n"
      "registry. If this is set to false, the log has to be manually\n"
      "initialized when used for the very first time.",
      true);

  add(&Flags::slave_reregister_timeout,
      "slave_reregister_timeout",
      "The timeout within which all slaves are expected to re-register\n"
      "when a new master is elected as the leader. Slaves that do not\n"
      "re-register within the timeout will be removed from the registry\n"
      "and will be shutdown if they attempt to communicate with master.\n"
      "NOTE: This value has to be atleast " +
        stringify(MIN_SLAVE_REREGISTER_TIMEOUT) + ".",
      MIN_SLAVE_REREGISTER_TIMEOUT);

  // TODO(bmahler): Add a 'Percentage' abstraction for flags.
  // TODO(bmahler): Add a --production flag for production defaults.
  add(&Flags::recovery_slave_removal_limit,
      "recovery_slave_removal_limit",
      "For failovers, limit on the percentage of slaves that can be removed\n"
      "from the registry *and* shutdown after the re-registration timeout\n"
      "elapses. If the limit is exceeded, the master will fail over rather\n"
      "than remove the slaves.\n"
      "This can be used to provide safety guarantees for production\n"
      "environments. Production environments may expect that across Master\n"
      "failovers, at most a certain percentage of slaves will fail\n"
      "permanently (e.g. due to rack-level failures).\n"
      "Setting this limit would ensure that a human needs to get\n"
      "involved should an unexpected widespread failure of slaves occur\n"
      "in the cluster.\n"
      "Values: [0%-100%]",
      stringify(RECOVERY_SLAVE_REMOVAL_PERCENT_LIMIT * 100.0) + "%");

  // TODO(vinod): Add a 'Rate' abstraction in stout and the
  // corresponding parser for flags.
  add(&Flags::slave_removal_rate_limit,
      "slave_removal_rate_limit",
      "The maximum rate (e.g., 1/10mins, 2/3hrs, etc) at which slaves will\n"
      "be removed from the master when they fail health checks. By default\n"
      "slaves will be removed as soon as they fail the health checks.\n"
      "The value is of the form <Number of slaves>/<Duration>.");

  add(&Flags::webui_dir,
      "webui_dir",
      "Directory path of the webui files/assets",
      PKGDATADIR "/webui");

  add(&Flags::whitelist,
      "whitelist",
      "Path to a file with a list of slaves\n"
      "(one per line) to advertise offers for.\n"
      "Path could be of the form 'file:///path/to/file' or '/path/to/file'.");

  add(&Flags::user_sorter,
      "user_sorter",
      "Policy to use for allocating resources\n"
      "between users. May be one of:\n"
      "  dominant_resource_fairness (drf)",
      "drf");

  add(&Flags::framework_sorter,
      "framework_sorter",
      "Policy to use for allocating resources\n"
      "between a given user's frameworks. Options\n"
      "are the same as for user_allocator.",
      "drf");

  add(&Flags::allocation_interval,
      "allocation_interval",
      "Amount of time to wait between performing\n"
      " (batch) allocations (e.g., 500ms, 1sec, etc).",
      DEFAULT_ALLOCATION_INTERVAL);

  add(&Flags::cluster,
      "cluster",
      "Human readable name for the cluster,\n"
      "displayed in the webui.");

  add(&Flags::roles,
      "roles",
      "A comma-separated list of the allocation roles that frameworks\n"
      "in this cluster may belong to. This flag is deprecated;\n"
      "if it is not specified, any role name can be used.");

  add(&Flags::weights,
      "weights",
      "A comma-separated list of role/weight pairs\n"
      "of the form 'role=weight,role=weight'. Weights\n"
      "are used to indicate forms of priority.");

  // TODO(adam-mesos): Deprecate --authenticate for --authenticate_frameworks.
  add(&Flags::authenticate_frameworks,
      "authenticate",
      "If authenticate is 'true' only authenticated frameworks are allowed\n"
      "to register. If 'false' unauthenticated frameworks are also\n"
      "allowed to register.",
      false);

  add(&Flags::authenticate_slaves,
      "authenticate_slaves",
      "If 'true' only authenticated slaves are allowed to register.\n"
      "If 'false' unauthenticated slaves are also allowed to register.",
      false);

  add(&Flags::authenticate_http,
      "authenticate_http",
      "If 'true' only authenticated requests for HTTP endpoints supporting\n"
      "authentication are allowed.\n"
      "If 'false' unauthenticated HTTP endpoint requests are also allowed.\n",
      false);

  add(&Flags::credentials,
      "credentials",
      "Either a path to a text file with a list of credentials,\n"
      "each line containing 'principal' and 'secret' separated by "
      "whitespace,\n"
      "or, a path to a JSON-formatted file containing credentials.\n"
      "Path could be of the form 'file:///path/to/file' or '/path/to/file'."
      "\n"
      "JSON file Example:\n"
      "{\n"
      "  \"credentials\": [\n"
      "    {\n"
      "      \"principal\": \"sherman\",\n"
      "      \"secret\": \"kitesurf\"\n"
      "    }\n"
      "  ]\n"
      "}\n"
      "Text file Example:\n"
      "username secret");

  add(&Flags::acls,
      "acls",
      "The value could be a JSON-formatted string of ACLs\n"
      "or a file path containing the JSON-formatted ACLs used\n"
      "for authorization. Path could be of the form 'file:///path/to/file'\n"
      "or '/path/to/file'.\n"
      "\n"
      "Note that if the flag --authorizers is provided with a value different\n"
      "than '" + DEFAULT_AUTHORIZER + "', the ACLs contents will be ignored.\n"
      "\n"
      "See the ACLs protobuf in authorizer.proto for the expected format.\n"
      "\n"
      "Example:\n"
      "{\n"
      "  \"register_frameworks\": [\n"
      "    {\n"
      "      \"principals\": { \"type\": \"ANY\" },\n"
      "      \"roles\": { \"values\": [\"a\"] }\n"
      "    }\n"
      "  ],\n"
      "  \"run_tasks\": [\n"
      "    {\n"
      "      \"principals\": { \"values\": [\"a\", \"b\"] },\n"
      "      \"users\": { \"values\": [\"c\"] }\n"
      "    }\n"
      "  ],\n"
      "  \"shutdown_frameworks\": [\n"
      "    {\n"
      "      \"principals\": { \"values\": [\"a\", \"b\"] },\n"
      "      \"framework_principals\": { \"values\": [\"c\"] }\n"
      "    }\n"
      "  ],\n"
      "  \"set_quotas\": [\n"
      "    {\n"
      "      \"principals\": { \"values\": [\"a\"] },\n"
      "      \"roles\": { \"values\": [\"a\", \"b\"] }\n"
      "    }\n"
      "  ],\n"
      "  \"remove_quotas\": [\n"
      "    {\n"
      "      \"principals\": { \"values\": [\"a\"] },\n"
      "      \"quota_principals\": { \"values\": [\"a\"] }\n"
      "    }\n"
      "  ]\n"
      "}");

  add(&Flags::firewall_rules,
      "firewall_rules",
      "The value could be a JSON-formatted string of rules or a\n"
      "file path containing the JSON-formatted rules used in the endpoints\n"
      "firewall. Path must be of the form 'file:///path/to/file'\n"
      "or '/path/to/file'.\n"
      "\n"
      "See the Firewall message in flags.proto for the expected format.\n"
      "\n"
      "Example:\n"
      "{\n"
      "  \"disabled_endpoints\" : {\n"
      "    \"paths\" : [\n"
      "      \"/files/browse\",\n"
      "      \"/slave(0)/stats.json\"\n"
      "    ]\n"
      "  }\n"
      "}");

  add(&Flags::rate_limits,
      "rate_limits",
      "The value could be a JSON-formatted string of rate limits\n"
      "or a file path containing the JSON-formatted rate limits used\n"
      "for framework rate limiting.\n"
      "Path could be of the form 'file:///path/to/file'\n"
      "or '/path/to/file'.\n"
      "\n"
      "See the RateLimits protobuf in mesos.proto for the expected format.\n"
      "\n"
      "Example:\n"
      "{\n"
      "  \"limits\": [\n"
      "    {\n"
      "      \"principal\": \"foo\",\n"
      "      \"qps\": 55.5\n"
      "    },\n"
      "    {\n"
      "      \"principal\": \"bar\"\n"
      "    }\n"
      "  ],\n"
      "  \"aggregate_default_qps\": 33.3\n"
      "}");

#ifdef WITH_NETWORK_ISOLATOR
  add(&Flags::max_executors_per_slave,
      "max_executors_per_slave",
      "Maximum number of executors allowed per slave. The network\n"
      "monitoring/isolation technique imposes an implicit resource\n"
      "acquisition on each executor (# ephemeral ports), as a result\n"
      "one can only run a certain number of executors on each slave.");
#endif // WITH_NETWORK_ISOLATOR

  // TODO(karya): When we have optimistic offers, this will only
  // benefit frameworks that accidentally lose an offer.
  add(&Flags::offer_timeout,
      "offer_timeout",
      "Duration of time before an offer is rescinded from a framework.\n"
      "This helps fairness when running frameworks that hold on to offers,\n"
      "or frameworks that accidentally drop offers.");

  // This help message for --modules flag is the same for
  // {master,slave,tests}/flags.hpp and should always be kept in
  // sync.
  // TODO(karya): Remove the JSON example and add reference to the
  // doc file explaining the --modules flag.
  add(&Flags::modules,
      "modules",
      "List of modules to be loaded and be available to the internal\n"
      "subsystems.\n"
      "\n"
      "Use --modules=filepath to specify the list of modules via a\n"
      "file containing a JSON-formatted string. 'filepath' can be\n"
      "of the form 'file:///path/to/file' or '/path/to/file'.\n"
      "\n"
      "Use --modules=\"{...}\" to specify the list of modules inline.\n"
      "\n"
      "Example:\n"
      "{\n"
      "  \"libraries\": [\n"
      "    {\n"
      "      \"file\": \"/path/to/libfoo.so\",\n"
      "      \"modules\": [\n"
      "        {\n"
      "          \"name\": \"org_apache_mesos_bar\",\n"
      "          \"parameters\": [\n"
      "            {\n"
      "              \"key\": \"X\",\n"
      "              \"value\": \"Y\"\n"
      "            }\n"
      "          ]\n"
      "        },\n"
      "        {\n"
      "          \"name\": \"org_apache_mesos_baz\"\n"
      "        }\n"
      "      ]\n"
      "    },\n"
      "    {\n"
      "      \"name\": \"qux\",\n"
      "      \"modules\": [\n"
      "        {\n"
      "          \"name\": \"org_apache_mesos_norf\"\n"
      "        }\n"
      "      ]\n"
      "    }\n"
      "  ]\n"
      "}");

  add(&Flags::authenticators,
      "authenticators",
      "Authenticator implementation to use when authenticating frameworks\n"
      "and/or slaves. Use the default '" + DEFAULT_AUTHENTICATOR + "', or\n"
      "load an alternate authenticator module using --modules.",
      DEFAULT_AUTHENTICATOR);

  add(&Flags::allocator,
      "allocator",
      "Allocator to use for resource allocation to frameworks.\n"
      "Use the default '" + DEFAULT_ALLOCATOR + "' allocator, or\n"
      "load an alternate allocator module using --modules.",
      DEFAULT_ALLOCATOR);

  add(&Flags::hooks,
      "hooks",
      "A comma-separated list of hook modules to be\n"
      "installed inside master.");

  add(&Flags::slave_ping_timeout,
      "slave_ping_timeout",
      "The timeout within which each slave is expected to respond to a\n"
      "ping from the master. Slaves that do not respond within\n"
      "max_slave_ping_timeouts ping retries will be asked to shutdown.\n"
      "NOTE: The total ping timeout (slave_ping_timeout multiplied by\n"
      "max_slave_ping_timeouts) should be greater than the ZooKeeper\n"
      "session timeout to prevent useless re-registration attempts.\n",
      DEFAULT_SLAVE_PING_TIMEOUT,
      [](const Duration& value) -> Option<Error> {
        if (value < Seconds(1) || value > Minutes(15)) {
          return Error("Expected --slave_ping_timeout to be between " +
                       stringify(Seconds(1)) + " and " +
                       stringify(Minutes(15)));
        }
        return None();
      });

  add(&Flags::max_slave_ping_timeouts,
      "max_slave_ping_timeouts",
      "The number of times a slave can fail to respond to a\n"
      "ping from the master. Slaves that do not respond within\n"
      "max_slave_ping_timeouts ping retries will be asked to shutdown.\n",
      DEFAULT_MAX_SLAVE_PING_TIMEOUTS,
      [](size_t value) -> Option<Error> {
        if (value < 1) {
          return Error("Expected --max_slave_ping_timeouts to be at least 1");
        }
        return None();
      });

  add(&Flags::authorizers,
      "authorizers",
      "Authorizer implementation to use when authorizating actions that\n"
      "required it.\n"
      "Use the default '" + DEFAULT_AUTHORIZER + "', or\n"
      "load an alternate authorizer module using --modules.\n"
      "\n"
      "Note that if the flag --authorizers is provided with a value different\n"
      "than the default '" + DEFAULT_AUTHORIZER + "', the ACLs passed\n"
      "through the --acls flag will be ignored.\n"
      "\n"
      "Currently there's no support for multiple authorizers.",
      DEFAULT_AUTHORIZER);

  add(&Flags::http_authenticators,
      "http_authenticators",
      "HTTP authenticator implementation to use when handling requests to\n"
      "authenticated endpoints. Use the default\n"
      "'" + DEFAULT_HTTP_AUTHENTICATOR + "', or load an alternate HTTP\n"
      "authenticator module using --modules.\n"
      "\n"
      "Currently there is no support for multiple HTTP authenticators.",
      DEFAULT_HTTP_AUTHENTICATOR);
}
Esempio n. 21
0
bool WebCPanel::MemoServ::Memos::OnRequest(HTTPProvider *server, const Anope::string &page_name, HTTPClient *client, HTTPMessage &message, HTTPReply &reply, NickAlias *na, TemplateFileServer::Replacements &replacements)
{
	const Anope::string &chname = message.get_data["channel"];
	ChannelInfo *ci;
	const MemoInfo *mi;
	Memo *m;

	for (registered_channel_map::const_iterator it = RegisteredChannelList->begin(), it_end = RegisteredChannelList->end(); it != it_end; ++it)
	{
		ci = it->second;

		if (ci->AccessFor(na->nc).HasPriv("MEMO"))
		{
			replacements["CHANNEL_NAMES"] = ci->name;
			replacements["ESCAPED_CHANNEL_NAMES"] = HTTPUtils::URLEncode(ci->name);
		}
	}

	if (chname.empty())
	{
		replacements["MESSAGES"] = "No Channel specified, displaying the memos for your Nick";
		mi = &na->nc->memos;
	}
	else
	{
		ci = ChannelInfo::Find(chname);
		if (ci)
		{
			replacements["MESSAGES"] = "Displaying the memos for " + chname + ".";
			mi = &ci->memos;
		}
		else
		{
			replacements["MESSAGES"] = "Channel " + chname + " not found, displaying the memos for your nick";
			mi = &na->nc->memos;
		}

		replacements["CHANNEL_NAME"] = ci->name;
		replacements["ESCAPED_CHANNEL_NAME"] = HTTPUtils::URLEncode(ci->name);
	}
	if (message.post_data.count("receiver") > 0 && message.post_data.count("message") > 0)
	{
		std::vector<Anope::string> params;
		params.push_back(HTTPUtils::URLDecode(message.post_data["receiver"]));
		params.push_back(HTTPUtils::URLDecode(message.post_data["message"]));

		WebPanel::RunCommand(na->nc->display, na->nc, "MemoServ", "memoserv/send", params, replacements, "CMDR");
	}
	if (message.get_data.count("del") > 0 && message.get_data.count("number") > 0)
	{
		std::vector<Anope::string> params;
		if (!chname.empty())
			params.push_back(chname);
		params.push_back(message.get_data["number"]);

		WebPanel::RunCommand(na->nc->display, na->nc, "MemoServ", "memoserv/del", params, replacements, "CMDR");
	}
	if (message.get_data.count("read") > 0 && message.get_data.count("number") > 0)
	{
		std::vector<Anope::string> params;
		int number = -1;

		try
		{
			number = convertTo<int>(message.get_data["number"]);
		}
		catch (const ConvertException &ex)
		{
			replacements["MESSAGES"] = "ERROR - invalid parameter for NUMBER";
		}

		if (number > 0)
		{
			m = mi->GetMemo(number-1);

			if (!m)
				replacements["MESSAGES"] = "ERROR - invalid memo number.";
			else if (message.get_data["read"] == "1")
				m->unread = false;
			else if (message.get_data["read"] == "2")
				m->unread = true;
		}
	}

	for (unsigned i = 0; i < mi->memos->size(); ++i)
	{
		m = mi->GetMemo(i);
		replacements["NUMBER"] = stringify(i+1);
		replacements["SENDER"] = m->sender;
		replacements["TIME"] = Anope::strftime(m->time);
		replacements["TEXT"] = HTTPUtils::Escape(m->text);
		if (m->unread)
			replacements["UNREAD"] = "YES";
		else
			replacements["UNREAD"] = "NO";
	}

	TemplateFileServer page("memoserv/memos.html");
	page.Serve(server, page_name, client, message, reply, replacements);
	return true;
}
  // Forwards the status update on the specified update stream.
  //
  // If `checkpoint` is `false`, the update will be retried as long as it is in
  // memory, but it will not be checkpointed.
  process::Future<Nothing> update(
      const UpdateType& update,
      const IDType& streamId,
      bool checkpoint)
  {
    LOG(INFO) << "Received " << statusUpdateType << " " << update;

    if (!streams.contains(streamId)) {
      Try<Nothing> create =
        createStatusUpdateStream(
            streamId,
            update.has_framework_id()
              ? Option<FrameworkID>(update.framework_id())
              : None(),
            checkpoint);

      if (create.isError()) {
        return process::Failure(create.error());
      }
    }
    CHECK(streams.contains(streamId));
    StatusUpdateStream* stream = streams[streamId].get();

    if (update.has_latest_status()) {
      return process::Failure(
          "Expected " + statusUpdateType + " to not contain 'latest_status'");
    }

    // Verify that we didn't get a non-checkpointable update for a
    // stream that is checkpointable, and vice-versa.
    if (stream->checkpointed() != checkpoint) {
      return process::Failure(
          "Mismatched checkpoint value for " + statusUpdateType + " " +
          stringify(update) + " (expected checkpoint=" +
          stringify(stream->checkpointed()) + " actual checkpoint=" +
          stringify(checkpoint) + ")");
    }

    // Verify that the framework ID of the update matches the framework ID
    // of the stream.
    if (update.has_framework_id() != stream->frameworkId.isSome()) {
      return process::Failure(
          "Mismatched framework ID for " + statusUpdateType +
          " " + stringify(update) + " (expected " +
          (stream->frameworkId.isSome()
             ? stringify(stream->frameworkId.get())
             : "no framework ID") +
          " got " +
          (update.has_framework_id()
             ? stringify(update.framework_id())
             : "no framework ID") +
          ")");
    }

    if (update.has_framework_id() &&
        update.framework_id() != stream->frameworkId.get()) {
      return process::Failure(
          "Mismatched framework ID for " + statusUpdateType +
          " " + stringify(update) +
          " (expected " + stringify(stream->frameworkId.get()) +
          " actual " + stringify(update.framework_id()) + ")");
    }

    // Handle the status update.
    Try<bool> result = stream->update(update);
    if (result.isError()) {
      return process::Failure(result.error());
    }

    // This only happens if the status update is a duplicate.
    if (!result.get()) {
      return Nothing();
    }

    // Forward the status update if this is at the front of the queue.
    // Subsequent status updates will be sent in `acknowledgement()`.
    if (!paused && stream->pending.size() == 1) {
      CHECK_NONE(stream->timeout);

      const Result<UpdateType>& next = stream->next();
      if (next.isError()) {
        return process::Failure(next.error());
      }

      CHECK_SOME(next);
      stream->timeout =
        forward(stream, next.get(), slave::STATUS_UPDATE_RETRY_INTERVAL_MIN);
    }

    return Nothing();
  }
Esempio n. 23
0
            .driver   = "virtio-balloon-pci",\
            .property = "event_idx",\
            .value    = "off",\
        }

static QEMUMachine pc_machine_v0_14 = {
    .name = "pc-0.14",
    .desc = "Standard PC",
    .init = pc_init_pci,
    .max_cpus = 255,
    .compat_props = (GlobalProperty[]) {
        PC_COMPAT_0_14, 
        {
            .driver   = "qxl",
            .property = "revision",
            .value    = stringify(2),
        },{
            .driver   = "qxl-vga",
            .property = "revision",
            .value    = stringify(2),
        },
        { /* end of list */ }
    },
    .hw_version = "0.14",
};

#define PC_COMPAT_0_13 \
        PC_COMPAT_0_14,\
        {\
            .driver   = TYPE_PCI_DEVICE,\
            .property = "command_serr_enable",\
Esempio n. 24
0
// The purpose of this test is to ensure that when slaves are removed
// from the master, and then attempt to send status updates, we send
// a ShutdownMessage to the slave. Why? Because during a network
// partition, the master will remove a partitioned slave, thus sending
// its tasks to LOST. At this point, when the partition is removed,
// the slave may attempt to send updates if it was unaware that the
// master removed it. We've already notified frameworks that these
// tasks were LOST, so we have to have the slave shut down.
TEST_F(PartitionTest, PartitionedSlaveStatusUpdates)
{
  master::Flags masterFlags = CreateMasterFlags();
  Try<PID<Master>> master = StartMaster(masterFlags);
  ASSERT_SOME(master);

  // Allow the master to PING the slave, but drop all PONG messages
  // from the slave. Note that we don't match on the master / slave
  // PIDs because it's actually the SlaveObserver Process that sends
  // the pings.
  Future<Message> ping = FUTURE_MESSAGE(Eq("PING"), _, _);
  DROP_MESSAGES(Eq("PONG"), _, _);

  Future<SlaveRegisteredMessage> slaveRegisteredMessage =
    FUTURE_PROTOBUF(SlaveRegisteredMessage(), _, _);

  MockExecutor exec(DEFAULT_EXECUTOR_ID);

  Try<PID<Slave>> slave = StartSlave(&exec);
  ASSERT_SOME(slave);

  AWAIT_READY(slaveRegisteredMessage);
  SlaveID slaveId = slaveRegisteredMessage.get().slave_id();

  MockScheduler sched;
  MesosSchedulerDriver driver(
      &sched, DEFAULT_FRAMEWORK_INFO, master.get(), DEFAULT_CREDENTIAL);

  Future<FrameworkID> frameworkId;
  EXPECT_CALL(sched, registered(&driver, _, _))
    .WillOnce(FutureArg<1>(&frameworkId));

  EXPECT_CALL(sched, resourceOffers(&driver, _))
    .WillRepeatedly(Return());

  driver.start();

  AWAIT_READY(frameworkId);

  // Drop the first shutdown message from the master (simulated
  // partition), allow the second shutdown message to pass when
  // the slave sends an update.
  Future<ShutdownMessage> shutdownMessage =
    DROP_PROTOBUF(ShutdownMessage(), _, slave.get());

  EXPECT_CALL(sched, offerRescinded(&driver, _))
    .WillRepeatedly(Return());

  Future<Nothing> slaveLost;
  EXPECT_CALL(sched, slaveLost(&driver, _))
    .WillOnce(FutureSatisfy(&slaveLost));

  Clock::pause();

  // Now, induce a partition of the slave by having the master
  // timeout the slave.
  size_t pings = 0;
  while (true) {
    AWAIT_READY(ping);
    pings++;
    if (pings == masterFlags.max_slave_ping_timeouts) {
     break;
    }
    ping = FUTURE_MESSAGE(Eq("PING"), _, _);
    Clock::advance(masterFlags.slave_ping_timeout);
    Clock::settle();
  }

  Clock::advance(masterFlags.slave_ping_timeout);
  Clock::settle();

  // Wait for the master to attempt to shut down the slave.
  AWAIT_READY(shutdownMessage);

  // The master will notify the framework that the slave was lost.
  AWAIT_READY(slaveLost);

  shutdownMessage = FUTURE_PROTOBUF(ShutdownMessage(), _, slave.get());

  // At this point, the slave still thinks it's registered, so we
  // simulate a status update coming from the slave.
  TaskID taskId;
  taskId.set_value("task_id");
  const StatusUpdate& update = protobuf::createStatusUpdate(
      frameworkId.get(),
      slaveId,
      taskId,
      TASK_RUNNING,
      TaskStatus::SOURCE_SLAVE,
      UUID::random());

  StatusUpdateMessage message;
  message.mutable_update()->CopyFrom(update);
  message.set_pid(stringify(slave.get()));

  process::post(master.get(), message);

  // The master should shutdown the slave upon receiving the update.
  AWAIT_READY(shutdownMessage);

  Clock::resume();

  driver.stop();
  driver.join();

  Shutdown();
}
Esempio n. 25
0
void test_stringify_cannot_malloc_returns_sane_result() {
  replace_function(&malloc, &always_failing_malloc);
  char *h = stringify('h');
  assert_string_equals("cannot_stringify", h);
}
Esempio n. 26
0
string getSlavePath(
    const string& rootDir,
    const SlaveID& slaveId)
{
  return path::join(rootDir, "slaves", stringify(slaveId));
}
Esempio n. 27
0
int determine_boot_type(void)
{
	DECLARE_GLOBAL_DATA_PTR;
	uint8_t charging;
	uint16_t batt_lvl;
	extern uint16_t check_charging(uint8_t* enabling);
	unsigned long bootcount = bootcount_load();
	char s [5];

	setenv("bootlimit", stringify(ACCLAIM_BOOTLIMIT));
	setenv("altbootcmd", "mmcinit 1; booti mmc1 recovery");
	batt_lvl = check_charging(&charging);
	lcd_console_init();
	// give subtle indicator if uboot is booting from emmc or sd


	lcd_console_setpos(0, 1); //indent slightly
	lcd_console_setcolor(CONSOLE_COLOR_GRAY, CONSOLE_COLOR_BLACK);
	if (running_from_sd()) {
		lcd_putc('S');
		} else {
		lcd_putc('I'); }
	sprintf(s, " %u", bootcount);
	lcd_puts(s);
	extern const char* board_rev_string(unsigned long btype);
	lcd_console_setpos(1, 1);
	lcd_printf("board rev: %s | %s", board_rev_string(gd->bd->bi_board_revision), (get_sdram_size() == SZ_512M?"512MB/8GB":"1GB/16GB"));
	lcd_console_setpos(2, 1);
	lcd_console_setcolor((batt_lvl < 30?(batt_lvl <= 10?CONSOLE_COLOR_RED:CONSOLE_COLOR_ORANGE):CONSOLE_COLOR_GREEN), CONSOLE_COLOR_BLACK);
	lcd_printf("batt level: %d\n charging %s", batt_lvl, (charging?"ENABLED":"DISABLED"));


	int action = get_boot_action();

	while(1){
		switch(action) {

	        //actually, boot from boot+512K -- thanks bauwks!
		case BOOT_EMMC_NORMAL:
			setenv("bootcmd", "mmcinit 1; booti mmc1 boot 0x80000");
			display_feedback(BOOT_EMMC_NORMAL);
			return 0;

		//actually, boot from recovery+512K -- thanks bauwks!
		case BOOT_EMMC_RECOVERY:
			setenv("bootcmd", "mmcinit 1; booti mmc1 recovery 0x80000");
			display_feedback(BOOT_EMMC_RECOVERY);
			return 0;

		// no 512K offset, this is just a file.
		case BOOT_EMMC_ALTBOOT:  
			setenv ("bootcmd", "setenv setbootargs setenv bootargs ${emmcbootargs}; run setbootargs; mmcinit 1; fatload mmc 1:5 0x81000000 altboot.img; booti 0x81000000");
			setenv ("altbootcmd", "run bootcmd"); // for emmc altboot altbootcmd is the same as bootcmd
			display_feedback(BOOT_EMMC_ALTBOOT);
			return 0;

		case BOOT_SD_RECOVERY:
			setenv ("bootcmd", "setenv setbootargs setenv bootargs ${sdbootargs}; run setbootargs; mmcinit 0; fatload mmc 0:1 0x81000000 recovery.img; booti 0x81000000");
			setenv ("altbootcmd", "run bootcmd"); // for sd boot altbootcmd is the same as bootcmd
			display_feedback(BOOT_SD_RECOVERY);
			return 0;

		case BOOT_SD_CM7:
			setenv ("bootcmd", "setenv setbootargs setenv bootargs ${sdbootargs}; run setbootargs; mmcinit 0; fatload mmc 0:1 0x81000000 cm7.img; booti 0x81000000");
			setenv ("altbootcmd", "run bootcmd"); // for sd boot altbootcmd is the same as bootcmd
			display_feedback(BOOT_SD_CM7);
			return 0;

		case BOOT_SD_CM9:
			setenv ("bootcmd", "setenv setbootargs setenv bootargs ${sdbootargs}; run setbootargs; mmcinit 0; fatload mmc 0:1 0x81000000 cm9.img; booti 0x81000000");
			setenv ("altbootcmd", "run bootcmd"); // for sd boot altbootcmd is the same as bootcmd
			display_feedback(BOOT_SD_CM9);
			return 0;

		case BOOT_SD_ALTBOOT1:
			setenv ("bootcmd", "setenv setbootargs setenv bootargs ${sdbootargs}; run setbootargs; mmcinit 0; fatload mmc 0:1 0x81000000 altboot1.img; booti 0x81000000");
			setenv ("altbootcmd", "run bootcmd"); // for sd boot altbootcmd is the same as bootcmd
			display_feedback(BOOT_SD_ALTBOOT1);
			return 0;

		case BOOT_SD_ALTBOOT2:
			setenv ("bootcmd", "setenv setbootargs setenv bootargs ${sdbootargs}; run setbootargs; mmcinit 0; fatload mmc 0:1 0x81000000 altboot2.img; booti 0x81000000");
			setenv ("altbootcmd", "run bootcmd"); // for sd boot altbootcmd is the same as bootcmd
			display_feedback(BOOT_SD_ALTBOOT2);
			return 0;

		case BOOT_SD_ALTBOOT3:
			setenv ("bootcmd", "setenv setbootargs setenv bootargs ${sdbootargs}; run setbootargs; mmcinit 0; fatload mmc 0:1 0x81000000 altboot3.img; booti 0x81000000");
			setenv ("altbootcmd", "run bootcmd"); // for sd boot altbootcmd is the same as bootcmd
			display_feedback(BOOT_SD_ALTBOOT3);
			return 0;

		case BOOT_FASTBOOT:
			display_feedback(BOOT_FASTBOOT);
			run_command("fastboot", 0);
			break;

		case INVALID:
		default:
			printf("Aborting boot!\n");
			return 1;
		}
		action = do_menu();
	}
}
Camera::Camera(GameHandle cameraHandle, 
               Ogre::SceneNode* camNode, 
               Ogre::RenderTarget* renderTarget, 
               s32 width, 
               s32 height) :
mCameraNode(camNode),
mRenderTarget(renderTarget),
mHandle(cameraHandle),
mNodeCreated(false),
mRenderTargetCreated(false)
{
	Ogre::SceneManager* sceneMgr;
	if (mCameraNode == NULL) // Create SceneNode
	{
		sceneMgr = Ogre::Root::getSingleton().getSceneManager(BFG_SCENEMANAGER);
		if (sceneMgr->hasSceneNode(stringify(mHandle)))
		{
			mCameraNode = sceneMgr->getSceneNode(stringify(mHandle));
		}
		else
		{
			mCameraNode = sceneMgr->getRootSceneNode()->createChildSceneNode(stringify(mHandle));
			mNodeCreated = true;
		}
	}
	else
	{
		sceneMgr = mCameraNode->getCreator();
	}
	mCameraNode->resetOrientation();
	mCameraNode->setPosition(toOgre(v3::ZERO));

	v3 target = toBFG(mCameraNode->getOrientation().zAxis());
	norm(target);

	Ogre::Camera* cam;
	cam = sceneMgr->createCamera(stringify(mHandle));

	cam->setFOVy(Ogre::Degree(60.0f));
	cam->setNearClipDistance(0.1f);
	cam->setFarClipDistance(250000.0f);
	cam->lookAt(toOgre(target) * 10);
	mCameraNode->attachObject(cam);

	infolog << "Camera: " << stringify(mHandle) << " created.";

	if (mRenderTarget == NULL)
	{
		// Create renderToTexture RenderTarget

		if (width == 0 || height == 0)
		{
			throw std::logic_error("Too few information to create a render target.");
		}

		cam->setAspectRatio((f32)width / (f32)height);

		Ogre::TexturePtr texture = Ogre::TextureManager::getSingleton().createManual
		(
			stringify(mHandle),
			Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME,
			Ogre::TEX_TYPE_2D,
			width,
			height,
			0,
			Ogre::PF_R8G8B8,
			Ogre::TU_RENDERTARGET
		);

		mRenderTarget = texture->getBuffer()->getRenderTarget();

		prepareRenderTarget();

		mRenderTarget->addViewport(cam);

		mRenderTarget->getViewport(0)->setClearEveryFrame(true);
		mRenderTarget->getViewport(0)->setBackgroundColour(Ogre::ColourValue::Black);
		mRenderTarget->getViewport(0)->setOverlaysEnabled(false);

		Ogre::MaterialPtr mat =
			Ogre::MaterialManager::getSingleton().getByName(stringify(mHandle));
		if (mat.isNull())
		{
			mat = Ogre::MaterialManager::getSingleton().create(
			    stringify(mHandle), 
			    Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME);
		}
		Ogre::Technique* tech = mat->getTechnique(0);
		if (!tech)
		{
			tech = mat->createTechnique();
		}
		Ogre::Pass* pass = tech->getPass(0);
		if (!pass)
		{
			pass = tech->createPass();
		}
		pass->setLightingEnabled(false);

		Ogre::TextureUnitState* txState = NULL;
		if (pass->getNumTextureUnitStates() > 0)
		{
			txState = pass->getTextureUnitState(0);
			txState->setTextureName(stringify(mHandle));
		}
		else
		{
			pass->createTextureUnitState(stringify(mHandle));
		}

		mRenderTarget->setAutoUpdated(true);

		mRenderTargetCreated = true;

		infolog << "Rendertarget: " << stringify(mHandle) << " created.";
	}
	else
	{
		prepareRenderTarget();
		f32 width = mRenderTarget->getWidth();
		f32 height = mRenderTarget->getHeight();
		cam->setAspectRatio(width / height);
		mRenderTarget->addViewport(cam);
	}
	
	Main::eventLoop()->connect
	(
		ID::VE_UPDATE_POSITION,
		this,
		&Camera::viewEventHandler,
		mHandle
	);
	
	Main::eventLoop()->connect
	(
		ID::VE_UPDATE_ORIENTATION,
		this,
		&Camera::viewEventHandler,
		mHandle
	);

}
Esempio n. 29
0
void FlagsBase::add(
    Option<T> Flags::*option,
    const std::string& name,
    const std::string& help,
    F validate)
{
  // Don't bother adding anything if the pointer is NULL.
  if (option == NULL) {
    return;
  }

  Flags* flags = dynamic_cast<Flags*>(this);
  if (flags == NULL) {
    ABORT("Attempted to add flag '" + name + "' with incompatible type");
  }

  Flag flag;
  flag.name = name;
  flag.help = help;
  flag.boolean = typeid(T) == typeid(bool);

  // NOTE: See comment above in Flags::T* overload of FLagsBase::add
  // for why we need to pass FlagsBase* (or const FlagsBase&) as a
  // parameter.

  flag.load =
    [option](FlagsBase* base, const std::string& value) -> Try<Nothing> {
      Flags* flags = dynamic_cast<Flags*>(base);
      if (flags != NULL) {
        // NOTE: 'fetch' "retrieves" the value if necessary and then
        // invokes 'parse'. See 'fetch' for more details.
        Try<T> t = fetch<T>(value);
        if (t.isSome()) {
          flags->*option = Some(t.get());
        } else {
          return Error("Failed to load value '" + value + "': " + t.error());
        }
      }
      return Nothing();
    };

  flag.stringify = [option](const FlagsBase& base) -> Option<std::string> {
    const Flags* flags = dynamic_cast<const Flags*>(&base);
    if (flags != NULL) {
      if ((flags->*option).isSome()) {
        return stringify((flags->*option).get());
      }
    }
    return None();
  };

  flag.validate = [option, validate](const FlagsBase& base) -> Option<Error> {
    const Flags* flags = dynamic_cast<const Flags*>(&base);
    if (flags != NULL) {
      return validate(flags->*option);
    }
    return None();
  };

  add(flag);
}
Esempio n. 30
0
void
HumanPlayer::handleMessageFromClient( const proto::ClientToServerMsg& msg )
{
    if( msg.has_player_named_card_preselection_ind() )
    {
        const proto::PlayerNamedCardPreselectionInd& ind = msg.player_named_card_preselection_ind();
        mPreselectedCard = std::make_shared<DraftCard>( ind.card().name(), ind.card().set_code() );
        mLogger->debug( "client indicated preselection card={}", *mPreselectedCard );
    }
    else if( msg.has_player_named_card_selection_req() )
    {
        const proto::PlayerNamedCardSelectionReq& req = msg.player_named_card_selection_req();
        DraftCard card( req.card().name(), req.card().set_code() );
        mLogger->debug( "client requested named selection pack_id={},card={}", req.pack_id(), card );
        mNamedSelectionZone = convertZone( req.zone() );
        bool result = mDraft->makeNamedCardSelection( getChairIndex(), req.pack_id(), card );
        if( !result )
        {
            // Notify of error (currently always saying invalid card)
            sendPlayerNamedCardSelectionRsp( false, req.pack_id(), card );
        }
    }
    else if( msg.has_player_indexed_card_selection_req() )
    {
        const proto::PlayerIndexedCardSelectionReq& req = msg.player_indexed_card_selection_req();
        std::vector<int> indices;
        for( auto index : req.indices() )
        {
            indices.push_back( index );
        }
        mLogger->debug( "client requested indexed selection pack_id={},indices={}", req.pack_id(), StringUtil::stringify( indices ) );
        mIndexedSelectionZone = convertZone( req.zone() );
        bool result = mDraft->makeIndexedCardSelection( getChairIndex(), req.pack_id(), indices );
        if( !result )
        {
            // Notify of error (currently always saying invalid card)
            sendPlayerIndexedCardSelectionRsp( false, req.pack_id(), indices, std::vector<DraftCard>() );
        }
    }
    else if( msg.has_player_ready_ind() )
    {
        const proto::PlayerReadyInd& ind = msg.player_ready_ind();
        emit readyUpdate( ind.ready() );
    }
    else if( msg.has_player_inventory_update_ind() )
    {
        const proto::PlayerInventoryUpdateInd& ind = msg.player_inventory_update_ind();
        mLogger->debug( "playerInventoryUpdate" );

        bool inSync = true;

        // Handle drafted card moves.
        for( int i = 0; (i < ind.drafted_card_moves_size()) && inSync; ++i )
        {
            const proto::PlayerInventoryUpdateInd::DraftedCardMove& move =
                    ind.drafted_card_moves( i );
            const proto::Card& card = move.card();
            mLogger->debug( "  {}: {} -> {}", card.name(), move.zone_from(), move.zone_to() );
            auto cardData = std::make_shared<SimpleCardData>( card.name(), card.set_code() );

            bool moveOk = mInventory.move( cardData,
                    convertZone( move.zone_from() ), convertZone( move.zone_to() ) );
            if( !moveOk )
            {
                // Error moving a card.  This should never happen, but if
                // it somehow does, set a flag to resync the client.
                mLogger->warn( "error moving card - client out of sync!" );
                inSync = false;
            }
        }

        // Handle basic land adjustments.
        for( int i = 0; (i < ind.basic_land_adjustments_size()) && inSync; ++i )
        {
            const proto::PlayerInventoryUpdateInd::BasicLandAdjustment& adj =
                    ind.basic_land_adjustments( i );
            mLogger->debug( "  {}: {} -> {}", stringify( adj.basic_land() ),
                    stringify( adj.zone() ), adj.adjustment() );

            bool adjOk = mInventory.adjustBasicLand( convertBasicLand( adj.basic_land() ),
                    convertZone( adj.zone() ), adj.adjustment() );
            if( !adjOk )
            {
                // Error adjusting a basic land.  This should never happen,
                // but if it somehow does, set a flag to resync the client.
                mLogger->warn( "error adjusting basic land - client out of sync!" );
                inSync = false;
            }
        }

        if( !inSync )
        {
            mLogger->notice( "resyncing client with new inventory" );
            sendPlayerInventoryInd();
        }

        emit deckUpdate();
    }
    else
    {
        // This may not be the only handler, so it's not an error to pass on
        // a message.
        mLogger->debug( "unhandled message from client: {}", msg.msg_case() );
    }
}