Beispiel #1
0
func UploadImage(fileURL, fileName, containerName string) bool {
	cDallas := swift.Connection{
		UserName: "",
		ApiKey:   "",
		AuthUrl:  "https://auth.api.rackspacecloud.com/v1.0",
		Region:   "DFW",
	}
	if err := cDallas.Authenticate(); err != nil {
		log.Println("Couldn't authenticate with rackspace Dallas")
		return false
	}
	var rspaceHeader swift.Headers
	fDallas, err := cDallas.ObjectCreate(containerName, fileName, false, "", "image/jpg", rspaceHeader)
	if err != nil {
		log.Println("Failed to create rackspace object ", err)
		return false
	}
	defer fDallas.Close()
	d, err := ioutil.ReadFile(fileURL)
	if err != nil {
		log.Println("Failed to read source file ", err)
		return false
	}
	log.Println("uploading path:", fileURL)
	if _, err := fDallas.Write(d); err != nil {
		log.Println("Failed to write file to rackspace Dallas server", err)
		return false
	}
	return true
}
func main() {
	// Create a connection
	c := swift.Connection{
		UserName: os.Getenv("SWIFT_API_USER"),
		ApiKey:   os.Getenv("SWIFT_API_KEY"),
		AuthUrl:  os.Getenv("SWIFT_AUTH_URL"),
		Domain:   "", // Name of the domain (v3 auth only)
		Tenant:   "", // Name of the tenant (v2 auth only)
	}

	if len(os.Args) < 3 {
		fmt.Printf("Usage: %s project files...\n", os.Args[0])
		os.Exit(1)
	}

	println("Starting objekt storage uploader")

	var (
		project = os.Args[1]
	)

	container_name := "project-" + project

	// Authenticate
	err := c.Authenticate()
	if err != nil {
		panic(err)
	}

	files := os.Args[2:]

	uploadFiles(container_name, files, c)

}
Beispiel #3
0
func TestTransport(t *testing.T) {
	UserName := os.Getenv("SWIFT_API_USER")
	ApiKey := os.Getenv("SWIFT_API_KEY")
	AuthUrl := os.Getenv("SWIFT_AUTH_URL")
	if UserName == "" || ApiKey == "" || AuthUrl == "" {
		t.Fatal("SWIFT_API_USER, SWIFT_API_KEY and SWIFT_AUTH_URL not all set")
	}
	tr := &someTransport{Transport: http.Transport{MaxIdleConnsPerHost: 2048}}
	ct := swift.Connection{
		UserName:       UserName,
		ApiKey:         ApiKey,
		AuthUrl:        AuthUrl,
		Tenant:         os.Getenv("SWIFT_TENANT"),
		TenantId:       os.Getenv("SWIFT_TENANT_ID"),
		Transport:      tr,
		ConnectTimeout: 60 * time.Second,
		Timeout:        60 * time.Second,
	}
	err := ct.Authenticate()
	if err != nil {
		t.Fatal("Auth failed", err)
	}
	if !ct.Authenticated() {
		t.Fatal("Not authenticated")
	}
}
func main() {
	// Create a connection
	c := swift.Connection{
		UserName: os.Getenv("SWIFT_API_USER"),
		ApiKey:   os.Getenv("SWIFT_API_KEY"),
		AuthUrl:  os.Getenv("SWIFT_AUTH_URL"),
		Domain:   "", // Name of the domain (v3 auth only)
		Tenant:   "", // Name of the tenant (v2 auth only)
	}

	println("Starting cleaner")

	// Authenticate
	err := c.Authenticate()
	if err != nil {
		panic(err)
	}

	containers := get_projects(c)

	fmt.Println("Found job containers:")
	fmt.Println(containers)

	for _, val := range containers {
		clean_old_jobs(c, val)
	}
}
Beispiel #5
0
func NewTask(ui common.UI) (workers.WorkerTask, error) {
	c := ui.ConfigGet()
	conf := c.GetSwiftConfig()
	if conf == nil {
		panic("Invalid Configuration object for swift worker")
	}

	conn := swift.Connection{
		UserName: conf.Username,
		ApiKey:   conf.ApiKey,
		AuthUrl:  conf.AuthUrl,
		// https://auth.api.rackspacecloud.com/v1.0
		Region:    conf.Region,
		UserAgent: fmt.Sprintf("hurl/1 http load tester; https://github.com/pquerna/hurl;  username=%s", conf.Username),
	}

	if authTokenCache != "" && storageUrlCache != "" {
		conn.AuthToken = authTokenCache
		conn.StorageUrl = storageUrlCache
	} else {
		err := conn.Authenticate()
		if err != nil {
			return nil, err
		}
		authTokenCache = conn.AuthToken
		storageUrlCache = conn.StorageUrl
	}

	return &Task{
		conf: conf,
		conn: &conn}, nil
}
Beispiel #6
0
// NewPublishedStorage creates new instance of PublishedStorage with specified Swift access
// keys, tenant and tenantId
func NewPublishedStorage(username string, password string, authURL string, tenant string, tenantID string, container string, prefix string) (*PublishedStorage, error) {
	if username == "" {
		if username = os.Getenv("OS_USERNAME"); username == "" {
			username = os.Getenv("ST_USER")
		}
	}
	if password == "" {
		if password = os.Getenv("OS_PASSWORD"); password == "" {
			password = os.Getenv("ST_KEY")
		}
	}
	if authURL == "" {
		if authURL = os.Getenv("OS_AUTH_URL"); authURL == "" {
			authURL = os.Getenv("ST_AUTH")
		}
	}
	if tenant == "" {
		tenant = os.Getenv("OS_TENANT_NAME")
	}
	if tenantID == "" {
		tenantID = os.Getenv("OS_TENANT_ID")
	}

	ct := swift.Connection{
		UserName:       username,
		ApiKey:         password,
		AuthUrl:        authURL,
		UserAgent:      "aptly/" + aptly.Version,
		Tenant:         tenant,
		TenantId:       tenantID,
		ConnectTimeout: 60 * time.Second,
		Timeout:        60 * time.Second,
	}
	err := ct.Authenticate()
	if err != nil {
		return nil, fmt.Errorf("swift authentication failed: %s", err)
	}

	var bulkDelete bool
	resp, err := http.Get(filepath.Join(ct.StorageUrl, "..", "..") + "/info")
	if err == nil {
		defer resp.Body.Close()
		decoder := json.NewDecoder(resp.Body)
		var infos swiftInfo
		if decoder.Decode(&infos) == nil {
			_, bulkDelete = infos["bulk_delete"]
		}
	}

	result := &PublishedStorage{
		conn:              ct,
		container:         container,
		prefix:            prefix,
		supportBulkDelete: bulkDelete,
	}

	return result, nil
}
func main() {

	fmt.Println("hello there")

	// Create a connection
	c := swift.Connection{
		UserName:    "******",
		ApiKey:      "password",
		AuthUrl:     "auth-url",
		Domain:      "domain", // Name of the domain
		AuthVersion: 3,
		TenantId:    "tenantId", // Id of the tenant/project
	}

	// Authenticate
	err := c.Authenticate()
	if err != nil {
		panic(err)
	}

	// List all containers
	containers, err := c.ContainerNamesAll(nil)
	if err != nil {
		panic(err)
	}
	fmt.Println("Containers: ")
	fmt.Println(containers)

	// Create new container
	err1 := c.ContainerCreate("testContainer", nil)
	if err1 != nil {
		panic(err1)
	}
	fmt.Println("Container created")

	// List objects
	object, headers, err := c.Object(CONTAINER, OBJECT)
	if err != nil {
		panic(err)
	}
	fmt.Println("Object Info: ")
	fmt.Println(object.Name)
	fmt.Println(headers.ObjectMetadata())

	// Account info
	info, headers, err := c.Account()
	if err != nil {
		panic(err)
	}
	fmt.Println("Account Info: ")
	fmt.Println(info)
	fmt.Println(headers)

}
Beispiel #8
0
// New constructs a new Driver with the given Openstack Swift credentials and container name
func New(params Parameters) (*Driver, error) {
	transport := &http.Transport{
		Proxy:               http.ProxyFromEnvironment,
		MaxIdleConnsPerHost: 2048,
		TLSClientConfig:     &tls.Config{InsecureSkipVerify: params.InsecureSkipVerify},
	}

	ct := swift.Connection{
		UserName:       params.Username,
		ApiKey:         params.Password,
		AuthUrl:        params.AuthURL,
		Region:         params.Region,
		UserAgent:      "distribution/" + version.Version,
		Tenant:         params.Tenant,
		TenantId:       params.TenantID,
		Domain:         params.Domain,
		DomainId:       params.DomainID,
		TrustId:        params.TrustID,
		Transport:      transport,
		ConnectTimeout: 60 * time.Second,
		Timeout:        15 * 60 * time.Second,
	}
	err := ct.Authenticate()
	if err != nil {
		return nil, fmt.Errorf("Swift authentication failed: %s", err)
	}

	if _, _, err := ct.Container(params.Container); err == swift.ContainerNotFound {
		if err := ct.ContainerCreate(params.Container, nil); err != nil {
			return nil, fmt.Errorf("Failed to create container %s (%s)", params.Container, err)
		}
	} else if err != nil {
		return nil, fmt.Errorf("Failed to retrieve info about container %s (%s)", params.Container, err)
	}

	d := &driver{
		Conn:              ct,
		Container:         params.Container,
		Prefix:            params.Prefix,
		BulkDeleteSupport: detectBulkDelete(params.AuthURL),
		ChunkSize:         params.ChunkSize,
	}

	return &Driver{
		baseEmbed: baseEmbed{
			Base: base.Base{
				StorageDriver: d,
			},
		},
	}, nil
}
Beispiel #9
0
func main() {
	//lol if you don't already use swiftly
	username := os.Getenv("SWIFTLY_AUTH_USER")
	apikey := os.Getenv("SWIFTLY_AUTH_KEY")
	authurl := os.Getenv("SWIFTLY_AUTH_URL")
	region := os.Getenv("SWIFTLY_REGION")
	snet := os.Getenv("SWIFTLY_SNET")
	dockerized := os.Getenv("DOCKERIZED")
	memcacheOverride := os.Getenv("MEMCACHEADDR")
	if strings.ToLower(dockerized) == "true" {
		memcacheOverride = fmt.Sprintf("%s:%s", os.Getenv("MEMCACHED_PORT_11211_TCP_ADDR"), os.Getenv("MEMCACHED_PORT_11211_TCP_PORT"))
	}
	memcacheAddr := "127.0.0.1:11211"
	if memcacheOverride != "" {
		memcacheAddr = memcacheOverride
	}
	internal := false
	if strings.ToLower(snet) == "true" {
		internal = true
	}
	//martini looks for a HOST and PORT env var to determine what to listen on
	m := martini.Classic()

	cf := swift.Connection{
		UserName: username,
		ApiKey:   apikey,
		AuthUrl:  authurl,
		Region:   region,
		Internal: internal,
	}
	// Authenticate
	err := cf.Authenticate()
	PanicIf(err)
	m.Map(&cf)
	log.Println(os.Environ())
	log.Println(memcacheAddr)
	mc := memcache.New(memcacheAddr)
	m.Map(mc)

	m.Use(render.Renderer())

	m.Get("/", IndexPage)
	m.Get("/history", GetHistory)
	m.Get("/:pasteid", GetPaste)
	m.Get("/:pasteid/:format", GetPaste)
	m.Post("/paste", binding.Json(Paste{}), binding.ErrorHandler, SavePaste)
	m.Put("/paste", binding.Json(Paste{}), binding.ErrorHandler, SavePaste)
	m.Run()
}
Beispiel #10
0
func Example() {
	// Create a connection
	c := swift.Connection{
		UserName: "******",
		ApiKey:   "key",
		AuthUrl:  "auth_url",
	}
	// Authenticate
	err := c.Authenticate()
	if err != nil {
		panic(err)
	}
	// List all the containers
	containers, err := c.ContainerNames(nil)
	fmt.Println(containers)
	// etc...
}
Beispiel #11
0
func ExampleConnection() {
	// Create a v1 auth connection
	c := swift.Connection{
		// This should be your username
		UserName: "******",
		// This should be your api key
		ApiKey: "key",
		// This should be a v1 auth url, eg
		//  Rackspace US        https://auth.api.rackspacecloud.com/v1.0
		//  Rackspace UK        https://lon.auth.api.rackspacecloud.com/v1.0
		//  Memset Memstore UK  https://auth.storage.memset.com/v1.0
		AuthUrl: "auth_url",
	}

	// Authenticate
	err := c.Authenticate()
	if err != nil {
		panic(err)
	}
	// List all the containers
	containers, err := c.ContainerNames(nil)
	fmt.Println(containers)
	// etc...

	// ------ or alternatively create a v2 connection ------

	// Create a v2 auth connection
	c = swift.Connection{
		// This is the sub user for the storage - eg "admin"
		UserName: "******",
		// This should be your api key
		ApiKey: "key",
		// This should be a version2 auth url, eg
		//  Rackspace v2        https://identity.api.rackspacecloud.com/v2.0
		//  Memset Memstore v2  https://auth.storage.memset.com/v2.0
		AuthUrl: "v2_auth_url",
		// Region to use - default is use first region if unset
		Region: "LON",
		// Name of the tenant - this is likely your username
		Tenant: "jim",
	}

	// as above...
}
Beispiel #12
0
func main() {
	//lol if you don't already use swiftly
	username := os.Getenv("SWIFTLY_AUTH_USER")
	apikey := os.Getenv("SWIFTLY_AUTH_KEY")
	authurl := os.Getenv("SWIFTLY_AUTH_URL")
	region := os.Getenv("SWIFTLY_REGION")
	snet := os.Getenv("SWIFTLY_SNET")
	internal := false
	if strings.ToLower(snet) == "true" {
		internal = true
	}
	//martini looks for a HOST and PORT env var to determine what to listen on
	m := martini.Classic()

	cf := swift.Connection{
		UserName: username,
		ApiKey:   apikey,
		AuthUrl:  authurl,
		Region:   region,
		Internal: internal,
	}
	// Authenticate
	err := cf.Authenticate()
	PanicIf(err)
	m.Map(&cf)

	mc := memcache.New("127.0.0.1:11211")
	m.Map(mc)

	m.Use(render.Renderer())

	m.Get("/", IndexPage)
	m.Get("/history", GetHistory)
	m.Get("/:pasteid", GetPaste)
	m.Get("/:pasteid/:format", GetPaste)
	m.Post("/paste", binding.Json(Paste{}), binding.ErrorHandler, SavePaste)
	m.Put("/paste", binding.Json(Paste{}), binding.ErrorHandler, SavePaste)
	m.Run()
}
Beispiel #13
0
func Main() {
	headers["X-Log-Retention"] = "true"
	headers["X-Container-Meta-fubar"] = "false"
	config := getConfig()
	err := config.Parse(os.Args[1:])

	if err != nil {
		fmt.Printf("error verifying flags, %v. See 'osync --help'.", err)
		os.Exit(1)
	}

	prefixlen = len(config.DataDir)

	if err = config.InitializeOSAuth(); nil != err {
		panic("Initial Openstack Authtication Code Failed With " + err.Error())
	}

	headers[OS_TEMP_URL_KEY] = config.OSAuth.TempURLKey

	c := swift.Connection{
		UserName: config.OSAuth.Username,
		ApiKey:   config.OSAuth.Password,
		AuthUrl:  config.OSAuth.Host,
		Tenant:   config.OSAuth.ProjectName,
	}
	// Authenticate
	err = c.Authenticate()
	if err != nil {
		panic(err)
	}

	// List all the containers
	containers, err := c.ContainerNames(nil)
	fmt.Println(containers)

	worker(c, config.DataDir, 0)
}
Beispiel #14
0
func TestTransport(t *testing.T) {
	var err error
	UserName := os.Getenv("SWIFT_API_USER")
	ApiKey := os.Getenv("SWIFT_API_KEY")
	AuthUrl := os.Getenv("SWIFT_AUTH_URL")
	if UserName == "" || ApiKey == "" || AuthUrl == "" {
		srv, err = swifttest.NewSwiftServer("localhost")
		if err != nil {
			t.Fatal("Failed to create server", err)
		}
		UserName = "******"
		ApiKey = "swifttest"
		AuthUrl = srv.AuthURL
	}
	tr := &someTransport{Transport: http.Transport{MaxIdleConnsPerHost: 2048}}
	ct := swift.Connection{
		UserName:       UserName,
		ApiKey:         ApiKey,
		AuthUrl:        AuthUrl,
		Tenant:         os.Getenv("SWIFT_TENANT"),
		TenantId:       os.Getenv("SWIFT_TENANT_ID"),
		Transport:      tr,
		ConnectTimeout: 60 * time.Second,
		Timeout:        60 * time.Second,
	}
	err = ct.Authenticate()
	if err != nil {
		t.Fatal("Auth failed", err)
	}
	if !ct.Authenticated() {
		t.Fatal("Not authenticated")
	}
	if srv != nil {
		srv.Close()
	}
}
func main() {
	// Create a connection
	c := swift.Connection{
		UserName: os.Getenv("SWIFT_API_USER"),
		ApiKey:   os.Getenv("SWIFT_API_KEY"),
		AuthUrl:  os.Getenv("SWIFT_AUTH_URL"),
		Domain:   "", // Name of the domain (v3 auth only)
		Tenant:   "", // Name of the tenant (v2 auth only)
	}

	if len(os.Args) < 5 {
		fmt.Printf("Usage: %s customer jobId status path\n", os.Args[0])
		os.Exit(1)
	}

	println("Starting objekt storage uploader")

	var (
		customer = os.Args[1]
		jobId    = os.Args[2]
		status   = os.Args[3]
		path     = os.Args[4]
	)

	container_name := "jobs-" + customer
	file_prefix := jobId

	// Authenticate
	err := c.Authenticate()
	if err != nil {
		panic(err)
	}

	uploadContentsInFolder(path, file_prefix, container_name, c)
	wpaumetadata.Add(c, container_name, jobId, status)
}
Beispiel #16
0
func TestSwiftBackend(t *testing.T) {
	if os.Getenv("OS_USERNAME") == "" || os.Getenv("OS_PASSWORD") == "" ||
		os.Getenv("OS_AUTH_URL") == "" {
		t.SkipNow()
	}
	username := os.Getenv("OS_USERNAME")
	password := os.Getenv("OS_PASSWORD")
	authUrl := os.Getenv("OS_AUTH_URL")
	tenant := os.Getenv("OS_TENANT_NAME")

	ts := time.Now().UnixNano()
	container := fmt.Sprintf("vault-test-%d", ts)

	cleaner := swift.Connection{
		UserName:  username,
		ApiKey:    password,
		AuthUrl:   authUrl,
		Tenant:    tenant,
		Transport: cleanhttp.DefaultPooledTransport(),
	}

	err := cleaner.Authenticate()
	if err != nil {
		t.Fatalf("err: %s", err)
	}

	err = cleaner.ContainerCreate(container, nil)
	if nil != err {
		t.Fatalf("Unable to create test container '%s': %v", container, err)
	}
	defer func() {
		newObjects, err := cleaner.ObjectNamesAll(container, nil)
		if err != nil {
			t.Fatalf("err: %s", err)
		}
		for _, o := range newObjects {
			err := cleaner.ObjectDelete(container, o)
			if err != nil {
				t.Fatalf("err: %s", err)
			}
		}
		err = cleaner.ContainerDelete(container)
		if err != nil {
			t.Fatalf("err: %s", err)
		}
	}()

	logger := logformat.NewVaultLogger(log.LevelTrace)

	b, err := NewBackend("swift", logger, map[string]string{
		"username":  username,
		"password":  password,
		"container": container,
		"auth_url":  authUrl,
		"tenant":    tenant,
	})
	if err != nil {
		t.Fatalf("err: %s", err)
	}

	testBackend(t, b)
	testBackend_ListPrefix(t, b)

}
Beispiel #17
0
// New constructs a new Driver with the given Openstack Swift credentials and container name
func New(params Parameters) (*Driver, error) {
	transport := &http.Transport{
		Proxy:               http.ProxyFromEnvironment,
		MaxIdleConnsPerHost: 2048,
		TLSClientConfig:     &tls.Config{InsecureSkipVerify: params.InsecureSkipVerify},
	}

	ct := swift.Connection{
		UserName:       params.Username,
		ApiKey:         params.Password,
		AuthUrl:        params.AuthURL,
		Region:         params.Region,
		UserAgent:      "distribution/" + version.Version,
		Tenant:         params.Tenant,
		TenantId:       params.TenantID,
		Domain:         params.Domain,
		DomainId:       params.DomainID,
		TrustId:        params.TrustID,
		Transport:      transport,
		ConnectTimeout: 60 * time.Second,
		Timeout:        15 * 60 * time.Second,
	}
	err := ct.Authenticate()
	if err != nil {
		return nil, fmt.Errorf("Swift authentication failed: %s", err)
	}

	if _, _, err := ct.Container(params.Container); err == swift.ContainerNotFound {
		if err := ct.ContainerCreate(params.Container, nil); err != nil {
			return nil, fmt.Errorf("Failed to create container %s (%s)", params.Container, err)
		}
	} else if err != nil {
		return nil, fmt.Errorf("Failed to retrieve info about container %s (%s)", params.Container, err)
	}

	d := &driver{
		Conn:           ct,
		Container:      params.Container,
		Prefix:         params.Prefix,
		ChunkSize:      params.ChunkSize,
		TempURLMethods: make([]string, 0),
		AccessKey:      params.AccessKey,
	}

	info := swiftInfo{}
	if config, err := d.Conn.QueryInfo(); err == nil {
		_, d.BulkDeleteSupport = config["bulk_delete"]

		if err := mapstructure.Decode(config, &info); err == nil {
			d.TempURLContainerKey = info.Swift.Version >= "2.3.0"
			d.TempURLMethods = info.Tempurl.Methods
		}
	} else {
		d.TempURLContainerKey = params.TempURLContainerKey
		d.TempURLMethods = params.TempURLMethods
	}

	if len(d.TempURLMethods) > 0 {
		secretKey := params.SecretKey
		if secretKey == "" {
			secretKey, _ = generateSecret()
		}

		// Since Swift 2.2.2, we can now set secret keys on containers
		// in addition to the account secret keys. Use them in preference.
		if d.TempURLContainerKey {
			_, containerHeaders, err := d.Conn.Container(d.Container)
			if err != nil {
				return nil, fmt.Errorf("Failed to fetch container info %s (%s)", d.Container, err)
			}

			d.SecretKey = containerHeaders["X-Container-Meta-Temp-Url-Key"]
			if d.SecretKey == "" || (params.SecretKey != "" && d.SecretKey != params.SecretKey) {
				m := swift.Metadata{}
				m["temp-url-key"] = secretKey
				if d.Conn.ContainerUpdate(d.Container, m.ContainerHeaders()); err == nil {
					d.SecretKey = secretKey
				}
			}
		} else {
			// Use the account secret key
			_, accountHeaders, err := d.Conn.Account()
			if err != nil {
				return nil, fmt.Errorf("Failed to fetch account info (%s)", err)
			}

			d.SecretKey = accountHeaders["X-Account-Meta-Temp-Url-Key"]
			if d.SecretKey == "" || (params.SecretKey != "" && d.SecretKey != params.SecretKey) {
				m := swift.Metadata{}
				m["temp-url-key"] = secretKey
				if err := d.Conn.AccountUpdate(m.AccountHeaders()); err == nil {
					d.SecretKey = secretKey
				}
			}
		}
	}

	return &Driver{
		baseEmbed: baseEmbed{
			Base: base.Base{
				StorageDriver: d,
			},
		},
	}, nil
}
Beispiel #18
0
func main() {

	// check for VCAP_SERVICES, parse it if exists

	var runport string
	var runhost string
	// var project string
	var domain string

	username := "******"
	password := "******"
	authurl := "http://127.0.0.1:12345/auth/v1.0"
	globalurl := "http://127.0.0.1:12345/auth/v1.0"

	if runport = os.Getenv("VCAP_APP_PORT"); len(runport) == 0 {
		runport = DEFAULT_PORT
	}
	if runhost = os.Getenv("VCAP_APP_HOST"); len(runhost) == 0 {
		runhost = DEFAULT_HOST
	}

	s := os.Getenv(CREDS_ENV)

	u := os.Getenv(UPLOAD_DISABLED)

	if s != "" {

		log.Printf("Found " + CREDS_ENV + " environment variable, parsing ....\n")

		objstorev2 := make(map[string]ObjStoreV2Info)
		err := json.Unmarshal([]byte(s), &objstorev2)
		if err != nil {
			log.Printf("Error parsing  connection information: %v\n", err.Error())
			panic(err)
		}

		info := objstorev2["CloudIntegration"]
		if &info == nil {
			log.Printf("No cloud integration services accessible to this application.\n")
			return
		}

		creds := info.Credentials
		authurl = info.Authurl + "/v3"
		username = creds.Userid
		password = creds.Password
		domain = info.Domain

	} else {
		log.Printf("No " + CREDS_ENV + ", using defaults.\n")
	}

	log.Printf("Using host %v+\n", runhost)
	log.Printf("Using port %v+\n", runport)
	log.Printf("Using authurl %v+\n", authurl)
	log.Printf("Using username %v+\n", username)
	log.Printf("Using password %v+\n", password)
	log.Printf("Using domain %v+\n", domain)

	log.Printf("Global URI is  %v+\n", globalurl)
	m := martini.Classic()

	c := swift.Connection{
		UserName: username,
		ApiKey:   password,
		AuthUrl:  authurl,
		Domain:   domain,
	}

	// Authenticate
	err2 := c.Authenticate()
	if err2 != nil {
		log.Printf("authenticate error: ", err2)
		// panic(err2)
	}

	m.Use(render.Renderer(render.Options{
		Directory: "tmpl",
		Layout:    "layout",
		Charset:   "UTF-8",
		Funcs: []template.FuncMap{
			{"getPhotoNames": func() template.HTML {

				var result = ""
				var leadstr = "<div class=\"m-item "
				var endstr = "\"><img src=\"pic/"
				var firstcls = "m-active"

				var endtag = "\"></div>"

				files, err := c.ObjectNamesAll("myphotos", nil)
				if err != nil {
					panic(err)
				}

				for i, file := range files {
					result = result + leadstr
					if i == 1 {
						result = result + firstcls
					}
					result = result + endstr + file + endtag

				}
				log.Printf("result is %v", result)
				return template.HTML(result)

			},
			},
		},
	}))

	if u != "" {
		m.Get("/upload", func(r render.Render) {
			fmt.Printf("%v\n", "g./upload")
			r.HTML(200, "uploaddisabled", "")
		})

	} else { // completely disable uplaod
		m.Get("/upload", func(r render.Render) {
			fmt.Printf("%v\n", "g./upload")
			r.HTML(200, "upload", "")
		})

		m.Post("/up", func(w http.ResponseWriter, r *http.Request) {
			fmt.Printf("%v\n", "p./up")

			file, header, err := r.FormFile("fileToUpload")

			defer file.Close()

			if err != nil {
				fmt.Fprintln(w, err)
				return
			}

			tmpFilename, err := readPhotoToTempfile(file)

			if err != nil {
				fmt.Fprint(w, err)
				return
			}

			err2 := sendTempfileToArchive(tmpFilename, header.Filename, c)

			if err2 != nil {
				fmt.Fprintln(w, err2)
				return
			}
			http.Redirect(w, r, "/", 302)
		})

	}

	m.Get("/", func(r render.Render) {
		fmt.Printf("%v\n", "g./album")
		r.HTML(200, "album", "")
	})

	m.Get("/pic/:who.jpg", func(args martini.Params, res http.ResponseWriter, req *http.Request) {

		_, err3 := c.ObjectGet(albumfolder, args["who"]+".jpg", res, false, nil)

		if err3 != nil {
			res.WriteHeader(500)
		}
	})

	m.RunOnAddr(runhost + ":" + runport)
}
Beispiel #19
0
// newSwiftBackend constructs a Swift backend using a pre-existing
// container. Credentials can be provided to the backend, sourced
// from the environment.
func newSwiftBackend(conf map[string]string, logger log.Logger) (Backend, error) {

	username := os.Getenv("OS_USERNAME")
	if username == "" {
		username = conf["username"]
		if username == "" {
			return nil, fmt.Errorf("missing username")
		}
	}
	password := os.Getenv("OS_PASSWORD")
	if password == "" {
		password = conf["password"]
		if password == "" {
			return nil, fmt.Errorf("missing password")
		}
	}
	authUrl := os.Getenv("OS_AUTH_URL")
	if authUrl == "" {
		authUrl = conf["auth_url"]
		if authUrl == "" {
			return nil, fmt.Errorf("missing auth_url")
		}
	}
	container := os.Getenv("OS_CONTAINER")
	if container == "" {
		container = conf["container"]
		if container == "" {
			return nil, fmt.Errorf("missing container")
		}
	}
	tenant := os.Getenv("OS_TENANT_NAME")
	if tenant == "" {
		tenant = conf["tenant"]
	}

	c := swift.Connection{
		UserName:  username,
		ApiKey:    password,
		AuthUrl:   authUrl,
		Tenant:    tenant,
		Transport: cleanhttp.DefaultPooledTransport(),
	}

	err := c.Authenticate()
	if err != nil {
		return nil, err
	}

	_, _, err = c.Container(container)
	if err != nil {
		return nil, fmt.Errorf("Unable to access container '%s': %v", container, err)
	}

	maxParStr, ok := conf["max_parallel"]
	var maxParInt int
	if ok {
		maxParInt, err = strconv.Atoi(maxParStr)
		if err != nil {
			return nil, errwrap.Wrapf("failed parsing max_parallel parameter: {{err}}", err)
		}
		if logger.IsDebug() {
			logger.Debug("swift: max_parallel set", "max_parallel", maxParInt)
		}
	}

	s := &SwiftBackend{
		client:     &c,
		container:  container,
		logger:     logger,
		permitPool: NewPermitPool(maxParInt),
	}
	return s, nil
}